Sub topic 5
Inject errors and malformed output
This chapter assumes you can write pytest tests, you know Python exceptions, and you have the scripted FakeClient from the previous chapter. The goal is to make failures happen on demand, so your error handling is tested instead of hoped for.
Why failures need to be injected
A live model rarely fails when you want it to. Real failures are rare, random, and hard to repeat: a rate limit, a timeout, a reply wrapped in prose, a JSON object missing a field. Code that handles these cases is still code, and untested handlers tend to break the first time they run in production.
A scripted fake solves this. You decide what the client returns, call by call, so each failure becomes an ordinary, repeatable test.
The fake already supports failures
Here is the fake again. The key lines are the ones that check whether a scripted reply is an exception.
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 replyIf a scripted item is a string, the fake returns it. If it is an exception instance, the fake raises it. That lets one list describe a whole sequence, such as "fail with a timeout, then succeed."
Two kinds of failure
Model code fails in two different ways, and they need different tests.
| Kind | What happens | How to script it |
|---|---|---|
| API error | The call itself raises, such as a timeout or a rate limit | Put an exception instance in the list |
| Malformed output | The call succeeds but the text is unusable | Put a bad string in the list |
Keep the two separate. An API error means you never got text. Malformed output means you got text your parser cannot use.
Malformed output
Common bad replies include text that is not JSON, JSON missing a required key, and JSON with the wrong type. Each is a separate case worth one test.
import json
import pytest
def extract_total(client, 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"])
@pytest.mark.parametrize(
"bad_reply, error",
[
("Sure! The total is 42.50", json.JSONDecodeError),
('{"amount": 42.5}', KeyError),
('{"total": "n/a"}', ValueError),
("", json.JSONDecodeError),
],
)
def test_extract_total_rejects_bad_replies(bad_reply, error):
client = FakeClient([bad_reply])
with pytest.raises(error):
extract_total(client, "Total: $42.50")Parametrizing keeps each case visible in the test report. Note that json.JSONDecodeError is a subclass of ValueError, so the third case would also match a looser check. Use the most specific exception you can, so the test fails if the code starts raising something different.
API errors
Pass an exception instance directly. This example uses a plain TimeoutError so it runs without any SDK. In real code, use the exception types your SDK raises.
def total_or_none(client, invoice_text: str):
try:
return extract_total(client, invoice_text)
except TimeoutError:
return None
def test_timeout_is_handled():
client = FakeClient([TimeoutError("simulated timeout")])
assert total_or_none(client, "x") is None
assert len(client.prompts) == 1Checking client.prompts confirms the code made exactly one attempt and did not loop.
Mixing failures and successes
The most useful scripts combine both. This one fails once, then recovers.
def extract_with_timeout_retry(client, invoice_text, attempts=3):
for attempt in range(attempts):
try:
return extract_total(client, invoice_text)
except TimeoutError:
if attempt == attempts - 1:
raise
def test_recovers_after_one_timeout():
client = FakeClient([TimeoutError("slow"), '{"total": 7}'])
assert extract_with_timeout_retry(client, "x") == 7.0
assert len(client.prompts) == 2The next chapter builds on this pattern to test full retry and validation logic.
Common mistakes
- Scripting too few replies. The fake raises
AssertionErrorwhen it runs out, which correctly shows the code called the model more often than expected. - Scripting too many replies. Assert on
len(client.prompts)so unused replies do not hide a missing retry. - Using
pytest.raises(Exception). It passes for almost any bug, including typos. - Inventing error types. Raise the real exception classes your SDK uses, or your handler may catch something the SDK never throws.
Exercise
Write a FakeClient script that tests code which retries up to 3 times on a malformed reply. The script should make the first two replies malformed and the third valid. What should the test assert about the prompts, and why?
Show answer
Use FakeClient(["oops", '{"amount": 1}', '{"total": 5}']). The test should assert the result equals 5.0 and that len(client.prompts) == 3. The prompt count proves the code retried exactly twice and stopped after success, instead of returning early or making extra calls.