Sub topic 6
Test parsing, validation, and retry logic
This chapter covers the code that sits between the model and the rest of your program: the parser that reads a reply, the validator that decides whether it is usable, and the retry loop that asks again when it is not. All of it is ordinary deterministic Python, so it can be tested thoroughly with a scripted fake.
You should already be comfortable with these:
- pytest basics, including
parametrizeandpytest.raises. - Python exceptions and classes.
- JSON replies from an LLM API.
- Passing a client into a function as an argument.
- The
ChatClientseam and the scriptedFakeClientfrom the earlier chapters.
What can go wrong with a reply
A model reply is untrusted input. It can fail in several distinct ways, and each failure should have its own test.
| Failure | Example reply | Where it is caught |
|---|---|---|
| Not JSON at all | `Sure! The total is 42.5` | Parser |
| Empty reply | an empty string | Parser |
| Wrong JSON shape | `[1, 2]` | Validator |
| Missing field | `{"amount": 3}` | Validator |
| Wrong type | `{"total": "42.5"}` or `{"total": true}` | Validator |
| Impossible value | `{"total": -1}` or `{"total": NaN}` | Validator |
| Transport failure | a timeout raised by the SDK | Not a reply problem. Handle it separately |
The last row matters for retries. A bad reply and a failed request are different problems, and they usually need different handling. The tests below keep them apart.
Separate parsing from the model call
The first design choice makes testing easy: put parsing and validation in a pure function. It takes a string and returns a value or raises. It never touches a client.
import json
import math
class ReplyError(ValueError):
"""The model's reply could not be used."""
def parse_total(reply: str) -> float:
try:
data = json.loads(reply)
except json.JSONDecodeError as exc:
raise ReplyError(f"reply is not JSON: {exc}") from exc
if not isinstance(data, dict) or "total" not in data:
raise ReplyError("reply has no 'total' field")
total = data["total"]
# bool is a subclass of int in Python, so exclude it explicitly.
if isinstance(total, bool) or not isinstance(total, (int, float)):
raise ReplyError(f"'total' must be a number, got {total!r}")
if not math.isfinite(total) or total < 0:
raise ReplyError(f"'total' out of range: {total!r}")
return float(total)Two details here come from real failures. Python's json.loads accepts NaN and Infinity by default, so the isfinite check is needed. And float(True) returns 1.0, so a model that answers true would otherwise pass as a valid total.
ReplyError subclasses ValueError but is its own type. The retry loop catches only ReplyError, so a genuine bug elsewhere, such as a TypeError, is not silently retried.
Test the parser with a table
Parsing tests need no fake client, because they take strings directly. pytest.mark.parametrize turns each failure mode into one row.
import pytest
@pytest.mark.parametrize(
("reply", "expected"),
[
('{"total": 42.5}', 42.5),
('{"total": 7}', 7.0),
('{"total": 0}', 0.0),
('{"total": 3, "currency": "USD"}', 3.0),
],
)
def test_parse_total_accepts_valid_replies(reply, expected):
assert parse_total(reply) == expected
@pytest.mark.parametrize(
"reply",
[
"not json",
"",
"[1, 2]",
'{"amount": 3}',
'{"total": "42.5"}',
'{"total": true}',
'{"total": -1}',
'{"total": NaN}',
'```json\n{"total": 1}\n```',
],
)
def test_parse_total_rejects_bad_replies(reply):
with pytest.raises(ReplyError):
parse_total(reply)The last row records a decision. This parser rejects replies wrapped in a Markdown code fence. You might decide instead to strip the fence, since models do this often. Either choice is fine, but the test makes it explicit. If you later add fence stripping, you move that row to the valid table, and the change shows up in review.
Build the failure rows from replies you have actually seen. When production logs show a new malformed reply, add it as a row. That is a cheap regression test.
Add the retry loop
The retry function calls the client, parses the reply, and tries again on ReplyError. This version also feeds the problem back into the next prompt, which often helps a real model correct itself.
from typing import Protocol
class ChatClient(Protocol):
def complete(self, prompt: str) -> str: ...
def build_prompt(invoice_text: str, problem: str | None = None) -> str:
prompt = f"Return JSON with a 'total' field for this invoice:\n{invoice_text}"
if problem:
prompt += f"\n\nYour previous reply was rejected: {problem}"
return prompt
def extract_total(client: ChatClient, invoice_text: str, attempts: int = 3) -> float:
problem = None
for _ in range(attempts):
reply = client.complete(build_prompt(invoice_text, problem))
try:
return parse_total(reply)
except ReplyError as exc:
problem = str(exc)
raise ReplyError(f"no valid reply after {attempts} attempts: {problem}")Test the retry behavior with a scripted fake
The fake from the previous chapter returns scripted replies in order, raises scripted exceptions, and records the prompts it receives. It is repeated here so the file runs on its own.
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 replyNow each path through the loop gets a test. A live model would almost never produce these sequences on demand.
def test_first_valid_reply_makes_one_call():
client = FakeClient(['{"total": 42.5}'])
assert extract_total(client, "Total: $42.50") == 42.5
assert len(client.prompts) == 1
def test_retries_after_malformed_reply():
client = FakeClient(["not json", '{"total": 10}'])
assert extract_total(client, "x") == 10.0
assert len(client.prompts) == 2
def test_retry_prompt_includes_the_problem():
client = FakeClient(["not json", '{"total": 10}'])
extract_total(client, "x")
assert "rejected" not in client.prompts[0]
assert "reply is not JSON" in client.prompts[1]
def test_gives_up_after_all_attempts():
client = FakeClient(["nope", "still nope", "no again"])
with pytest.raises(ReplyError, match="3 attempts"):
extract_total(client, "x")
assert len(client.prompts) == 3
def test_validation_failures_are_retried_too():
client = FakeClient(['{"total": -5}', '{"total": 5}'])
assert extract_total(client, "x") == 5.0
def test_transport_errors_are_not_swallowed():
client = FakeClient([TimeoutError("slow")])
with pytest.raises(TimeoutError):
extract_total(client, "x")
assert len(client.prompts) == 1Each test asserts something beyond the return value:
- Call count.
len(client.prompts)proves the loop made exactly the calls you expect. Without it, a loop that retried twice too many times would still pass. - Prompt content. The feedback test checks that the second prompt differs from the first in the intended way.
- Error identity.
match="3 attempts"checks the message the caller will see, not only the exception type.
The AssertionError in FakeClient also guards against over-calling. If a bug makes the loop call a fourth time, the fake raises AssertionError. That is not a ReplyError, so the loop does not swallow it and the test fails loudly.
Edge cases worth a test
- Zero attempts. With
attempts=0the loop body never runs, and the function raises withproblemstillNone. Decide whether that is acceptable or whether to rejectattempts < 1up front, then test your choice. - Different failures on each attempt. Script
["not json", '{"amount": 1}', '{"total": 2}']. The final error message should name the last problem, not the first. - Partial success. If the reply is valid JSON with extra fields, the parser should accept it. The fourth row of the valid table covers this. Strict rejection of unknown fields is a design choice, so test whichever way you chose.
- Retryable API errors. Rate limits and timeouts often deserve a retry with a delay. Keep that logic in a separate layer from reply retries, with its own tests, and pass the sleep function in as an argument. A test can then supply a no-op or a recorder instead of waiting. Never call
time.sleepfor real in a unit test.
What these tests do not tell you
These tests prove that your code handles the replies you scripted. They do not prove the real model will produce those replies, or that a retry with feedback actually helps a real model. Both of those are questions about the model, and unit tests with a fake cannot answer them. Later chapters cover recorded responses, which capture real replies, and live smoke tests, which check the integration against the real API.
Exercise
Your retry loop catches ReplyError. A teammate changes parse_total so that a reply of {"total": "42.5"} (a string) is converted with float() instead of rejected. Which tests should change, and what new test would you add to pin down the behavior?
Show answer
In test_parse_total_rejects_bad_replies, remove the '{"total": "42.5"}' row, because that reply is now valid. Add ('{"total": "42.5"}', 42.5) to the valid table in test_parse_total_accepts_valid_replies. Also add a rejection row for a string that is not a number, such as '{"total": "abc"}'. float("abc") raises ValueError, not ReplyError, so the parser must wrap the conversion and raise ReplyError. Otherwise the retry loop would not catch it, and the new row would fail until the wrapping is added.