Files
adamfandClaude Opus 5.5 b7021ca117
Test and publish / test (push) Successful in 1m59s
Test and publish / publish (push) Successful in 1m41s
Remove the email pipeline
The mailbox sync (Microsoft Graph and IMAP), its Claude classifier, the
/email routes and the Settings page's email section are taken out while
the pipeline is unused. The last commit with it is tagged
email-pipeline-last; reverting this commit brings it back.

The status rules the capture path shares (statusOrder, StatusAdvances,
NormalizeStatus) move to job_status.go with their tests. ProcessedEmail
stays in the migration, marked dormant, so its history survives for a
restored pipeline. golang.org/x/oauth2 is no longer needed.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-14 22:48:07 +01:00

343 lines
13 KiB
Go

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 := "<url>https://jobs.example/1</url>\n<title>Engineer | Acme</title>\n<page>\nAcme is hiring an Engineer in London.\n</page>"
if user != want {
t.Errorf("user turn = %q\nwant %q", user, want)
}
}
func TestExtractPostingNormalisesTheReply(t *testing.T) {
cases := []struct {
reply string
title, company string
hasLocation, hasN bool
}{
// Not a posting: the popup is filled in by hand rather than erroring.
{`{"jobTitle": "", "company": "", "location": null, "notes": null}`, "", "", false, false},
// Nulls where strings were asked for, and keys left out altogether.
{`{"jobTitle": null, "company": null}`, "", "", false, false},
{`{}`, "", "", false, false},
// Whitespace is trimmed, and a blank optional field becomes null.
{`{"jobTitle": " Engineer ", "company": "Acme\n", "location": " ", "notes": ""}`, "Engineer", "Acme", false, false},
}
for _, c := range cases {
got, err := replying(c.reply).client(t, "").ExtractPosting(context.Background(), "", "", "x")
if err != nil {
t.Fatalf("%s: %v", c.reply, err)
}
if got.JobTitle != c.title || got.Company != c.company || (got.Location != nil) != c.hasLocation || (got.Notes != nil) != c.hasN {
t.Errorf("%s: got %+v", c.reply, got)
}
}
}
func TestExtractPostingFailures(t *testing.T) {
cases := map[string]*fakeAPI{
"empty response from the posting reader": {status: 200, body: message("end_turn")},
"failed to parse the posting": replying(`{"jobTitle": ["Engineer"], "company": "Acme"}`),
"failed to read the posting": {status: 500, body: `{"type":"error","error":{"type":"api_error","message":"x"}}`},
}
for want, api := range cases {
if _, err := api.client(t, "").ExtractPosting(context.Background(), "", "", "x"); err == nil || err.Error() != want {
t.Errorf("err = %v, want %q", err, want)
}
}
}
// --- score.go -------------------------------------------------------------
func TestScorePostingSendsProfileAndPostingAsDelimitedData(t *testing.T) {
api := replying(`{"score": 82, "reasons": "Your Go experience matches; no payments background."}`)
got, err := api.client(t, "").ScorePosting(context.Background(),
"Five years of Go. Want a backend role in London.", "Backend Engineer", "Acme", "London", "We build payments in Go.")
if err != nil {
t.Fatal(err)
}
if got != (LeadScore{82, "Your Go experience matches; no payments background."}) {
t.Errorf("got %+v", got)
}
user := api.calls[0]["messages"].([]any)[0].(map[string]any)["content"].([]any)[0].(map[string]any)["text"]
want := "<profile>\nFive years of Go. Want a backend role in London.\n</profile>\n" +
"<posting>\n<title>Backend Engineer</title>\n<company>Acme</company>\n" +
"<location>London</location>\n<description>\nWe build payments in Go.\n</description>\n</posting>"
if user != want {
t.Errorf("user turn = %q\nwant %q", user, want)
}
}
func TestScorePostingNormalisesTheReply(t *testing.T) {
cases := map[string]LeadScore{
`{"score": 82.0, "reasons": " ok "}`: {82, "ok"},
`{"score": "40"}`: {40, ""},
`{"score": 0, "reasons": null}`: {0, ""},
`{"score": 100, "reasons": "Perfect"}`: {100, "Perfect"},
`{"score": 82.5}`: {82, ""}, // half to even, as Python's round()
"```json\n{\"score\": 82}\n```": {82, ""},
}
for reply, want := range cases {
got, err := replying(reply).client(t, "").ScorePosting(context.Background(), "p", "t", "", "", "")
if err != nil || got != want {
t.Errorf("%s: got %+v, %v; want %+v", reply, got, err, want)
}
}
}
func TestScorePostingFailures(t *testing.T) {
cases := []struct {
api *fakeAPI
want string
}{
{&fakeAPI{status: 200, body: message("end_turn")}, "empty response from the posting scorer"},
{replying("This looks like a great role!"), "failed to parse the score"},
// No usable number is a failure, never a score of zero.
{replying(`{"reasons": "Good fit"}`), "failed to parse the score"},
{replying(`{"score": null, "reasons": "Good fit"}`), "failed to parse the score"},
{replying(`{"score": "high"}`), "failed to parse the score"},
{replying(`{"score": 140}`), "failed to parse the score"},
{replying(`{"score": -5}`), "failed to parse the score"},
{&fakeAPI{status: 500, body: `{"type":"error","error":{"type":"api_error","message":"x"}}`}, "failed to score the posting"},
}
for _, c := range cases {
_, err := c.api.client(t, "").ScorePosting(context.Background(), "p", "t", "", "", "")
if err == nil || err.Error() != c.want {
t.Errorf("body %s: err = %v, want %q", c.api.body, err, c.want)
}
}
}