Sub topic 7
Record real responses and replay them offline
This chapter assumes you can write pytest tests, read basic Python classes and exceptions, and have called an LLM API and parsed its JSON reply. It also assumes you know dependency injection, meaning you pass a dependency to a function as an argument. You should already have the narrow ChatClient seam and the scripted fake from the earlier chapters.
Why scripted fakes are not always enough
A scripted fake returns whatever you wrote by hand. That is ideal for testing your own logic: retries, error handling, and parsing rules. It has one weakness. You wrote the reply, so it only contains the shapes you imagined.
Real model output is messier. It may wrap JSON in a Markdown fence, add a sentence before the JSON, use a different key casing, or return numbers as strings. A hand-written fake will not surprise you with any of these.
A recorded response fixes that. You call the real model once, save the reply to a file, and replay it in every later test run. The test then runs on real output, but it needs no network, no API key, and no money.
A minimal recording client
The client below sits behind the same one-method ChatClient seam. The code under test cannot tell it apart from the real client or from the fake.
import hashlib
import json
import os
class RecordingClient:
"""Replays saved replies; calls the real client only for prompts not yet recorded."""
def __init__(self, path, real_client=None):
self.path = path
self.real_client = real_client
self.entries = {}
if os.path.exists(path):
with open(path, encoding="utf-8") as f:
self.entries = json.load(f)
def complete(self, prompt: str) -> str:
key = hashlib.sha256(prompt.encode("utf-8")).hexdigest()
if key not in self.entries:
if self.real_client is None:
raise LookupError(
"No recorded reply for this prompt. Re-record with a real client."
)
self.entries[key] = self.real_client.complete(prompt)
with open(self.path, "w", encoding="utf-8") as f:
json.dump(self.entries, f, indent=2, sort_keys=True)
return self.entries[key]Three design choices matter here.
- The key is a hash of the prompt. The same prompt always maps to the same entry. If someone edits the prompt template, the hash changes, the lookup misses, and the test fails loudly. Without this, a stale reply could keep a test green after the prompt it was recorded for no longer exists.
- Replay mode has no real client. When
real_clientisNone, a missing entry raisesLookupError. The test suite can never reach the network by accident. - The file is written with
sort_keys=Trueandindent=2. Output is stable between runs, so a re-recording produces a small, readable diff in version control.
Recording once, replaying always
The workflow has two modes. In record mode you pass a real client. In replay mode you pass nothing.
The helper below chooses the mode from an environment variable, so the default is always replay.
import os
def make_client(path):
if os.environ.get("RECORD_LLM") == "1":
from my_app.llm import build_real_client # your own SDK wrapper
return RecordingClient(path, real_client=build_real_client())
return RecordingClient(path)my_app.llm.build_real_client stands for whatever function in your project creates the SDK-backed client. Replace it with your own.
A test then looks like this:
import pytest
@pytest.fixture
def client(request):
return make_client("tests/recordings/extract_total.json")
def test_extract_total_from_real_reply(client):
assert extract_total(client, "Invoice 18\nTotal: $42.50") == 42.5To create the recording, run the test once with the variable set:
RECORD_LLM=1 pytest tests/test_extract.py::test_extract_total_from_real_replyCommit tests/recordings/extract_total.json. After that, a plain pytest run replays the file in milliseconds.
If the real model wraps its JSON in a Markdown fence, json.loads fails on the recording. You now have a real failing case. Fix extract_total to strip the fence, and the saved reply keeps guarding that fix from then on. This is the main payoff of recording.
Recording at the HTTP level with vcrpy
The client above records at the seam. That means your own wrapper is bypassed in replay mode, so the code that builds the HTTP request and parses the SDK response is not exercised.
A second option is to record the HTTP traffic itself. The vcrpy library intercepts HTTP calls made by the real SDK and stores each request and response pair in a file called a cassette. In replay mode the SDK runs normally, and vcrpy answers its requests from the cassette.
import vcr
my_vcr = vcr.VCR(
cassette_library_dir="tests/cassettes",
record_mode="none",
filter_headers=["authorization", "x-api-key"],
match_on=["method", "uri", "body"],
)
@my_vcr.use_cassette("summarize.yaml")
def test_summarize_replays_recorded_http():
... # call code that uses the real SDK; HTTP traffic is replayed from the cassetteThe three options each do one job:
record_mode="none"replays existing recordings and forbids any new network call. A request with no matching entry raises an error instead of reaching the network.filter_headersremoves the listed headers before the cassette is written, so your API key does not end up in version control.match_onlists which parts of an incoming request must equal the recorded one before vcrpy returns the saved response.
To make a new cassette, switch to record_mode="once" for one run. With once, vcrpy records if the cassette file does not exist and replays if it does. Then switch back to none.
Which level to record at
| Row | Seam-level recording | HTTP-level recording |
|---|---|---|
| What is replayed | The string returned by `complete` | The raw HTTP response |
| SDK and wrapper code covered | No | Yes |
| Depends on SDK internals | No | Yes, request body format can change on SDK upgrade |
| Recording file | Small JSON of prompt hash to text | Larger files with headers and full bodies |
| Secret exposure risk | Low, only prompts and replies | Higher, headers and URLs are captured |
Start with seam-level recording. It is simpler, and it survives an SDK upgrade. Add HTTP-level recording only when you need to test the code between your seam and the network.
Edge cases to plan for
Non-determinism in the prompt. If the prompt contains a timestamp, a random ID, or a dictionary printed in unstable order, the hash differs on every run and replay always misses. Make the prompt a pure function of its inputs, or pass the clock and ID generator in as arguments so tests can fix them.
Two calls with the same prompt. The client above stores one reply per prompt. If the code calls the model twice with an identical prompt and expects different answers, for example a retry, replay returns the same text both times. Test retry logic with a scripted fake instead, which can return a bad reply followed by a good one.
Concurrent tests. If tests run in parallel and several record into the same file, writes can overwrite each other. Use one recording file per test, or record serially.
Whitespace in prompts. A trailing newline changes the hash. That strictness is useful, but it means a harmless formatting edit invalidates recordings. Re-record deliberately, and review the diff.
Recordings that hide a bug. A recording proves the code handles that one reply. It does not prove the model will keep producing it. A later chapter covers drift and smoke tests, which catch this.
Keeping recordings reviewable
Treat a recording like a snapshot test fixture. Keep one per test or per small group of tests, so a diff shows exactly which behavior changed. Open the file before you commit it. If you cannot read it in a code review, it is too large or too noisy.
Checklist
- Put the recorder behind the same
ChatClientseam as the fake. - Default to replay. Require an explicit switch such as
RECORD_LLM=1to record. - Make a missing recording a loud failure.
- Record using synthetic inputs.
- Read the recording and commit it with the test.
Exercise
A teammate edits the wording of the prompt template in extract_total. After the change, a test that uses RecordingClient in replay mode fails with LookupError. Is this a bug in the test, and what should the teammate do?
Show answer
It is not a bug. The key is a hash of the exact prompt, so the new wording produces a new hash with no recorded entry. This is the intended safeguard, because the old reply was produced for the old prompt and could hide a regression. The teammate should re-record with RECORD_LLM=1, read the changed recording, check that the code still parses the new reply, and commit the updated file with the prompt change.
Exercise
A function calls the model, and on invalid JSON it calls the model again with the same prompt. Why is RecordingClient a poor tool for testing the retry path, and what should you use instead?
Show answer
RecordingClient stores one reply per prompt hash, so both calls get the same saved text. If the first reply was invalid, the retry gets the same invalid reply, and you can never reach the success path. A scripted fake that returns a malformed reply first and a valid one second exercises the retry deterministically.
Exercise
You record with vcrpy using match_on=["method", "uri"] only. Your code later changes the request body, for example a different model name, but the test still passes in replay. Why, and how do you fix it?
Show answer
Because the body is not in match_on, vcrpy treats any request to the same method and URI as a match and returns the old response. Add "body" to match_on so a changed request fails to match, then re-record.