Sub topic 5
Inject errors and malformed output
The scripted fake from the previous chapter can return good replies in order. This chapter uses it for the cases a live model almost never produces on demand: API errors, timeouts, empty replies, truncated JSON, and replies with the wrong shape. You will script these failures and check that your code handles each one in a defined way.
Prerequisites
This chapter assumes you have:
- written pytest tests, including
pytest.mark.parametrizeandpytest.raises - a
ChatClientseam, meaning a one-method protocol your code receives as an argument - the scripted
FakeClientfrom the previous chapter, which returns replies in order and records the prompts it receives
Why failures need injection
Production LLM code fails in ways you rarely see during development. Providers return rate-limit errors under load. Requests time out. A model asked for JSON sometimes wraps it in prose, cuts it off at the token limit, or leaves out a field. If the first time your code meets these cases is in production, you have not tested it.
A live model cannot be asked to fail on request. A fake can. Scripting a failure makes the test deterministic and instant, and it costs nothing.
Two kinds of failure
Keep two categories separate, because the code responds to them differently.
- Transport failures. The call itself fails: rate limit, timeout, connection reset, server error. No reply exists. The usual responses are to retry, back off, or give up.
- Content failures. The call succeeds but the reply is unusable: not JSON, wrong keys, wrong types. A retry with the same prompt might help, or the prompt might need repair.
The two categories need different exception types, so the code can tell them apart. Define them at the seam, in your own module, instead of leaking SDK exception classes into the rest of the program.
The code under test
This module defines the error types and a stricter extract_total. It wraps every parsing problem in BadReply and lets transport errors pass through untouched.
# invoice.py
import json
import math
class LLMError(Exception):
"""Base class for transport failures raised by the client seam."""
class RateLimitError(LLMError):
pass
class LLMTimeout(LLMError):
pass
class BadReply(Exception):
"""The model answered, but the answer is unusable."""
def extract_total(client, invoice_text: str) -> float:
reply = client.complete(
f"Return JSON with a 'total' field for this invoice:\n{invoice_text}"
)
try:
data = json.loads(reply)
total = data["total"]
if isinstance(total, bool):
raise TypeError("total must be a number, not a boolean")
total = float(total)
except (ValueError, KeyError, TypeError) as exc:
raise BadReply(f"unusable reply: {reply[:80]!r}") from exc
if not math.isfinite(total):
raise BadReply(f"total is not finite: {total}")
return totalThree details matter here.
json.JSONDecodeErroris a subclass ofValueError, so oneexceptclause covers invalid JSON andfloat("abc").- A top-level list such as
[42.5]raisesTypeErrorwhen you index it with a string. A string reply such as"hello"fails the same way. - Python's
json.loadsacceptsNaNandInfinityby default, andfloat(True)returns1.0. Without the two extra checks, both would pass as valid totals.
Raising errors from the fake
The fake from the previous chapter already raises any Exception instance found in its script. Here it is again, so this chapter stands alone.
# fakes.py
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 replyThe fake records the prompt before it raises. That order matters: a test can then confirm the code made the call that failed.
A transport failure test is short.
# test_failures.py
import pytest
from fakes import FakeClient
from invoice import (
BadReply,
LLMTimeout,
RateLimitError,
extract_total,
)
def test_rate_limit_propagates_and_is_not_a_bad_reply():
client = FakeClient([RateLimitError("429 Too Many Requests")])
with pytest.raises(RateLimitError):
extract_total(client, "Total: $42.50")
assert len(client.prompts) == 1
def test_timeout_propagates():
client = FakeClient([LLMTimeout("read timed out after 30s")])
with pytest.raises(LLMTimeout):
extract_total(client, "Total: $42.50")The assertion len(client.prompts) == 1 checks that nothing retries silently. If a later change adds a hidden retry loop, this test fails, and you decide on purpose whether that is what you want.
No test sleeps. The fake raises LLMTimeout immediately, so you test the handling of a timeout without waiting for one.
Scripting malformed replies
A parametrized test gives each bad reply its own named case. The id shows up in the pytest output, so a failure tells you which shape broke.
MALFORMED_REPLIES = [
pytest.param("", id="empty"),
pytest.param('{"total": 42.5', id="truncated-json"),
pytest.param('Sure! {"total": 42.5}', id="prose-around-json"),
pytest.param('```json\n{"total": 42.5}\n```', id="markdown-fence"),
pytest.param('{"amount": 42.5}', id="missing-key"),
pytest.param('{"total": "forty-two"}', id="non-numeric-string"),
pytest.param('{"total": null}', id="null-total"),
pytest.param('{"total": true}', id="boolean-total"),
pytest.param("[42.5]", id="list-instead-of-object"),
pytest.param('{"total": NaN}', id="nan"),
]
@pytest.mark.parametrize("reply", MALFORMED_REPLIES)
def test_malformed_reply_raises_bad_reply(reply):
client = FakeClient([reply])
with pytest.raises(BadReply):
extract_total(client, "Total: $42.50")Each entry mirrors something real models do. Truncation happens when the output hits the token limit. Prose and Markdown fences appear when the model is chatty. A missing key or a null appears when the invoice text did not contain the field.
Two of these cases show a decision, not a bug. prose-around-json and markdown-fence hold a valid payload, and you could write a tolerant parser that strips the fence and accepts them. The test above documents that this code rejects them. If you add a tolerant parser later, move those two cases into a "should succeed" test. The parametrized list is where that decision lives.
Failures in the middle of a sequence
Real code often makes several calls. A fake that mixes good replies, errors, and bad output tests what happens to the whole batch.
# batch.py
from invoice import BadReply, LLMError, extract_total
def process_batch(client, invoices):
"""Return (totals, failures). One bad invoice must not stop the rest."""
totals, failures = {}, {}
for name, text in invoices.items():
try:
totals[name] = extract_total(client, text)
except (LLMError, BadReply) as exc:
failures[name] = type(exc).__name__
return totals, failures# test_batch.py
from batch import process_batch
from fakes import FakeClient
from invoice import RateLimitError
def test_batch_continues_after_failures():
client = FakeClient([
'{"total": 1}',
RateLimitError("429"),
"oops",
'{"total": 4}',
])
invoices = {"a": "A", "b": "B", "c": "C", "d": "D"}
totals, failures = process_batch(client, invoices)
assert totals == {"a": 1.0, "d": 4.0}
assert failures == {"b": "RateLimitError", "c": "BadReply"}
assert len(client.prompts) == 4The script is positional, so the test depends on the order of calls. That is fine for a loop over a dictionary, because Python keeps insertion order. If your code makes calls in parallel, positional scripts become unreliable. A fake that picks its reply by matching the prompt is safer there, and the chapter on matching requests covers that idea.
What to inject
This table lists a starting set. Add cases when production shows you a new one.
| Failure | How to script it | What to assert |
|---|---|---|
| Rate limit | `RateLimitError("429")` | Propagates or is retried, as designed. |
| Timeout | `LLMTimeout("...")` | Propagates or is retried, as designed. |
| Empty reply | `""` | `BadReply`, not a crash in the parser. |
| Truncated JSON | A valid payload cut mid-way | `BadReply`. |
| Wrong shape | A list, a string, a missing key | `BadReply`. |
| Wrong type | `null`, a boolean, a non-numeric string | `BadReply`. |
| Out-of-range value | `NaN`, a negative total | The rule your code states. |
| Script exhausted | Fewer replies than calls | `AssertionError` from the fake. |
Common mistakes
- Asserting on the exception message. Match on the exception type. Messages change, and a test that pins the wording breaks for no good reason.
- Catching
Exceptionin the code under test. A broad catch makes every malformed-reply test pass, including ones where the cause is a typo in your own code. Catch the specific types you expect. - Injecting only transport errors, or only bad content. Write both. They exercise different branches.
- Using one shared exception instance across tests. Exceptions carry tracebacks. Create a fresh instance in each test or fixture.
- Letting the fake hide a missing call. If the code under test makes fewer calls than the script holds, leftover replies go unnoticed. Add an assertion on
len(client.prompts), or give the fake a method that checks the script was fully consumed.
What this chapter does not cover
The tests here check that failures are detected and classified. They do not check what the code does next, such as retrying with a limit or giving up with a clear error. That behavior is the subject of the next chapter, which builds on the same scripted failures.
Exercise
A teammate's extract_total wraps the whole body in except Exception: raise BadReply(...). Their parametrized malformed-reply test passes for all ten cases. Name one problem this introduces and one test you would add to expose it.
Show answer
The broad catch converts transport failures into BadReply, so a RateLimitError or LLMTimeout is mislabeled as a content problem. Any caller that retries only on transport errors, or that treats BadReply as "fix the prompt", will then take the wrong action. It also hides programming errors such as a typo that raises NameError. Add a test like test_rate_limit_propagates_and_is_not_a_bad_reply: script FakeClient([RateLimitError("429")]) and assert pytest.raises(RateLimitError). With the broad catch, that test fails because BadReply is raised instead.
Exercise
Add a case to MALFORMED_REPLIES for a reply whose total is a negative number, and decide where the check belongs. What change to extract_total makes the case pass?
Show answer
Add pytest.param('{"total": -5}', id="negative-total"). The check belongs in extract_total, next to the math.isfinite check, because a negative invoice total is a content failure and callers should receive BadReply. Add if total < 0: raise BadReply(f"total is negative: {total}") after the finite check. If your business rules allow credit notes with negative totals, skip the check and move the case into a test that expects success.