From ce9ccb30993e2e77e16c98be6a215a2b804ac0f4 Mon Sep 17 00:00:00 2001 From: raashed Date: Wed, 7 Oct 2026 23:04:42 +0530 Subject: [PATCH 1/4] fix(llm): return error on empty choices from openai-compatible providers - Guard Choices[0] access in openai, grok and groq clients with a length check - Return "no response choices from " instead of panicking with index out of range - Align behavior with the deepseek, kimi, qwen and perplexity HTTP clients --- internal/llm/grok/client.go | 3 +++ internal/llm/groq/client.go | 3 +++ internal/llm/openai/client.go | 3 +++ 3 files changed, 9 insertions(+) diff --git a/internal/llm/grok/client.go b/internal/llm/grok/client.go index 8fa3105..3b49d27 100644 --- a/internal/llm/grok/client.go +++ b/internal/llm/grok/client.go @@ -68,5 +68,8 @@ The git diff is in the second next message.`), if err != nil { return "", fmt.Errorf("error while prompting to Grok: %w", err) } + if len(chatCompletion.Choices) == 0 { + return "", fmt.Errorf("no response choices from Grok") + } return chatCompletion.Choices[0].Message.Content, nil } diff --git a/internal/llm/groq/client.go b/internal/llm/groq/client.go index b643a84..61f82aa 100644 --- a/internal/llm/groq/client.go +++ b/internal/llm/groq/client.go @@ -68,5 +68,8 @@ The git diff is in the second next message.`), if err != nil { return "", fmt.Errorf("error while prompting to Groq: %w", err) } + if len(chatCompletion.Choices) == 0 { + return "", fmt.Errorf("no response choices from Groq") + } return chatCompletion.Choices[0].Message.Content, nil } diff --git a/internal/llm/openai/client.go b/internal/llm/openai/client.go index e41bcc1..a782516 100644 --- a/internal/llm/openai/client.go +++ b/internal/llm/openai/client.go @@ -63,5 +63,8 @@ The git diff is in the second next message.`), if err != nil { return fmt.Sprintf("error while prompting to open-ai at: %v", err), err } + if len(chatCompletion.Choices) == 0 { + return "", fmt.Errorf("no response choices from OpenAI") + } return chatCompletion.Choices[0].Message.Content, nil } From 16bbce2f066f43148181efad5cb8881550f57c24 Mon Sep 17 00:00:00 2001 From: raashed Date: Wed, 7 Oct 2026 23:04:42 +0530 Subject: [PATCH 2/4] test(llm): exercise every provider against local http servers - Expose apiURL in deepseek, kimi, qwen and perplexity and baseURL in grok and groq as package vars - Add endpointOptions to the gemini client so tests can target a local REST endpoint - Drive openai and anthropic tests through OPENAI_BASE_URL and ANTHROPIC_BASE_URL, and ollama through OLLAMA_HOST - Replace tautological constant checks with tests asserting request shape, auth headers, model and response parsing - Cover non-200, malformed json, empty choices, invalid url and unreachable server error paths - Isolate HOME and provider env vars so tests never read real keys or call live APIs --- internal/llm/anthropic/client_test.go | 138 ++++++++++++------- internal/llm/deepseek/client.go | 5 +- internal/llm/deepseek/client_test.go | 171 ++++++++++++++++------- internal/llm/gemini/client.go | 5 +- internal/llm/gemini/client_test.go | 151 ++++++++++---------- internal/llm/grok/client.go | 5 +- internal/llm/grok/client_test.go | 130 ++++++++++++----- internal/llm/groq/client.go | 5 +- internal/llm/groq/client_test.go | 130 ++++++++++++----- internal/llm/kimi/client.go | 5 +- internal/llm/kimi/client_test.go | 165 ++++++++++++++++------ internal/llm/ollama/client_test.go | 137 +++++++++++------- internal/llm/openai/client_test.go | 157 ++++++++++++--------- internal/llm/perplexity/client.go | 5 +- internal/llm/perplexity/client_test.go | 184 ++++++++++++++++--------- internal/llm/qwen/client.go | 5 +- internal/llm/qwen/client_test.go | 172 ++++++++++++++++++----- 17 files changed, 1063 insertions(+), 507 deletions(-) diff --git a/internal/llm/anthropic/client_test.go b/internal/llm/anthropic/client_test.go index e7fbf68..1a9a220 100644 --- a/internal/llm/anthropic/client_test.go +++ b/internal/llm/anthropic/client_test.go @@ -2,72 +2,104 @@ package anthropic import ( "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" "testing" ) -// TestClientRegistration verifies the client is registered correctly -func TestClientRegistration(t *testing.T) { - var _ interface { - GenerateCommitMessage(ctx context.Context, diff string, additionalContext string) (string, error) - } = &client{} +// isolate keeps the developer's real keys file and environment out of the test. +func isolate(t *testing.T) { + t.Helper() + t.Setenv("HOME", t.TempDir()) + t.Setenv("ANTHROPIC_API_KEY", "") } -// TestAPIKeyValidation verifies API key validation follows Anthropic documentation -// According to Anthropic docs: API key should be checked before making requests -func TestAPIKeyValidation(t *testing.T) { - c := &client{} - ctx := context.Background() +// serve points the SDK at a local server via ANTHROPIC_BASE_URL. +func serve(t *testing.T, status int, body string) { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost || r.URL.Path != "/v1/messages" { + t.Errorf("request = %s %s, want POST /v1/messages", r.Method, r.URL.Path) + } + if got := r.Header.Get("X-Api-Key"); got != "test-key" { + t.Errorf("X-Api-Key = %q, want test-key", got) + } + var req struct { + Model string `json:"model"` + Messages []struct { + Content []struct { + Text string `json:"text"` + } `json:"content"` + } `json:"messages"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + t.Fatalf("decode request: %v", err) + } + if req.Model != "claude-3-5-haiku-20241022" { + t.Errorf("model = %q, want claude-3-5-haiku-20241022", req.Model) + } + if len(req.Messages) != 1 || len(req.Messages[0].Content) != 1 || !strings.Contains(req.Messages[0].Content[0].Text, "the diff") { + t.Errorf("messages = %+v, want a single user message containing the diff", req.Messages) + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + w.Write([]byte(body)) + })) + t.Cleanup(srv.Close) + t.Setenv("ANTHROPIC_BASE_URL", srv.URL) +} - // Test that missing API key returns proper error message - // Anthropic docs specify: "ANTHROPIC_API_KEY environment variable not set" - _, err := c.GenerateCommitMessage(ctx, "test diff", "") - if err == nil { - t.Error("GenerateCommitMessage() should return error when API key is missing") - } - if err != nil && err.Error() != "ANTHROPIC_API_KEY environment variable not set" { - t.Errorf("GenerateCommitMessage() error message = %q, want 'ANTHROPIC_API_KEY environment variable not set'", err.Error()) - } +func message(content string) string { + return `{"id":"msg_1","type":"message","role":"assistant","model":"claude-3-5-haiku-20241022","content":` + content + + `,"stop_reason":"end_turn","usage":{"input_tokens":1,"output_tokens":1}}` } -// TestModelSelection verifies the correct model is used -// According to Anthropic docs: claude-3-5-haiku-20241022 should be used -func TestModelSelection(t *testing.T) { - // Verify the model constant matches Anthropic's documented model identifier - // The code uses: anthropicsdk.ModelClaude3_5Haiku20241022 - expectedModel := "claude-3-5-haiku-20241022" - if expectedModel != "claude-3-5-haiku-20241022" { - t.Errorf("Model should be claude-3-5-haiku-20241022, got %s", expectedModel) +func TestGenerateCommitMessageMissingKey(t *testing.T) { + isolate(t) + + _, err := (&client{}).GenerateCommitMessage(context.Background(), "the diff", "") + if err == nil || err.Error() != "ANTHROPIC_API_KEY environment variable not set" { + t.Fatalf("err = %v, want missing ANTHROPIC_API_KEY error", err) } } -// TestRequestStructure verifies request structure matches Anthropic API spec -// According to Anthropic docs: POST /v1/messages with model, messages, system, max_tokens -func TestRequestStructure(t *testing.T) { - // Verify the implementation uses: - // 1. Messages array with NewUserMessage and NewTextBlock - // 2. System parameter with TextBlockParam array - // 3. MaxTokens parameter (1024 as per code) - // 4. Model parameter +func TestGenerateCommitMessageSuccess(t *testing.T) { + isolate(t) + t.Setenv("ANTHROPIC_API_KEY", "test-key") + serve(t, http.StatusOK, message(`[{"type":"text","text":"feat: add thing"}]`)) - // The code structure matches Anthropic's documented format: - // - Messages: []anthropicsdk.MessageParam with NewUserMessage(NewTextBlock(...)) - // - System: []anthropicsdk.TextBlockParam - // - MaxTokens: 1024 - // - Model: ModelClaude3_5Haiku20241022 + got, err := (&client{}).GenerateCommitMessage(context.Background(), "the diff", "ctx") + if err != nil { + t.Fatalf("GenerateCommitMessage() error = %v", err) + } + if got != "feat: add thing" { + t.Errorf("GenerateCommitMessage() = %q, want %q", got, "feat: add thing") + } } -// TestResponseHandling verifies response parsing matches Anthropic API spec -// According to Anthropic docs: response has Content array with Text field -func TestResponseHandling(t *testing.T) { - // Verify the implementation correctly accesses: - // - message.Content[0].Text (as per Anthropic API response structure) - // - Checks for empty Content array - // The code matches Anthropic's documented response format -} +func TestGenerateCommitMessageErrors(t *testing.T) { + tests := []struct { + name string + status int + body string + wantErr string + }{ + {"api error", http.StatusBadRequest, `{"type":"error","error":{"type":"invalid_request_error","message":"bad"}}`, "error while prompting to Anthropic"}, + {"empty content", http.StatusOK, message(`[]`), "no response generated"}, + } -// TestErrorHandling verifies error handling follows Anthropic documentation -func TestErrorHandling(t *testing.T) { - // Verify error messages follow Anthropic's error format - // The code uses: fmt.Errorf("error while prompting to Anthropic: %w", err) - // This provides context and wraps errors as recommended + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + isolate(t) + t.Setenv("ANTHROPIC_API_KEY", "test-key") + serve(t, tt.status, tt.body) + + _, err := (&client{}).GenerateCommitMessage(context.Background(), "the diff", "") + if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("err = %v, want it to contain %q", err, tt.wantErr) + } + }) + } } diff --git a/internal/llm/deepseek/client.go b/internal/llm/deepseek/client.go index e9c4924..423ca7b 100644 --- a/internal/llm/deepseek/client.go +++ b/internal/llm/deepseek/client.go @@ -13,6 +13,9 @@ import ( "github.com/rshdhere/vibecheck/internal/llm" ) +// apiURL is the chat completions endpoint; tests point it at a local server. +var apiURL = "https://api.deepseek.com/v1/chat/completions" + type client struct{} func init() { @@ -82,7 +85,7 @@ The git diff is in the second next message.` return "", fmt.Errorf("marshal request: %w", err) } - req, err := http.NewRequestWithContext(ctx, "POST", "https://api.deepseek.com/v1/chat/completions", bytes.NewBuffer(jsonData)) + req, err := http.NewRequestWithContext(ctx, "POST", apiURL, bytes.NewBuffer(jsonData)) if err != nil { return "", fmt.Errorf("create request: %w", err) } diff --git a/internal/llm/deepseek/client_test.go b/internal/llm/deepseek/client_test.go index 914a476..e260d52 100644 --- a/internal/llm/deepseek/client_test.go +++ b/internal/llm/deepseek/client_test.go @@ -2,68 +2,143 @@ package deepseek import ( "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" "testing" ) -// TestClientRegistration verifies the client is registered correctly -func TestClientRegistration(t *testing.T) { - var _ interface { - GenerateCommitMessage(ctx context.Context, diff string, additionalContext string) (string, error) - } = &client{} +const ( + envVar = "DEEPSEEK_API_KEY" + wantModel = "deepseek-chat" +) + +// isolate keeps the developer's real keys file and environment out of the test. +func isolate(t *testing.T) { + t.Helper() + t.Setenv("HOME", t.TempDir()) + t.Setenv(envVar, "") } -// TestAPIKeyValidation verifies API key validation -func TestAPIKeyValidation(t *testing.T) { - c := &client{} - ctx := context.Background() +// serve points apiURL at a local server for the duration of the test. +func serve(t *testing.T, h http.HandlerFunc) { + t.Helper() + srv := httptest.NewServer(h) + t.Cleanup(srv.Close) + setAPIURL(t, srv.URL) +} - _, err := c.GenerateCommitMessage(ctx, "test diff", "") - if err == nil { - t.Error("GenerateCommitMessage() should return error when API key is missing") - } - if err != nil && err.Error() != "DEEPSEEK_API_KEY environment variable not set" { - t.Errorf("GenerateCommitMessage() error message = %q, want 'DEEPSEEK_API_KEY environment variable not set'", err.Error()) - } +func setAPIURL(t *testing.T, url string) { + t.Helper() + old := apiURL + apiURL = url + t.Cleanup(func() { apiURL = old }) } -// TestEndpointURL verifies the endpoint URL matches DeepSeek API documentation -// According to DeepSeek docs: https://api.deepseek.com/v1/chat/completions -func TestEndpointURL(t *testing.T) { - expectedURL := "https://api.deepseek.com/v1/chat/completions" - if expectedURL != "https://api.deepseek.com/v1/chat/completions" { - t.Errorf("Endpoint URL should be https://api.deepseek.com/v1/chat/completions, got %s", expectedURL) +func TestGenerateCommitMessageMissingKey(t *testing.T) { + isolate(t) + + _, err := (&client{}).GenerateCommitMessage(context.Background(), "diff", "") + if err == nil || err.Error() != envVar+" environment variable not set" { + t.Fatalf("err = %v, want missing %s error", err, envVar) } } -// TestRequestStructure verifies request structure matches DeepSeek API spec -// According to DeepSeek docs: OpenAI-compatible format with model and messages -func TestRequestStructure(t *testing.T) { - // Verify the implementation uses: - // 1. Model: "deepseek-chat" (as per DeepSeek docs) - // 2. Messages array with role and content - // 3. System message with role "system" - // 4. User messages with role "user" - - expectedModel := "deepseek-chat" - if expectedModel != "deepseek-chat" { - t.Errorf("Model should be deepseek-chat, got %s", expectedModel) +func TestGenerateCommitMessageSuccess(t *testing.T) { + isolate(t) + t.Setenv(envVar, "test-key") + + serve(t, func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + t.Errorf("method = %s, want POST", r.Method) + } + if got := r.Header.Get("Authorization"); got != "Bearer test-key" { + t.Errorf("Authorization = %q, want Bearer test-key", got) + } + if got := r.Header.Get("Content-Type"); got != "application/json" { + t.Errorf("Content-Type = %q, want application/json", got) + } + var req chatRequest + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + t.Fatalf("decode request: %v", err) + } + if req.Model != wantModel { + t.Errorf("model = %q, want %q", req.Model, wantModel) + } + if len(req.Messages) != 3 || req.Messages[0].Role != "system" { + t.Fatalf("messages = %+v, want system + 2 user messages", req.Messages) + } + if !strings.Contains(req.Messages[1].Content, "extra context") { + t.Errorf("context message = %q, want it to include the user context", req.Messages[1].Content) + } + if req.Messages[2].Content != "the diff" { + t.Errorf("diff message = %q, want %q", req.Messages[2].Content, "the diff") + } + w.Write([]byte(`{"choices":[{"message":{"role":"assistant","content":"feat: add thing"}}]}`)) + }) + + got, err := (&client{}).GenerateCommitMessage(context.Background(), "the diff", "extra context") + if err != nil { + t.Fatalf("GenerateCommitMessage() error = %v", err) + } + if got != "feat: add thing" { + t.Errorf("GenerateCommitMessage() = %q, want %q", got, "feat: add thing") } } -// TestHeaders verifies HTTP headers match DeepSeek API documentation -// According to DeepSeek docs: Authorization: Bearer , Content-Type: application/json -func TestHeaders(t *testing.T) { - // Verify headers are set correctly: - // - Content-Type: application/json - // - Authorization: Bearer - // The code matches DeepSeek's documented header requirements +func TestGenerateCommitMessageResponseErrors(t *testing.T) { + tests := []struct { + name string + status int + body string + wantErr string + }{ + {"non-200 status", http.StatusUnauthorized, "bad key", "status 401: bad key"}, + {"invalid json", http.StatusOK, "not json", "decode response"}, + {"no choices", http.StatusOK, `{"choices":[]}`, "no response choices"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + isolate(t) + t.Setenv(envVar, "test-key") + serve(t, func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(tt.status) + w.Write([]byte(tt.body)) + }) + + _, err := (&client{}).GenerateCommitMessage(context.Background(), "diff", "") + if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("err = %v, want it to contain %q", err, tt.wantErr) + } + }) + } } -// TestResponseStructure verifies response parsing matches DeepSeek API spec -// According to DeepSeek docs: OpenAI-compatible response with choices array -func TestResponseStructure(t *testing.T) { - // Verify the implementation correctly accesses: - // - chatResp.Choices[0].Message.Content - // - Checks for empty Choices array - // The code matches DeepSeek's documented response format +func TestGenerateCommitMessageRequestErrors(t *testing.T) { + closed := httptest.NewServer(http.NotFoundHandler()) + closed.Close() + + tests := []struct { + name string + url string + wantErr string + }{ + {"invalid url", "://bad-url", "create request"}, + {"unreachable server", closed.URL, "send request"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + isolate(t) + t.Setenv(envVar, "test-key") + setAPIURL(t, tt.url) + + _, err := (&client{}).GenerateCommitMessage(context.Background(), "diff", "") + if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("err = %v, want it to contain %q", err, tt.wantErr) + } + }) + } } diff --git a/internal/llm/gemini/client.go b/internal/llm/gemini/client.go index b01a699..e290ea4 100644 --- a/internal/llm/gemini/client.go +++ b/internal/llm/gemini/client.go @@ -11,6 +11,9 @@ import ( "google.golang.org/api/option" ) +// endpointOptions are appended to the client options; tests use them to target a local server. +var endpointOptions []option.ClientOption + type client struct{} func init() { @@ -23,7 +26,7 @@ func (c *client) GenerateCommitMessage(ctx context.Context, diff string, additio return "", fmt.Errorf("GEMINI_API_KEY environment variable not set") } - client, err := genai.NewClient(ctx, option.WithAPIKey(key)) + client, err := genai.NewClient(ctx, append([]option.ClientOption{option.WithAPIKey(key)}, endpointOptions...)...) if err != nil { return "", fmt.Errorf("create gemini client: %w", err) } diff --git a/internal/llm/gemini/client_test.go b/internal/llm/gemini/client_test.go index 332a4a8..0155ed5 100644 --- a/internal/llm/gemini/client_test.go +++ b/internal/llm/gemini/client_test.go @@ -2,103 +2,90 @@ package gemini import ( "context" + "io" + "net/http" + "net/http/httptest" + "strings" "testing" + + "google.golang.org/api/option" ) -// TestClientRegistration verifies the client is registered correctly -func TestClientRegistration(t *testing.T) { - var _ interface { - GenerateCommitMessage(ctx context.Context, diff string, additionalContext string) (string, error) - } = &client{} +// isolate keeps the developer's real keys file and environment out of the test. +func isolate(t *testing.T) { + t.Helper() + t.Setenv("HOME", t.TempDir()) + t.Setenv("GEMINI_API_KEY", "") } -// TestAPIKeyValidation verifies API key validation -// Note: Gemini SDK may not fail immediately on client creation, but will fail on API call -func TestAPIKeyValidation(t *testing.T) { - c := &client{} - ctx := context.Background() - - // The implementation checks for API key before creating client - // According to Gemini docs: API key should be validated before making requests - _, err := c.GenerateCommitMessage(ctx, "test diff", "") - // Error may occur at client creation or API call, both are valid - if err == nil { - // If no error, the test environment might have a key set - // This is acceptable - the important part is the code checks for the key - t.Log("No error returned - API key may be set in test environment") - } else { - // Verify error message mentions GEMINI_API_KEY or client creation - if err.Error() != "GEMINI_API_KEY environment variable not set" && - !contains(err.Error(), "GEMINI_API_KEY") && - !contains(err.Error(), "create gemini client") { - t.Logf("Error message: %q (may be from client creation, which is valid)", err.Error()) +// serve points the client at a local server that replies with status and body. +func serve(t *testing.T, status int, body string) { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if !strings.Contains(r.URL.Path, "gemini-2.5-flash") { + t.Errorf("path = %q, want it to target gemini-2.5-flash", r.URL.Path) } - } -} + req, _ := io.ReadAll(r.Body) + if !strings.Contains(string(req), "the diff") { + t.Errorf("request body does not include the diff: %s", req) + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + w.Write([]byte(body)) + })) + t.Cleanup(srv.Close) -func contains(s, substr string) bool { - return len(s) >= len(substr) && - (s == substr || - (len(s) > len(substr) && - (s[:len(substr)] == substr || - s[len(s)-len(substr):] == substr || - containsHelper(s, substr)))) + old := endpointOptions + endpointOptions = []option.ClientOption{option.WithEndpoint(srv.URL)} + t.Cleanup(func() { endpointOptions = old }) } -func containsHelper(s, substr string) bool { - for i := 0; i <= len(s)-len(substr); i++ { - if s[i:i+len(substr)] == substr { - return true - } - } - return false -} +func TestGenerateCommitMessageMissingKey(t *testing.T) { + isolate(t) -// TestModelSelection verifies the correct model is used -// According to Gemini docs: gemini-2.5-flash should be used -func TestModelSelection(t *testing.T) { - expectedModel := "gemini-2.5-flash" - if expectedModel != "gemini-2.5-flash" { - t.Errorf("Model should be gemini-2.5-flash, got %s", expectedModel) + _, err := (&client{}).GenerateCommitMessage(context.Background(), "the diff", "") + if err == nil || err.Error() != "GEMINI_API_KEY environment variable not set" { + t.Fatalf("err = %v, want missing GEMINI_API_KEY error", err) } } -// TestModelParameters verifies model parameters match Gemini API documentation -// According to Gemini docs: Temperature, TopK, TopP, MaxOutputTokens are supported -func TestModelParameters(t *testing.T) { - // Verify the implementation sets: - // - Temperature: 0.7 (as per code) - // - TopK: 40 (as per code) - // - TopP: 0.95 (as per code) - // - MaxOutputTokens: 1024 (as per code) - // These parameters match Gemini's documented API -} +func TestGenerateCommitMessageSuccess(t *testing.T) { + isolate(t) + t.Setenv("GEMINI_API_KEY", "test-key") + serve(t, http.StatusOK, `{"candidates":[{"content":{"role":"model","parts":[{"text":"feat: add thing"}]},"finishReason":"STOP"}]}`) -// TestSafetySettings verifies safety settings match Gemini API documentation -// According to Gemini docs: SafetySettings array with Category and Threshold -func TestSafetySettings(t *testing.T) { - // Verify the implementation sets safety settings for: - // - HarmCategoryHarassment: HarmBlockOnlyHigh - // - HarmCategoryHateSpeech: HarmBlockOnlyHigh - // - HarmCategorySexuallyExplicit: HarmBlockOnlyHigh - // - HarmCategoryDangerousContent: HarmBlockOnlyHigh - // These match Gemini's documented safety settings API + got, err := (&client{}).GenerateCommitMessage(context.Background(), "the diff", "ctx") + if err != nil { + t.Fatalf("GenerateCommitMessage() error = %v", err) + } + if got != "feat: add thing" { + t.Errorf("GenerateCommitMessage() = %q, want %q", got, "feat: add thing") + } } -// TestSystemInstruction verifies system instruction format matches Gemini API -// According to Gemini docs: SystemInstruction with Content.Parts array -func TestSystemInstruction(t *testing.T) { - // Verify the implementation uses: - // - model.SystemInstruction = &genai.Content{Parts: []genai.Part{genai.Text(...)}} - // This matches Gemini's documented SystemInstruction format -} +func TestGenerateCommitMessageErrors(t *testing.T) { + tests := []struct { + name string + status int + body string + wantErr string + }{ + {"api error", http.StatusBadRequest, `{"error":{"code":400,"message":"bad request"}}`, "generate content"}, + {"no candidates", http.StatusOK, `{"candidates":[]}`, "no candidates"}, + {"unexpected finish reason", http.StatusOK, `{"candidates":[{"content":{"role":"model","parts":[{"text":"x"}]},"finishReason":"OTHER"}]}`, "finish reason"}, + {"empty content", http.StatusOK, `{"candidates":[{"finishReason":"STOP"}]}`, "empty content"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + isolate(t) + t.Setenv("GEMINI_API_KEY", "test-key") + serve(t, tt.status, tt.body) -// TestResponseHandling verifies response parsing matches Gemini API spec -// According to Gemini docs: response has Candidates array with Content.Parts -func TestResponseHandling(t *testing.T) { - // Verify the implementation correctly accesses: - // - resp.Candidates[0].Content.Parts[0] - // - Checks for empty Candidates array - // - Checks FinishReason (Stop or MaxTokens) - // The code matches Gemini's documented response format + _, err := (&client{}).GenerateCommitMessage(context.Background(), "the diff", "") + if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("err = %v, want it to contain %q", err, tt.wantErr) + } + }) + } } diff --git a/internal/llm/grok/client.go b/internal/llm/grok/client.go index 3b49d27..0fe5f9c 100644 --- a/internal/llm/grok/client.go +++ b/internal/llm/grok/client.go @@ -11,6 +11,9 @@ import ( "github.com/rshdhere/vibecheck/internal/llm" ) +// baseURL is the OpenAI-compatible API root; tests point it at a local server. +var baseURL = "https://api.x.ai/v1" + type client struct{} func init() { @@ -26,7 +29,7 @@ func (c *client) GenerateCommitMessage(ctx context.Context, diff string, additio // Grok uses OpenAI-compatible API client := openaisdk.NewClient( option.WithAPIKey(key), - option.WithBaseURL("https://api.x.ai/v1"), + option.WithBaseURL(baseURL), ) // Using grok-beta model diff --git a/internal/llm/grok/client_test.go b/internal/llm/grok/client_test.go index 7da298e..ce33e0b 100644 --- a/internal/llm/grok/client_test.go +++ b/internal/llm/grok/client_test.go @@ -2,51 +2,115 @@ package grok import ( "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" "testing" ) -// TestClientRegistration verifies the client is registered correctly -func TestClientRegistration(t *testing.T) { - var _ interface { - GenerateCommitMessage(ctx context.Context, diff string, additionalContext string) (string, error) - } = &client{} +const ( + envVar = "XAI_API_KEY" + wantModel = "grok-beta" +) + +// isolate keeps the developer's real keys file and environment out of the test. +func isolate(t *testing.T) { + t.Helper() + t.Setenv("HOME", t.TempDir()) + t.Setenv(envVar, "") } -// TestAPIKeyValidation verifies API key validation -func TestAPIKeyValidation(t *testing.T) { - c := &client{} - ctx := context.Background() +// point directs the client at url for the duration of the test. +func point(t *testing.T, url string) { + t.Helper() + old := baseURL + baseURL = url + t.Cleanup(func() { baseURL = old }) +} - _, err := c.GenerateCommitMessage(ctx, "test diff", "") - if err == nil { - t.Error("GenerateCommitMessage() should return error when API key is missing") - } - if err != nil && err.Error() != "XAI_API_KEY environment variable not set" { - t.Errorf("GenerateCommitMessage() error message = %q, want 'XAI_API_KEY environment variable not set'", err.Error()) - } +// serve starts an OpenAI-compatible stand-in that replies with status and body. +func serve(t *testing.T, status int, body string) { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost || !strings.HasSuffix(r.URL.Path, "/chat/completions") { + t.Errorf("request = %s %s, want POST .../chat/completions", r.Method, r.URL.Path) + } + if got := r.Header.Get("Authorization"); got != "Bearer test-key" { + t.Errorf("Authorization = %q, want Bearer test-key", got) + } + var req struct { + Model string `json:"model"` + Messages []struct { + Role string `json:"role"` + Content string `json:"content"` + } `json:"messages"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + t.Fatalf("decode request: %v", err) + } + if req.Model != wantModel { + t.Errorf("model = %q, want %q", req.Model, wantModel) + } + if len(req.Messages) != 3 || req.Messages[0].Role != "system" || req.Messages[2].Content != "the diff" { + t.Errorf("messages = %+v, want system + context + diff", req.Messages) + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + w.Write([]byte(body)) + })) + t.Cleanup(srv.Close) + point(t, srv.URL) +} + +func completion(choices string) string { + return `{"id":"c1","object":"chat.completion","created":0,"model":"` + wantModel + `","choices":` + choices + `}` } -// TestBaseURL verifies the base URL matches xAI Grok API documentation -// According to xAI docs: https://api.x.ai/v1 (OpenAI-compatible) -func TestBaseURL(t *testing.T) { - expectedURL := "https://api.x.ai/v1" - if expectedURL != "https://api.x.ai/v1" { - t.Errorf("Base URL should be https://api.x.ai/v1, got %s", expectedURL) +func TestGenerateCommitMessageMissingKey(t *testing.T) { + isolate(t) + + _, err := (&client{}).GenerateCommitMessage(context.Background(), "the diff", "") + if err == nil || err.Error() != envVar+" environment variable not set" { + t.Fatalf("err = %v, want missing %s error", err, envVar) } } -// TestModelSelection verifies the correct model is used -// According to xAI docs: grok-beta is the model name -func TestModelSelection(t *testing.T) { - expectedModel := "grok-beta" - if expectedModel != "grok-beta" { - t.Errorf("Model should be grok-beta, got %s", expectedModel) +func TestGenerateCommitMessageSuccess(t *testing.T) { + isolate(t) + t.Setenv(envVar, "test-key") + serve(t, http.StatusOK, completion(`[{"index":0,"finish_reason":"stop","message":{"role":"assistant","content":"feat: add thing"}}]`)) + + got, err := (&client{}).GenerateCommitMessage(context.Background(), "the diff", "ctx") + if err != nil { + t.Fatalf("GenerateCommitMessage() error = %v", err) + } + if got != "feat: add thing" { + t.Errorf("GenerateCommitMessage() = %q, want %q", got, "feat: add thing") } } -// TestOpenAICompatibility verifies Grok uses OpenAI-compatible API format -// According to xAI docs: Grok API is OpenAI-compatible -func TestOpenAICompatibility(t *testing.T) { - // Verify the implementation uses OpenAI SDK with custom base URL - // This matches xAI's documented OpenAI-compatible API approach +func TestGenerateCommitMessageErrors(t *testing.T) { + tests := []struct { + name string + status int + body string + wantErr string + }{ + {"api error", http.StatusBadRequest, `{"error":{"message":"bad request"}}`, "400"}, + {"no choices", http.StatusOK, completion(`[]`), "no response choices"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + isolate(t) + t.Setenv(envVar, "test-key") + serve(t, tt.status, tt.body) + + _, err := (&client{}).GenerateCommitMessage(context.Background(), "the diff", "") + if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("err = %v, want it to contain %q", err, tt.wantErr) + } + }) + } } diff --git a/internal/llm/groq/client.go b/internal/llm/groq/client.go index 61f82aa..054adf9 100644 --- a/internal/llm/groq/client.go +++ b/internal/llm/groq/client.go @@ -11,6 +11,9 @@ import ( "github.com/rshdhere/vibecheck/internal/llm" ) +// baseURL is the OpenAI-compatible API root; tests point it at a local server. +var baseURL = "https://api.groq.com/openai/v1" + type client struct{} func init() { @@ -26,7 +29,7 @@ func (c *client) GenerateCommitMessage(ctx context.Context, diff string, additio // Groq uses OpenAI-compatible API client := openaisdk.NewClient( option.WithAPIKey(key), - option.WithBaseURL("https://api.groq.com/openai/v1"), + option.WithBaseURL(baseURL), ) // Using llama-3.3-70b-versatile for excellent performance and speed diff --git a/internal/llm/groq/client_test.go b/internal/llm/groq/client_test.go index 5200ef0..7f4f53f 100644 --- a/internal/llm/groq/client_test.go +++ b/internal/llm/groq/client_test.go @@ -2,51 +2,115 @@ package groq import ( "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" "testing" ) -// TestClientRegistration verifies the client is registered correctly -func TestClientRegistration(t *testing.T) { - var _ interface { - GenerateCommitMessage(ctx context.Context, diff string, additionalContext string) (string, error) - } = &client{} +const ( + envVar = "GROQ_API_KEY" + wantModel = "llama-3.3-70b-versatile" +) + +// isolate keeps the developer's real keys file and environment out of the test. +func isolate(t *testing.T) { + t.Helper() + t.Setenv("HOME", t.TempDir()) + t.Setenv(envVar, "") } -// TestAPIKeyValidation verifies API key validation -func TestAPIKeyValidation(t *testing.T) { - c := &client{} - ctx := context.Background() +// point directs the client at url for the duration of the test. +func point(t *testing.T, url string) { + t.Helper() + old := baseURL + baseURL = url + t.Cleanup(func() { baseURL = old }) +} - _, err := c.GenerateCommitMessage(ctx, "test diff", "") - if err == nil { - t.Error("GenerateCommitMessage() should return error when API key is missing") - } - if err != nil && err.Error() != "GROQ_API_KEY environment variable not set" { - t.Errorf("GenerateCommitMessage() error message = %q, want 'GROQ_API_KEY environment variable not set'", err.Error()) - } +// serve starts an OpenAI-compatible stand-in that replies with status and body. +func serve(t *testing.T, status int, body string) { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost || !strings.HasSuffix(r.URL.Path, "/chat/completions") { + t.Errorf("request = %s %s, want POST .../chat/completions", r.Method, r.URL.Path) + } + if got := r.Header.Get("Authorization"); got != "Bearer test-key" { + t.Errorf("Authorization = %q, want Bearer test-key", got) + } + var req struct { + Model string `json:"model"` + Messages []struct { + Role string `json:"role"` + Content string `json:"content"` + } `json:"messages"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + t.Fatalf("decode request: %v", err) + } + if req.Model != wantModel { + t.Errorf("model = %q, want %q", req.Model, wantModel) + } + if len(req.Messages) != 3 || req.Messages[0].Role != "system" || req.Messages[2].Content != "the diff" { + t.Errorf("messages = %+v, want system + context + diff", req.Messages) + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + w.Write([]byte(body)) + })) + t.Cleanup(srv.Close) + point(t, srv.URL) +} + +func completion(choices string) string { + return `{"id":"c1","object":"chat.completion","created":0,"model":"` + wantModel + `","choices":` + choices + `}` } -// TestBaseURL verifies the base URL matches Groq API documentation -// According to Groq docs: https://api.groq.com/openai/v1 (OpenAI-compatible) -func TestBaseURL(t *testing.T) { - expectedURL := "https://api.groq.com/openai/v1" - if expectedURL != "https://api.groq.com/openai/v1" { - t.Errorf("Base URL should be https://api.groq.com/openai/v1, got %s", expectedURL) +func TestGenerateCommitMessageMissingKey(t *testing.T) { + isolate(t) + + _, err := (&client{}).GenerateCommitMessage(context.Background(), "the diff", "") + if err == nil || err.Error() != envVar+" environment variable not set" { + t.Fatalf("err = %v, want missing %s error", err, envVar) } } -// TestModelSelection verifies the correct model is used -// According to Groq docs: llama-3.3-70b-versatile is available -func TestModelSelection(t *testing.T) { - expectedModel := "llama-3.3-70b-versatile" - if expectedModel != "llama-3.3-70b-versatile" { - t.Errorf("Model should be llama-3.3-70b-versatile, got %s", expectedModel) +func TestGenerateCommitMessageSuccess(t *testing.T) { + isolate(t) + t.Setenv(envVar, "test-key") + serve(t, http.StatusOK, completion(`[{"index":0,"finish_reason":"stop","message":{"role":"assistant","content":"feat: add thing"}}]`)) + + got, err := (&client{}).GenerateCommitMessage(context.Background(), "the diff", "ctx") + if err != nil { + t.Fatalf("GenerateCommitMessage() error = %v", err) + } + if got != "feat: add thing" { + t.Errorf("GenerateCommitMessage() = %q, want %q", got, "feat: add thing") } } -// TestOpenAICompatibility verifies Groq uses OpenAI-compatible API format -// According to Groq docs: Groq API is OpenAI-compatible -func TestOpenAICompatibility(t *testing.T) { - // Verify the implementation uses OpenAI SDK with custom base URL - // This matches Groq's documented OpenAI-compatible API approach +func TestGenerateCommitMessageErrors(t *testing.T) { + tests := []struct { + name string + status int + body string + wantErr string + }{ + {"api error", http.StatusBadRequest, `{"error":{"message":"bad request"}}`, "400"}, + {"no choices", http.StatusOK, completion(`[]`), "no response choices"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + isolate(t) + t.Setenv(envVar, "test-key") + serve(t, tt.status, tt.body) + + _, err := (&client{}).GenerateCommitMessage(context.Background(), "the diff", "") + if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("err = %v, want it to contain %q", err, tt.wantErr) + } + }) + } } diff --git a/internal/llm/kimi/client.go b/internal/llm/kimi/client.go index 2dd7610..2a7b7a5 100644 --- a/internal/llm/kimi/client.go +++ b/internal/llm/kimi/client.go @@ -13,6 +13,9 @@ import ( "github.com/rshdhere/vibecheck/internal/llm" ) +// apiURL is the chat completions endpoint; tests point it at a local server. +var apiURL = "https://api.moonshot.cn/v1/chat/completions" + type client struct{} func init() { @@ -82,7 +85,7 @@ The git diff is in the second next message.` return "", fmt.Errorf("marshal request: %w", err) } - req, err := http.NewRequestWithContext(ctx, "POST", "https://api.moonshot.cn/v1/chat/completions", bytes.NewBuffer(jsonData)) + req, err := http.NewRequestWithContext(ctx, "POST", apiURL, bytes.NewBuffer(jsonData)) if err != nil { return "", fmt.Errorf("create request: %w", err) } diff --git a/internal/llm/kimi/client_test.go b/internal/llm/kimi/client_test.go index e452fe8..b059494 100644 --- a/internal/llm/kimi/client_test.go +++ b/internal/llm/kimi/client_test.go @@ -2,62 +2,143 @@ package kimi import ( "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" "testing" ) -// TestClientRegistration verifies the client is registered correctly -func TestClientRegistration(t *testing.T) { - var _ interface { - GenerateCommitMessage(ctx context.Context, diff string, additionalContext string) (string, error) - } = &client{} +const ( + envVar = "MOONSHOT_API_KEY" + wantModel = "moonshot-v1-auto" +) + +// isolate keeps the developer's real keys file and environment out of the test. +func isolate(t *testing.T) { + t.Helper() + t.Setenv("HOME", t.TempDir()) + t.Setenv(envVar, "") } -// TestAPIKeyValidation verifies API key validation -func TestAPIKeyValidation(t *testing.T) { - c := &client{} - ctx := context.Background() +// serve points apiURL at a local server for the duration of the test. +func serve(t *testing.T, h http.HandlerFunc) { + t.Helper() + srv := httptest.NewServer(h) + t.Cleanup(srv.Close) + setAPIURL(t, srv.URL) +} - _, err := c.GenerateCommitMessage(ctx, "test diff", "") - if err == nil { - t.Error("GenerateCommitMessage() should return error when API key is missing") - } - if err != nil && err.Error() != "MOONSHOT_API_KEY environment variable not set" { - t.Errorf("GenerateCommitMessage() error message = %q, want 'MOONSHOT_API_KEY environment variable not set'", err.Error()) - } +func setAPIURL(t *testing.T, url string) { + t.Helper() + old := apiURL + apiURL = url + t.Cleanup(func() { apiURL = old }) } -// TestEndpointURL verifies the endpoint URL matches Moonshot Kimi API documentation -// According to Moonshot docs: https://api.moonshot.cn/v1/chat/completions -func TestEndpointURL(t *testing.T) { - expectedURL := "https://api.moonshot.cn/v1/chat/completions" - if expectedURL != "https://api.moonshot.cn/v1/chat/completions" { - t.Errorf("Endpoint URL should be https://api.moonshot.cn/v1/chat/completions, got %s", expectedURL) +func TestGenerateCommitMessageMissingKey(t *testing.T) { + isolate(t) + + _, err := (&client{}).GenerateCommitMessage(context.Background(), "diff", "") + if err == nil || err.Error() != envVar+" environment variable not set" { + t.Fatalf("err = %v, want missing %s error", err, envVar) } } -// TestModelSelection verifies the correct model is used -// According to Moonshot docs: moonshot-v1-auto is available -func TestModelSelection(t *testing.T) { - expectedModel := "moonshot-v1-auto" - if expectedModel != "moonshot-v1-auto" { - t.Errorf("Model should be moonshot-v1-auto, got %s", expectedModel) +func TestGenerateCommitMessageSuccess(t *testing.T) { + isolate(t) + t.Setenv(envVar, "test-key") + + serve(t, func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + t.Errorf("method = %s, want POST", r.Method) + } + if got := r.Header.Get("Authorization"); got != "Bearer test-key" { + t.Errorf("Authorization = %q, want Bearer test-key", got) + } + if got := r.Header.Get("Content-Type"); got != "application/json" { + t.Errorf("Content-Type = %q, want application/json", got) + } + var req chatRequest + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + t.Fatalf("decode request: %v", err) + } + if req.Model != wantModel { + t.Errorf("model = %q, want %q", req.Model, wantModel) + } + if len(req.Messages) != 3 || req.Messages[0].Role != "system" { + t.Fatalf("messages = %+v, want system + 2 user messages", req.Messages) + } + if !strings.Contains(req.Messages[1].Content, "extra context") { + t.Errorf("context message = %q, want it to include the user context", req.Messages[1].Content) + } + if req.Messages[2].Content != "the diff" { + t.Errorf("diff message = %q, want %q", req.Messages[2].Content, "the diff") + } + w.Write([]byte(`{"choices":[{"message":{"role":"assistant","content":"feat: add thing"}}]}`)) + }) + + got, err := (&client{}).GenerateCommitMessage(context.Background(), "the diff", "extra context") + if err != nil { + t.Fatalf("GenerateCommitMessage() error = %v", err) + } + if got != "feat: add thing" { + t.Errorf("GenerateCommitMessage() = %q, want %q", got, "feat: add thing") } } -// TestRequestStructure verifies request structure matches Moonshot API spec -// According to Moonshot docs: OpenAI-compatible format with model and messages -func TestRequestStructure(t *testing.T) { - // Verify the implementation uses: - // 1. Model: "moonshot-v1-auto" - // 2. Messages array with role and content - // 3. System message with role "system" - // 4. User messages with role "user" +func TestGenerateCommitMessageResponseErrors(t *testing.T) { + tests := []struct { + name string + status int + body string + wantErr string + }{ + {"non-200 status", http.StatusUnauthorized, "bad key", "status 401: bad key"}, + {"invalid json", http.StatusOK, "not json", "decode response"}, + {"no choices", http.StatusOK, `{"choices":[]}`, "no response choices"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + isolate(t) + t.Setenv(envVar, "test-key") + serve(t, func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(tt.status) + w.Write([]byte(tt.body)) + }) + + _, err := (&client{}).GenerateCommitMessage(context.Background(), "diff", "") + if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("err = %v, want it to contain %q", err, tt.wantErr) + } + }) + } } -// TestHeaders verifies HTTP headers match Moonshot API documentation -// According to Moonshot docs: Authorization: Bearer , Content-Type: application/json -func TestHeaders(t *testing.T) { - // Verify headers are set correctly: - // - Content-Type: application/json - // - Authorization: Bearer +func TestGenerateCommitMessageRequestErrors(t *testing.T) { + closed := httptest.NewServer(http.NotFoundHandler()) + closed.Close() + + tests := []struct { + name string + url string + wantErr string + }{ + {"invalid url", "://bad-url", "create request"}, + {"unreachable server", closed.URL, "send request"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + isolate(t) + t.Setenv(envVar, "test-key") + setAPIURL(t, tt.url) + + _, err := (&client{}).GenerateCommitMessage(context.Background(), "diff", "") + if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("err = %v, want it to contain %q", err, tt.wantErr) + } + }) + } } diff --git a/internal/llm/ollama/client_test.go b/internal/llm/ollama/client_test.go index 114e4d1..3ab1453 100644 --- a/internal/llm/ollama/client_test.go +++ b/internal/llm/ollama/client_test.go @@ -2,66 +2,109 @@ package ollama import ( "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" "testing" ) -// TestClientRegistration verifies the client is registered correctly -func TestClientRegistration(t *testing.T) { - var _ interface { - GenerateCommitMessage(ctx context.Context, diff string, additionalContext string) (string, error) - } = &client{} +// isolate keeps the developer's real keys file and environment out of the test. +func isolate(t *testing.T) { + t.Helper() + t.Setenv("HOME", t.TempDir()) + t.Setenv("OLLAMA_HOST", "") } -// TestDefaultHost verifies default host matches Ollama documentation -// According to Ollama docs: Default host is http://localhost:11434 -func TestDefaultHost(t *testing.T) { - expectedDefault := "http://localhost:11434" - if expectedDefault != "http://localhost:11434" { - t.Errorf("Default host should be http://localhost:11434, got %s", expectedDefault) - } +// serve starts a local Ollama stand-in and points OLLAMA_HOST at it. +func serve(t *testing.T, h http.HandlerFunc) { + t.Helper() + srv := httptest.NewServer(h) + t.Cleanup(srv.Close) + t.Setenv("OLLAMA_HOST", srv.URL) } -// TestEndpointURL verifies the endpoint URL matches Ollama API documentation -// According to Ollama docs: POST /api/generate -func TestEndpointURL(t *testing.T) { - expectedPath := "/api/generate" - if expectedPath != "/api/generate" { - t.Errorf("Endpoint path should be /api/generate, got %s", expectedPath) +func TestGenerateCommitMessageSuccess(t *testing.T) { + isolate(t) + serve(t, func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost || r.URL.Path != "/api/generate" { + t.Errorf("request = %s %s, want POST /api/generate", r.Method, r.URL.Path) + } + var req generateRequestBody + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + t.Fatalf("decode request: %v", err) + } + if req.Model != GitCommitMessage { + t.Errorf("model = %q, want %q", req.Model, GitCommitMessage) + } + if req.Stream { + t.Error("stream = true, want false") + } + if !strings.Contains(req.Prompt, "extra context") || !strings.Contains(req.Prompt, "the diff") { + t.Errorf("prompt does not include the context and the diff: %q", req.Prompt) + } + w.Write([]byte(`{"response":"feat: add thing"}`)) + }) + + got, err := (&client{}).GenerateCommitMessage(context.Background(), "the diff", "extra context") + if err != nil { + t.Fatalf("GenerateCommitMessage() error = %v", err) + } + if got != "feat: add thing" { + t.Errorf("GenerateCommitMessage() = %q, want %q", got, "feat: add thing") } } -// TestModelSelection verifies the correct model is used -// According to Ollama docs: gpt-oss:20b is a valid model -func TestModelSelection(t *testing.T) { - expectedModel := GitCommitMessage - if expectedModel != "gpt-oss:20b" { - t.Errorf("Model should be gpt-oss:20b, got %s", expectedModel) +func TestGenerateCommitMessageResponseErrors(t *testing.T) { + tests := []struct { + name string + status int + body string + wantErr string + }{ + {"non-200 status", http.StatusNotFound, `{"error":"model 'gpt-oss:20b' not found"}`, "status 404"}, + {"invalid json", http.StatusOK, "not json", "decode"}, + {"empty response", http.StatusOK, `{"response":""}`, "empty response"}, } -} -// TestRequestStructure verifies request structure matches Ollama API spec -// According to Ollama docs: POST /api/generate with model, prompt, stream, raw -func TestRequestStructure(t *testing.T) { - // Verify the implementation uses: - // 1. Model: "gpt-oss:20b" - // 2. Prompt: string containing system prompt + user context + diff - // 3. Stream: false (as per code) - // 4. Raw: false (as per code) - // This matches Ollama's documented /api/generate endpoint format -} + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + isolate(t) + serve(t, func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(tt.status) + w.Write([]byte(tt.body)) + }) -// TestResponseStructure verifies response parsing matches Ollama API spec -// According to Ollama docs: Response has "response" field with generated text -func TestResponseStructure(t *testing.T) { - // Verify the implementation correctly accesses: - // - resBody.Response - // - Checks for empty Response - // The code matches Ollama's documented response format + _, err := (&client{}).GenerateCommitMessage(context.Background(), "diff", "") + if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("err = %v, want it to contain %q", err, tt.wantErr) + } + }) + } } -// TestErrorHandling verifies error handling for missing model -// According to Ollama docs: Empty response indicates model not available -func TestErrorHandling(t *testing.T) { - // Verify the implementation checks for empty response and returns - // appropriate error message about model availability +func TestGenerateCommitMessageRequestErrors(t *testing.T) { + closed := httptest.NewServer(http.NotFoundHandler()) + closed.Close() + + tests := []struct { + name string + host string + wantErr string + }{ + {"invalid host", "://bad-host", "new req"}, + {"unreachable host", closed.URL, "http do"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + isolate(t) + t.Setenv("OLLAMA_HOST", tt.host) + + _, err := (&client{}).GenerateCommitMessage(context.Background(), "diff", "") + if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("err = %v, want it to contain %q", err, tt.wantErr) + } + }) + } } diff --git a/internal/llm/openai/client_test.go b/internal/llm/openai/client_test.go index 49ce941..916d73f 100644 --- a/internal/llm/openai/client_test.go +++ b/internal/llm/openai/client_test.go @@ -2,90 +2,113 @@ package openai import ( "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" "testing" ) -// TestClientRegistration verifies the client is registered correctly -func TestClientRegistration(t *testing.T) { - // Verify client implements the Provider interface - var _ interface { - GenerateCommitMessage(ctx context.Context, diff string, additionalContext string) (string, error) - } = &client{} +const ( + envVar = "OPENAI_API_KEY" + wantModel = "gpt-4o-mini" +) + +// isolate keeps the developer's real keys file and environment out of the test. +func isolate(t *testing.T) { + t.Helper() + t.Setenv("HOME", t.TempDir()) + t.Setenv(envVar, "") } -// TestAPIKeyValidation verifies API key validation follows OpenAI documentation -// According to OpenAI docs: API key should be checked before making requests -func TestAPIKeyValidation(t *testing.T) { - c := &client{} - ctx := context.Background() +// point directs the SDK at url for the duration of the test. +func point(t *testing.T, url string) { + t.Helper() + t.Setenv("OPENAI_BASE_URL", url) +} - // Test that missing API key returns proper error message - // OpenAI docs specify: "OPENAI_API_KEY environment variable not set" - // Note: This test verifies the error message format matches OpenAI's documentation - // The actual API call may fail at different stages, but the key check happens first - _, err := c.GenerateCommitMessage(ctx, "test diff", "") - if err != nil { - // Verify error message mentions OPENAI_API_KEY (may be from key check or API call) - if !contains(err.Error(), "OPENAI_API_KEY") && !contains(err.Error(), "open-ai") { - t.Logf("Error message: %q (may be from API call, which is valid)", err.Error()) +// serve starts an OpenAI-compatible stand-in that replies with status and body. +func serve(t *testing.T, status int, body string) { + t.Helper() + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost || !strings.HasSuffix(r.URL.Path, "/chat/completions") { + t.Errorf("request = %s %s, want POST .../chat/completions", r.Method, r.URL.Path) } - } else { - // If no error, API key may be set in test environment - t.Log("No error - API key may be set in test environment") - } + if got := r.Header.Get("Authorization"); got != "Bearer test-key" { + t.Errorf("Authorization = %q, want Bearer test-key", got) + } + var req struct { + Model string `json:"model"` + Messages []struct { + Role string `json:"role"` + Content string `json:"content"` + } `json:"messages"` + } + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + t.Fatalf("decode request: %v", err) + } + if req.Model != wantModel { + t.Errorf("model = %q, want %q", req.Model, wantModel) + } + if len(req.Messages) != 3 || req.Messages[0].Role != "system" || req.Messages[2].Content != "the diff" { + t.Errorf("messages = %+v, want system + context + diff", req.Messages) + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(status) + w.Write([]byte(body)) + })) + t.Cleanup(srv.Close) + point(t, srv.URL) } -func contains(s, substr string) bool { - return len(s) >= len(substr) && - (s == substr || - (len(s) > len(substr) && - (s[:len(substr)] == substr || - s[len(s)-len(substr):] == substr || - containsHelper(s, substr)))) +func completion(choices string) string { + return `{"id":"c1","object":"chat.completion","created":0,"model":"` + wantModel + `","choices":` + choices + `}` } -func containsHelper(s, substr string) bool { - for i := 0; i <= len(s)-len(substr); i++ { - if s[i:i+len(substr)] == substr { - return true - } +func TestGenerateCommitMessageMissingKey(t *testing.T) { + isolate(t) + + _, err := (&client{}).GenerateCommitMessage(context.Background(), "the diff", "") + if err == nil || err.Error() != envVar+" environment variable not set" { + t.Fatalf("err = %v, want missing %s error", err, envVar) } - return false } -// TestModelSelection verifies the correct model is used -// According to OpenAI docs: gpt-4o-mini should be used (ChatModelGPT4oMini) -func TestModelSelection(t *testing.T) { - // Verify the model constant is used correctly in the implementation - // The code uses: openaisdk.ChatModelGPT4oMini - // This matches OpenAI's documented model identifier - expectedModel := "gpt-4o-mini" - if expectedModel != "gpt-4o-mini" { - t.Errorf("Model should be gpt-4o-mini, got %s", expectedModel) +func TestGenerateCommitMessageSuccess(t *testing.T) { + isolate(t) + t.Setenv(envVar, "test-key") + serve(t, http.StatusOK, completion(`[{"index":0,"finish_reason":"stop","message":{"role":"assistant","content":"feat: add thing"}}]`)) + + got, err := (&client{}).GenerateCommitMessage(context.Background(), "the diff", "ctx") + if err != nil { + t.Fatalf("GenerateCommitMessage() error = %v", err) + } + if got != "feat: add thing" { + t.Errorf("GenerateCommitMessage() = %q, want %q", got, "feat: add thing") } } -// TestRequestStructure verifies request structure matches OpenAI API spec -// According to OpenAI docs: POST /v1/chat/completions with messages array -func TestRequestStructure(t *testing.T) { - // Verify the implementation uses: - // 1. Messages array with SystemMessage and UserMessage - // 2. Model parameter - // 3. Correct message structure (role + content) - - // The code structure matches OpenAI's documented format: - // - SystemMessage for system prompt - // - UserMessage for user content - // - Model: ChatModelGPT4oMini +func TestGenerateCommitMessageErrors(t *testing.T) { + tests := []struct { + name string + status int + body string + wantErr string + }{ + {"api error", http.StatusBadRequest, `{"error":{"message":"bad request"}}`, "400"}, + {"no choices", http.StatusOK, completion(`[]`), "no response choices"}, + } - // This test verifies the structure is correct without making API calls - // The actual implementation in client.go follows OpenAI's documented structure -} + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + isolate(t) + t.Setenv(envVar, "test-key") + serve(t, tt.status, tt.body) -// TestErrorHandling verifies error handling follows OpenAI documentation -// According to OpenAI docs: errors should be wrapped with context -func TestErrorHandling(t *testing.T) { - // Verify error messages follow OpenAI's error format - // The code uses: fmt.Sprintf("error while prompting to open-ai at: %v", err) - // This provides context as recommended in OpenAI docs + _, err := (&client{}).GenerateCommitMessage(context.Background(), "the diff", "") + if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("err = %v, want it to contain %q", err, tt.wantErr) + } + }) + } } diff --git a/internal/llm/perplexity/client.go b/internal/llm/perplexity/client.go index 0b6f00d..39f9fc8 100644 --- a/internal/llm/perplexity/client.go +++ b/internal/llm/perplexity/client.go @@ -13,6 +13,9 @@ import ( "github.com/rshdhere/vibecheck/internal/llm" ) +// apiURL is the chat completions endpoint; tests point it at a local server. +var apiURL = "https://api.perplexity.ai/chat/completions" + type client struct{} func init() { @@ -91,7 +94,7 @@ The git diff is in the second next message.` return "", fmt.Errorf("marshal request: %w", err) } - req, err := http.NewRequestWithContext(ctx, http.MethodPost, "https://api.perplexity.ai/chat/completions", bytes.NewBuffer(jsonData)) + req, err := http.NewRequestWithContext(ctx, http.MethodPost, apiURL, bytes.NewBuffer(jsonData)) if err != nil { return "", fmt.Errorf("create request: %w", err) } diff --git a/internal/llm/perplexity/client_test.go b/internal/llm/perplexity/client_test.go index d0206a6..7bc4385 100644 --- a/internal/llm/perplexity/client_test.go +++ b/internal/llm/perplexity/client_test.go @@ -2,86 +2,146 @@ package perplexity import ( "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" "testing" ) -// TestClientRegistration verifies the client is registered correctly -func TestClientRegistration(t *testing.T) { - var _ interface { - GenerateCommitMessage(ctx context.Context, diff string, additionalContext string) (string, error) - } = &client{} +const ( + envVar = "PERPLEXITY_API_KEY" + wantModel = "sonar" +) + +// isolate keeps the developer's real keys file and environment out of the test. +func isolate(t *testing.T) { + t.Helper() + t.Setenv("HOME", t.TempDir()) + t.Setenv(envVar, "") } -// TestAPIKeyValidation verifies API key validation -// According to Perplexity docs: API key should be checked before making requests -func TestAPIKeyValidation(t *testing.T) { - c := &client{} - ctx := context.Background() +// serve points apiURL at a local server for the duration of the test. +func serve(t *testing.T, h http.HandlerFunc) { + t.Helper() + srv := httptest.NewServer(h) + t.Cleanup(srv.Close) + setAPIURL(t, srv.URL) +} - // Test that missing API key returns proper error message - // The actual API call may fail at different stages, but the key check happens first - _, err := c.GenerateCommitMessage(ctx, "test diff", "") - if err != nil { - // Verify error message mentions PERPLEXITY_API_KEY (may be from key check or API call) - if !contains(err.Error(), "PERPLEXITY_API_KEY") && !contains(err.Error(), "perplexity") { - t.Logf("Error message: %q (may be from API call, which is valid)", err.Error()) - } - } else { - // If no error, API key may be set in test environment - t.Log("No error - API key may be set in test environment") - } +func setAPIURL(t *testing.T, url string) { + t.Helper() + old := apiURL + apiURL = url + t.Cleanup(func() { apiURL = old }) } -func contains(s, substr string) bool { - return len(s) >= len(substr) && - (s == substr || - (len(s) > len(substr) && - (s[:len(substr)] == substr || - s[len(s)-len(substr):] == substr || - containsHelper(s, substr)))) +func TestGenerateCommitMessageMissingKey(t *testing.T) { + isolate(t) + + _, err := (&client{}).GenerateCommitMessage(context.Background(), "diff", "") + if err == nil || err.Error() != envVar+" environment variable not set" { + t.Fatalf("err = %v, want missing %s error", err, envVar) + } } -func containsHelper(s, substr string) bool { - for i := 0; i <= len(s)-len(substr); i++ { - if s[i:i+len(substr)] == substr { - return true +func TestGenerateCommitMessageSuccess(t *testing.T) { + isolate(t) + t.Setenv(envVar, "test-key") + + serve(t, func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + t.Errorf("method = %s, want POST", r.Method) + } + if got := r.Header.Get("Authorization"); got != "Bearer test-key" { + t.Errorf("Authorization = %q, want Bearer test-key", got) + } + if got := r.Header.Get("Content-Type"); got != "application/json" { + t.Errorf("Content-Type = %q, want application/json", got) + } + var req chatRequest + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + t.Fatalf("decode request: %v", err) + } + if req.Model != wantModel { + t.Errorf("model = %q, want %q", req.Model, wantModel) + } + if got := r.Header.Get("Accept"); got != "application/json" { + t.Errorf("Accept = %q, want application/json", got) } + if len(req.Messages) != 2 || req.Messages[0].Role != "system" || req.Messages[1].Role != "user" { + t.Fatalf("messages = %+v, want system + user message", req.Messages) + } + if user := req.Messages[1].Content; !strings.Contains(user, "extra context") || !strings.Contains(user, "the diff") { + t.Errorf("user message = %q, want it to include the context and the diff", user) + } + if req.MaxTokens != 512 { + t.Errorf("max_tokens = %d, want 512", req.MaxTokens) + } + w.Write([]byte(`{"choices":[{"message":{"role":"assistant","content":"feat: add thing"}}]}`)) + }) + + got, err := (&client{}).GenerateCommitMessage(context.Background(), "the diff", "extra context") + if err != nil { + t.Fatalf("GenerateCommitMessage() error = %v", err) + } + if got != "feat: add thing" { + t.Errorf("GenerateCommitMessage() = %q, want %q", got, "feat: add thing") } - return false } -// TestEndpointURL verifies the endpoint URL matches Perplexity API documentation -// According to Perplexity docs: https://api.perplexity.ai/chat/completions -func TestEndpointURL(t *testing.T) { - expectedURL := "https://api.perplexity.ai/chat/completions" - if expectedURL != "https://api.perplexity.ai/chat/completions" { - t.Errorf("Endpoint URL should be https://api.perplexity.ai/chat/completions, got %s", expectedURL) +func TestGenerateCommitMessageResponseErrors(t *testing.T) { + tests := []struct { + name string + status int + body string + wantErr string + }{ + {"non-200 status", http.StatusUnauthorized, "bad key", "status 401: bad key"}, + {"invalid json", http.StatusOK, "not json", "decode response"}, + {"no choices", http.StatusOK, `{"choices":[]}`, "no response choices"}, } -} -// TestModelSelection verifies the correct model is used -// According to Perplexity docs: sonar is the model name -func TestModelSelection(t *testing.T) { - expectedModel := "sonar" - if expectedModel != "sonar" { - t.Errorf("Model should be sonar, got %s", expectedModel) + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + isolate(t) + t.Setenv(envVar, "test-key") + serve(t, func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(tt.status) + w.Write([]byte(tt.body)) + }) + + _, err := (&client{}).GenerateCommitMessage(context.Background(), "diff", "") + if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("err = %v, want it to contain %q", err, tt.wantErr) + } + }) } } -// TestRequestParameters verifies request parameters match Perplexity API documentation -// According to Perplexity docs: MaxTokens and Temperature are supported -func TestRequestParameters(t *testing.T) { - // Verify the implementation sets: - // - MaxTokens: 512 (as per code) - // - Temperature: 0.2 (as per code) - // These parameters match Perplexity's documented API -} +func TestGenerateCommitMessageRequestErrors(t *testing.T) { + closed := httptest.NewServer(http.NotFoundHandler()) + closed.Close() + + tests := []struct { + name string + url string + wantErr string + }{ + {"invalid url", "://bad-url", "create request"}, + {"unreachable server", closed.URL, "send request"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + isolate(t) + t.Setenv(envVar, "test-key") + setAPIURL(t, tt.url) -// TestHeaders verifies HTTP headers match Perplexity API documentation -// According to Perplexity docs: Authorization, Content-Type, and Accept headers required -func TestHeaders(t *testing.T) { - // Verify headers are set correctly: - // - Content-Type: application/json - // - Accept: application/json - // - Authorization: Bearer + _, err := (&client{}).GenerateCommitMessage(context.Background(), "diff", "") + if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("err = %v, want it to contain %q", err, tt.wantErr) + } + }) + } } diff --git a/internal/llm/qwen/client.go b/internal/llm/qwen/client.go index 729568f..bea00e2 100644 --- a/internal/llm/qwen/client.go +++ b/internal/llm/qwen/client.go @@ -13,6 +13,9 @@ import ( "github.com/rshdhere/vibecheck/internal/llm" ) +// apiURL is the chat completions endpoint; tests point it at a local server. +var apiURL = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions" + type client struct{} func init() { @@ -87,7 +90,7 @@ The git diff is in the second next message.` return "", fmt.Errorf("marshal request: %w", err) } - req, err := http.NewRequestWithContext(ctx, "POST", "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions", bytes.NewBuffer(jsonData)) + req, err := http.NewRequestWithContext(ctx, "POST", apiURL, bytes.NewBuffer(jsonData)) if err != nil { return "", fmt.Errorf("create request: %w", err) } diff --git a/internal/llm/qwen/client_test.go b/internal/llm/qwen/client_test.go index 9d55048..c9bbea8 100644 --- a/internal/llm/qwen/client_test.go +++ b/internal/llm/qwen/client_test.go @@ -2,53 +2,159 @@ package qwen import ( "context" + "encoding/json" + "net/http" + "net/http/httptest" + "strings" "testing" ) -// TestClientRegistration verifies the client is registered correctly -func TestClientRegistration(t *testing.T) { - var _ interface { - GenerateCommitMessage(ctx context.Context, diff string, additionalContext string) (string, error) - } = &client{} +const ( + envVar = "QWEN_API_KEY" + wantModel = "qwen-turbo" +) + +// isolate keeps the developer's real keys file and environment out of the test. +func isolate(t *testing.T) { + t.Helper() + t.Setenv("HOME", t.TempDir()) + t.Setenv(envVar, "") +} + +// serve points apiURL at a local server for the duration of the test. +func serve(t *testing.T, h http.HandlerFunc) { + t.Helper() + srv := httptest.NewServer(h) + t.Cleanup(srv.Close) + setAPIURL(t, srv.URL) +} + +func setAPIURL(t *testing.T, url string) { + t.Helper() + old := apiURL + apiURL = url + t.Cleanup(func() { apiURL = old }) } -// TestAPIKeyValidation verifies API key validation -func TestAPIKeyValidation(t *testing.T) { - c := &client{} - ctx := context.Background() +func TestGenerateCommitMessageMissingKey(t *testing.T) { + isolate(t) + + _, err := (&client{}).GenerateCommitMessage(context.Background(), "diff", "") + if err == nil || err.Error() != envVar+" environment variable not set" { + t.Fatalf("err = %v, want missing %s error", err, envVar) + } +} + +func TestGenerateCommitMessageSuccess(t *testing.T) { + isolate(t) + t.Setenv(envVar, "test-key") + + serve(t, func(w http.ResponseWriter, r *http.Request) { + if r.Method != http.MethodPost { + t.Errorf("method = %s, want POST", r.Method) + } + if got := r.Header.Get("Authorization"); got != "Bearer test-key" { + t.Errorf("Authorization = %q, want Bearer test-key", got) + } + if got := r.Header.Get("Content-Type"); got != "application/json" { + t.Errorf("Content-Type = %q, want application/json", got) + } + var req chatRequest + if err := json.NewDecoder(r.Body).Decode(&req); err != nil { + t.Fatalf("decode request: %v", err) + } + if req.Model != wantModel { + t.Errorf("model = %q, want %q", req.Model, wantModel) + } + if len(req.Messages) != 3 || req.Messages[0].Role != "system" { + t.Fatalf("messages = %+v, want system + 2 user messages", req.Messages) + } + if !strings.Contains(req.Messages[1].Content, "extra context") { + t.Errorf("context message = %q, want it to include the user context", req.Messages[1].Content) + } + if req.Messages[2].Content != "the diff" { + t.Errorf("diff message = %q, want %q", req.Messages[2].Content, "the diff") + } + w.Write([]byte(`{"choices":[{"message":{"role":"assistant","content":"feat: add thing"}}]}`)) + }) - _, err := c.GenerateCommitMessage(ctx, "test diff", "") - if err == nil { - t.Error("GenerateCommitMessage() should return error when API key is missing") + got, err := (&client{}).GenerateCommitMessage(context.Background(), "the diff", "extra context") + if err != nil { + t.Fatalf("GenerateCommitMessage() error = %v", err) } - if err != nil && err.Error() != "QWEN_API_KEY environment variable not set" { - t.Errorf("GenerateCommitMessage() error message = %q, want 'QWEN_API_KEY environment variable not set'", err.Error()) + if got != "feat: add thing" { + t.Errorf("GenerateCommitMessage() = %q, want %q", got, "feat: add thing") } } -// TestEndpointURL verifies the endpoint URL matches Alibaba Qwen API documentation -// According to Qwen docs: https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions -func TestEndpointURL(t *testing.T) { - expectedURL := "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions" - if expectedURL != "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions" { - t.Errorf("Endpoint URL should be https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions, got %s", expectedURL) +func TestGenerateCommitMessageDashScopeOutputFormat(t *testing.T) { + isolate(t) + t.Setenv(envVar, "test-key") + serve(t, func(w http.ResponseWriter, r *http.Request) { + w.Write([]byte(`{"output":{"choices":[{"message":{"role":"assistant","content":"fix: handle nil"}}]}}`)) + }) + + got, err := (&client{}).GenerateCommitMessage(context.Background(), "diff", "") + if err != nil { + t.Fatalf("GenerateCommitMessage() error = %v", err) + } + if got != "fix: handle nil" { + t.Errorf("GenerateCommitMessage() = %q, want %q", got, "fix: handle nil") } } -// TestModelSelection verifies the correct model is used -// According to Qwen docs: qwen-turbo is available -func TestModelSelection(t *testing.T) { - expectedModel := "qwen-turbo" - if expectedModel != "qwen-turbo" { - t.Errorf("Model should be qwen-turbo, got %s", expectedModel) +func TestGenerateCommitMessageResponseErrors(t *testing.T) { + tests := []struct { + name string + status int + body string + wantErr string + }{ + {"non-200 status", http.StatusUnauthorized, "bad key", "status 401: bad key"}, + {"invalid json", http.StatusOK, "not json", "decode response"}, + {"no choices", http.StatusOK, `{"choices":[]}`, "no response choices"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + isolate(t) + t.Setenv(envVar, "test-key") + serve(t, func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(tt.status) + w.Write([]byte(tt.body)) + }) + + _, err := (&client{}).GenerateCommitMessage(context.Background(), "diff", "") + if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("err = %v, want it to contain %q", err, tt.wantErr) + } + }) } } -// TestResponseStructure verifies response parsing handles Qwen's dual format -// According to Qwen docs: Response may be in Choices or Output.Choices -func TestResponseStructure(t *testing.T) { - // Verify the implementation checks both: - // - chatResp.Choices[0].Message.Content - // - chatResp.Output.Choices[0].Message.Content - // This matches Qwen's documented response format flexibility +func TestGenerateCommitMessageRequestErrors(t *testing.T) { + closed := httptest.NewServer(http.NotFoundHandler()) + closed.Close() + + tests := []struct { + name string + url string + wantErr string + }{ + {"invalid url", "://bad-url", "create request"}, + {"unreachable server", closed.URL, "send request"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + isolate(t) + t.Setenv(envVar, "test-key") + setAPIURL(t, tt.url) + + _, err := (&client{}).GenerateCommitMessage(context.Background(), "diff", "") + if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("err = %v, want it to contain %q", err, tt.wantErr) + } + }) + } } From 5585f05aef3ec62f2e1740e119547185d15a989f Mon Sep 17 00:00:00 2001 From: raashed Date: Wed, 7 Oct 2026 23:04:42 +0530 Subject: [PATCH 3/4] test(cmd): cover commit, keys, models, dashboard and upgrade commands - Add teaOptions to root.go and pass it to every bubbletea program so tests can script input and capture output - Make githubAPIURL and executablePath vars in upgrade.go to substitute a local server and scratch binary - Run commit end to end in a temp git repo with fake providers, covering success, notices and error paths - Test keys, models and dashboard models directly plus via RunE with scripted keystrokes - Test release fetch, download, tar.gz and zip extraction, binary replacement and the full upgrade flow - Replace the skipped CommitWMessage test with real ones using GIT_EDITOR to avoid an interactive editor --- cmd/commit_test.go | 134 +++++++++++ cmd/dashboard.go | 2 +- cmd/dashboard_test.go | 114 +++++++++ cmd/helpers_test.go | 58 +++++ cmd/keys.go | 2 +- cmd/keys_test.go | 241 +++++++++++++++++++ cmd/models.go | 2 +- cmd/models_test.go | 122 ++++++++++ cmd/root.go | 4 + cmd/upgrade.go | 11 +- cmd/upgrade_test.go | 448 ++++++++++++++++++++++++++++++++++++ internal/git/commit_test.go | 45 +++- 12 files changed, 1172 insertions(+), 11 deletions(-) create mode 100644 cmd/dashboard_test.go create mode 100644 cmd/helpers_test.go create mode 100644 cmd/keys_test.go create mode 100644 cmd/models_test.go diff --git a/cmd/commit_test.go b/cmd/commit_test.go index 3428be6..713b071 100644 --- a/cmd/commit_test.go +++ b/cmd/commit_test.go @@ -1,7 +1,16 @@ package cmd import ( + "context" + "errors" + "os" + "os/exec" + "path/filepath" + "strings" "testing" + + "github.com/rshdhere/vibecheck/internal/llm" + "github.com/rshdhere/vibecheck/internal/stats" ) func TestDetectMissingEnvVar(t *testing.T) { @@ -105,3 +114,128 @@ type testError struct { func (e *testError) Error() string { return e.msg } + +// fakeProvider returns a canned message or error. +type fakeProvider struct { + msg string + err error +} + +func (f fakeProvider) GenerateCommitMessage(context.Context, string, string) (string, error) { + return f.msg, f.err +} + +func init() { + llm.Register("test-ok", fakeProvider{msg: "feat(cmd): add thing\n\n- detail"}) + llm.Register("test-missing-key", fakeProvider{err: errors.New("FAKE_API_KEY environment variable not set")}) + llm.Register("test-missing-model", fakeProvider{err: errors.New("model 'fake-model' not found")}) + llm.Register("test-fail", fakeProvider{err: errors.New("boom")}) +} + +// setupRepo creates a git repo with one staged file and makes it the working directory. +func setupRepo(t *testing.T, stage bool) string { + t.Helper() + isolateHome(t) + dir := t.TempDir() + t.Chdir(dir) + t.Setenv("GIT_EDITOR", "true") + runGit(t, "init", "-q") + runGit(t, "config", "user.email", "test@example.com") + runGit(t, "config", "user.name", "Test User") + runGit(t, "config", "commit.gpgsign", "false") + if stage { + if err := os.WriteFile(filepath.Join(dir, "file.txt"), []byte("hello\n"), 0644); err != nil { + t.Fatal(err) + } + runGit(t, "add", "file.txt") + } + return dir +} + +func runGit(t *testing.T, args ...string) string { + t.Helper() + out, err := exec.Command("git", args...).CombinedOutput() + if err != nil { + t.Fatalf("git %v: %v\n%s", args, err, out) + } + return string(out) +} + +func headMessage(t *testing.T) string { + t.Helper() + out, err := exec.Command("git", "log", "-1", "--format=%B").CombinedOutput() + if err != nil { + return "" + } + return strings.TrimSpace(string(out)) +} + +func TestCommitCmdCommitsGeneratedMessage(t *testing.T) { + setupRepo(t, true) + + if err := execute(t, "commit", "--provider", "test-ok", "--prompt", "ctx"); err != nil { + t.Fatalf("commit error = %v", err) + } + + if got := headMessage(t); got != "feat(cmd): add thing\n\n- detail" { + t.Errorf("HEAD message = %q, want the generated message", got) + } + recent, err := stats.GetRecentCommits(1) + if err != nil || len(recent) != 1 { + t.Fatalf("recent commits = %v, %v; want one record", recent, err) + } + if recent[0].Model != "test-ok" || recent[0].CommitMsg != "feat(cmd): add thing" { + t.Errorf("recorded %+v, want model test-ok and the first message line", recent[0]) + } +} + +func TestCommitCmdHandledProviderErrors(t *testing.T) { + for _, provider := range []string{"test-missing-key", "test-missing-model"} { + t.Run(provider, func(t *testing.T) { + setupRepo(t, true) + + if err := execute(t, "commit", "--provider", provider, "--prompt", ""); err != nil { + t.Fatalf("commit error = %v, want nil after showing a notice", err) + } + if got := headMessage(t); got != "" { + t.Errorf("HEAD message = %q, want no commit", got) + } + }) + } +} + +func TestCommitCmdNothingStaged(t *testing.T) { + setupRepo(t, false) + + if err := execute(t, "commit", "--provider", "test-ok", "--prompt", ""); err != nil { + t.Fatalf("commit error = %v, want nil after the stage reminder", err) + } + if got := headMessage(t); got != "" { + t.Errorf("HEAD message = %q, want no commit", got) + } +} + +func TestCommitCmdErrors(t *testing.T) { + tests := []struct { + name string + provider string + setup func(t *testing.T) + wantErr string + }{ + {"not a git repo", "test-ok", func(t *testing.T) { isolateHome(t); t.Chdir(t.TempDir()) }, "staged changes"}, + {"unknown provider", "no-such-provider", func(t *testing.T) { setupRepo(t, true) }, llm.ErrNoProvider.Error()}, + {"provider failure", "test-fail", func(t *testing.T) { setupRepo(t, true) }, "generated commit message: boom"}, + {"git commit aborted", "test-ok", func(t *testing.T) { setupRepo(t, true); t.Setenv("GIT_EDITOR", "false") }, "commit with message"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + tt.setup(t) + + err := execute(t, "commit", "--provider", tt.provider, "--prompt", "") + if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("commit error = %v, want it to contain %q", err, tt.wantErr) + } + }) + } +} diff --git a/cmd/dashboard.go b/cmd/dashboard.go index e2518ba..2a0e93b 100644 --- a/cmd/dashboard.go +++ b/cmd/dashboard.go @@ -282,7 +282,7 @@ var dashboardCmd = &cobra.Command{ height: 24, } - p := tea.NewProgram(m, tea.WithAltScreen()) + p := tea.NewProgram(m, append([]tea.ProgramOption{tea.WithAltScreen()}, teaOptions...)...) if _, err := p.Run(); err != nil { return fmt.Errorf("error running dashboard: %w", err) } diff --git a/cmd/dashboard_test.go b/cmd/dashboard_test.go new file mode 100644 index 0000000..57ba944 --- /dev/null +++ b/cmd/dashboard_test.go @@ -0,0 +1,114 @@ +package cmd + +import ( + "strings" + "testing" + "time" + + tea "github.com/charmbracelet/bubbletea" + "github.com/rshdhere/vibecheck/internal/stats" +) + +func TestDashboardModelUpdate(t *testing.T) { + var m tea.Model = dashboardModel{} + + if m.(dashboardModel).Init() == nil { + t.Error("Init() should load stats and start the refresh tick") + } + + m, _ = m.Update(tea.WindowSizeMsg{Width: 100, Height: 40}) + if d := m.(dashboardModel); d.width != 100 || d.height != 40 { + t.Errorf("size = %dx%d, want 100x40", d.width, d.height) + } + + loaded := statsLoadedMsg{totalCommits: 3, mostUsedModel: "groq", avgLatency: 1.5, lastUsed: time.Now()} + m, _ = m.Update(loaded) + if d := m.(dashboardModel); d.totalCommits != 3 || d.mostUsedModel != "groq" || d.avgLatency != 1.5 { + t.Errorf("stats not applied: %+v", d) + } + + if _, cmd := m.Update(tickMsg{}); cmd == nil { + t.Error("tick should reload stats and schedule the next tick") + } + if _, cmd := m.Update(keyRunes("r")); cmd == nil { + t.Error("r should reload stats") + } + if _, cmd := m.Update(keyRunes("x")); cmd != nil { + t.Error("unbound keys should do nothing") + } + + m, cmd := m.Update(keyRunes("q")) + if !m.(dashboardModel).quitting || cmd == nil { + t.Error("q should quit") + } + if m.View() != "" { + t.Error("view should be empty after quitting") + } +} + +func TestDashboardModelView(t *testing.T) { + t.Run("empty", func(t *testing.T) { + view := dashboardModel{mostUsedModel: "N/A"}.View() + for _, want := range []string{"Vibecheck Dashboard", "Never", "None", "0.0s", "No commits yet"} { + if !strings.Contains(view, want) { + t.Errorf("view missing %q", want) + } + } + }) + + lastUsed := []struct { + ago time.Duration + want string + }{ + {10 * time.Second, "Just now"}, + {5 * time.Minute, "5m ago"}, + {3 * time.Hour, "3h ago"}, + {50 * time.Hour, "2d ago"}, + } + for _, tt := range lastUsed { + t.Run(tt.want, func(t *testing.T) { + m := dashboardModel{ + width: 120, + height: 40, + totalCommits: 2, + mostUsedModel: "openai", + avgLatency: 2.25, + lastUsed: time.Now().Add(-tt.ago), + recentCommits: []stats.CommitRecord{{Model: "openai", Latency: 2.25, CommitMsg: "feat: add dashboard"}}, + } + view := m.View() + for _, want := range []string{tt.want, "openai", "2.2s", "feat: add dashboard"} { + if !strings.Contains(view, want) { + t.Errorf("view missing %q", want) + } + } + }) + } +} + +func TestLoadStats(t *testing.T) { + isolateHome(t) + if err := stats.RecordCommit("groq", 1.0, "feat: one"); err != nil { + t.Fatal(err) + } + + msg, ok := loadStats()().(statsLoadedMsg) + if !ok { + t.Fatal("loadStats() did not return statsLoadedMsg") + } + if msg.totalCommits != 1 || msg.mostUsedModel != "groq" || len(msg.recentCommits) != 1 { + t.Errorf("loaded %+v, want the recorded commit", msg) + } + if tick() == nil { + t.Error("tick() returned nil") + } +} + +func TestDashboardCmd(t *testing.T) { + isolateHome(t) + scriptTUI(t, "q") + + if err := execute(t, "dashboard"); err != nil { + t.Fatalf("dashboard error = %v", err) + } +} diff --git a/cmd/helpers_test.go b/cmd/helpers_test.go new file mode 100644 index 0000000..eb2ca28 --- /dev/null +++ b/cmd/helpers_test.go @@ -0,0 +1,58 @@ +package cmd + +import ( + "bytes" + "strings" + "testing" + + tea "github.com/charmbracelet/bubbletea" + "github.com/rshdhere/vibecheck/internal/keys" +) + +// isolateHome points HOME at a fresh directory and clears provider env vars so +// config, keys and stats never touch the developer's real files. +func isolateHome(t *testing.T) string { + t.Helper() + dir := t.TempDir() + t.Setenv("HOME", dir) + for _, envVar := range keys.ProviderToEnvVar { + t.Setenv(envVar, "") + } + return dir +} + +// scriptTUI feeds input to the next interactive program and returns its output. +func scriptTUI(t *testing.T, input string) *bytes.Buffer { + t.Helper() + var out bytes.Buffer + old := teaOptions + teaOptions = []tea.ProgramOption{ + tea.WithInput(strings.NewReader(input)), + tea.WithOutput(&out), + tea.WithoutSignalHandler(), + } + t.Cleanup(func() { teaOptions = old }) + return &out +} + +// execute runs the root command with args and returns its error. +func execute(t *testing.T, args ...string) error { + t.Helper() + var out bytes.Buffer + rootCmd.SetOut(&out) + rootCmd.SetErr(&out) + rootCmd.SetArgs(args) + t.Cleanup(func() { + rootCmd.SetOut(nil) + rootCmd.SetErr(nil) + rootCmd.SetArgs(nil) + }) + return rootCmd.Execute() +} + +func keyRunes(s string) tea.KeyMsg { return tea.KeyMsg{Type: tea.KeyRunes, Runes: []rune(s)} } + +var ( + keyEnter = tea.KeyMsg{Type: tea.KeyEnter} + keyEsc = tea.KeyMsg{Type: tea.KeyEsc} +) diff --git a/cmd/keys.go b/cmd/keys.go index 4797b8d..ad026ed 100644 --- a/cmd/keys.go +++ b/cmd/keys.go @@ -458,7 +458,7 @@ var keysCmd = &cobra.Command{ state: "list", } - p := tea.NewProgram(m) + p := tea.NewProgram(m, teaOptions...) if _, err := p.Run(); err != nil { return fmt.Errorf("error running program: %w", err) } diff --git a/cmd/keys_test.go b/cmd/keys_test.go new file mode 100644 index 0000000..335057e --- /dev/null +++ b/cmd/keys_test.go @@ -0,0 +1,241 @@ +package cmd + +import ( + "bytes" + "strings" + "testing" + + "github.com/charmbracelet/bubbles/list" + "github.com/charmbracelet/bubbles/textinput" + tea "github.com/charmbracelet/bubbletea" + "github.com/rshdhere/vibecheck/internal/keys" +) + +func newTestKeysModel(items ...list.Item) keysModel { + return keysModel{ + list: list.New(items, keyItemDelegate{}, 80, 15), + items: items, + textInput: textinput.New(), + state: "list", + } +} + +func update(t *testing.T, m keysModel, msg tea.Msg) (keysModel, tea.Cmd) { + t.Helper() + next, cmd := m.Update(msg) + return next.(keysModel), cmd +} + +func TestKeyItem(t *testing.T) { + set := KeyItem{provider: "openai", displayName: "OpenAI", envVar: "OPENAI_API_KEY", hasKey: true, maskedKey: "sk-...1234"} + unset := KeyItem{provider: "gemini", displayName: "Google Gemini", envVar: "GEMINI_API_KEY"} + + if got := set.Title(); got != "✓ OpenAI" { + t.Errorf("Title() = %q, want %q", got, "✓ OpenAI") + } + if got := unset.Title(); got != "✗ Google Gemini" { + t.Errorf("Title() = %q, want %q", got, "✗ Google Gemini") + } + if got := set.Description(); got != "sk-...1234 • OPENAI_API_KEY" { + t.Errorf("Description() = %q", got) + } + if got := unset.Description(); got != "Not set • GEMINI_API_KEY" { + t.Errorf("Description() = %q", got) + } + if got := set.FilterValue(); got != "openai" { + t.Errorf("FilterValue() = %q, want openai", got) + } +} + +func TestLoadKeyItems(t *testing.T) { + isolateHome(t) + if err := keys.SetAPIKey("anthropic", "sk-ant-0123456789"); err != nil { + t.Fatal(err) + } + + items := loadKeyItems() + + if len(items) == 0 { + t.Fatal("loadKeyItems() returned no items") + } + first := items[0].(KeyItem) + if first.provider != "anthropic" || !first.hasKey || first.displayName != "Anthropic Claude" { + t.Errorf("first item = %+v, want anthropic with a key listed first", first) + } + for _, item := range items { + ki := item.(KeyItem) + if ki.provider == "ollama" { + t.Error("ollama should not be listed: it needs no API key") + } + if ki.provider != "anthropic" && ki.hasKey { + t.Errorf("%s reported a key, want only anthropic", ki.provider) + } + } +} + +func TestKeysModelSetKey(t *testing.T) { + isolateHome(t) + m := newTestKeysModel(KeyItem{provider: "openai", displayName: "OpenAI", envVar: "OPENAI_API_KEY"}) + + m, _ = update(t, m, keyEnter) + if m.state != "input" || m.selectedItem.provider != "openai" { + t.Fatalf("after enter: state = %q, selected = %q; want input for openai", m.state, m.selectedItem.provider) + } + if view := m.View(); !strings.Contains(view, "Set API Key for") || !strings.Contains(view, "OPENAI_API_KEY") { + t.Errorf("input view missing prompt: %q", view) + } + + m, _ = update(t, m, keyRunes("sk-test-key")) + m, cmd := update(t, m, keyEnter) + if m.state != "list" || cmd == nil { + t.Fatalf("after save: state = %q, cmd = %v; want list and a reload", m.state, cmd) + } + if got, _ := keys.GetAPIKey("openai"); got != "sk-test-key" { + t.Errorf("stored key = %q, want sk-test-key", got) + } + + m, _ = update(t, m, cmd()) + for _, item := range m.items { + if ki := item.(KeyItem); ki.provider == "openai" && !ki.hasKey { + t.Error("reloaded openai item should report a key") + } + } +} + +func TestKeysModelDeleteKey(t *testing.T) { + t.Run("d on a stored key", func(t *testing.T) { + isolateHome(t) + if err := keys.SetAPIKey("openai", "sk-old"); err != nil { + t.Fatal(err) + } + m := newTestKeysModel(KeyItem{provider: "openai", hasKey: true}) + + _, cmd := update(t, m, keyRunes("d")) + if cmd == nil { + t.Error("delete should trigger a reload") + } + if _, ok := keys.GetAPIKey("openai"); ok { + t.Error("key still stored after delete") + } + }) + + t.Run("empty input", func(t *testing.T) { + isolateHome(t) + if err := keys.SetAPIKey("openai", "sk-old"); err != nil { + t.Fatal(err) + } + m := newTestKeysModel(KeyItem{provider: "openai", hasKey: true}) + + m, _ = update(t, m, keyEnter) + m, cmd := update(t, m, keyEnter) + if m.state != "list" || cmd == nil { + t.Errorf("state = %q, cmd = %v; want list and a reload", m.state, cmd) + } + if _, ok := keys.GetAPIKey("openai"); ok { + t.Error("key still stored after submitting empty input") + } + }) +} + +func TestKeysModelErrors(t *testing.T) { + isolateHome(t) + bogus := KeyItem{provider: "bogus", displayName: "Bogus", hasKey: true} + + t.Run("delete", func(t *testing.T) { + m, _ := update(t, newTestKeysModel(bogus), keyRunes("d")) + if !strings.Contains(m.errorMsg, "Error deleting key") { + t.Errorf("errorMsg = %q, want a delete error", m.errorMsg) + } + if !strings.Contains(m.View(), "ERROR: Error deleting key") { + t.Error("view should show the error") + } + }) + + t.Run("save", func(t *testing.T) { + m, _ := update(t, newTestKeysModel(bogus), keyEnter) + m, _ = update(t, m, keyRunes("x")) + m, _ = update(t, m, keyEnter) + if !strings.Contains(m.errorMsg, "Error saving key") { + t.Errorf("errorMsg = %q, want a save error", m.errorMsg) + } + }) + + t.Run("clear", func(t *testing.T) { + m, _ := update(t, newTestKeysModel(bogus), keyEnter) + m, _ = update(t, m, keyEnter) + if !strings.Contains(m.errorMsg, "Error deleting key") { + t.Errorf("errorMsg = %q, want a delete error", m.errorMsg) + } + }) +} + +func TestKeysModelNavigation(t *testing.T) { + m := newTestKeysModel(KeyItem{provider: "openai"}) + + m, _ = update(t, m, tea.WindowSizeMsg{Width: 120, Height: 40}) + if m.list.Width() != 120 { + t.Errorf("list width = %d, want 120", m.list.Width()) + } + + m, _ = update(t, m, keyEnter) + m, _ = update(t, m, keyEsc) + if m.state != "list" { + t.Errorf("esc from input: state = %q, want list", m.state) + } + if view := m.View(); !strings.Contains(view, "VIBECHECK API KEYS") || !strings.Contains(view, "navigate") { + t.Errorf("list view missing title or help: %q", view) + } + + m, _ = update(t, m, keyRunes("j")) + m, cmd := update(t, m, keyRunes("q")) + if !m.quitting || cmd == nil { + t.Error("q should quit") + } + if m.View() != "" { + t.Error("view should be empty after quitting") + } +} + +func TestKeyItemDelegateRender(t *testing.T) { + items := []list.Item{ + KeyItem{provider: "openai", displayName: "OpenAI", envVar: "OPENAI_API_KEY", hasKey: true, maskedKey: "sk-...1234"}, + KeyItem{provider: "gemini", displayName: "Google Gemini", envVar: "GEMINI_API_KEY"}, + } + l := list.New(items, keyItemDelegate{}, 80, 15) + d := keyItemDelegate{} + + if d.Height() != 2 || d.Spacing() != 0 || d.Update(nil, &l) != nil { + t.Error("unexpected delegate layout") + } + for i := range items { + var buf bytes.Buffer + for _, selected := range []int{0, 1} { + l.Select(selected) + buf.Reset() + d.Render(&buf, l, i, items[i]) + if !strings.Contains(buf.String(), items[i].(KeyItem).displayName) { + t.Errorf("render of item %d (selected %d) = %q, missing display name", i, selected, buf.String()) + } + } + } + + var buf bytes.Buffer + d.Render(&buf, l, 0, Model{name: "not-a-key-item"}) + if buf.Len() != 0 { + t.Error("render should ignore non-KeyItem items") + } +} + +func TestKeysCmdSavesKey(t *testing.T) { + isolateHome(t) + scriptTUI(t, "\rsk-from-tui\rq") + + if err := execute(t, "keys"); err != nil { + t.Fatalf("keys error = %v", err) + } + + stored, err := keys.GetAllKeys() + if err != nil || len(stored) != 1 { + t.Fatalf("stored keys = %v, %v; want exactly one", stored, err) + } +} diff --git a/cmd/models.go b/cmd/models.go index 7e90dd8..5ea6106 100644 --- a/cmd/models.go +++ b/cmd/models.go @@ -276,7 +276,7 @@ var modelsCmd = &cobra.Command{ currentModel: currentDefault, } - p := tea.NewProgram(m) + p := tea.NewProgram(m, teaOptions...) finalModel, err := p.Run() if err != nil { return fmt.Errorf("error running program: %w", err) diff --git a/cmd/models_test.go b/cmd/models_test.go new file mode 100644 index 0000000..e167023 --- /dev/null +++ b/cmd/models_test.go @@ -0,0 +1,122 @@ +package cmd + +import ( + "bytes" + "strings" + "testing" + + "github.com/charmbracelet/bubbles/list" + tea "github.com/charmbracelet/bubbletea" + "github.com/rshdhere/vibecheck/internal/config" +) + +func modelItems() []list.Item { + items := make([]list.Item, len(availableModels)) + for i, m := range availableModels { + items[i] = m + } + return items +} + +func TestModelItem(t *testing.T) { + m := availableModels[0] + if m.Title() != m.displayName || m.Description() != m.description || m.FilterValue() != m.name { + t.Errorf("list item accessors do not match %+v", m) + } +} + +func TestModelSelectionUpdate(t *testing.T) { + m := modelSelection{list: list.New(modelItems(), itemDelegate{}, 80, 22), currentModel: "openai"} + + next, _ := m.Update(tea.WindowSizeMsg{Width: 100, Height: 30}) + m = next.(modelSelection) + if m.list.Width() != 100 { + t.Errorf("list width = %d, want 100", m.list.Width()) + } + + next, _ = m.Update(keyRunes("j")) + m = next.(modelSelection) + if view := m.View(); !strings.Contains(view, "VIBECHECK MODEL SELECTION") || !strings.Contains(view, "Current:") { + t.Errorf("view missing title or current model: %q", view) + } + + next, cmd := m.Update(keyEnter) + m = next.(modelSelection) + if m.choice != availableModels[1].name || cmd == nil { + t.Errorf("choice = %q, want %q and a quit", m.choice, availableModels[1].name) + } +} + +func TestModelSelectionQuit(t *testing.T) { + m := modelSelection{list: list.New(modelItems(), itemDelegate{}, 80, 22)} + + next, cmd := m.Update(keyRunes("q")) + m = next.(modelSelection) + if !m.quitting || cmd == nil { + t.Fatal("q should quit") + } + if !strings.Contains(m.View(), "Selection cancelled") { + t.Errorf("view = %q, want cancellation notice", m.View()) + } + + m.choice = "openai" + if m.View() != "" { + t.Error("view should be empty after quitting with a choice") + } +} + +func TestItemDelegateRender(t *testing.T) { + items := modelItems() + l := list.New(items, itemDelegate{}, 80, 22) + d := itemDelegate{} + + if d.Height() != 2 || d.Spacing() != 0 || d.Update(nil, &l) != nil { + t.Error("unexpected delegate layout") + } + for i, item := range items { + for _, selected := range []int{0, i} { + l.Select(selected) + var buf bytes.Buffer + d.Render(&buf, l, i, item) + m := item.(Model) + if !strings.Contains(buf.String(), m.displayName) || !strings.Contains(buf.String(), m.model) { + t.Errorf("render of %s = %q, missing name or model", m.name, buf.String()) + } + if m.badge != "" && !strings.Contains(buf.String(), m.badge) { + t.Errorf("render of %s missing badge %q", m.name, m.badge) + } + } + } + + var buf bytes.Buffer + d.Render(&buf, l, 0, KeyItem{}) + if buf.Len() != 0 { + t.Error("render should ignore non-Model items") + } +} + +func TestModelsCmd(t *testing.T) { + tests := []struct { + name string + input string + want string + }{ + {"select next provider", "j\r", availableModels[1].name}, + {"keep current provider", "\r", "openai"}, + {"cancel", "q", "openai"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + isolateHome(t) + scriptTUI(t, tt.input) + + if err := execute(t, "models"); err != nil { + t.Fatalf("models error = %v", err) + } + if got := config.GetDefaultProvider(); got != tt.want { + t.Errorf("default provider = %q, want %q", got, tt.want) + } + }) + } +} diff --git a/cmd/root.go b/cmd/root.go index 99664cd..d625a84 100644 --- a/cmd/root.go +++ b/cmd/root.go @@ -7,12 +7,16 @@ package cmd import ( "os" + tea "github.com/charmbracelet/bubbletea" "github.com/spf13/cobra" ) // version will be set at build time via ldflags var version = "dev" +// teaOptions are passed to every interactive program; tests use them to script input and capture output. +var teaOptions []tea.ProgramOption + // rootCmd represents the base command when called without any subcommands var rootCmd = &cobra.Command{ Use: "vibecheck", diff --git a/cmd/upgrade.go b/cmd/upgrade.go index be8da56..33613c6 100644 --- a/cmd/upgrade.go +++ b/cmd/upgrade.go @@ -25,9 +25,12 @@ import ( "github.com/rshdhere/vibecheck/internal/ui/banner" ) -const ( - githubAPIURL = "https://api.github.com/repos/rshdhere/vibecheck/releases/latest" - repoURL = "rshdhere/vibecheck" +const repoURL = "rshdhere/vibecheck" + +// githubAPIURL and executablePath are variables so tests can substitute a local server and a scratch binary. +var ( + githubAPIURL = "https://api.github.com/repos/rshdhere/vibecheck/releases/latest" + executablePath = os.Executable ) type GitHubRelease struct { @@ -45,7 +48,7 @@ var upgradeCmd = &cobra.Command{ Version: version, RunE: func(cmd *cobra.Command, args []string) error { // Get current executable path - execPath, err := os.Executable() + execPath, err := executablePath() if err != nil { return fmt.Errorf("failed to get executable path: %w", err) } diff --git a/cmd/upgrade_test.go b/cmd/upgrade_test.go index 71d848d..4c58577 100644 --- a/cmd/upgrade_test.go +++ b/cmd/upgrade_test.go @@ -1,9 +1,17 @@ package cmd import ( + "archive/tar" + "archive/zip" + "compress/gzip" + "errors" + "fmt" + "net/http" + "net/http/httptest" "os" "path/filepath" "runtime" + "strings" "testing" ) @@ -152,3 +160,443 @@ func TestExtractBinary(t *testing.T) { } }) } + +type archiveEntry struct { + name string + body string // empty for directories + dir bool +} + +func writeTarGz(t *testing.T, path string, entries ...archiveEntry) { + t.Helper() + f, err := os.Create(path) + if err != nil { + t.Fatal(err) + } + defer f.Close() + gz := gzip.NewWriter(f) + tw := tar.NewWriter(gz) + for _, e := range entries { + hdr := &tar.Header{Name: e.name, Mode: 0755, Size: int64(len(e.body)), Typeflag: tar.TypeReg} + if e.dir { + hdr.Typeflag, hdr.Size = tar.TypeDir, 0 + } + if err := tw.WriteHeader(hdr); err != nil { + t.Fatal(err) + } + if _, err := tw.Write([]byte(e.body)); err != nil { + t.Fatal(err) + } + } + if err := tw.Close(); err != nil { + t.Fatal(err) + } + if err := gz.Close(); err != nil { + t.Fatal(err) + } +} + +func writeZip(t *testing.T, path string, entries ...archiveEntry) { + t.Helper() + f, err := os.Create(path) + if err != nil { + t.Fatal(err) + } + defer f.Close() + zw := zip.NewWriter(f) + for _, e := range entries { + name := e.name + if e.dir { + name += "/" + } + w, err := zw.Create(name) + if err != nil { + t.Fatal(err) + } + if _, err := w.Write([]byte(e.body)); err != nil { + t.Fatal(err) + } + } + if err := zw.Close(); err != nil { + t.Fatal(err) + } +} + +func readFile(t *testing.T, path string) string { + t.Helper() + data, err := os.ReadFile(path) + if err != nil { + t.Fatal(err) + } + return string(data) +} + +func TestExtractTarGz(t *testing.T) { + t.Run("finds binary", func(t *testing.T) { + dir := t.TempDir() + archive := filepath.Join(dir, "release.tar.gz") + writeTarGz(t, archive, + archiveEntry{name: "docs", dir: true}, + archiveEntry{name: "docs/README.md", body: "readme"}, + archiveEntry{name: "vibecheck", body: "new binary"}, + ) + + got, err := extractBinary(archive, dir) + if err != nil { + t.Fatalf("extractBinary() error = %v", err) + } + if got != filepath.Join(dir, "vibecheck") || readFile(t, got) != "new binary" { + t.Errorf("extracted %q with unexpected contents", got) + } + }) + + t.Run("missing binary", func(t *testing.T) { + dir := t.TempDir() + archive := filepath.Join(dir, "release.tar.gz") + writeTarGz(t, archive, archiveEntry{name: "README.md", body: "readme"}) + + if _, err := extractBinary(archive, dir); err == nil || !strings.Contains(err.Error(), "not found") { + t.Errorf("err = %v, want binary not found", err) + } + }) + + t.Run("not gzip", func(t *testing.T) { + dir := t.TempDir() + archive := filepath.Join(dir, "release.tar.gz") + os.WriteFile(archive, []byte("plain text"), 0644) + + if _, err := extractBinary(archive, dir); err == nil { + t.Error("expected an error for a non-gzip archive") + } + }) + + t.Run("missing archive", func(t *testing.T) { + if _, err := extractTarGz(filepath.Join(t.TempDir(), "nope.tar.gz"), t.TempDir()); err == nil { + t.Error("expected an error for a missing archive") + } + }) +} + +func TestExtractZip(t *testing.T) { + t.Run("finds binary", func(t *testing.T) { + dir := t.TempDir() + archive := filepath.Join(dir, "release.zip") + writeZip(t, archive, + archiveEntry{name: "docs", dir: true}, + archiveEntry{name: "docs/README.md", body: "readme"}, + archiveEntry{name: "vibecheck.exe", body: "new binary"}, + ) + + got, err := extractBinary(archive, dir) + if err != nil { + t.Fatalf("extractBinary() error = %v", err) + } + if got != filepath.Join(dir, "vibecheck.exe") || readFile(t, got) != "new binary" { + t.Errorf("extracted %q with unexpected contents", got) + } + }) + + t.Run("missing binary", func(t *testing.T) { + dir := t.TempDir() + archive := filepath.Join(dir, "release.zip") + writeZip(t, archive, archiveEntry{name: "README.md", body: "readme"}) + + if _, err := extractBinary(archive, dir); err == nil || !strings.Contains(err.Error(), "not found") { + t.Errorf("err = %v, want binary not found", err) + } + }) + + t.Run("not a zip", func(t *testing.T) { + dir := t.TempDir() + archive := filepath.Join(dir, "release.zip") + os.WriteFile(archive, []byte("plain text"), 0644) + + if _, err := extractBinary(archive, dir); err == nil { + t.Error("expected an error for an invalid zip") + } + }) +} + +func TestReplaceBinary(t *testing.T) { + t.Run("replaces and keeps mode", func(t *testing.T) { + dir := t.TempDir() + oldPath, newPath := filepath.Join(dir, "vibecheck"), filepath.Join(dir, "new") + os.WriteFile(oldPath, []byte("old"), 0700) + os.WriteFile(newPath, []byte("new"), 0644) + + if err := replaceBinary(oldPath, newPath); err != nil { + t.Fatalf("replaceBinary() error = %v", err) + } + if readFile(t, oldPath) != "new" { + t.Error("binary was not replaced") + } + if info, _ := os.Stat(oldPath); info.Mode().Perm() != 0700 { + t.Errorf("mode = %v, want 0700", info.Mode().Perm()) + } + if _, err := os.Stat(oldPath + ".backup"); !os.IsNotExist(err) { + t.Error("backup was not removed") + } + }) + + t.Run("missing current binary", func(t *testing.T) { + dir := t.TempDir() + if err := replaceBinary(filepath.Join(dir, "vibecheck"), filepath.Join(dir, "new")); err == nil { + t.Error("expected an error when the current binary is missing") + } + }) + + t.Run("restores backup when copy fails", func(t *testing.T) { + dir := t.TempDir() + oldPath := filepath.Join(dir, "vibecheck") + os.WriteFile(oldPath, []byte("old"), 0755) + + err := replaceBinary(oldPath, filepath.Join(dir, "missing")) + if err == nil || !strings.Contains(err.Error(), "failed to install new binary") { + t.Fatalf("err = %v, want install failure", err) + } + if readFile(t, oldPath) != "old" { + t.Error("original binary was not restored") + } + }) +} + +func TestCopyFileErrors(t *testing.T) { + dir := t.TempDir() + if err := copyFile(filepath.Join(dir, "missing"), filepath.Join(dir, "dst")); err == nil { + t.Error("expected an error for a missing source") + } + src := filepath.Join(dir, "src") + os.WriteFile(src, []byte("x"), 0644) + if err := copyFile(src, filepath.Join(dir, "no-such-dir", "dst")); err == nil { + t.Error("expected an error for an unwritable destination") + } +} + +func TestDownloadFile(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/missing" { + http.NotFound(w, r) + return + } + w.Write([]byte("payload")) + })) + defer srv.Close() + dir := t.TempDir() + + dst := filepath.Join(dir, "asset") + if err := downloadFile(dst, srv.URL+"/asset"); err != nil { + t.Fatalf("downloadFile() error = %v", err) + } + if readFile(t, dst) != "payload" { + t.Error("downloaded contents do not match") + } + + if err := downloadFile(dst, srv.URL+"/missing"); err == nil || !strings.Contains(err.Error(), "status 404") { + t.Errorf("err = %v, want status 404", err) + } + if err := downloadFile(filepath.Join(dir, "no-such-dir", "asset"), srv.URL+"/asset"); err == nil { + t.Error("expected an error for an unwritable destination") + } + if err := downloadFile(dst, "://bad-url"); err == nil { + t.Error("expected an error for an invalid url") + } +} + +func TestFetchLatestRelease(t *testing.T) { + tests := []struct { + name string + status int + body string + wantErr string + }{ + {"success", http.StatusOK, `{"tag_name":"v9.9.9","assets":[{"name":"a","browser_download_url":"u"}]}`, ""}, + {"non-200", http.StatusForbidden, "rate limited", "status 403"}, + {"invalid json", http.StatusOK, "not json", "invalid character"}, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + serveRelease(t, func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(tt.status) + w.Write([]byte(tt.body)) + }) + + release, err := fetchLatestRelease() + if tt.wantErr != "" { + if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("err = %v, want it to contain %q", err, tt.wantErr) + } + return + } + if err != nil || release.TagName != "v9.9.9" || len(release.Assets) != 1 { + t.Fatalf("release = %+v, err = %v", release, err) + } + }) + } + + t.Run("unreachable", func(t *testing.T) { + setVar(t, &githubAPIURL, "://bad-url") + if _, err := fetchLatestRelease(); err == nil { + t.Error("expected an error for an invalid url") + } + }) +} + +func setVar[T any](t *testing.T, v *T, val T) { + t.Helper() + old := *v + *v = val + t.Cleanup(func() { *v = old }) +} + +// serveRelease points githubAPIURL at a local server and returns its base URL. +func serveRelease(t *testing.T, h http.HandlerFunc) string { + t.Helper() + srv := httptest.NewServer(h) + t.Cleanup(srv.Close) + setVar(t, &githubAPIURL, srv.URL+"/releases/latest") + return srv.URL +} + +// platformAsset is the release asset name findAssetForPlatform expects on this machine. +func platformAsset() string { + osName := map[string]string{"darwin": "Darwin", "linux": "Linux", "windows": "Windows"}[runtime.GOOS] + arch := map[string]string{"amd64": "x86_64", "386": "i386", "arm64": "arm64"}[runtime.GOARCH] + ext := ".tar.gz" + if runtime.GOOS == "windows" { + ext = ".zip" + } + return "vibecheck_" + osName + "_" + arch + ext +} + +// fakeInstall makes the upgrade command treat a scratch file as the running binary. +func fakeInstall(t *testing.T) string { + t.Helper() + exe := filepath.Join(t.TempDir(), "vibecheck") + if err := os.WriteFile(exe, []byte("old binary"), 0755); err != nil { + t.Fatal(err) + } + setVar(t, &executablePath, func() (string, error) { return exe, nil }) + setVar(t, &version, "v1.0.0") + return exe +} + +func TestUpgradeCmdInstallsLatestRelease(t *testing.T) { + if runtime.GOOS == "windows" { + t.Skip("release archive fixture is tar.gz") + } + exe := fakeInstall(t) + archive := filepath.Join(t.TempDir(), platformAsset()) + writeTarGz(t, archive, archiveEntry{name: "vibecheck", body: "new binary"}) + + var base string + base = serveRelease(t, func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/download" { + http.ServeFile(w, r, archive) + return + } + fmt.Fprintf(w, `{"tag_name":"v2.0.0","assets":[{"name":%q,"browser_download_url":%q}]}`, platformAsset(), base+"/download") + }) + + if err := execute(t, "upgrade"); err != nil { + t.Fatalf("upgrade error = %v", err) + } + if readFile(t, exe) != "new binary" { + t.Error("binary was not replaced with the release") + } +} + +func TestUpgradeCmdAlreadyLatest(t *testing.T) { + exe := fakeInstall(t) + setVar(t, &version, "v2.0.0-3-gabc1234-dirty") + serveRelease(t, func(w http.ResponseWriter, r *http.Request) { + w.Write([]byte(`{"tag_name":"v2.0.0"}`)) + }) + + if err := execute(t, "upgrade"); err != nil { + t.Fatalf("upgrade error = %v", err) + } + if readFile(t, exe) != "old binary" { + t.Error("binary should be untouched when already up to date") + } +} + +func TestUpgradeCmdErrors(t *testing.T) { + brokenArchive := filepath.Join(t.TempDir(), "broken") + os.WriteFile(brokenArchive, []byte("not an archive"), 0644) + + tests := []struct { + name string + handler func(base string) http.HandlerFunc + wantErr string + }{ + { + name: "release lookup fails", + handler: func(string) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusInternalServerError) } + }, + wantErr: "failed to fetch latest release", + }, + { + name: "no asset for platform", + handler: func(string) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { w.Write([]byte(`{"tag_name":"v2.0.0","assets":[]}`)) } + }, + wantErr: "no compatible release found", + }, + { + name: "download fails", + handler: func(base string) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/download" { + http.NotFound(w, r) + return + } + fmt.Fprintf(w, `{"tag_name":"v2.0.0","assets":[{"name":%q,"browser_download_url":%q}]}`, platformAsset(), base+"/download") + } + }, + wantErr: "failed to download release", + }, + { + name: "archive is corrupt", + handler: func(base string) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/download" { + http.ServeFile(w, r, brokenArchive) + return + } + fmt.Fprintf(w, `{"tag_name":"v2.0.0","assets":[{"name":%q,"browser_download_url":%q}]}`, platformAsset(), base+"/download") + } + }, + wantErr: "failed to extract binary", + }, + } + + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + fakeInstall(t) + var base string + base = serveRelease(t, func(w http.ResponseWriter, r *http.Request) { tt.handler(base)(w, r) }) + + err := execute(t, "upgrade") + if err == nil || !strings.Contains(err.Error(), tt.wantErr) { + t.Fatalf("upgrade error = %v, want it to contain %q", err, tt.wantErr) + } + }) + } + + t.Run("executable path unavailable", func(t *testing.T) { + setVar(t, &executablePath, func() (string, error) { return "", errors.New("no exe") }) + if err := execute(t, "upgrade"); err == nil || !strings.Contains(err.Error(), "failed to get executable path") { + t.Fatalf("upgrade error = %v, want executable path failure", err) + } + }) + + t.Run("executable path unresolvable", func(t *testing.T) { + missing := filepath.Join(t.TempDir(), "missing") + setVar(t, &executablePath, func() (string, error) { return missing, nil }) + if err := execute(t, "upgrade"); err == nil || !strings.Contains(err.Error(), "failed to resolve executable path") { + t.Fatalf("upgrade error = %v, want resolve failure", err) + } + }) +} diff --git a/internal/git/commit_test.go b/internal/git/commit_test.go index 7401b25..2211b3f 100644 --- a/internal/git/commit_test.go +++ b/internal/git/commit_test.go @@ -1,12 +1,49 @@ package git_test import ( + "context" + "os" + "os/exec" + "path/filepath" + "strings" "testing" + + "github.com/rshdhere/vibecheck/internal/git" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" ) +// stagedRepo creates a repo with one staged file, makes it the working directory +// and sets GIT_EDITOR so `git commit -e` runs without an interactive editor. +func stagedRepo(t *testing.T, editor string) { + t.Helper() + t.Setenv("HOME", t.TempDir()) + t.Setenv("GIT_EDITOR", editor) + dir := t.TempDir() + t.Chdir(dir) + for _, args := range [][]string{ + {"init", "-q"}, + {"config", "user.email", "test@example.com"}, + {"config", "user.name", "Test User"}, + } { + require.NoError(t, exec.Command("git", args...).Run()) + } + require.NoError(t, os.WriteFile(filepath.Join(dir, "file.txt"), []byte("hello\n"), 0644)) + require.NoError(t, exec.Command("git", "add", "file.txt").Run()) +} + func TestCommitWMessage(t *testing.T) { - // Skip this test as git commit -em opens an editor which will hang in tests - // The function requires interactive input which is not suitable for automated testing - // In a real scenario, this would require mocking the exec.Command or using a different approach - t.Skip("Skipping TestCommitWMessage - git commit -em requires interactive editor input") + stagedRepo(t, "true") + + require.NoError(t, git.CommitWMessage(context.Background(), "feat: add file")) + + out, err := exec.Command("git", "log", "-1", "--format=%s").Output() + require.NoError(t, err) + assert.Equal(t, "feat: add file", strings.TrimSpace(string(out))) +} + +func TestCommitWMessageEditorAborts(t *testing.T) { + stagedRepo(t, "false") + + assert.Error(t, git.CommitWMessage(context.Background(), "feat: add file")) } From 61d52db0bcc81c700a65ceac8a21c2f3ec0dc212 Mon Sep 17 00:00:00 2001 From: raashed Date: Wed, 7 Oct 2026 23:04:42 +0530 Subject: [PATCH 4/4] ci(github-actions): measure coverage across all packages - Run go test with -coverprofile over ./... instead of a hand-picked subset of internal packages - Enable -race with atomic cover mode to catch data races in CI - Read the Go version from go.mod instead of pinning 1.22, which mismatched the 1.25 toolchain --- .github/workflows/coverage.yaml | 16 +++------------- 1 file changed, 3 insertions(+), 13 deletions(-) diff --git a/.github/workflows/coverage.yaml b/.github/workflows/coverage.yaml index 75247f1..18636b2 100644 --- a/.github/workflows/coverage.yaml +++ b/.github/workflows/coverage.yaml @@ -15,21 +15,11 @@ jobs: - uses: actions/setup-go@7b8cf10d4e4a01d4992d18a89f4d7dc5a3e6d6f4 # v4.3.0 with: - go-version: '1.22' + go-version-file: go.mod - name: Run tests with coverage - run: | - # Test core packages (exclude LLM clients that require API keys and UI-heavy cmd packages) - # Focus on testable internal packages - go test \ - ./internal/config \ - ./internal/keys \ - ./internal/stats \ - ./internal/git \ - ./internal/llm \ - ./internal/ui/banner \ - ./internal/ui/notify \ - -coverprofile=coverage.out + # Cover every package so the reported number matches `go test -cover ./...`. + run: go test -race -covermode=atomic -coverprofile=coverage.out ./... - name: Upload coverage to Codecov uses: codecov/codecov-action@671740ac38dd9b0130fbe1cec585b89eea48d3de # v5.5.2