grokkit/cmd/chat_test.go

107 lines
2.6 KiB
Go
Raw Permalink Normal View History

package cmd
import (
"os"
"path/filepath"
"testing"
)
func TestGetChatHistoryFile(t *testing.T) {
// Save original HOME
oldHome := os.Getenv("HOME")
defer func() { _ = os.Setenv("HOME", oldHome) }()
tmpDir := t.TempDir()
if err := os.Setenv("HOME", tmpDir); err != nil {
t.Fatal(err)
}
histFile := getChatHistoryFile()
expected := filepath.Join(tmpDir, ".config", "grokkit", "chat_history.json")
if histFile != expected {
t.Errorf("getChatHistoryFile() = %q, want %q", histFile, expected)
}
}
func setHomeForTest(t *testing.T, dir string) {
t.Helper()
if err := os.Setenv("HOME", dir); err != nil {
t.Fatal(err)
}
}
func TestLoadChatHistory_NoFile(t *testing.T) {
tmpDir := t.TempDir()
oldHome := os.Getenv("HOME")
setHomeForTest(t, tmpDir)
defer func() { _ = 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")
setHomeForTest(t, tmpDir)
defer func() { _ = 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")
setHomeForTest(t, tmpDir)
defer func() { _ = os.Setenv("HOME", oldHome) }()
// Create invalid JSON file
histDir := filepath.Join(tmpDir, ".config", "grokkit")
if err := os.MkdirAll(histDir, 0755); err != nil {
t.Fatalf("MkdirAll() error: %v", err)
}
histFile := filepath.Join(histDir, "chat_history.json")
if err := os.WriteFile(histFile, []byte("invalid json{{{"), 0644); err != nil {
t.Fatalf("WriteFile() error: %v", err)
}
history := loadChatHistory()
if history != nil {
t.Errorf("loadChatHistory() expected nil for invalid JSON, got %v", history)
}
}