package claude
import (
"context"
"encoding/json"
"errors"
"io"
"net/http"
"net/http/httptest"
"reflect"
"testing"
"github.com/anthropics/anthropic-sdk-go/option"
)
// These tests run the real SDK against a fake Messages API, so what is
// pinned is the request as it goes over the wire and the handling of every
// kind of reply. Ported from the main site's python/tests/test_claude.py,
// test_jobs.py and test_job_score.py.
// fakeAPI answers POST /v1/messages with status and body, and records each
// request body it was sent.
type fakeAPI struct {
status int
body string
calls []map[string]any
}
func (f *fakeAPI) client(t *testing.T, model string) *Client {
t.Helper()
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
raw, _ := io.ReadAll(r.Body)
var call map[string]any
if err := json.Unmarshal(raw, &call); err != nil {
t.Errorf("request body is not JSON: %s", raw)
}
f.calls = append(f.calls, call)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(f.status)
io.WriteString(w, f.body)
}))
t.Cleanup(srv.Close)
// No retries: a 529 should fail once, not three times with backoff.
return New("test-key", model, option.WithBaseURL(srv.URL), option.WithMaxRetries(0))
}
// message builds a Messages API reply with the given content blocks.
func message(stopReason string, blocks ...map[string]any) string {
if blocks == nil {
blocks = []map[string]any{}
}
b, _ := json.Marshal(map[string]any{
"id": "msg_1", "type": "message", "role": "assistant", "model": "claude-sonnet-5-5",
"stop_reason": stopReason, "content": blocks,
"usage": map[string]any{"input_tokens": 1, "output_tokens": 1},
})
return string(b)
}
func text(s string) map[string]any { return map[string]any{"type": "text", "text": s} }
func thinking() map[string]any {
return map[string]any{"type": "thinking", "thinking": "", "signature": "sig"}
}
func replying(s string) *fakeAPI {
return &fakeAPI{status: 200, body: message("end_turn", text(s))}
}
type count struct {
N int `json:"n"`
}
var testMessages = messages{failed: "call failed", empty: "nothing came back", unparseable: "could not parse"}
func ask(t *testing.T, api *fakeAPI, model string) (count, error) {
t.Helper()
return askJSON[count](context.Background(), api.client(t, model), "count things", "how many?", 64, testMessages, nil)
}
func TestAskJSONSendsTheRequestAndDecodesTheReply(t *testing.T) {
api := replying(`{"n": 3}`)
got, err := ask(t, api, "")
if err != nil || got.N != 3 {
t.Fatalf("got %+v, %v", got, err)
}
if len(api.calls) != 1 {
t.Fatalf("%d calls, want 1", len(api.calls))
}
call := api.calls[0]
if call["model"] != DefaultModel {
t.Errorf("model = %v, want the default %s", call["model"], DefaultModel)
}
system, _ := json.Marshal(call["system"])
if string(system) != `[{"text":"count things","type":"text"}]` {
t.Errorf("system = %s", system)
}
msgs, _ := json.Marshal(call["messages"])
if string(msgs) != `[{"content":[{"text":"how many?","type":"text"}],"role":"user"}]` {
t.Errorf("messages = %s", msgs)
}
}
// Thinking is billed against max_tokens, so the caller's reply ceiling alone
// would starve the answer.
func TestThinkingModelGetsHeadroomAndLowEffort(t *testing.T) {
for _, model := range []string{"claude-sonnet-5-5", "claude-opus-5-5", "some-future-model"} {
api := replying(`{}`)
ask(t, api, model)
call := api.calls[0]
if call["max_tokens"] != float64(64+thinkingHeadroom) {
t.Errorf("%s: max_tokens = %v, want %d", model, call["max_tokens"], 64+thinkingHeadroom)
}
if !reflect.DeepEqual(call["output_config"], map[string]any{"effort": "low"}) {
t.Errorf("%s: output_config = %v", model, call["output_config"])
}
// Nothing these models reject: no thinking override, sampling or forced tool.
for _, key := range []string{"thinking", "temperature", "top_p", "top_k", "tool_choice"} {
if _, ok := call[key]; ok {
t.Errorf("%s: request carries %q", model, key)
}
}
}
}
// Haiku 4.5 rejects output_config.effort and does not think unless asked to.
func TestHaikuGetsThePlainRequest(t *testing.T) {
api := replying(`{}`)
ask(t, api, "claude-haiku-4-5")
call := api.calls[0]
if call["max_tokens"] != float64(64) {
t.Errorf("max_tokens = %v, want 64", call["max_tokens"])
}
if _, ok := call["output_config"]; ok {
t.Errorf("output_config sent to Haiku: %v", call["output_config"])
}
}
func TestAnswerIsFoundAfterAThinkingBlock(t *testing.T) {
api := &fakeAPI{status: 200, body: message("end_turn", thinking(), text(`{"n": 7}`))}
if got, err := ask(t, api, ""); err != nil || got.N != 7 {
t.Fatalf("got %+v, %v", got, err)
}
}
func TestFencedJSONIsAccepted(t *testing.T) {
if got, err := ask(t, replying("```json\n{\"n\": 3}\n```"), ""); err != nil || got.N != 3 {
t.Fatalf("got %+v, %v", got, err)
}
}
func TestEachFailureIsTheCallersMessage(t *testing.T) {
refusal := `{"id":"msg_1","type":"message","role":"assistant","model":"m","stop_reason":"refusal",` +
`"stop_details":{"type":"refusal","category":"general_harms","explanation":"no"},"content":[],"usage":{"input_tokens":1,"output_tokens":0}}`
cases := []struct {
name string
api *fakeAPI
want string
}{
{"overloaded", &fakeAPI{status: 529, body: `{"type":"error","error":{"type":"overloaded_error","message":"busy"}}`}, "call failed"},
{"bad request", &fakeAPI{status: 400, body: `{"type":"error","error":{"type":"invalid_request_error","message":"bad"}}`}, "call failed"},
// A refusal is a failed call, not an empty reply.
{"refusal", &fakeAPI{status: 200, body: refusal}, "call failed"},
{"no content", &fakeAPI{status: 200, body: message("end_turn")}, "nothing came back"},
// Out of tokens while thinking.
{"only thinking", &fakeAPI{status: 200, body: message("max_tokens", thinking())}, "nothing came back"},
{"prose", replying("three, I think"), "could not parse"},
// Valid JSON of the wrong shape is the same failure.
{"wrong type", replying(`{"n": "lots"}`), "could not parse"},
{"array", replying(`[3]`), "could not parse"},
}
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
_, err := ask(t, c.api, "")
var readErr *ReadError
// Exactly the caller's text: it is shown to the admin, so
// nothing from the API error or the reply may be appended.
if !errors.As(err, &readErr) || err.Error() != c.want {
t.Fatalf("err = %v, want ReadError %q", err, c.want)
}
})
}
}
func TestUnreachableAPIIsAFailedCall(t *testing.T) {
c := New("test-key", "", option.WithBaseURL("http://127.0.0.1:1"), option.WithMaxRetries(0))
_, err := askJSON[count](context.Background(), c, "s", "u", 64, testMessages, nil)
if err == nil || err.Error() != "call failed" {
t.Fatalf("err = %v, want \"call failed\"", err)
}
}
// The caller giving up must stay visible as the context's error, so it is
// never mistaken for Claude failing on the input.
func TestCancelledCallIsNotAReadError(t *testing.T) {
api := replying(`{"n": 1}`)
c := api.client(t, "")
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err := askJSON[count](ctx, c, "s", "u", 64, testMessages, nil)
var readErr *ReadError
if !errors.Is(err, context.Canceled) || errors.As(err, &readErr) {
t.Fatalf("err = %v, want a wrapped context.Canceled", err)
}
}
func TestMissingAPIKeyIsNotConfigured(t *testing.T) {
for _, c := range []*Client{New("", ""), nil} {
_, err := c.ExtractPosting(context.Background(), "", "", "x")
if !errors.Is(err, ErrNotConfigured) {
t.Fatalf("err = %v, want ErrNotConfigured", err)
}
}
}
func TestBlankModelIsTheDefault(t *testing.T) {
if m := New("k", " ").Model(); m != DefaultModel {
t.Fatalf("Model() = %q", m)
}
}
// --- posting.go -----------------------------------------------------------
func TestExtractPostingSendsThePageAsDelimitedData(t *testing.T) {
api := replying(`{"jobTitle": "Engineer", "company": "Acme", "location": "London", "notes": "£70k, hybrid"}`)
got, err := api.client(t, "").ExtractPosting(context.Background(),
"https://jobs.example/1", "Engineer | Acme", "Acme is hiring an Engineer in London.")
if err != nil {
t.Fatal(err)
}
if got.JobTitle != "Engineer" || got.Company != "Acme" || *got.Location != "London" || *got.Notes != "£70k, hybrid" {
t.Errorf("got %+v", got)
}
call := api.calls[0]
if call["system"].([]any)[0].(map[string]any)["text"] != postingSystem {
t.Error("system prompt is not postingSystem")
}
user := call["messages"].([]any)[0].(map[string]any)["content"].([]any)[0].(map[string]any)["text"]
want := "