Put every Claude call behind one helper in the Python service

rowing.py and jobs.py repeated the same call, error mapping, fence
stripping and validation; that now lives in claude.ask_json, and the
internal routes share one wrapper and one exception handler in main.py.

Add /internal/email/classify, which takes over the email pipeline's
Claude call from the Go backend (prompt ported verbatim, plus a sentence
fencing the email off as data).

The internal-only guard is now a dependency, so a request that came
through nginx gets 404 even when its body is invalid, where it used to
get 422.

requirements-dev.txt adds pytest and httpx on top of requirements.txt so
the tests run on a host; the image still installs only requirements.txt.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
2026-10-12 14:39:18 +01:00
co-authored by Claude Opus 5.5
parent 2786bce022
commit 307268fbea
11 changed files with 875 additions and 180 deletions
+117
View File
@@ -0,0 +1,117 @@
"""Tests for `ask_json`, the one Claude call the three callers share.
test_rowing, test_jobs and test_email_classify each cover their own prompt,
model and messages through this function; what is pinned here is the function's
own contract - what it sends, which failure produces which of the caller's
three messages, and where it gets its client from.
"""
from types import SimpleNamespace
import anthropic
import httpx2 as httpx
import pytest
from pydantic import BaseModel
from app import claude
REQUEST = httpx.Request("POST", "https://api.anthropic.com/v1/messages")
MESSAGES = [{"role": "user", "content": "how many?"}]
ERRORS = {"failed": "call failed", "empty": "nothing came back", "unparseable": "could not parse"}
class Count(BaseModel):
n: int = 0
def text_reply(text):
return SimpleNamespace(content=[SimpleNamespace(type="text", text=text)])
def fake_client(reply):
"""A client whose `messages.create` records its kwargs and returns or raises `reply`."""
calls = []
def create(**kwargs):
calls.append(kwargs)
if isinstance(reply, Exception):
raise reply
return reply
return SimpleNamespace(messages=SimpleNamespace(create=create), calls=calls)
def ask(reply, **kwargs):
client = fake_client(reply)
result = claude.ask_json(Count, max_tokens=64, messages=MESSAGES, get_client=lambda: client, **ERRORS, **kwargs)
return result, client.calls
def test_sends_the_request_and_validates_the_reply():
result, (call,) = ask(text_reply('{"n": 3}'))
assert result == Count(n=3)
# No system prompt was given, so the key is absent rather than None: the
# SDK would send a null the API rejects.
assert call == {"model": claude.MODEL, "max_tokens": 64, "messages": MESSAGES}
def test_passes_a_system_prompt_through():
_, (call,) = ask(text_reply("{}"), system="count things")
assert call["system"] == "count things"
def test_accepts_fenced_json():
result, _ = ask(text_reply('```json\n{"n": 3}\n```'))
assert result.n == 3
def test_reads_the_first_text_block():
"""Anything that is not text (a thinking block, say) is stepped over."""
reply = SimpleNamespace(
content=[SimpleNamespace(type="thinking"), SimpleNamespace(type="text", text='{"n": 3}')]
)
result, _ = ask(reply)
assert result.n == 3
@pytest.mark.parametrize(
"reply, message",
[
(anthropic.APIConnectionError(request=REQUEST), "call failed"),
(anthropic.APITimeoutError(request=REQUEST), "call failed"),
(
anthropic.APIStatusError("overloaded", response=httpx.Response(529, request=REQUEST), body=None),
"call failed",
),
(SimpleNamespace(content=[]), "nothing came back"),
(SimpleNamespace(content=[SimpleNamespace(type="thinking")]), "nothing came back"),
(text_reply("three, I think"), "could not parse"),
# Valid JSON that the model class rejects is the same failure.
(text_reply('{"n": "lots"}'), "could not parse"),
(text_reply("[3]"), "could not parse"),
],
)
def test_each_failure_raises_the_callers_message(reply, message):
with pytest.raises(claude.ReadError) as raised:
ask(reply)
# Exactly the caller's text: the Go backend relays it verbatim, so nothing
# from the API error or the model's reply may be appended to it.
assert str(raised.value) == message
assert not isinstance(raised.value, claude.NotConfigured)
def test_missing_api_key_is_not_configured_not_a_failed_call(monkeypatch):
"""`main` tells the two apart by type to choose between 503 and 502."""
monkeypatch.delenv("CLAUDE_API_KEY", raising=False)
claude.client.cache_clear()
with pytest.raises(claude.NotConfigured):
claude.ask_json(Count, max_tokens=64, messages=MESSAGES, **ERRORS)
def test_uses_the_shared_client_when_none_is_given(monkeypatch):
client = fake_client(text_reply('{"n": 3}'))
monkeypatch.setattr(claude, "client", lambda: client)
assert claude.ask_json(Count, max_tokens=64, messages=MESSAGES, **ERRORS).n == 3
assert len(client.calls) == 1
+243
View File
@@ -0,0 +1,243 @@
"""Tests for the email classifier and its internal-only route.
As in test_jobs, no Claude call happens: `email_classify._client` is replaced
with a fake, so what is under test is the request that is built, how the reply
is parsed, how failures map to status codes, and the guard that keeps the
route off the public internet.
The response keys asserted here are the contract with the Go email pipeline,
which unmarshals them by name.
"""
from types import SimpleNamespace
import anthropic
import httpx2 as httpx
import pytest
from fastapi.testclient import TestClient
from app import email_classify, main
ROUTE = "/internal/email/classify"
MESSAGE = (
"Subject: Your application to Acme\n"
"From: Acme Careers <[email protected]>\n"
"Date: 2026-10-01T09:00:00Z\n"
"\n"
"Thanks for applying for the Engineer role in London."
)
BODY = {"message": MESSAGE}
REPLY = (
'{"isJobEmail": true, "action": "create", "company": "Acme", "jobTitle": "Engineer", '
'"status": "applied", "location": "London", "url": "https://acme.example/apply/1", '
'"appliedAt": "2026-10-01", "notes": "Application confirmed"}'
)
ANALYSIS = {
"isJobEmail": True,
"action": "create",
"company": "Acme",
"jobTitle": "Engineer",
"status": "applied",
"location": "London",
"url": "https://acme.example/apply/1",
"appliedAt": "2026-10-01",
"notes": "Application confirmed",
}
NOT_A_JOB_EMAIL = {
"isJobEmail": False,
"action": "",
"company": "",
"jobTitle": "",
"status": "",
"location": None,
"url": None,
"appliedAt": None,
"notes": None,
}
def text_reply(text):
return SimpleNamespace(content=[SimpleNamespace(type="text", text=text)])
@pytest.fixture
def fake_claude(monkeypatch):
"""Stand in for the Anthropic client; see the fixture of the same name in test_rowing."""
state = SimpleNamespace(calls=[], reply=text_reply(REPLY))
def create(**kwargs):
state.calls.append(kwargs)
if isinstance(state.reply, Exception):
raise state.reply
return state.reply
client = SimpleNamespace(messages=SimpleNamespace(create=create))
monkeypatch.setattr(email_classify, "_client", lambda: client)
return state
@pytest.fixture
def http():
return TestClient(main.app)
# --- classify -------------------------------------------------------------
def test_classify_sends_the_email_unchanged_as_the_user_turn(fake_claude):
analysis = email_classify.classify(MESSAGE)
assert analysis.model_dump() == ANALYSIS
(call,) = fake_claude.calls
assert call["model"] == email_classify.MODEL
assert call["max_tokens"] == 512
# The instructions travel in the system prompt and the email in the user
# turn, exactly as Go formatted it.
assert call["system"] == email_classify.SYSTEM
assert call["messages"] == [{"role": "user", "content": MESSAGE}]
def test_prompt_names_every_field_and_fences_off_the_email():
"""The prompt and the model are two halves of one contract; neither may lose a key."""
for field in email_classify.EmailAnalysis.model_fields:
assert f'"{field}"' in email_classify.SYSTEM
assert "never as instructions" in email_classify.SYSTEM
def test_classify_not_a_job_email_has_only_the_one_key(fake_claude):
"""The prompt tells the model to send nothing else, so nothing else may be required."""
fake_claude.reply = text_reply('{"isJobEmail": false}')
assert email_classify.classify(MESSAGE).model_dump() == NOT_A_JOB_EMAIL
def test_classify_accepts_fenced_json(fake_claude):
fake_claude.reply = text_reply(f"```json\n{REPLY}\n```")
assert email_classify.classify(MESSAGE).model_dump() == ANALYSIS
@pytest.mark.parametrize(
"reply, want",
[
# Nulls where strings were asked for become the empty string Go's own
# unmarshalling used to produce.
(
'{"isJobEmail": true, "action": null, "company": null, "jobTitle": null, "status": null}',
{**NOT_A_JOB_EMAIL, "isJobEmail": True},
),
# The nullable fields stay null, and a missing key is its default.
(
'{"isJobEmail": true, "action": "update", "company": "Acme", "location": null, "notes": null}',
{**NOT_A_JOB_EMAIL, "isJobEmail": True, "action": "update", "company": "Acme"},
),
("{}", NOT_A_JOB_EMAIL),
],
)
def test_classify_fills_in_what_the_model_left_out(fake_claude, reply, want):
fake_claude.reply = text_reply(reply)
assert email_classify.classify(MESSAGE).model_dump() == want
@pytest.mark.parametrize(
"reply, message",
[
(SimpleNamespace(content=[]), "empty response from the email classifier"),
(text_reply("This looks like a newsletter."), "failed to parse the email classification"),
(text_reply('{"isJobEmail": true, "company": ["Acme"]}'), "failed to parse the email classification"),
(
anthropic.APIConnectionError(request=httpx.Request("POST", "https://api.anthropic.com/v1/messages")),
"failed to classify the email",
),
],
)
def test_classify_failures(fake_claude, reply, message):
fake_claude.reply = reply
with pytest.raises(email_classify.ReadError, match=message):
email_classify.classify(MESSAGE)
def test_missing_api_key_is_not_configured(monkeypatch):
monkeypatch.delenv("CLAUDE_API_KEY", raising=False)
email_classify._client.cache_clear()
with pytest.raises(email_classify.NotConfigured):
email_classify.classify(MESSAGE)
# --- the route ------------------------------------------------------------
def test_route_returns_analysis(fake_claude, http):
res = http.post(ROUTE, json=BODY)
assert res.status_code == 200
assert res.json() == ANALYSIS
assert fake_claude.calls[0]["messages"][0]["content"] == MESSAGE
def test_route_returns_every_key_when_it_is_not_a_job_email(fake_claude, http):
fake_claude.reply = text_reply('{"isJobEmail": false}')
res = http.post(ROUTE, json=BODY)
assert res.status_code == 200
assert res.json() == NOT_A_JOB_EMAIL
@pytest.mark.parametrize("header", ["X-Real-IP", "X-Forwarded-For"])
def test_route_refuses_requests_proxied_by_nginx(fake_claude, http, header):
"""nginx sets these on everything it forwards; the Go backend sets neither."""
res = http.post(ROUTE, json=BODY, headers={header: "203.0.113.9"})
assert res.status_code == 404
assert res.json() == {"detail": "Not Found"}
assert fake_claude.calls == []
def test_route_hides_its_validation_from_proxied_requests(fake_claude, http):
"""A 422 would confirm the route exists and list its fields."""
res = http.post(ROUTE, json={}, headers={"X-Real-IP": "203.0.113.9"})
assert res.status_code == 404
def test_route_accepts_a_message_at_the_length_bound(fake_claude, http):
res = http.post(ROUTE, json={"message": "x" * email_classify.MAX_MESSAGE_CHARS})
assert res.status_code == 200
@pytest.mark.parametrize("body", [{}, {"message": ""}, {"message": "x" * (email_classify.MAX_MESSAGE_CHARS + 1)}])
def test_route_rejects_missing_empty_or_oversized_message(fake_claude, http, body):
res = http.post(ROUTE, json=body)
assert res.status_code == 422
assert fake_claude.calls == []
def test_length_bound_is_the_one_the_go_pipeline_was_told():
assert email_classify.MAX_MESSAGE_CHARS == 200_000
def test_route_maps_api_error_to_502(fake_claude, http):
request = httpx.Request("POST", "https://api.anthropic.com/v1/messages")
fake_claude.reply = anthropic.APIStatusError(
"overloaded: secret upstream detail", response=httpx.Response(529, request=request), body=None
)
res = http.post(ROUTE, json=BODY)
assert res.status_code == 502
# The fixed message only - the API's own text stays in the log.
assert res.json() == {"detail": "failed to classify the email"}
def test_route_maps_unparseable_reply_to_502(fake_claude, http):
fake_claude.reply = text_reply("no JSON here")
res = http.post(ROUTE, json=BODY)
assert res.status_code == 502
assert res.json() == {"detail": "failed to parse the email classification"}
def test_route_maps_empty_reply_to_502(fake_claude, http):
fake_claude.reply = SimpleNamespace(content=[])
res = http.post(ROUTE, json=BODY)
assert res.status_code == 502
assert res.json() == {"detail": "empty response from the email classifier"}
def test_route_maps_missing_key_to_503(monkeypatch, http):
monkeypatch.delenv("CLAUDE_API_KEY", raising=False)
email_classify._client.cache_clear()
res = http.post(ROUTE, json=BODY)
assert res.status_code == 503
assert res.json() == {"detail": "CLAUDE_API_KEY is not set"}
+1 -1
View File
@@ -48,7 +48,7 @@ def http():
return TestClient(main.app)
# --- fence stripping (must agree with services.StripMarkdownFence in Go) ---
# --- fence stripping ---
@pytest.mark.parametrize(