Files
coder/coderd/x/chatd/chattest/errors.go
T
Michael Suchacz 50b7c04398 refactor(coderd/x/chatd/chattest): drop write-only fake state and share the shape check (#30950)
The OpenAI and Anthropic fakes stored each request in a `request` field
under a mutex that nothing read, and kept the `httptest.Server` in a
field that only their constructors used. This PR deletes both fields,
the mutex and its lock blocks. It also merges the three copies of the
response-shape switch into one `responseShapeError` helper, and the two
copies of the OpenAI request decode into `decodeOpenAIRequest`.

**Why it is safe**

- Nothing read `request`, so dropping it and its mutex changes no
behavior.
- `responseShapeError` returns the same four strings, byte for byte, in
the same order. Each writer still checks `resp.Error` first, writes the
same plain-text 500 with `http.Error`, and keeps its own serializers.
The layer below pins the "both" and "empty" errors, and the existing
mismatch tests pin the other two: removing any case from the helper
fails one of them.
- `decodeOpenAIRequest` returns the read or decode error unwrapped, so
the 400 body is unchanged, and `handleResponses` still runs
`ValidateResponsesAPIInput` before the handler. It sets `RawBody` after
decoding, as both copies did, so the field comment no longer claims it
is set before.

**Review focus**

The writers now use `switch msg := responseShapeError(...); { case msg
!= "": ... }`, which leaves the streaming and non-streaming cases as
they were.

**Validation**

- `go test ./coderd/x/chatd/chattest/ -count=1`: ok before and after
- `go test -race ./coderd/x/chatd/chattest/ -count=1`: ok
- `go test ./coderd/x/chatd/ -count=1 -p 4 -parallel 4`: ok before and
after
- `go vet ./coderd/x/chatd/chattest/`: ok
- `golangci-lint run --fix=false ./coderd/x/chatd/chattest/`: 0 issues
- pre-commit hook: passed

**Stack**

The stack makes the chattest fake tests fail on wrong output, then drops
the fakes' write-only state and shares their response-shape check.

1. #30948 table the OpenAI fake positive tests and fail on error streams
2. #30949 pin the fake response-shape errors
3. #30950 drop write-only fake state and share the shape check (this PR)

> Xum, an AI agent, opened this PR for @ibetitsmike and wrote this
description.
2026-10-28 00:03:54 +00:00

66 lines
2.0 KiB
Go

package chattest
import (
"encoding/json"
"net/http"
"testing"
)
// ErrorResponse describes an HTTP error that a test server should return
// instead of a normal streaming or JSON response.
type ErrorResponse struct {
StatusCode int
Type string
Code string
Message string
}
// writeErrorResponse writes a JSON error response matching the common
// provider error format used by both Anthropic and OpenAI.
func writeErrorResponse(t testing.TB, w http.ResponseWriter, errResp *ErrorResponse) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(errResp.StatusCode)
errorBody := map[string]interface{}{
"type": errResp.Type,
"message": errResp.Message,
}
if errResp.Code != "" {
errorBody["code"] = errResp.Code
}
body := map[string]interface{}{"error": errorBody}
if err := json.NewEncoder(w).Encode(body); err != nil {
t.Errorf("writeErrorResponse: failed to encode error response: %v", err)
}
}
func responseShapeError(stream, hasStreaming, hasNonStreaming bool) string {
switch {
case hasStreaming && hasNonStreaming:
return "handler returned both streaming and non-streaming responses"
case !hasStreaming && !hasNonStreaming:
return "handler returned empty response"
case stream && !hasStreaming:
return "handler returned non-streaming response for streaming request"
case !stream && !hasNonStreaming:
return "handler returned streaming response for non-streaming request"
}
return ""
}
// OpenAIErrorResponse returns an OpenAIResponse that causes the
// test server to respond with the given HTTP status code and error.
func OpenAIErrorResponse(statusCode int, errorType, message string) OpenAIResponse {
return OpenAIResponse{
Error: &ErrorResponse{
StatusCode: statusCode,
Type: errorType,
Message: message,
},
}
}
// OpenAIRateLimitResponse returns a 429 rate limit error.
func OpenAIRateLimitResponse() OpenAIResponse {
return OpenAIErrorResponse(http.StatusTooManyRequests, "rate_limit_exceeded", "Rate limit exceeded")
}