Sub topic 6
Test parsing, validation, and retry logic
This chapter assumes you can write pytest tests, read basic Python classes and exceptions, and pass a dependency as an argument. It builds on the scripted fake client from earlier chapters, so you only need its behavior here.
What you are testing
Parsing, validation, and retry code is your code, not the model's. A live model will almost never return a malformed reply on demand. A scripted fake can return one every time, so you can check each branch.
Three behaviors are worth testing:
- Parsing: does valid output become the value you expect?
- Validation: does output that parses but is wrong get rejected?
- Retry: does the code try again after a bad reply, and does it stop after the limit?
The code under test
The application code depends on a one-method ChatClient protocol. A protocol is a type that describes the methods an object must have, so any object with a complete method fits.
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"])Two things can go wrong here. json.loads raises json.JSONDecodeError when the reply is not JSON. Indexing data["total"] raises KeyError when the field is missing.
The scripted fake
The fake returns scripted replies in order. It raises any scripted exception and keeps the prompts it received.
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]The last assertion checks the request as well as the result. It confirms the invoice text reached the prompt.
Add a retry loop
Wrap the call in a loop that catches only the errors a bad reply can cause.
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_errorScripting a bad reply followed by a good one exercises the retry path deterministically.
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 checks two facts: the final value is correct, and exactly two calls were made. The second confirms the loop stops at the limit and raises a clear error.
Common errors
- Catching too much.
except Exceptionwould hide bugs such as aTypeErrorin your own code. Catch only the errors a bad reply can cause. - Skipping the call count. A retry test that checks only the final value passes even if the code retried ten times. Assert on
len(client.prompts). - Too few scripted replies. If the code calls the client more often than you planned, the fake raises
AssertionError. This is intended, because it exposes extra calls. - Testing only invalid JSON. Valid JSON with the wrong shape, such as
'{"amount": 5}', takes theKeyErrorpath. Script that case too.
Exercise
Write a test that scripts the reply '{"amount": 5}' followed by '{"total": 7}' and shows that extracttotalwith_retry returns 7.0. Why does the first reply trigger a retry?
Show answer
def testretriesaftermissingfield(): client = FakeClient(['{"amount": 5}', '{"total": 7}']) assert extracttotalwith_retry(client, "x") == 7.0 assert len(client.prompts) == 2 The first reply is valid JSON, so json.loads succeeds. Then data["total"] raises KeyError, which the retry loop catches, so it calls the client again and gets the second reply.