package cmd import ( "os" "path/filepath" "testing" ) func TestGetChatHistoryFile(t *testing.T) { // Save original HOME oldHome := os.Getenv("HOME") defer os.Setenv("HOME", oldHome) tmpDir := t.TempDir() os.Setenv("HOME", tmpDir) histFile := getChatHistoryFile() expected := filepath.Join(tmpDir, ".config", "grokkit", "chat_history.json") if histFile != expected { t.Errorf("getChatHistoryFile() = %q, want %q", histFile, expected) } } func TestLoadChatHistory_NoFile(t *testing.T) { tmpDir := t.TempDir() oldHome := os.Getenv("HOME") os.Setenv("HOME", tmpDir) defer os.Setenv("HOME", oldHome) history := loadChatHistory() if history != nil { t.Errorf("loadChatHistory() expected nil for non-existent file, got %v", history) } } func TestSaveAndLoadChatHistory(t *testing.T) { tmpDir := t.TempDir() oldHome := os.Getenv("HOME") os.Setenv("HOME", tmpDir) defer os.Setenv("HOME", oldHome) // Create test messages messages := []map[string]string{ {"role": "system", "content": "test system message"}, {"role": "user", "content": "hello"}, {"role": "assistant", "content": "hi there"}, } // Save err := saveChatHistory(messages) if err != nil { t.Fatalf("saveChatHistory() error: %v", err) } // Load loaded := loadChatHistory() if loaded == nil { t.Fatal("loadChatHistory() returned nil") } if len(loaded) != len(messages) { t.Errorf("loadChatHistory() length = %d, want %d", len(loaded), len(messages)) } // Verify content for i, msg := range loaded { if msg["role"] != messages[i]["role"] { t.Errorf("Message[%d] role = %q, want %q", i, msg["role"], messages[i]["role"]) } if msg["content"] != messages[i]["content"] { t.Errorf("Message[%d] content = %q, want %q", i, msg["content"], messages[i]["content"]) } } } func TestLoadChatHistory_InvalidJSON(t *testing.T) { tmpDir := t.TempDir() oldHome := os.Getenv("HOME") os.Setenv("HOME", tmpDir) defer os.Setenv("HOME", oldHome) // Create invalid JSON file histDir := filepath.Join(tmpDir, ".config", "grokkit") os.MkdirAll(histDir, 0755) histFile := filepath.Join(histDir, "chat_history.json") os.WriteFile(histFile, []byte("invalid json{{{"), 0644) history := loadChatHistory() if history != nil { t.Errorf("loadChatHistory() expected nil for invalid JSON, got %v", history) } }