errors_test.go

402 lines
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402
package assistant_test

import (
	"bytes"
	"errors"
	"fmt"
	"io"
	"net/http"
	"testing"

	"congo.gg/pkg/assistant"
)

func TestAPIErrorWithType(t *testing.T) {
	err := &assistant.APIError{
		StatusCode: 429,
		Type:       "rate_limit_error",
		Message:    "You have exceeded your rate limit.",
	}

	expected := "API error 429 (rate_limit_error): You have exceeded your rate limit."
	if err.Error() != expected {
		t.Errorf("Error() = %q, want %q", err.Error(), expected)
	}
}

func TestAPIErrorWithoutType(t *testing.T) {
	err := &assistant.APIError{
		StatusCode: 500,
		Message:    "Internal server error",
	}

	expected := "API error 500: Internal server error"
	if err.Error() != expected {
		t.Errorf("Error() = %q, want %q", err.Error(), expected)
	}
}

func TestAPIErrorEmptyMessage(t *testing.T) {
	err := &assistant.APIError{
		StatusCode: 503,
		Type:       "overloaded",
		Message:    "",
	}

	expected := "API error 503 (overloaded): "
	if err.Error() != expected {
		t.Errorf("Error() = %q, want %q", err.Error(), expected)
	}
}

func TestAPIErrorImplementsError(t *testing.T) {
	var err error = &assistant.APIError{StatusCode: 400, Message: "bad request"}
	if err == nil {
		t.Error("APIError should implement error interface")
	}
}

func TestIsRateLimitedWithErrRateLimited(t *testing.T) {
	if !assistant.IsRateLimited(assistant.ErrRateLimited) {
		t.Error("IsRateLimited(ErrRateLimited) = false, want true")
	}
}

func TestIsRateLimitedWithWrappedErrRateLimited(t *testing.T) {
	wrapped := fmt.Errorf("provider: %w", assistant.ErrRateLimited)
	if !assistant.IsRateLimited(wrapped) {
		t.Error("IsRateLimited(wrapped ErrRateLimited) = false, want true")
	}
}

func TestIsRateLimitedWithAPIError429(t *testing.T) {
	err := &assistant.APIError{StatusCode: 429, Message: "too many requests"}
	if !assistant.IsRateLimited(err) {
		t.Error("IsRateLimited(APIError{429}) = false, want true")
	}
}

func TestIsRateLimitedWithWrappedAPIError429(t *testing.T) {
	apiErr := &assistant.APIError{StatusCode: 429, Message: "too many requests"}
	wrapped := fmt.Errorf("provider: %w", apiErr)
	if !assistant.IsRateLimited(wrapped) {
		t.Error("IsRateLimited(wrapped APIError{429}) = false, want true")
	}
}

func TestIsRateLimitedWithNonRateLimitError(t *testing.T) {
	tests := []struct {
		name string
		err  error
	}{
		{"nil", nil},
		{"generic", errors.New("some error")},
		{"APIError 400", &assistant.APIError{StatusCode: 400, Message: "bad request"}},
		{"APIError 500", &assistant.APIError{StatusCode: 500, Message: "server error"}},
		{"APIError 401", &assistant.APIError{StatusCode: 401, Message: "unauthorized"}},
		{"ErrNoAPIKey", assistant.ErrNoAPIKey},
		{"ErrEmptyResponse", assistant.ErrEmptyResponse},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if assistant.IsRateLimited(tt.err) {
				t.Errorf("IsRateLimited(%v) = true, want false", tt.err)
			}
		})
	}
}

func TestIsAuthErrorWithErrNoAPIKey(t *testing.T) {
	if !assistant.IsAuthError(assistant.ErrNoAPIKey) {
		t.Error("IsAuthError(ErrNoAPIKey) = false, want true")
	}
}

func TestIsAuthErrorWithWrappedErrNoAPIKey(t *testing.T) {
	wrapped := fmt.Errorf("config: %w", assistant.ErrNoAPIKey)
	if !assistant.IsAuthError(wrapped) {
		t.Error("IsAuthError(wrapped ErrNoAPIKey) = false, want true")
	}
}

func TestIsAuthErrorWithAPIError401(t *testing.T) {
	err := &assistant.APIError{StatusCode: 401, Message: "invalid api key"}
	if !assistant.IsAuthError(err) {
		t.Error("IsAuthError(APIError{401}) = false, want true")
	}
}

func TestIsAuthErrorWithAPIError403(t *testing.T) {
	err := &assistant.APIError{StatusCode: 403, Message: "forbidden"}
	if !assistant.IsAuthError(err) {
		t.Error("IsAuthError(APIError{403}) = false, want true")
	}
}

func TestIsAuthErrorWithWrappedAPIError401(t *testing.T) {
	apiErr := &assistant.APIError{StatusCode: 401, Message: "unauthorized"}
	wrapped := fmt.Errorf("provider: %w", apiErr)
	if !assistant.IsAuthError(wrapped) {
		t.Error("IsAuthError(wrapped APIError{401}) = false, want true")
	}
}

func TestIsAuthErrorWithNonAuthError(t *testing.T) {
	tests := []struct {
		name string
		err  error
	}{
		{"nil", nil},
		{"generic", errors.New("some error")},
		{"APIError 400", &assistant.APIError{StatusCode: 400, Message: "bad request"}},
		{"APIError 429", &assistant.APIError{StatusCode: 429, Message: "rate limited"}},
		{"APIError 500", &assistant.APIError{StatusCode: 500, Message: "server error"}},
		{"ErrRateLimited", assistant.ErrRateLimited},
		{"ErrEmptyResponse", assistant.ErrEmptyResponse},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if assistant.IsAuthError(tt.err) {
				t.Errorf("IsAuthError(%v) = true, want false", tt.err)
			}
		})
	}
}

func TestParseErrorResponseWithJSONBody(t *testing.T) {
	body := `{"error":{"type":"invalid_request_error","message":"max_tokens must be positive"}}`
	resp := &http.Response{
		StatusCode: 400,
		Body:       io.NopCloser(bytes.NewBufferString(body)),
	}

	err := assistant.ParseErrorResponse(resp)
	if err == nil {
		t.Fatal("ParseErrorResponse returned nil")
	}

	var apiErr *assistant.APIError
	if !errors.As(err, &apiErr) {
		t.Fatalf("expected *APIError, got %T", err)
	}
	if apiErr.StatusCode != 400 {
		t.Errorf("StatusCode = %d, want 400", apiErr.StatusCode)
	}
	if apiErr.Type != "invalid_request_error" {
		t.Errorf("Type = %q, want %q", apiErr.Type, "invalid_request_error")
	}
	if apiErr.Message != "max_tokens must be positive" {
		t.Errorf("Message = %q, want %q", apiErr.Message, "max_tokens must be positive")
	}
}

func TestParseErrorResponseWithJSONNoType(t *testing.T) {
	body := `{"error":{"message":"Something went wrong"}}`
	resp := &http.Response{
		StatusCode: 500,
		Body:       io.NopCloser(bytes.NewBufferString(body)),
	}

	err := assistant.ParseErrorResponse(resp)
	var apiErr *assistant.APIError
	if !errors.As(err, &apiErr) {
		t.Fatalf("expected *APIError, got %T", err)
	}
	if apiErr.StatusCode != 500 {
		t.Errorf("StatusCode = %d, want 500", apiErr.StatusCode)
	}
	if apiErr.Type != "" {
		t.Errorf("Type = %q, want empty string", apiErr.Type)
	}
	if apiErr.Message != "Something went wrong" {
		t.Errorf("Message = %q, want %q", apiErr.Message, "Something went wrong")
	}
}

func TestParseErrorResponseFallbackToRawBody(t *testing.T) {
	body := "Service Unavailable"
	resp := &http.Response{
		StatusCode: 503,
		Body:       io.NopCloser(bytes.NewBufferString(body)),
	}

	err := assistant.ParseErrorResponse(resp)
	var apiErr *assistant.APIError
	if !errors.As(err, &apiErr) {
		t.Fatalf("expected *APIError, got %T", err)
	}
	if apiErr.StatusCode != 503 {
		t.Errorf("StatusCode = %d, want 503", apiErr.StatusCode)
	}
	if apiErr.Type != "" {
		t.Errorf("Type = %q, want empty string", apiErr.Type)
	}
	if apiErr.Message != "Service Unavailable" {
		t.Errorf("Message = %q, want %q", apiErr.Message, "Service Unavailable")
	}
}

func TestParseErrorResponseEmptyBody(t *testing.T) {
	resp := &http.Response{
		StatusCode: 502,
		Body:       io.NopCloser(bytes.NewBufferString("")),
	}

	err := assistant.ParseErrorResponse(resp)
	var apiErr *assistant.APIError
	if !errors.As(err, &apiErr) {
		t.Fatalf("expected *APIError, got %T", err)
	}
	if apiErr.StatusCode != 502 {
		t.Errorf("StatusCode = %d, want 502", apiErr.StatusCode)
	}
	if apiErr.Message != "" {
		t.Errorf("Message = %q, want empty string", apiErr.Message)
	}
}

func TestParseErrorResponseMalformedJSON(t *testing.T) {
	body := `{"error": {"type": "bad`
	resp := &http.Response{
		StatusCode: 400,
		Body:       io.NopCloser(bytes.NewBufferString(body)),
	}

	err := assistant.ParseErrorResponse(resp)
	var apiErr *assistant.APIError
	if !errors.As(err, &apiErr) {
		t.Fatalf("expected *APIError, got %T", err)
	}
	// Falls back to raw body
	if apiErr.Message != body {
		t.Errorf("Message = %q, want raw body %q", apiErr.Message, body)
	}
}

func TestParseErrorResponseJSONWithEmptyMessage(t *testing.T) {
	// JSON parses but error.message is empty -> falls back to raw body
	body := `{"error":{"type":"some_type","message":""}}`
	resp := &http.Response{
		StatusCode: 422,
		Body:       io.NopCloser(bytes.NewBufferString(body)),
	}

	err := assistant.ParseErrorResponse(resp)
	var apiErr *assistant.APIError
	if !errors.As(err, &apiErr) {
		t.Fatalf("expected *APIError, got %T", err)
	}
	// Empty message means JSON parse condition fails, raw body used
	if apiErr.StatusCode != 422 {
		t.Errorf("StatusCode = %d, want 422", apiErr.StatusCode)
	}
	if apiErr.Message != body {
		t.Errorf("Message = %q, want raw body %q", apiErr.Message, body)
	}
}

func TestParseErrorResponseHTMLBody(t *testing.T) {
	body := "<html><body><h1>502 Bad Gateway</h1></body></html>"
	resp := &http.Response{
		StatusCode: 502,
		Body:       io.NopCloser(bytes.NewBufferString(body)),
	}

	err := assistant.ParseErrorResponse(resp)
	var apiErr *assistant.APIError
	if !errors.As(err, &apiErr) {
		t.Fatalf("expected *APIError, got %T", err)
	}
	if apiErr.StatusCode != 502 {
		t.Errorf("StatusCode = %d, want 502", apiErr.StatusCode)
	}
	if apiErr.Message != body {
		t.Errorf("Message = %q, want HTML body", apiErr.Message)
	}
}

func TestSentinelErrors(t *testing.T) {
	// Verify sentinel errors have expected messages
	tests := []struct {
		name     string
		err      error
		expected string
	}{
		{"ErrNoAPIKey", assistant.ErrNoAPIKey, "API key is required"},
		{"ErrRateLimited", assistant.ErrRateLimited, "rate limited"},
		{"ErrEmptyResponse", assistant.ErrEmptyResponse, "empty response"},
	}

	for _, tt := range tests {
		t.Run(tt.name, func(t *testing.T) {
			if tt.err.Error() != tt.expected {
				t.Errorf("%s.Error() = %q, want %q", tt.name, tt.err.Error(), tt.expected)
			}
		})
	}
}

func TestSentinelErrorsAreDistinct(t *testing.T) {
	if errors.Is(assistant.ErrNoAPIKey, assistant.ErrRateLimited) {
		t.Error("ErrNoAPIKey should not match ErrRateLimited")
	}
	if errors.Is(assistant.ErrNoAPIKey, assistant.ErrEmptyResponse) {
		t.Error("ErrNoAPIKey should not match ErrEmptyResponse")
	}
	if errors.Is(assistant.ErrRateLimited, assistant.ErrEmptyResponse) {
		t.Error("ErrRateLimited should not match ErrEmptyResponse")
	}
}

func TestIsRateLimitedNilError(t *testing.T) {
	if assistant.IsRateLimited(nil) {
		t.Error("IsRateLimited(nil) = true, want false")
	}
}

func TestIsAuthErrorNilError(t *testing.T) {
	if assistant.IsAuthError(nil) {
		t.Error("IsAuthError(nil) = true, want false")
	}
}

func TestParseErrorResponse429IsRateLimited(t *testing.T) {
	body := `{"error":{"type":"rate_limit_error","message":"Rate limit exceeded"}}`
	resp := &http.Response{
		StatusCode: 429,
		Body:       io.NopCloser(bytes.NewBufferString(body)),
	}

	err := assistant.ParseErrorResponse(resp)
	if !assistant.IsRateLimited(err) {
		t.Error("ParseErrorResponse(429) should be rate limited")
	}
}

func TestParseErrorResponse401IsAuthError(t *testing.T) {
	body := `{"error":{"type":"authentication_error","message":"Invalid API key"}}`
	resp := &http.Response{
		StatusCode: 401,
		Body:       io.NopCloser(bytes.NewBufferString(body)),
	}

	err := assistant.ParseErrorResponse(resp)
	if !assistant.IsAuthError(err) {
		t.Error("ParseErrorResponse(401) should be auth error")
	}
}

func TestParseErrorResponse403IsAuthError(t *testing.T) {
	body := `{"error":{"type":"permission_error","message":"Forbidden"}}`
	resp := &http.Response{
		StatusCode: 403,
		Body:       io.NopCloser(bytes.NewBufferString(body)),
	}

	err := assistant.ParseErrorResponse(resp)
	if !assistant.IsAuthError(err) {
		t.Error("ParseErrorResponse(403) should be auth error")
	}
}