AI and machine learning · Intermediate · 24 min
Test Claude API code offline against a stub server
By Padding · Updated 27 Nov 2026
Python 3.15 · anthropic SDK 2.14.0 · pytest 9.2.0
You will have a pytest suite that checks your Claude API code against a local stub of the Messages API, covering the request it sends, text and tool_use replies, a max_tokens stop and 429 and 529 errors, with a folder of fixtures and a rule for refreshing them.
On this page
Code that calls a language model is still code, and it has the usual bugs: the wrong model name, a missing system prompt, a parser that crashes when the reply has no text. Testing it against the real API is slow, costs money on every run, needs a key in your CI system, and gives a different answer each time. None of that helps you check your own logic.
This tutorial builds a stub: a small HTTP server, written with Python's standard library, that answers POST /v1/messages with the JSON the Messages API reference documents. You point Anthropic's Python SDK at it with base_url, and pytest checks what your code sends and what it does with each kind of reply. The whole suite runs in a few seconds with no network, which also matters if you pay for mobile data by the megabyte: offline tests cost nothing to re-run.
The code under test sorts customer support tickets into labels with claude-opus-5-5 and a tool. The tests cover:
- the request body: model,
max_tokens, system prompt and tools - a reply with a
tool_useblock, and one with only text - a reply that hit
max_tokensbefore writing any text 429and529errors, which the SDK raises as typed exceptions
A stub proves your code handles the documented shapes. It cannot tell you what a real model will say, so the last step adds a script that records real replies as fixtures and a rule for when to refresh them. Later tutorials in this library reuse the same stub, so keep the project folder when you finish.
Step 1 · Create the project
Make a throwaway project and add the SDK and pytest. The versions are pinned exactly, because the tests check details (headers, exception classes) that a new SDK release could change:
mkdir -p ~/claude-stub-demo
cd ~/claude-stub-demo
uv init --no-package
uv add "anthropic==2.14.0"
uv add --dev "pytest==9.2.0"
mkdir -p fixturesuv add --dev puts pytest in a development group, so it is installed for you but not for anything you deploy.
Check it worked
uv run python -c "import anthropic, pytest; print(anthropic.__version__, pytest.__version__)" | tee /tmp/versions.txt
grep -qx "2.14.0 9.2.0" /tmp/versions.txtThe output is 2.14.0 9.2.0.
Step 2 · Write the code you want to test
Create triage.py. It sends a ticket to Claude with one tool, record_triage, and turns the reply into a Triage result. Three details matter for the tests:
max_tokensis 4000, not 200. Opus 5.5 thinks before it answers, and thinking tokens count towardsmax_tokens, so a small limit can run out before any answer appears.tool_choiceis left at its default,auto. Opus 5.5 returns a 400 error for a forced tool choice, so Claude may answer in prose instead of calling the tool. The code sends those replies to a person asneeds_reviewrather than guessing a label.- Rate limits (
429) and overload (529) become one exception of your own,TryLater, so the rest of your app can queue the ticket without knowing about SDK classes.
cat > triage.py <<'PY'
"""Sort support tickets with Claude. This is the code the tests check."""
from dataclasses import dataclass
import anthropic
MODEL = "claude-opus-5-5"
MAX_TOKENS = 4000 # thinking counts towards this, so leave room for it
SYSTEM = (
"You triage customer support tickets for an online shop. "
"Call the record_triage tool once with a label and a one-line reason."
)
LABELS = ["billing", "delivery", "account", "other"]
TRIAGE_TOOL = {
"name": "record_triage",
"description": "Record the label and the reason for one support ticket.",
"input_schema": {
"type": "object",
"properties": {
"label": {"type": "string", "enum": LABELS},
"reason": {"type": "string"},
},
"required": ["label", "reason"],
},
}
class NoAnswer(Exception):
"""Claude stopped without a usable answer."""
class TryLater(Exception):
"""The API is rate limiting or overloaded. Queue the ticket and retry later."""
@dataclass
class Triage:
label: str
reason: str
def triage(client: anthropic.Anthropic, ticket: str) -> Triage:
try:
message = client.messages.create(
model=MODEL,
max_tokens=MAX_TOKENS,
system=SYSTEM,
tools=[TRIAGE_TOOL],
messages=[{"role": "user", "content": ticket}],
)
except (anthropic.RateLimitError, anthropic.OverloadedError) as err:
raise TryLater(f"API returned {err.status_code}, request {err.request_id}") from err
for block in message.content:
if block.type == "tool_use" and block.name == "record_triage":
label = block.input.get("label")
if label not in LABELS:
return Triage("needs_review", f"unknown label {label!r}")
return Triage(label, block.input.get("reason", ""))
if message.stop_reason == "max_tokens":
raise NoAnswer(f"stopped at max_tokens ({MAX_TOKENS}) before answering")
text = "".join(block.text for block in message.content if block.type == "text").strip()
if text:
# Claude answered in prose instead of calling the tool: a person decides.
return Triage("needs_review", text)
raise NoAnswer(f"empty reply, stop_reason {message.stop_reason}")
PYThe function takes the client as an argument instead of creating one. That is what makes it testable: your app passes a client built from ANTHROPIC_API_KEY, and the tests pass one pointed at the stub.
Check it worked
uv run python -c "import triage; print(triage.MODEL, triage.MAX_TOKENS, triage.LABELS)" | tee /tmp/triage-check.txt
grep -qxF "claude-opus-5-5 4000 ['billing', 'delivery', 'account', 'other']" /tmp/triage-check.txtThe output is claude-opus-5-5 4000 ['billing', 'delivery', 'account', 'other'].
Step 3 · Write fixtures from the API reference
A fixture is one saved reply: the HTTP status, any headers, and the JSON body. Write five, by hand, from the response and error examples in the Messages API and errors references. Each has a _meta block saying where it came from, so nobody mistakes a hand-written reply for a recorded one.
A successful reply has id, type (message), role (assistant), model, a list of content blocks, stop_reason, stop_sequence and usage. Each reply here starts with a thinking block whose thinking text is empty, which is what Opus 5.5 returns when thinking display is left off. Your parser has to skip it.
The first fixture is the reply you hope for, a tool call:
cat > fixtures/tool_use_reply.json <<'JSON'
{
"_meta": {
"source": "hand-written from the Messages API reference",
"recorded_at": "2026-11-26",
"model": "claude-opus-5-5",
"sdk": "anthropic 2.14.0"
},
"status": 200,
"headers": {"request-id": "req_stub_tool_use"},
"body": {
"id": "msg_stub_tool_use",
"type": "message",
"role": "assistant",
"model": "claude-opus-5-5",
"content": [
{"type": "thinking", "thinking": "", "signature": "stub-signature"},
{"type": "text", "text": "I'll record this ticket."},
{
"type": "tool_use",
"id": "toolu_stub_01",
"name": "record_triage",
"input": {"label": "billing", "reason": "Charged twice for order 1042"}
}
],
"stop_reason": "tool_use",
"stop_sequence": null,
"usage": {"input_tokens": 412, "output_tokens": 236}
}
}
JSONNext, a reply where Claude wrote prose and did not call the tool:
cat > fixtures/text_reply.json <<'JSON'
{
"_meta": {
"source": "hand-written from the Messages API reference",
"recorded_at": "2026-11-26",
"model": "claude-opus-5-5",
"sdk": "anthropic 2.14.0"
},
"status": 200,
"headers": {"request-id": "req_stub_text"},
"body": {
"id": "msg_stub_text",
"type": "message",
"role": "assistant",
"model": "claude-opus-5-5",
"content": [
{"type": "thinking", "thinking": "", "signature": "stub-signature"},
{"type": "text", "text": "This reads like a delivery problem, but the ticket also mentions a refund."}
],
"stop_reason": "end_turn",
"stop_sequence": null,
"usage": {"input_tokens": 405, "output_tokens": 188}
}
}
JSONA reply that ran out of tokens while still thinking. stop_reason is max_tokens and there is no text block at all:
cat > fixtures/max_tokens_no_text.json <<'JSON'
{
"_meta": {
"source": "hand-written from the Messages API reference",
"recorded_at": "2026-11-26",
"model": "claude-opus-5-5",
"sdk": "anthropic 2.14.0"
},
"status": 200,
"headers": {"request-id": "req_stub_max_tokens"},
"body": {
"id": "msg_stub_max_tokens",
"type": "message",
"role": "assistant",
"model": "claude-opus-5-5",
"content": [
{"type": "thinking", "thinking": "", "signature": "stub-signature"}
],
"stop_reason": "max_tokens",
"stop_sequence": null,
"usage": {"input_tokens": 405, "output_tokens": 4000}
}
}
JSONErrors use a different body: type is error, and an error object holds its own type and a message. A 429 carries a retry-after header in seconds; this one asks for one second so the retry test stays quick. A 529 means the API is overloaded for everyone, not only for you:
cat > fixtures/rate_limited.json <<'JSON'
{
"_meta": {
"source": "hand-written from the errors reference",
"recorded_at": "2026-11-26",
"model": "claude-opus-5-5",
"sdk": "anthropic 2.14.0"
},
"status": 429,
"headers": {"request-id": "req_stub_429", "retry-after": "1"},
"body": {
"type": "error",
"error": {"type": "rate_limit_error", "message": "Number of request tokens has exceeded your rate limit."},
"request_id": "req_stub_429"
}
}
JSON
cat > fixtures/overloaded.json <<'JSON'
{
"_meta": {
"source": "hand-written from the errors reference",
"recorded_at": "2026-11-26",
"model": "claude-opus-5-5",
"sdk": "anthropic 2.14.0"
},
"status": 529,
"headers": {"request-id": "req_stub_529"},
"body": {
"type": "error",
"error": {"type": "overloaded_error", "message": "Overloaded"},
"request_id": "req_stub_529"
}
}
JSONThe ticket text, IDs and token counts are made up. Keep it that way: fixtures end up in Git, so never paste a real customer's message into one.
Check it worked
for f in fixtures/*.json; do uv run python -m json.tool "$f" > /dev/null && echo "valid $f"; doneFive lines start with valid, one per fixture. A typo such as a trailing comma makes json.tool print the line and column of the mistake instead.
Step 4 · Build the stub server
Create stub_server.py. The StubAPI class wraps a ThreadingHTTPServer and keeps two lists: queued, the fixture names to answer with in order, and received, every request it was sent. When the queue is empty it answers with a default fixture. Any path other than /v1/messages gets a 404 in the API's error shape, so a wrong URL fails loudly.
Port 0 asks the operating system for any free port, so each test gets its own server and tests never collide. Run as a script, it listens on a fixed port instead:
cat > stub_server.py <<'PY'
"""A local stand-in for the Claude Messages API. Standard library only."""
import json
import sys
import threading
from collections import deque
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from pathlib import Path
FIXTURES = Path(__file__).parent / "fixtures"
def load_fixture(name):
data = json.loads((FIXTURES / f"{name}.json").read_text())
return data["status"], data.get("headers", {}), data["body"]
class StubAPI:
def __init__(self, default="tool_use_reply", port=0):
self.default = default # fixture used when nothing is queued
self.queued = deque() # fixture names to answer with, in order
self.received = [] # every request: path, headers, JSON body
stub = self
class Handler(BaseHTTPRequestHandler):
def do_POST(self):
length = int(self.headers.get("Content-Length", 0))
body = json.loads(self.rfile.read(length) or b"{}")
headers = {key.lower(): value for key, value in self.headers.items()}
stub.received.append({"path": self.path, "headers": headers, "body": body})
if self.path != "/v1/messages":
error = {"type": "not_found_error", "message": f"no stub for {self.path}"}
return self.reply(404, {}, {"type": "error", "error": error})
name = stub.queued.popleft() if stub.queued else stub.default
self.reply(*load_fixture(name))
def reply(self, status, headers, payload):
data = json.dumps(payload).encode()
self.send_response(status)
self.send_header("Content-Type", "application/json")
self.send_header("Content-Length", str(len(data)))
for key, value in headers.items():
self.send_header(key, value)
self.end_headers()
self.wfile.write(data)
def log_message(self, format, *args):
pass
self.server = ThreadingHTTPServer(("127.0.0.1", port), Handler)
@property
def base_url(self):
host, port = self.server.server_address[:2]
return f"http://{host}:{port}"
def start(self):
threading.Thread(target=self.server.serve_forever, daemon=True).start()
return self
def stop(self):
self.server.shutdown()
self.server.server_close()
if __name__ == "__main__":
port = int(sys.argv[1]) if len(sys.argv) > 1 else 8801
fixture = sys.argv[2] if len(sys.argv) > 2 else "tool_use_reply"
stub = StubAPI(default=fixture, port=port)
print(f"Stub Messages API on {stub.base_url}, answering with {fixture}", flush=True)
stub.server.serve_forever()
PYStart it in a second terminal, from the same folder, answering every request with the tool call fixture. Leave it running:
cd ~/claude-stub-demo
uv run stub_server.py 8801 tool_use_replyIt prints Stub Messages API on http://127.0.0.1:8801, answering with tool_use_reply. Back in the first terminal, send it a request by hand:
curl -s http://127.0.0.1:8801/v1/messages \
-H "content-type: application/json" \
-d '{"model": "claude-opus-5-5", "max_tokens": 100, "messages": [{"role": "user", "content": "hi"}]}' \
| tee /tmp/stub-reply.json
echo
grep -q '"stop_reason": "tool_use"' /tmp/stub-reply.jsonCheck it worked
curl prints the body of tool_use_reply.json: one line of JSON starting {"id": "msg_stub_tool_use", "type": "message" and containing "stop_reason": "tool_use".
Step 5 · Point the SDK at the stub
The SDK reads ANTHROPIC_BASE_URL from the environment, or takes base_url= in code, and sends every request there instead of https://api.anthropic.com. Write a short script that builds a client from the environment and runs triage:
cat > try_stub.py <<'PY'
import anthropic
from triage import triage
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY and ANTHROPIC_BASE_URL
print(triage(client, "I was charged twice for order 1042."))
PY
ANTHROPIC_BASE_URL=http://127.0.0.1:8801 ANTHROPIC_API_KEY=stub-key uv run try_stub.py | tee /tmp/try-stub.txt
grep -qxF "Triage(label='billing', reason='Charged twice for order 1042')" /tmp/try-stub.txtstub-key is not a key. The stub ignores it, but the SDK refuses to send a request without one. Your real key stays in its private file and is never needed for these tests.
Check it worked
The output is Triage(label='billing', reason='Charged twice for order 1042'). Your code ran end to end, through the real SDK, without leaving your machine. Stop the stub with Ctrl+C in the second terminal.
Step 6 · Test the request your code sends
The tests start their own stub, so nothing needs to be running in the second terminal from now on. Create conftest.py with two pytest fixtures: stub starts a fresh server for each test and stops it afterwards, and client is an SDK client pointed at it. max_retries=0 stops the SDK retrying errors on its own, which it does twice by default; one test below turns retries back on deliberately.
cat > conftest.py <<'PY'
import anthropic
import pytest
from stub_server import StubAPI
@pytest.fixture
def stub():
server = StubAPI().start()
yield server
server.stop()
@pytest.fixture
def client(stub):
# "stub-key" is not a real key; the stub never checks it.
return anthropic.Anthropic(api_key="stub-key", base_url=stub.base_url, max_retries=0)
PYNow test the request itself. Because the stub records every request, the test can read back exactly what went over the wire, after the SDK has turned your Python arguments into JSON:
cat > test_request.py <<'PY'
from triage import MAX_TOKENS, MODEL, SYSTEM, triage
def test_request_body(stub, client):
triage(client, "I was charged twice for order 1042.")
assert len(stub.received) == 1
sent = stub.received[0]
assert sent["path"] == "/v1/messages"
assert sent["headers"]["authorization"] == "Bearer stub-key"
assert "anthropic-version" in sent["headers"]
body = sent["body"]
assert body["model"] == MODEL == "claude-opus-5-5"
assert body["max_tokens"] == MAX_TOKENS
assert body["system"] == SYSTEM
assert body["messages"] == [
{"role": "user", "content": "I was charged twice for order 1042."}
]
assert [tool["name"] for tool in body["tools"]] == ["record_triage"]
assert "tool_choice" not in body
PY
uv run pytest -q test_request.pyThe assertion MODEL == "claude-opus-5-5" looks redundant, but it catches someone changing the constant to a model you did not mean to pay for. SDK 2.14 sends api_key as an Authorization: Bearer header (older releases used X-Api-Key, so a stub that checks the old header starts returning 401 after an upgrade), along with an anthropic-version header whose value it sets for you, so the test only checks that header is there.
Check it worked
pytest prints 1 passed. To see it catch a bug, change MODEL in triage.py to "claude-sonnet-5-5" and run it again: the test fails on the model line and shows both values. Put it back to "claude-opus-5-5".
Step 7 · Test how your code reads each reply
Each test queues one fixture, calls triage, and checks the result. The second checks that a prose answer is never turned into a label, and the third that a reply cut off by max_tokens raises NoAnswer instead of returning an empty or half-written answer:
cat > test_parsing.py <<'PY'
import pytest
from stub_server import FIXTURES
from triage import LABELS, NoAnswer, Triage, triage
def test_tool_use_block_becomes_a_label(stub, client):
stub.queued.append("tool_use_reply")
assert triage(client, "Charged twice") == Triage("billing", "Charged twice for order 1042")
def test_text_only_reply_goes_to_a_person(stub, client):
stub.queued.append("text_reply")
result = triage(client, "Parcel late, want refund")
assert result.label == "needs_review"
assert "delivery problem" in result.reason
def test_max_tokens_with_no_text_raises(stub, client):
stub.queued.append("max_tokens_no_text")
with pytest.raises(NoAnswer, match="before answering"):
triage(client, "A very long ticket")
def test_recorded_tool_calls_parse(stub, client):
names = [path.stem for path in sorted(FIXTURES.glob("recorded_tool_use*.json"))]
if not names:
pytest.skip("no recorded fixtures yet: see record_fixture.py")
for name in names:
stub.queued.append(name)
result = triage(client, "I was charged twice for order 1042.")
assert result.label in LABELS, name
assert result.reason.strip(), name
PY
uv run pytest -q test_parsing.py | tee /tmp/parsing.txt
grep -q "3 passed, 1 skipped" /tmp/parsing.txtThe first three tests use the hand-written fixtures, which is why they can compare exact values such as the reason "Charged twice for order 1042". A real model will not write that sentence word for word, so recorded replies get the fourth, looser test: for every fixture named recorded_tool_use..., the label must be one of LABELS and the reason must not be empty. You record those in the last step; until then the test skips itself.
The thinking block at the start of every fixture is in these tests for a reason. A common bug reads message.content[0].text, which works in a quick demo without thinking and crashes with AttributeError on a reply that starts with a thinking block. Looping over blocks and checking block.type avoids it.
Check it worked
pytest prints 3 passed, 1 skipped. Then break the parser on purpose: in triage.py, delete the two lines starting if message.stop_reason == "max_tokens": and run the file again. test_max_tokens_with_no_text_raises fails: the code now reports an empty reply instead of saying it stopped at max_tokens before answering, and that message is what tells you to raise the limit. Restore the lines and the test passes.
Step 8 · Test rate limits and overload errors
The SDK turns error statuses into exception classes: RateLimitError for 429 and OverloadedError for 529, both subclasses of APIStatusError with status_code and request_id attributes. Test that your code turns both into TryLater and keeps the original as the cause, and that the SDK's own retry recovers from one 429:
cat > test_errors.py <<'PY'
import anthropic
import pytest
from triage import TryLater, triage
def test_429_raises_try_later(stub, client):
stub.queued.append("rate_limited")
with pytest.raises(TryLater) as caught:
triage(client, "Charged twice")
cause = caught.value.__cause__
assert isinstance(cause, anthropic.RateLimitError)
assert cause.status_code == 429
assert cause.request_id == "req_stub_429"
def test_529_raises_try_later(stub, client):
stub.queued.append("overloaded")
with pytest.raises(TryLater) as caught:
triage(client, "Charged twice")
assert isinstance(caught.value.__cause__, anthropic.OverloadedError)
def test_sdk_retries_a_429_by_itself(stub):
patient = anthropic.Anthropic(api_key="stub-key", base_url=stub.base_url, max_retries=1)
stub.queued.extend(["rate_limited", "tool_use_reply"])
assert triage(patient, "Charged twice").label == "billing"
assert len(stub.received) == 2
PY
uv run pytest -q test_errors.pyThe retry test builds its own client with max_retries=1. The stub answers 429 first, the SDK waits the one second the retry-after header asks for, sends the request again, and gets the tool call. len(stub.received) == 2 proves the retry happened. Keep the request ID from an error in your logs: it is what Anthropic support asks for.
Check it worked
pytest prints 3 passed, and takes about a second longer than the other files because of the retry wait.
Step 9 · Keep the fixtures honest
Hand-written fixtures drift from reality when the API or the SDK changes. Two things stop that. First, a test that loads every fixture and validates each successful body with the SDK's own Message type, so a missing field or a misspelt block type fails, and that warns when a fixture is older than 90 days:
cat > test_fixtures.py <<'PY'
import datetime
import json
import warnings
from pathlib import Path
import pytest
from anthropic.types import Message
FIXTURES = sorted((Path(__file__).parent / "fixtures").glob("*.json"))
MAX_AGE_DAYS = 90
@pytest.mark.parametrize("path", FIXTURES, ids=lambda p: p.stem)
def test_fixture_matches_the_api_shape(path):
data = json.loads(path.read_text())
assert {"source", "recorded_at", "model", "sdk"} <= data["_meta"].keys()
if data["status"] == 200:
Message.model_validate(data["body"]) # raises if a field is missing or wrong
else:
assert data["body"]["type"] == "error"
assert {"type", "message"} <= data["body"]["error"].keys()
recorded = datetime.date.fromisoformat(data["_meta"]["recorded_at"])
age = (datetime.date.today() - recorded).days
if age > MAX_AGE_DAYS:
warnings.warn(f"{path.name} is {age} days old: re-record it", stacklevel=1)
PY
uv run pytest -q test_fixtures.pyThe age check is a warning, not a failure, so an old fixture never blocks a release, but it shows in every test run's summary until someone acts.
Second, a script that records a real reply in the same format. It sends the same request triage sends, so the fixture matches your real call. It refuses names that do not start with recorded_, so a recording can never overwrite a hand-written fixture that the exact tests depend on:
cat > record_fixture.py <<'PY'
"""Record one real reply as a fixture. Costs one API call."""
import datetime
import json
import sys
from pathlib import Path
import anthropic
from triage import MAX_TOKENS, MODEL, SYSTEM, TRIAGE_TOOL
name, ticket = sys.argv[1], sys.argv[2]
if not name.startswith("recorded_"):
sys.exit("fixture name must start with recorded_, so hand-written fixtures stay as they are")
client = anthropic.Anthropic() # reads ANTHROPIC_API_KEY from the environment
message = client.messages.create(
model=MODEL,
max_tokens=MAX_TOKENS,
system=SYSTEM,
tools=[TRIAGE_TOOL],
messages=[{"role": "user", "content": ticket}],
)
fixture = {
"_meta": {
"source": "recorded",
"recorded_at": datetime.date.today().isoformat(),
"model": MODEL,
"sdk": f"anthropic {anthropic.__version__}",
},
"status": 200,
"headers": {"request-id": message._request_id or ""},
"body": message.to_dict(mode="json"),
}
path = Path(__file__).parent / "fixtures" / f"{name}.json"
path.write_text(json.dumps(fixture, indent=2) + "\n")
print(f"wrote {path.name}: stop_reason {message.stop_reason}, {message.usage.output_tokens} output tokens")
PY
uv run python record_fixture.py tool_use_reply "test" 2>&1 | tee /tmp/record-guard.txt || true
grep -qF "fixture name must start with recorded_" /tmp/record-guard.txtThat command checks the guard: asked to write tool_use_reply, the script stops with that message before it makes any API call, and fixtures/tool_use_reply.json is untouched.
Run it with your real key from the private file made in calling an LLM API from Python. Each run is one paid call to Opus 5.5:
uv run --env-file ~/.config/llm-demo/env record_fixture.py recorded_tool_use_1042 "I was charged twice for order 1042."It prints something like wrote recorded_tool_use_1042.json: stop_reason tool_use, 240 output tokens, and test_recorded_tool_calls_parse now runs instead of skipping. If the stop reason is not tool_use, the model answered in prose, and the loose test fails because needs_review is not one of LABELS. That is a real finding: your system prompt no longer gets a tool call reliably. Read the new file before you commit it, and check git diff shows only the changes you expect.
The rule for refreshing, to keep in the project's README:
- Re-record every
recorded_fixture when you changeMODEL, the system prompt or the tool definition, or upgrade the SDK by a minor version. - Re-record when the age warning appears, and at least every 90 days. For a hand-written fixture, re-read the API reference and update the file and its
recorded_atdate by hand. - Never record over a hand-written fixture. Those back the exact assertions, and they cover cases a real model rarely produces on demand, such as
max_tokens_no_text,rate_limitedandoverloaded. - Use made-up tickets only, and never edit a recorded body by hand except to remove personal data.
Check it worked
Run the whole suite:
uv run pytest -q | tee /tmp/suite.txt
grep -q "12 passed, 1 skipped" /tmp/suite.txtpytest prints 12 passed, 1 skipped: 1 request test, 3 parsing tests, 3 error tests and 5 fixture checks, with the recorded-fixture test skipped until you record one. After you record recorded_tool_use_1042 it reads 14 passed: the loose parsing test runs, and the new file gets its own fixture check. More than 90 days after the recorded_at date in the hand-written fixtures you also see the age warning, which is the check doing its job. Run the suite with your network switched off and you get the same result.
Next steps
- Return a fixed JSON shape instead of a tool call, and add its fixture to this suite: get structured JSON output from an LLM.
- Go back to the basics of keys, errors and cost: call an LLM API from Python.
- Learn more pytest features used here, such as fixtures and
pytest.raises: write and run tests with pytest. - Reuse this stub, extended with server-sent events, to test streaming: stream Claude responses token by token in Python.
Related tutorials
- Send images and PDF documents to Claude from PythonYou will send Claude a receipt photo as base64 and by URL, a multi-page PDF with page citations, and a file uploaded once through the Files API, after checking each file against the documented limits and shrinking large photos with Pillow.
- Process thousands of prompts at half price with the Message Batches APIYou will tag 2,000 product reviews with Claude Haiku 5.5 through the Message Batches API, match results by custom_id, retry only the requests that failed or expired, and finish with a script you can stop and resume.
- Improve LLM answers with few-shot examples and measure the differenceYou will score a small local model on 40 labelled customer messages with zero, three and eight examples in the prompt, and end with a table that shows what the examples changed.
Need this done for you?
Padding does this work for growing companies, from the first diagnosis to a system that keeps working.
Get new tutorials