grokkit/cmd/chat_test.go
Greg Gauthier 13519438a2 test: add unit tests for chat history, edit helper, and code cleaning
- Introduce tests for chat history file handling, loading/saving, and error cases in cmd/chat_test.go
- Add tests for removeLastModifiedComments in cmd/edit_helper_test.go
- Add comprehensive tests for CleanCodeResponse in internal/grok/cleancode_test.go
- Update Makefile to centralize build artifacts in build/ directory for coverage reports and binary
- Adjust .gitignore to ignore chat_history.json and remove obsolete coverage file entries
2026-03-01 12:44:20 +00:00

94 lines
2.3 KiB
Go

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)
}
}