Sub topic 4
Build a scripted fake client
This chapter assumes you can write pytest tests, know basic Python classes and exceptions, and have already put your model calls behind a narrow client interface (the seam from the previous chapter). Here you build the test double that plugs into that seam.
What a scripted fake does
A scripted fake is a small class that implements the same method as your real client. You hand it a list of replies when you create it. Each call to complete returns the next reply in order. It also remembers every prompt it received, so the test can check what your code sent.
It does three jobs:
- It returns canned replies, so the test gives the same result on every run.
- It records prompts, so you can assert on the input as well as the output.
- It fails loudly when the script is wrong, so a test never silently gets an unexpected value.
The code under test
This function depends only on a ChatClient protocol, which is any object with a complete(prompt) -> str method.
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"])Because extract_total never imports an SDK, a test can pass in anything that has the right method.
The fake and a first test
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 reply
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]Some details in this class are deliberate.
list(replies)copies the input. Popping from the copy does not change the list the test passed in.- The prompt is stored before anything else happens. If the fake raises, the test can still see what was sent.
- An empty script raises
AssertionError, notIndexError. That tells you the code made more calls than the test expected, which is usually a bug in the code or in the test. - If a scripted item is an
Exceptioninstance, the fake raises it instead of returning it. The next chapter uses this to simulate timeouts and rate limits.
Assert on prompts, but not too tightly
The assertion "Total: $42.50" in client.prompts[0] checks that the invoice text reached the model. It does not compare the whole prompt string. An exact comparison breaks every time you reword the instructions, even when behavior is unchanged. Check the parts that carry meaning: the user data, a required field name, or the number of calls.
Common mistakes
- Replies that are too clean. Real models add code fences, extra text, or trailing commas. Script a few realistic bad replies, not only perfect ones.
- Sharing one fake across tests. The fake holds state. Create a new one in each test, or in a fixture with the default function scope.
- Mocking the SDK instead of the seam. Patching
openai.OpenAIties your tests to library internals. A fake at your own interface survives an SDK upgrade. - A fake that is smarter than the code. If the fake contains branching logic that mirrors the real model, you are testing your fake. Keep it to "pop and return."
Exercise
A test creates FakeClient(['{"total": 1}']) and calls code that invokes complete twice. What happens, and why is that useful?
Show answer
The second call finds no scripted replies left and raises AssertionError("FakeClient ran out of scripted replies"). The test fails right away and shows that the code made more model calls than the test expected, instead of returning a made-up value.
Exercise
Add a method to FakeClient called assert_exhausted that fails the test if any scripted replies were never used. Write it.
Show answer
def assertexhausted(self): assert not self.replies, f"{len(self._replies)} scripted replies were never used"