Search GimmeJob

Type at least 2 characters. Enter also searches by meaning.
GimmeJob
Sign in
Generative AI & LLM · Chapter 10 / 20

Generative AI & LLM

Testing LLM code without the model

Most of the code in an LLM application never needs a model to be tested. Prompt rendering, context assembly, history truncation, output parsing, tool routing and authorization, retries, streaming, guardrail wiring, logging and cost accounting are deterministic, and their defects are ordinary defects: wrong branches, missing checks, off-by-one budgets. Testing them through a real model is slow, expensive and flaky, and it hides the cause of a failure behind the randomness of generation.

This chapter shows how to test that code quickly, offline and deterministically: test doubles for model clients, dependency injection, invariant tests for context assembly, snapshot tests for prompts, record and replay of real HTTP traffic, contract fixtures for provider responses, and a test-suite layout that separates offline tests from live checks and quality evaluation.

Prerequisites: LLM application anatomy and APIs, Structured output and validation, and basic pytest.

What to test without a model

ComponentBehaviour to verifyTest double needed
Prompt renderingEvery template renders with realistic and hostile values; structure stays intactNone
Context assemblySystem prompt kept, budget respected, newest turns kept in order, right user's dataNone, or a fake tokenizer
Output parsing and validationEvery recorded output shape is accepted or rejected correctlyRecorded outputs
Stop-reason handlingEach stop reason leads to the specified actionStub responses
Tool routing and authorizationUnknown tools, invalid arguments and other users' data are rejectedScripted tool calls
Retries and timeoutsOnly retryable errors are retried, within attempt and time limitsFailing client, fake clock
StreamingInterrupted streams are never shown as completeRecorded streams
Guardrail wiringBlocked inputs never reach the model; blocked outputs never reach the userStub classifier
Logging and tracingEvery call records model, prompt version, usage and context identifiersSpy
FallbacksPrimary model failure switches to the fallback pathFailing client

None of these tests says whether the model's answers are good. That is the job of evaluation (Evaluation methodology and datasets). The two kinds of testing complement each other: offline tests make the system reliable, evaluations make it useful.

Test doubles for model clients

A test double replaces a real dependency in a test. The classic vocabulary distinguishes several kinds, and each has a clear use for model clients:

DoubleWhat it doesTypical use with a model client
DummyFills a parameter that the test path never usesA client passed to code that should not call it at all
StubReturns canned answersExercising parsing and post-processing of a known response
SpyRecords how it was called, often wrapping another doubleAsserting what was sent: messages, parameters, tools, prompt version
MockIs programmed with expectations and fails when they are not metVerifying that a call happens exactly once or never
FakeA working, simplified implementationRule-based answers for many inputs; an in-memory order database for tools
Fault injectorRaises errors or returns malformed dataTimeouts, rate limits, truncated and invalid responses

The precondition is a seam: the code under test must receive its client instead of creating it. The function below takes client as a parameter, so any double can be injected.

Python
editable · browser sandbox
Result
Run the code to see the result.

Output:

stub, spy, fault injection and fake: all checks passed

Creating the seam

If code creates its client internally, tests have to patch it. Prefer moving creation to the edge of the application:

# Hard to test: the client is created inside the function.
def answer_question(question: str) -> str:
    client = OpenAI()                       # every test needs patching and network
    ...

# Testable: the client is a parameter with a production default created at startup.
class SupportAssistant:
    def __init__(self, client: ModelClient, retriever: Retriever, clock: Clock):
        self.client, self.retriever, self.clock = client, retriever, clock

When you cannot change the code yet, pytest's monkeypatch fixture can replace a module attribute for one test. Treat that as a temporary measure: tests that patch internals break whenever the internals are refactored.

def test_answer_uses_the_fallback_message_on_timeout(monkeypatch):
    monkeypatch.setattr(support, "create_client", lambda: FailingClient(TimeoutError()))
    assert "not available" in support.answer_question("Hi")

Mocks: use them for interactions, not for answers

A mock that asserts the exact text of a prompt couples the test to an implementation detail; every harmless prompt edit breaks it. Use mocks and spies to verify interactions that matter: the model is not called when the input guardrail blocks; the tool is called with the authenticated user's ID; the fallback model is called after the primary fails. Verify the exact prompt text with snapshot tests instead, where changes are reviewed deliberately (see below).

Testing context assembly

Context assembly decides what the model sees: system prompt, conversation history, retrieved documents, user profile, tool definitions, within a token budget. Its defects are silent: a dropped system prompt or another user's data in the context does not raise an exception, it changes behaviour.

Test it with invariants that must hold for every conversation, and check them on many generated conversations:

Python
editable · browser sandbox
Result
Run the code to see the result.

Output:

['Answer from the ', 'Order A-1042?', 'It ships today.', 'And returns?']
500 random conversations: invariants hold

Other invariants worth checking in real systems: retrieved documents belong to the requesting tenant; personal data is redacted before it enters the context; tool definitions match the user's permissions; the context never exceeds the model's window minus the reserved output budget. For production code, use the provider's real tokenizer in these tests; a wrong token estimate is itself a common defect.

Snapshot tests for prompts

A snapshot (golden-file) test renders a prompt for fixed inputs and compares it with a committed file. Any change to the rendered text fails the test until someone reviews the difference and updates the snapshot. This catches unintended changes: a refactoring that drops a rule, a template variable that renders as empty, an example accidentally duplicated.

# pip install syrupy
def test_support_prompt_snapshot(snapshot):
    rendered = render_system(policy_chunks=["Returns: 30 days from delivery."], few_shot_examples=["Q: ... A: ..."])
    assert rendered == snapshot          # pytest --snapshot-update rewrites the file after review

Snapshots have one well-known failure mode: people update them without reading the diff. Keep them small (one snapshot per template, with short fixed inputs), review snapshot diffs like prompt diffs (Prompts as testable artifacts), and never use snapshots for model output, which varies by design.

Record and replay

Some tests need real HTTP traffic: the integration between your client wrapper and the provider SDK, request headers, error bodies, streaming formats. Record and replay captures real interactions once and replays them afterwards. With vcrpy (or the pytest-recording plugin built on it), a test runs against the real API the first time and stores the exchange in a cassette file; later runs replay the cassette without network access.

# pip install vcrpy
import vcr

replay = vcr.VCR(
    cassette_library_dir="tests/cassettes",
    record_mode="none",                       # CI: never touch the network; fail if a cassette is missing
    filter_headers=["authorization", "x-api-key", "openai-organization"],
    match_on=["method", "scheme", "host", "path", "body"],
)


@replay.use_cassette("refund_question.yaml")
def test_client_wrapper_parses_a_real_response():
    response = assistant.client.complete([{"role": "user", "content": "Can I return worn shoes?"}])
    assert response.stop_reason == "end"
    assert response.input_tokens > 0

Rules that keep cassettes safe and useful:

  • Filter secrets (API keys, organization IDs, cookies) before the first recording, and scan cassettes in CI for anything that looks like a key.
  • Record deliberately. Use a mode that records only when explicitly asked (once locally, none in CI), so a test never silently calls a paid API.
  • Match on the request body. Otherwise a changed prompt replays an old answer and the test passes for the wrong reason.
  • Re-record on purpose, for example when upgrading the SDK, and review the cassette diff.
  • Do not assert on generated text in replayed tests beyond what the parsing code handles. The replayed answer was produced once by a model; it is a fixture, not a quality measurement.

Contract fixtures for provider responses

Recorded cassettes show common responses. Rare shapes, such as tool calls, refusals, truncation, content filters, multiple tool calls and empty content, may never appear in your recordings, yet your parsing code must handle them. Contract fixtures are response bodies in the shape the provider documents, stored as JSON files and used to test the normalization code. When the SDK or API version changes, compare new real responses with the fixtures.

Python
editable · browser sandbox
Result
Run the code to see the result.

Output:

openai   : {'text': '', 'stop': 'tool_calls', 'tool_calls': [{'name': 'get_order_status', 'arguments': {'order_id': 'A-1042'}}], 'tokens': (812, 19)}
anthropic: {'text': 'Let me check.', 'stop': 'tool_use', 'tool_calls': [{'name': 'get_order_status', 'arguments': {'order_id': 'A-1042'}}], 'tokens': (790, 24)}

Note two details that contract fixtures catch and happy-path tests do not: OpenAI returns content: null when the model only calls tools, and tool arguments arrive as a JSON string that must be parsed (and can be invalid). Anthropic returns arguments as an object, and text and tool calls can share one response.

Testing tool routing and authorization

When the model requests a tool call, the request is untrusted input: the model can choose a tool that does not exist, send invalid arguments, or be manipulated into asking for another customer's data. The router that executes tool calls is security-critical code and is fully testable without a model.

Python
editable · browser sandbox
Result
Run the code to see the result.

Output:

own order                  -> {'result': {'order_id': 'A-1042', 'status': 'shipped'}}
order of another customer  -> {'error': 'order not found'}
model injects user_id      -> {'error': 'invalid arguments'}
unknown tool               -> {'error': "unknown tool 'issue_refund'"}
wrong argument type        -> {'error': 'invalid argument types'}

The design decisions that the tests protect:

  • The user identity comes from the authenticated session, never from the model. The third case shows a model trying to pass user_id itself; the router rejects any argument it does not expect.
  • "Not found" and "not yours" give the same answer, so the tool cannot be used to discover which order IDs exist.
  • Errors go back to the model as tool results so it can explain the situation to the user, and they are logged for monitoring.

Time, randomness and concurrency

Three more sources of flaky tests have standard remedies:

  • Time. Inject a clock. Retry and timeout logic tested with a fake clock runs instantly and deterministically (LLM application anatomy and APIs shows a complete example). Date-dependent behaviour ("your return window ends tomorrow") needs a fixed "now".
  • Randomness. Seed every random generator used in tests, including sampling in fakes and data generators, and print the seed on failure.
  • Asynchrony. Streaming and parallel tool calls are usually asynchronous. Test them with an async test runner (for example pytest-asyncio), drive streams from recorded events, and test cancellation explicitly: a cancelled request must stop consuming the stream and must not leave half-written state.

Organizing the test suite

Separate tests by what they need and how often they run:

LayerNeedsSpeedWhen it runsExample
Unit (offline)Nothing externalMillisecondsEvery commitParsing, routing, context assembly with doubles
Recorded integrationCassettes and fixturesSecondsEvery commitSDK wrapper against replayed traffic
Live smokeAPI key, networkSeconds, costs moneyNightly and before releaseOne real call per provider path: stop reasons, usage, structured output
EvaluationDatasets, model, scorersMinutes to hoursPull requests that change behaviour, nightlyQuality metrics with thresholds

Markers make the layers explicit, and the default run stays offline:

[tool.pytest.ini_options]
addopts = "-m 'not live and not eval'"
markers = [
  "live: calls a real model provider; needs API keys",
  "eval: runs an evaluation dataset against a model",
]

Run pytest -m live or pytest -m eval deliberately, in the pipeline stages described in Production quality.

Example project

The method of this chapter is implemented and tested in examples/llm-testing/07-testing-without-the-model: a support assistant built around an injected model client, all six kinds of test doubles, context-assembly invariants checked with Hypothesis, a prompt snapshot, provider contract fixtures, a router that enforces tool authorization, and a record-and-replay test that runs offline from a committed cassette. All tests run offline, without a model or API keys:

uv sync --project examples/llm-testing
uv run --project examples/llm-testing pytest examples/llm-testing/07-testing-without-the-model

Common mistakes

  • Testing deterministic code through a real model, which makes tests slow, costly and flaky, and hides the cause of failures.
  • Creating the client inside business logic, so that tests can only patch internals.
  • Mocking exact prompt text in behavioural tests, so that every prompt edit breaks unrelated tests.
  • Cassettes with secrets, or cassettes that do not match on the request body.
  • Only happy-path response fixtures: no tool-call, refusal, truncation or null-content shapes.
  • Trusting tool arguments from the model, including identity or permission fields.
  • One undifferentiated test suite that mixes offline tests, paid live calls and slow evaluations.

Summary

  • Most LLM application code is deterministic; test it offline, with test doubles, in milliseconds.
  • Dependency injection creates the seam. Use stubs for canned responses, spies to check what was sent, fakes for realistic behaviour, fault injectors for failures and mocks only for interactions that matter.
  • Test context assembly with invariants over many generated conversations.
  • Snapshot tests catch unintended prompt changes; review their diffs deliberately.
  • Record and replay real traffic with filtered secrets and body matching; cover rare response shapes with contract fixtures.
  • The tool router is security-critical: identity from the session, strict argument validation, uniform errors.
  • Separate unit, recorded, live and evaluation layers with markers, and keep the default run offline.

Source registry

9 chapter references
Test Double

Vocabulary of test doubles (dummy, stub, spy, mock, fake) applied to model clients.

Martin Fowler · article
Source ↗
Mocks Aren't Stubs

State versus interaction verification; why mocks should verify interactions that matter.

Martin Fowler · article
Source ↗
VCR.py documentation

Record and replay HTTP interactions; record modes, header filtering and request matching.

vcrpy · tool
Source ↗
pytest-recording

pytest plugin on top of vcrpy with record modes controlled from the command line.

Kiwi.com · tool
Source ↗
syrupy — snapshot testing for pytest

Snapshot (golden-file) tests for rendered prompts.

syrupy · tool
Source ↗
How to monkeypatch/mock modules and environments

Temporary replacement of module attributes when code has no injection seam yet.

pytest · official docs
Source ↗
Working with custom markers

Separating offline, live and evaluation test layers with markers.

pytest · official docs
Source ↗
pytest-asyncio

Testing asynchronous streaming and cancellation.

pytest-dev · tool
Source ↗
Hypothesis documentation

Property-based testing library used to fuzz the validation pipeline.

Hypothesis · tool
Source ↗