Sub topic 4
Build a scripted fake client
This chapter builds the main tool for testing code that calls an LLM: a scripted fake client. It assumes you can write pytest tests, you know Python classes and exceptions, you have called an LLM API and parsed JSON replies, and you can pass a dependency as an argument. It also assumes the narrow ChatClient seam from the previous chapter, a protocol with one complete(prompt) -> str method.
What a scripted fake is
A scripted fake is a small class that has the same method as your real client but never touches the network. You give it a list of replies when you create it. Each call to complete returns the next reply in the list.
Three properties make it useful for LLM code:
- It is deterministic. The same script gives the same behavior on every run, on every machine.
- It is fast and free. A test finishes in microseconds and spends no tokens.
- It is inspectable. It remembers every prompt it received, so a test can check what your code sent as well as what it did with the reply.
The seam looks like this:
import json
from typing import Protocol
class ChatClient(Protocol):
def complete(self, prompt: str) -> str: ...
def extract_total(client: ChatClient, invoice_text: str) -> float:
reply = client.complete(
f"Return JSON with a 'total' field for this invoice:\n{invoice_text}"
)
data = json.loads(reply)
return float(data["total"])extract_total depends only on the protocol. It does not import an SDK, read an API key, or know whether a real model is on the other end. That is why a test can hand it any object with a complete method.
The fake
Here is the whole fake. It is about fifteen lines.
class FakeClient:
def __init__(self, replies):
self._replies = list(replies)
self.prompts = []
def complete(self, prompt: str) -> str:
self.prompts.append(prompt)
if not self._replies:
raise AssertionError("FakeClient ran out of scripted replies")
reply = self._replies.pop(0)
if isinstance(reply, Exception):
raise reply
return replyEach part of it does one job.
| Part | Purpose |
|---|---|
| `list(replies)` | Copies the script, so the caller's list is not changed when the fake pops from it. |
| `self.prompts` | Records every prompt, in order, so tests can assert on what was sent. |
| `pop(0)` | Returns replies in the order you scripted them. |
| `isinstance(reply, Exception)` | Lets the script contain errors. The fake raises them instead of returning them. |
| `AssertionError` when empty | Fails the test loudly if the code calls the client more times than you planned. |
The last two rows deserve a closer look, so the next sections cover them. The error-raising part is developed further in the chapter on failure injection.
Your first test
def test_extract_total():
client = FakeClient(['{"total": 42.5}'])
assert extract_total(client, "Total: $42.50") == 42.5
assert "Total: $42.50" in client.prompts[0]The test has three steps.
- Arrange: create a fake whose only reply is a JSON string.
- Act: call
extract_totalwith the fake in place of a real client. - Assert: check the returned value, and check that the invoice text appears in the prompt.
The second assertion matters. If someone later changes the prompt-building code and drops the invoice text, the reply would still parse and the first assertion would still pass. A model would then be asked about nothing. Checking client.prompts[0] catches that class of bug.
A fake like this tests your code, not the model. You are not checking that the model can read invoices. You are checking that your code builds a sensible prompt, parses the reply, and converts the value.
Design choices in the fake
Why scripted replies and not one fixed reply
A simpler fake could return the same string every time. That works for a single call, but LLM code often makes several calls: a retry after bad output, a follow-up question, or a loop over many documents. A script lets each call get a different reply. It also makes call counts part of the test, because an unused reply can be detected and an extra call fails.
Why the fake fails when the script runs out
If the fake returned a default reply once the script was empty, a bug that causes an extra call would go unnoticed. Raising AssertionError turns "my code called the model one time too many" into a clear test failure with a message that names the cause.
You can add the opposite check too. After the code under test finishes, assert that the fake used all its replies:
def test_uses_every_scripted_reply():
client = FakeClient(['{"total": 1}'])
extract_total(client, "x")
assert client._replies == []Reading a private attribute from a test is a small shortcut. If you do it often, add a public remaining property instead.
Why the fake raises exceptions from the script
Real clients fail in ways that return nothing useful: timeouts, rate limits, dropped connections. Putting an exception object in the script lets a test place a failure at an exact position in a sequence of calls:
client = FakeClient([TimeoutError("slow"), '{"total": 10}'])The first call raises TimeoutError. The second returns valid JSON. This is how you test a retry loop without waiting for a real timeout.
Why record prompts rather than count calls
A call count tells you how many times the code called the client. The stored prompts tell you what it said each time. Prompts are where most bugs in LLM code live: a missing variable, a truncated document, instructions in the wrong order. Storing them costs one list.
Using the fake to test retries
Scripted order is what makes retry tests possible. Here is code that retries when the model returns malformed output:
def extract_total_with_retry(client, invoice_text, attempts=2):
last_error = None
for _ in range(attempts):
try:
return extract_total(client, invoice_text)
except (json.JSONDecodeError, KeyError) as exc:
last_error = exc
raise ValueError("model never returned valid JSON") from last_errorA live model almost never returns bad JSON on demand, so you cannot reliably reproduce this path against one. With the fake you script it:
def test_retries_after_malformed_reply():
client = FakeClient(["not json", '{"total": 10}'])
assert extract_total_with_retry(client, "x") == 10.0
assert len(client.prompts) == 2
def test_gives_up_after_repeated_bad_replies():
import pytest
client = FakeClient(["nope", "still nope"])
with pytest.raises(ValueError):
extract_total_with_retry(client, "x")The first test proves that a bad reply followed by a good one succeeds, and that exactly two calls were made. The second proves that when every attempt fails, the function raises ValueError rather than returning garbage or looping forever.
Both tests run in a few milliseconds. The later chapter on parsing and retry logic covers more cases, such as valid JSON with the wrong shape.
Fake, stub, or mock
People use these words loosely. This fake is closest to a stub with a recorder attached: it supplies canned answers and it remembers its inputs. It is not a mock in the strict sense, because it does not carry expectations that it verifies itself. The test does the asserting. Keeping the assertions in the test makes failures easier to read, because the failing line is in your test and not inside a helper.
Common errors
- Sharing one fake between tests. The script is consumed as calls happen, so reusing an instance leaks state from one test to the next. Create a fresh fake inside each test, or in a pytest fixture with function scope.
- Passing a list and then changing it. The constructor copies the list for this reason. If you remove the copy,
pop(0)mutates the caller's data. - Scripting a reply that the real model would never produce. A fake only proves your code handles the replies you wrote. If you invent a tidy
{"total": 42.5}and the real model wraps its answer in a Markdown fence, your tests pass and production fails. Copy real replies into your scripts when you can, and see the chapter on recorded responses for the more systematic version. - Over-asserting on prompt text.
assert client.prompts[0] == "...the whole prompt..."breaks whenever you reword the instructions. Assert on the parts that carry meaning, such as the invoice text, and leave the wording alone. - Raising the exception class instead of an instance.
FakeClient([TimeoutError])stores a class, soisinstance(reply, Exception)is false and the fake returns the class as if it were text. ScriptTimeoutError("slow")with parentheses. - Forgetting that
pop(0)on a list is O(n). For a handful of replies this does not matter. If a test scripts thousands of replies, usecollections.dequeandpopleft.
Where this fits
The scripted fake is the base for the rest of the tutorial. Failure injection reuses its exception handling. Parsing and retry tests build on its ordered replies. Recorded responses reuse the same one-method interface, so the code under test does not change when you switch from a fake to a recording.
Exercise
Write a test for extract_total_with_retry that checks the second prompt sent to the model is identical to the first prompt. Then say what this test would reveal if a future change added the previous error message to the retry prompt.
Show answer
Script one bad reply and one good reply, then compare the recorded prompts: def testretryresendssameprompt(): client = FakeClient(["not json", '{"total": 10}']) extracttotalwithretry(client, "Total: $10") assert client.prompts[0] == client.prompts[1] The test passes today because `extracttotal` builds the same prompt on each attempt. If a change appended the previous error to the retry prompt, the two prompts would differ and this test would fail. That is a signal to decide whether the new behavior is intended. If it is, update the test to assert that the second prompt contains the error text and still contains the invoice text.
Exercise
A teammate writes client = FakeClient([ValueError]) to simulate an API failure, and the test never sees an exception. Why, and how do you fix it?
Show answer
ValueError without parentheses is the class, not an instance, so isinstance(reply, Exception) is false. The fake returns the class object as if it were a reply, and the code under test then fails later with an unrelated error, or not at all. Fix it by scripting an instance: FakeClient([ValueError("boom")]). You could also make the fake stricter by checking isinstance(reply, type) and issubclass(reply, Exception) and raising that too.