Delete the old job code now that the tracker runs on its own
The job tracker has run from its own image at /jobs/ since 931b02c, so its
old copy here goes: the GraphQL schema, resolvers and models for
applications, references, sources, leads and the search profile; the
capture and email handlers and services; the Python posting reader, lead
scorer and email classifier; the Vue pages, stores and the capture-token
card on the Environment tab; and the userscript (nginx already redirects
its old URL to /jobs/).
The six old tables stay in the stp database: AutoMigrate never drops
anything, and dropping them is a manual step. The env variables stay in
the registry, where they already belong to the jobs service.
Docs (CLAUDE.md, DEPLOYMENT.md and the three READMEs) now describe the
site without the tracker, and DEPLOYMENT.md lists the jobs service and
./jobs-data.
Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
@@ -1,6 +1,6 @@
|
||||
"""Tests for `ask_json`, the one Claude call the four callers share.
|
||||
"""Tests for `ask_json`, the Claude call every caller goes through.
|
||||
|
||||
test_rowing, test_jobs, test_job_score and test_email_classify each cover their own prompt,
|
||||
test_rowing covers its 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.
|
||||
|
||||
@@ -1,245 +0,0 @@
|
||||
"""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 claude, 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
|
||||
# 512 is the reply's ceiling; what is sent adds room for thinking on a
|
||||
# model that thinks (claude._model_options).
|
||||
assert call["max_tokens"] == claude._model_options(claude.MODEL, 512)["max_tokens"]
|
||||
# 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,175 +0,0 @@
|
||||
"""Tests for the job lead scorer and its internal-only route.
|
||||
|
||||
As in test_jobs, no Claude call happens: `job_score._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.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import anthropic
|
||||
import httpx2 as httpx
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app import job_score, main
|
||||
|
||||
BODY = {
|
||||
"profile": "Five years of Go. Want a backend role in London.",
|
||||
"jobTitle": "Backend Engineer",
|
||||
"company": "Acme",
|
||||
"location": "London",
|
||||
"description": "We build payments in Go.",
|
||||
}
|
||||
REPLY = '{"score": 82, "reasons": "Your Go experience matches; no payments background."}'
|
||||
|
||||
|
||||
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(job_score, "_client", lambda: client)
|
||||
return state
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def http():
|
||||
return TestClient(main.app)
|
||||
|
||||
|
||||
def score(**overrides):
|
||||
args = {**BODY, **overrides}
|
||||
return job_score.score_posting(args["profile"], args["jobTitle"], args["company"], args["location"], args["description"])
|
||||
|
||||
|
||||
# --- score_posting --------------------------------------------------------
|
||||
|
||||
|
||||
def test_score_sends_profile_and_posting_as_delimited_data(fake_claude):
|
||||
result = score()
|
||||
|
||||
assert result.model_dump() == {"score": 82, "reasons": "Your Go experience matches; no payments background."}
|
||||
(call,) = fake_claude.calls
|
||||
assert call["model"] == job_score.MODEL
|
||||
# The instructions travel in the system prompt; the profile and the
|
||||
# third-party posting travel in the user turn, inside the tags the system
|
||||
# prompt tells the model to treat as data.
|
||||
assert call["system"] == job_score.SYSTEM
|
||||
(message,) = call["messages"]
|
||||
assert message["role"] == "user"
|
||||
assert message["content"] == (
|
||||
"<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>"
|
||||
)
|
||||
|
||||
|
||||
def test_score_accepts_fenced_json(fake_claude):
|
||||
fake_claude.reply = text_reply(f"```json\n{REPLY}\n```")
|
||||
assert score().score == 82
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"reply, want",
|
||||
[
|
||||
('{"score": 82.0, "reasons": " ok "}', (82, "ok")),
|
||||
('{"score": "40"}', (40, "")),
|
||||
('{"score": 0, "reasons": null}', (0, "")),
|
||||
('{"score": 100, "reasons": "Perfect"}', (100, "Perfect")),
|
||||
],
|
||||
)
|
||||
def test_score_normalises_what_the_model_returns(fake_claude, reply, want):
|
||||
fake_claude.reply = text_reply(reply)
|
||||
result = score()
|
||||
assert (result.score, result.reasons) == want
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"reply, message",
|
||||
[
|
||||
(SimpleNamespace(content=[]), "empty response from the posting scorer"),
|
||||
(text_reply("This looks like a great role!"), "failed to parse the score"),
|
||||
# No usable number is a failure, never a score of zero.
|
||||
(text_reply('{"reasons": "Good fit"}'), "failed to parse the score"),
|
||||
(text_reply('{"score": null, "reasons": "Good fit"}'), "failed to parse the score"),
|
||||
(text_reply('{"score": "high"}'), "failed to parse the score"),
|
||||
(text_reply('{"score": 140}'), "failed to parse the score"),
|
||||
(text_reply('{"score": -5}'), "failed to parse the score"),
|
||||
(
|
||||
anthropic.APIConnectionError(request=httpx.Request("POST", "https://api.anthropic.com/v1/messages")),
|
||||
"failed to score the posting",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_score_failures(fake_claude, reply, message):
|
||||
fake_claude.reply = reply
|
||||
with pytest.raises(job_score.ReadError, match=message):
|
||||
score()
|
||||
|
||||
|
||||
def test_missing_api_key_is_not_configured(monkeypatch):
|
||||
monkeypatch.delenv("CLAUDE_API_KEY", raising=False)
|
||||
job_score._client.cache_clear()
|
||||
with pytest.raises(job_score.NotConfigured):
|
||||
score()
|
||||
|
||||
|
||||
# --- the route ------------------------------------------------------------
|
||||
|
||||
|
||||
def test_route_returns_score(fake_claude, http):
|
||||
res = http.post("/internal/jobs/score", json=BODY)
|
||||
assert res.status_code == 200
|
||||
assert res.json() == {"score": 82, "reasons": "Your Go experience matches; no payments background."}
|
||||
|
||||
|
||||
def test_route_needs_only_profile_and_title(fake_claude, http):
|
||||
assert http.post("/internal/jobs/score", json={"profile": "p", "jobTitle": "Engineer"}).status_code == 200
|
||||
|
||||
|
||||
@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("/internal/jobs/score", json=BODY, headers={header: "203.0.113.9"})
|
||||
assert res.status_code == 404
|
||||
assert fake_claude.calls == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"body",
|
||||
[
|
||||
{**BODY, "profile": ""},
|
||||
{**BODY, "jobTitle": ""},
|
||||
{**BODY, "description": "x" * (job_score.MAX_DESCRIPTION_CHARS + 1)},
|
||||
{**BODY, "profile": "x" * (job_score.MAX_PROFILE_CHARS + 1)},
|
||||
],
|
||||
)
|
||||
def test_route_validates_the_body(fake_claude, http, body):
|
||||
assert http.post("/internal/jobs/score", json=body).status_code == 422
|
||||
assert fake_claude.calls == []
|
||||
|
||||
|
||||
def test_route_maps_failures_to_status_codes(fake_claude, http, monkeypatch):
|
||||
fake_claude.reply = text_reply("nope")
|
||||
res = http.post("/internal/jobs/score", json=BODY)
|
||||
assert res.status_code == 502
|
||||
assert res.json() == {"detail": "failed to parse the score"}
|
||||
|
||||
def not_configured():
|
||||
raise job_score.NotConfigured("CLAUDE_API_KEY is not set")
|
||||
|
||||
monkeypatch.setattr(job_score, "_client", not_configured)
|
||||
assert http.post("/internal/jobs/score", json=BODY).status_code == 503
|
||||
@@ -1,160 +0,0 @@
|
||||
"""Tests for the job posting reader and its internal-only route.
|
||||
|
||||
As in test_rowing, no Claude call happens: `jobs._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.
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import anthropic
|
||||
import httpx2 as httpx
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from app import jobs, main
|
||||
|
||||
BODY = {"url": "https://jobs.example/1", "title": "Engineer | Acme", "text": "Acme is hiring an Engineer in London."}
|
||||
REPLY = '{"jobTitle": "Engineer", "company": "Acme", "location": "London", "notes": "£70k, hybrid"}'
|
||||
|
||||
|
||||
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(jobs, "_client", lambda: client)
|
||||
return state
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def http():
|
||||
return TestClient(main.app)
|
||||
|
||||
|
||||
# --- extract_posting ------------------------------------------------------
|
||||
|
||||
|
||||
def test_extract_sends_page_as_delimited_data(fake_claude):
|
||||
posting = jobs.extract_posting(BODY["url"], BODY["title"], BODY["text"])
|
||||
|
||||
assert posting.model_dump() == {
|
||||
"jobTitle": "Engineer",
|
||||
"company": "Acme",
|
||||
"location": "London",
|
||||
"notes": "£70k, hybrid",
|
||||
}
|
||||
(call,) = fake_claude.calls
|
||||
assert call["model"] == jobs.MODEL
|
||||
# The instructions travel in the system prompt and the page in the user
|
||||
# turn, inside the <page> tags the system prompt tells the model to treat
|
||||
# as data.
|
||||
assert call["system"] == jobs.SYSTEM
|
||||
(message,) = call["messages"]
|
||||
assert message["role"] == "user"
|
||||
assert message["content"] == (
|
||||
"<url>https://jobs.example/1</url>\n<title>Engineer | Acme</title>\n"
|
||||
"<page>\nAcme is hiring an Engineer in London.\n</page>"
|
||||
)
|
||||
|
||||
|
||||
def test_extract_accepts_fenced_json(fake_claude):
|
||||
fake_claude.reply = text_reply(f"```json\n{REPLY}\n```")
|
||||
assert jobs.extract_posting("", "", "x").company == "Acme"
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"reply, want",
|
||||
[
|
||||
# Not a posting: the popup is filled in by hand rather than erroring.
|
||||
('{"jobTitle": "", "company": "", "location": null, "notes": null}', ("", "", None, None)),
|
||||
# Nulls where strings were asked for, and keys left out altogether.
|
||||
('{"jobTitle": null, "company": null}', ("", "", None, None)),
|
||||
("{}", ("", "", None, None)),
|
||||
# Whitespace is trimmed, and a blank optional field becomes null.
|
||||
('{"jobTitle": " Engineer ", "company": "Acme\\n", "location": " ", "notes": ""}', ("Engineer", "Acme", None, None)),
|
||||
],
|
||||
)
|
||||
def test_extract_normalises_what_the_model_returns(fake_claude, reply, want):
|
||||
fake_claude.reply = text_reply(reply)
|
||||
posting = jobs.extract_posting("", "", "x")
|
||||
assert (posting.jobTitle, posting.company, posting.location, posting.notes) == want
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"reply, message",
|
||||
[
|
||||
(SimpleNamespace(content=[]), "empty response from the posting reader"),
|
||||
(text_reply("This looks like a great role!"), "failed to parse the posting"),
|
||||
(text_reply('{"jobTitle": ["Engineer"], "company": "Acme"}'), "failed to parse the posting"),
|
||||
(
|
||||
anthropic.APIConnectionError(request=httpx.Request("POST", "https://api.anthropic.com/v1/messages")),
|
||||
"failed to read the posting",
|
||||
),
|
||||
],
|
||||
)
|
||||
def test_extract_failures(fake_claude, reply, message):
|
||||
fake_claude.reply = reply
|
||||
with pytest.raises(jobs.ReadError, match=message):
|
||||
jobs.extract_posting("", "", "x")
|
||||
|
||||
|
||||
def test_missing_api_key_is_not_configured(monkeypatch):
|
||||
monkeypatch.delenv("CLAUDE_API_KEY", raising=False)
|
||||
jobs._client.cache_clear()
|
||||
with pytest.raises(jobs.NotConfigured):
|
||||
jobs.extract_posting("", "", "x")
|
||||
|
||||
|
||||
# --- the route ------------------------------------------------------------
|
||||
|
||||
|
||||
def test_route_returns_posting(fake_claude, http):
|
||||
res = http.post("/internal/jobs/extract", json=BODY)
|
||||
assert res.status_code == 200
|
||||
assert res.json() == {"jobTitle": "Engineer", "company": "Acme", "location": "London", "notes": "£70k, hybrid"}
|
||||
|
||||
|
||||
def test_route_needs_only_the_text(fake_claude, http):
|
||||
assert http.post("/internal/jobs/extract", json={"text": "x"}).status_code == 200
|
||||
|
||||
|
||||
@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("/internal/jobs/extract", json=BODY, headers={header: "203.0.113.9"})
|
||||
assert res.status_code == 404
|
||||
assert fake_claude.calls == []
|
||||
|
||||
|
||||
@pytest.mark.parametrize("text", ["", "x" * (jobs.MAX_TEXT_CHARS + 1)])
|
||||
def test_route_rejects_empty_or_oversized_text(fake_claude, http, text):
|
||||
res = http.post("/internal/jobs/extract", json={**BODY, "text": text})
|
||||
assert res.status_code == 422
|
||||
assert fake_claude.calls == []
|
||||
|
||||
|
||||
def test_route_maps_read_error_to_502(fake_claude, http):
|
||||
fake_claude.reply = text_reply("no JSON here")
|
||||
res = http.post("/internal/jobs/extract", json=BODY)
|
||||
assert res.status_code == 502
|
||||
assert res.json() == {"detail": "failed to parse the posting"}
|
||||
|
||||
|
||||
def test_route_maps_missing_key_to_503(monkeypatch, http):
|
||||
monkeypatch.delenv("CLAUDE_API_KEY", raising=False)
|
||||
jobs._client.cache_clear()
|
||||
res = http.post("/internal/jobs/extract", json=BODY)
|
||||
assert res.status_code == 503
|
||||
Reference in New Issue
Block a user