Sub topic 2
Inject Errors and Malformed Output
Assume you can write pytest tests, define Python classes, catch exceptions, and pass dependencies into functions. The goal is to test your application logic without asking a live model for every test response.
Inject errors and malformed output
A scripted fake is a test double that returns predetermined replies or raises predetermined exceptions. It lets you reproduce failures on demand.
import json
class FakeClient:
def __init__(self, replies):
self.replies = list(replies)
self.prompts = []
def complete(self, prompt):
self.prompts.append(prompt)
if not self.replies:
raise AssertionError("No scripted reply remains")
reply = self.replies.pop(0)
if isinstance(reply, Exception):
raise reply
return reply
def extract_total(client, invoice_text):
reply = client.complete(f"Return JSON with a total field:\n{invoice_text}")
data = json.loads(reply)
total = float(data["total"])
if total < 0:
raise ValueError("total cannot be negative")
return totalThe fake can inject malformed JSON, missing fields, invalid values, or API errors:
client = FakeClient(["not JSON"])
try:
extract_total(client, "Total: $10")
except json.JSONDecodeError:
pass
client = FakeClient([TimeoutError("API timed out")])
try:
extract_total(client, "Total: $10")
except TimeoutError:
passTest parsing, validation, and retry logic
Test each boundary separately. A retry test should prove both that a retry occurs and that repeated failure eventually stops.
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, ValueError) as exc:
last_error = exc
raise ValueError("model returned no valid total") from last_error
def test_retries_after_bad_json():
client = FakeClient(["bad", '{"total": 10}'])
assert extract_total_with_retry(client, "invoice") == 10.0
assert len(client.prompts) == 2Record real responses and replay them offline
A recording stores a response for a request. Replay tests avoid latency and cost, while still exercising realistic response shapes.
import hashlib
import json
import os
class RecordingClient:
def __init__(self, path, real_client=None):
self.path = path
self.real_client = real_client
self.entries = {}
if os.path.exists(path):
with open(path, encoding="utf-8") as file:
self.entries = json.load(file)
def complete(self, prompt):
key = hashlib.sha256(prompt.encode()).hexdigest()
if key not in self.entries:
if self.real_client is None:
raise LookupError("No recording for this request")
self.entries[key] = self.real_client.complete(prompt)
with open(self.path, "w", encoding="utf-8") as file:
json.dump(self.entries, file, indent=2, sort_keys=True)
return self.entries[key]Match requests to recordings
Hashing the complete prompt makes changed instructions fail loudly. Include model settings, tools, and relevant request fields in the recorded key when they can change the response.
Exercise
Why should a recording test fail when its request hash changes?
Show answer
The changed request may need a new response. Failing prevents the test from silently using stale data.