Sub topic 11
Choose between a fake and a recording
This chapter assumes you can write pytest tests and that your code already calls the model through a narrow client seam. It also assumes you have used a scripted fake and a record/replay client. Here you will learn how to pick one for each test.
The two techniques answer different questions
A scripted fake and a recorded response both let a test run offline, without cost, and with the same result every time. They differ in where the reply came from.
- With a fake, you wrote the reply. The test says "if the model returns this, my code does that."
- With a recording, the real model wrote the reply. The test says "my code handles what the model actually returned when I captured it."
That difference decides which bugs each one can catch. A fake can only contain situations you imagined. A recording can contain surprises, such as prose around the JSON or an unexpected field name, but it can only contain what happened on the day you recorded it.
| Property | Scripted fake | Recorded response |
|---|---|---|
| Source of the reply | You write it | The real model produced it |
| Setup cost | Low: a list in the test | Higher: needs a real call, an API key, and a file to commit |
| Failure modes it can cover | Anything you can script, including timeouts and rate limits | Only what the model did while recording |
| Catches wrong assumptions about reply shape | No, your assumption is baked into the fake | Yes, if the recording is recent |
| Test readability | High: input and output sit next to the assertion | Lower: the reply lives in another file |
| Maintenance | Rarely changes | Must be re-recorded when prompts or models change |
| Detects prompt changes | Only if you assert on `prompts` | Yes, if the match includes the prompt |
Questions that decide the choice
Ask these questions in order for each test. Stop at the first one that gives a clear answer.
- Does the test need a failure the model rarely produces? Examples are a malformed reply, a rate-limit exception, a timeout, or an empty string. Use a fake. You cannot get a real model to fail on demand, and a recording of a failure is hard to capture and easy to lose when you re-record.
- Does the test need a call sequence you control exactly? A retry that fails once and then succeeds is the usual case. Use a fake, because it replays replies in the order you script.
- Is the question "does my parser cope with what the model really says?" Use a recording. Your own sample reply will look the way you expect, so it tells you little about real output.
- Does the test cover a long or awkward reply that is tedious to write by hand? Examples are a multi-paragraph summary or a tool-call payload with nested arguments. A recording saves you from inventing realistic text.
- Is the logic around the model, such as routing, caching, or branching on a field? Use a fake. The exact text of the reply is irrelevant, so the shortest possible reply is best.
- Does the code use the vendor SDK directly, with no seam of your own? Recorded HTTP, such as a vcrpy cassette, is the practical option. You can only inject a fake where you own the interface.
If both fit, prefer the fake. It is cheaper to write, easier to read, and does not go stale.
A worked example: the same parser, two tests
Suppose a parser must pull a JSON object out of a model reply. The code below has two tests. The first uses a fake to check the happy path and the failure path. The second uses a reply captured from a real model, where the JSON is wrapped in chat text.
import json
import re
import pytest
def parse_total(reply: str) -> float:
match = re.search(r"\{.*\}", reply, re.DOTALL)
if match is None:
raise ValueError("no JSON object in reply")
return float(json.loads(match.group(0))["total"])
class FakeClient:
def __init__(self, replies):
self._replies = list(replies)
self.prompts = []
def complete(self, prompt: str) -> str:
self.prompts.append(prompt)
reply = self._replies.pop(0)
if isinstance(reply, Exception):
raise reply
return reply
class ReplayClient:
"""Serves replies captured earlier from a real model, keyed by prompt."""
def __init__(self, entries):
self.entries = entries
def complete(self, prompt: str) -> str:
return self.entries[prompt]
def get_total(client, invoice_text: str) -> float:
prompt = f"Return JSON with a 'total' field:\n{invoice_text}"
return parse_total(client.complete(prompt))
# Captured from a real model on the day the test was written.
RECORDED = {
"Return JSON with a 'total' field:\nTotal: $42.50": (
"Sure! Here is the invoice data:\n"
'{"total": 42.5}\n'
"Let me know if you need anything else."
)
}
def test_fake_covers_a_failure_you_script():
client = FakeClient(["I cannot read this invoice."])
with pytest.raises(ValueError):
get_total(client, "Total: $42.50")
def test_recording_covers_the_real_reply_shape():
client = ReplayClient(RECORDED)
assert get_total(client, "Total: $42.50") == 42.5The fake test is two lines of setup and needs nothing from a real model. The recorded test would have failed if parse_total had been a plain json.loads(reply), which is what a developer who only ever wrote tidy fakes would probably have written. The recording exposed an assumption that the fake hid.
In a real project, ReplayClient is the RecordingClient from the earlier chapter, reading its entries from a committed file. The inline dictionary here only keeps the example self-contained.
What a recording does not prove
A recording is a snapshot, not a guarantee. Three limits are worth knowing before you rely on one.
- One sample is not the distribution. The model may phrase the reply differently tomorrow. A single recording confirms that your code handles one real reply, not all of them. If the reply format matters, record two or three varied cases, such as a long invoice and an invoice with no total.
- The prompt is part of the key. If a recording is matched on the prompt hash, any edit to the prompt makes the entry unreachable. This is useful because it forces you to look at the reply again. It also means prompt tuning triggers many re-recordings. Keep prompts that change often out of recording-based tests.
- Recordings age. Model versions are retired and API shapes change. The next chapter covers drift and re-recording in detail. For this decision, treat the age of a recording as a cost that fakes do not have.
What a fake does not prove
A fake has its own blind spot: it can never disagree with you. If you believe the SDK raises RateLimitError and it raises a different class, your fake raises the wrong thing and your test passes. Fakes check your logic against your beliefs about the API.
Two habits reduce the risk:
- Build fake errors from the real exception classes of the SDK instead of inventing your own.
- Keep at least one recording-based test for each kind of reply your code parses, so a real reply is checked somewhere.
Combining both in one suite
Most projects end up with a layered suite. Each layer uses the cheapest tool that can answer its question.
- Many small tests with fakes. These cover branching, retries, error handling, prompt contents, and anything that depends on a scripted sequence. They make up the bulk of the suite.
- A few tests with recordings. These cover parsing of real replies, tool-call payloads, and long outputs. Keep one recording per distinct reply shape, not one per feature.
- A very small number of live checks. These run outside the normal test run and are covered at the end of this tutorial.
The goal is not an even split. A suite where every test replays a recording is slow to maintain, and a suite where every test uses a hand-written fake never meets real output.
Common mistakes
- Recording to avoid thinking about the input. If a test only needs "any valid reply," a recording adds a file and a maintenance burden for no benefit. Use a one-line fake.
- Using a fake to test the parser against your own examples only. If every sample reply is written by the same person who wrote the parser, the parser and the samples share the same blind spots.
- Trying to record failures. Rate limits and timeouts cannot be produced on demand, and a cassette of an outage will be accidentally overwritten the next time you re-record. Script these with a fake.
- Asserting on exact model wording in a recording test. The recording is stable, but the assertion then ties your test to one phrasing. Assert on the parsed result, such as the extracted total, not on the raw text.
- Forgetting to assert on the prompt. Neither technique checks what you sent unless you ask. With a fake, assert on
client.prompts. With a recording, a prompt-based key already makes a changed prompt fail loudly.
Summary of the decision
Use a fake when you control the scenario: errors, retries, ordering, and logic that ignores the reply text. Use a recording when the real model's output is the thing under test: reply shape, wording variations, and long or nested payloads. Keep both, keep recordings few, and let the fakes carry most of the weight.
Exercise
Your function calls the model, then retries up to three times if the reply is not valid JSON. You want to test (a) that it gives up after three bad replies and (b) that it correctly parses a long, nested JSON reply the model produced for a real customer request. Which technique do you use for each, and why?
Show answer
Use a scripted fake for (a). You need exactly three bad replies in a row, and a real model will not produce that on demand. Use a recording for (b). The reply is long and nested, so writing it by hand is tedious, and the point is to check the parser against output a real model actually produced. Redact any customer data in the recording before committing it.
Exercise
A teammate's test passes against a fake that returns '{"total": 42.5}'. In production the parser fails because the model replies with a sentence before the JSON. Why did the fake not catch this, and what is the smallest change to the test suite that would?
Show answer
The fake was written by the same person who wrote the parser, so it encoded the same assumption that the reply is bare JSON. A fake cannot disagree with its author. Add one recording-based test using a reply captured from the real model, which contains the surrounding sentence. That test fails against the old parser and drives the fix.