A test is worth the bug it would catch: for each behaviour, pick the cheapest deterministic check that fails when that behaviour breaks (a unit test, a generated property, a real database, a contract, a schema), run the cheap checks on every change, and judge the suite by what it notices (mutation score, flakiness), not by what it runs (coverage).
Every bug below was run for this page on 2026-10-04 against small pieces of the LLM chat product from the parent topic (a document chunker, a retry policy, chat search, a model-output parser, a data schema, a training loop). Fig. 1 draws them at the lowest layer that caught them; higher layers run more of the system per test, cost more and fail for more reasons.
The rule under every section: test each behaviour at the lowest layer that can catch its bugs.
You need: Python; pytest basics are recapped in a closed block in section 3. Elsewhere: how to structure code so it is testable (functional core, dependency injection, characterization tests) is Code design's; measuring model and prompt quality (golden sets, regression gates, A/B tests) is Production eval engineering's; chaos testing and deploy safety are Reliability engineering's; load testing is Capacity planning and performance's.
An automated test writes down the check you would do by hand (run the code, try an input, look at the output) so a machine repeats it in milliseconds whenever anything changes. It buys three things. Confidence to change: the day you refactor, upgrade a library or swap a model provider, the suite tells you within a minute whether anything a caller relies on broke; without it every change is a gamble, so people stop changing things and the code rots. Documentation that cannot go stale: test_client_errors_are_not_retried[404] says what the retry policy promises and fails the moment it stops being true. Design pressure: code that is hard to test (it opens its own database connection, reads the clock, calls the model directly) is usually hard to change for the same reasons.
It cannot prove the code correct. Edsger Dijkstra, 1970: "Program testing can be used to show the presence of bugs, but never to show their absence!" (EWD249). (A machine-checked proof can show absence, for one stated property under stated assumptions: section 6.) Each kind of test is a different net; the craft is choosing nets that catch the bugs you are likely to have, at a cost you can afford to run on every change.
Its usual source is Boehm and Basili's 2001 "Software Defect Reduction Top 10 List" (IEEE Computer): "Finding and fixing a software problem after delivery is often 100 times more expensive than finding and fixing it during the requirements and design phase", which the same article qualifies: for small, noncritical systems the factor is "more like 5:1 than 100:1". It traces back to 1970s and 1980s data from large waterfall projects. Menzies, Nichols, Shull and Layman tested it on 171 modern projects and "found no evidence for the delayed issue effect" (arXiv 1609.04886, Empirical Software Engineering 2017); Laurent Bossavit traces how the figure spread in The Leprechauns of Software Engineering (chapter 10).
What does hold, without a multiplier: a bug caught by a test on your laptop costs you seconds and nobody else anything; the same bug in production costs an incident, a rollback, a postmortem and some users' trust (Reliability engineering). Argue for tests from that, not from the 100x.
Tests are grouped by how much of the system one test runs: a unit test runs one function or class in one process, no network or disk (milliseconds); an integration test runs your code with a real dependency such as a database, queue or another module (milliseconds to seconds); an end-to-end test drives the whole deployed system like a user (HTTP requests to the real API, a browser clicking the UI: seconds to minutes, and the flakiest); static checks (mypy, pyright, ruff) read the code without running it. Because "unit" and "integration" mean different things to different teams, Google sorts tests by the resources they use instead: "small tests run in a single process, medium tests run on a single machine, and large tests run wherever they want" (Software Engineering at Google, ch. 11). The PostgreSQL tests on this page are medium: one machine, a local server.
The test pyramid (Mike Cohn, Succeeding with Agile, 2009; Fowler's summary, 2012): many fast unit tests at the base, fewer integration tests, very few end-to-end tests. Google's testing blog suggested "a 70/20/10 split: 70% unit tests, 20% integration tests, and 10% end-to-end tests" as a first guess (Wacker, 2015). The testing trophy (Kent C. Dodds, 2018; his 2021 write-up) puts static checks at the base and makes integration the widest layer, after Guillermo Rauch's line "Write tests. Not too many. Mostly integration." (2016).
Which shape? Both want most of the checking done by fast, reliable tests and few slow end-to-end ones. The pyramid fits code with a lot of logic of its own (a retry policy, a tokenizer, a pricing engine); the trophy fits code that is mostly wiring between other systems (a web front end, a thin API over a database), where a unit test with everything mocked checks little. ML systems add a band on top, evals, which score a model or prompt on a set of cases against a threshold; they are statistical, slow and costly, so they run on merge or nightly (Production eval engineering owns them).
Band widths are the shapes' proportions, not measurements. Click a band for what that layer catches, misses and costs on this page.
The first piece of the chat product under test is the chunker: before a document can be searched by meaning (retrieval, the R in RAG), it is cut into overlapping windows of text, each embedded separately. The function and three ordinary pytest tests:
experiments/hyp/chunking.pydef chunk(text: str, size: int, overlap: int) -> list[str]:
"""Split text into windows of `size` characters; neighbours share `overlap` characters."""
if not 0 <= overlap < size:
raise ValueError("need 0 <= overlap < size")
step = size - overlap
return [text[i:i + size] for i in range(0, len(text) - size + 1, step)]
def unchunk(chunks: list[str], overlap: int) -> str:
"""Inverse of chunk: glue the windows back, dropping each repeated overlap."""
if not chunks:
return ""
return chunks[0] + "".join(c[overlap:] for c in chunks[1:])
experiments/hyp/test_chunking_examples.pyfrom chunking import chunk, unchunk
def test_splits_into_overlapping_windows():
assert chunk("abcdefghij", size=4, overlap=1) == ["abcd", "defg", "ghij"]
def test_no_overlap():
assert chunk("abcdef", size=2, overlap=0) == ["ab", "cd", "ef"]
def test_round_trip():
text = "the quick brown fox jumps over the lazy dog!!" # 45 characters
assert unchunk(chunk(text, size=10, overlap=5), overlap=5) == text
All green, and the function has a bug: look at len(text) - size + 1. Any document shorter than one window produces no chunks at all, so it silently vanishes from the search index. The three examples happen to use lengths where the windows fit exactly. Section 6 finds it without being told where to look.
The most useful idea in test design: a test checks what the code promises (its outputs, its errors, its effects others can see), not how it does it. Google's testing book puts the goal as tests that are "unchanging": they only need to change when the requirements change (Software Engineering at Google, ch. 12). The figure is why: the two kinds of test answer two kinds of change in opposite ways.
def test_backoff_uses_min(mocker):
spy = mocker.spy(builtins, "min")
backoff_delay(3)
spy.assert_called_once()
def test_retryable_set():
assert 503 in retrypolicy.RETRYABLEdef test_backoff_doubles_from_base_then_caps():
assert [backoff_delay(a) for a in range(1, 7)] \
== [0.5, 1, 2, 4, 8, 8]
def test_stops_at_max_attempts():
assert not should_retry(503, attempt=3)How a good test reads:
test_retry_preserves_idempotency_key, not test_retry_2. When it goes red in CI, the name is the bug report.pytest is the standard test runner for Python. A test runner finds your tests, runs each one in isolation, and reports which passed. pytest's rules are short: files named test_*.py, functions named test_*, and a plain assert statement as the check. When an assert fails, pytest rewrites it to show both sides (assertion introspection), so you never need special assertEqual methods.
| Command | What it does |
|---|---|
pytest -q | Run everything under the current folder, one character per test. |
pytest tests/test_search.py::test_search_ignores_case | Run one test by its node id (file, then ::, then name). |
pytest -k "retry and not slow" | Run tests whose names match an expression. |
pytest -x --lf | Stop at the first failure; rerun only the tests that failed last time. |
pytest -m "not slow" | Skip tests carrying the slow marker (below). |
pytest --durations=10 | List the ten slowest tests: where your suite's time goes. |
Fixtures. A fixture is a function that builds something a test needs (a database connection, a temporary folder, a fake server) and cleans it up afterwards. A test asks for it by naming it as an argument; pytest calls the fixture, passes in the value, and after the test runs the code after yield (fixtures docs). The scope says how often it is rebuilt: function (default, once per test), module, or session (once per run, for expensive things). Fixtures shared by many files live in a conftest.py, which pytest loads automatically. These are the real fixtures behind the PostgreSQL tests in section 5:
experiments/integ/conftest.py (timing code removed)import sqlite3, tempfile
import pytest, psycopg, pgserver
@pytest.fixture
def sqlite_conn():
conn = sqlite3.connect(":memory:")
yield conn # the test runs here
conn.close() # teardown, even if the test failed
@pytest.fixture(scope="session") # start PostgreSQL once for the whole run
def pg_server():
yield pgserver.get_server(tempfile.mkdtemp(prefix="pgtest"), cleanup_mode="stop")
@pytest.fixture
def pg_conn(pg_server): # fixtures can use other fixtures
with psycopg.connect(pg_server.get_uri(), autocommit=False) as conn:
yield conn
conn.rollback() # every test's writes vanish: tests stay independent
pytest ships useful fixtures too: tmp_path (a fresh folder per test), monkeypatch (change an attribute, dict item or environment variable and undo it after the test; it fixes the order-dependent flake in section 9), capsys (capture printed output) and caplog (capture log records).
Parametrisation. @pytest.mark.parametrize runs the same test body once per row, each reported as its own test (test_parse_retry_after[-3-0.0]), so one bad row does not hide the others (parametrize docs). From the retry policy the chat product uses when the model provider fails:
experiments/mut/tests/test_strong.py (excerpt)import pytest
from retrypolicy import should_retry, backoff_delay, parse_retry_after
@pytest.mark.parametrize("status", [408, 429, 500, 502, 503, 504])
def test_retryable_statuses_are_retried(status):
assert should_retry(status, attempt=1)
@pytest.mark.parametrize("header,expected", [
("2", 2.0), ("1.5", 1.5), ("0", 0.0), ("-3", 0.0), (None, None), ("soon", None),
])
def test_parse_retry_after(header, expected):
assert parse_retry_after(header) == expected
with pytest.raises(ValueError, match="overlap"): passes only if the block raises that exception type with a matching message. Assert the type and the condition, not merely that "something failed".assert total == pytest.approx(0.3) compares floats with a tolerance (default relative 1e-6); 0.1 + 0.2 == 0.3 is false in binary floating point. Section 8 shows why this matters for ML code.@pytest.mark.slow, @pytest.mark.gpu. Declare them under markers in your config and add --strict-markers so a typo is an error, not a silently unselected test (markers docs).pyproject.toml (a sensible starting config)[tool.pytest.ini_options] testpaths = ["tests"] addopts = "-ra --strict-markers --strict-config" markers = [ "slow: takes more than a second; skipped on every push", "gpu: needs a GPU runner", ]
The retry policy's backoff_delay(attempt) returns 0.5 s doubled per attempt, capped at 8. The real bug is mutant backoff_delay #2 from section 10 (cap 8 changed to 9), which survived the weak suite. The brittle test is illustrative (mocker comes from pytest-mock).
Real dependencies (the model provider, a payment API, a database) can be slow, cost money, need network access or fail at random. A test double stands in for one during a test, the way a stunt double stands in for an actor. Gerard Meszaros named the kinds in xUnit Test Patterns (2007); Martin Fowler's Mocks Aren't Stubs (2004, revised 2007) is the classic explanation. A dummy fills a parameter and is never used (a logger=None); a stub returns canned answers (a model client whose complete() always returns "Hello"); a spy is a stub that also records how it was called; a mock is pre-programmed with expected calls and fails the test if they differ (unittest.mock, pytest-mock: client.complete.assert_called_once_with(...)); a fake is a small working implementation with shortcuts (an in-memory chat store, an HTTP handler that answers like a chat-completions API).
test_search_ignores_case seeds three chats ("Trip planning for Lisbon" and "trip budget spreadsheet" for ada, "Trip ideas" for bob), searches "trip" for ada and expects [1, 2]. search_chats takes its connection as an argument: the seam where a test chooses what stands behind it.assert_called_once_with(sql). That proves the handler made the call you expected and nothing about the results: the mock catches nothing about results, because it checks that a call was made, so it passes with the case bug.LIKE ignores ASCII case: the test passes and the bug ships. A hand-written in-memory fake proves the results are right against your model of the store; it catches this bug only if whoever wrote the fake knew PostgreSQL's rule. Keep it honest with a contract test (below).LIKE is case-sensitive, so "Trip planning for Lisbon" is missed and assert [2] == [1, 2] fails. Only the real engine catches the case-sensitivity bug in section 5, where its measured cost is: ms a test plus s startup.lower(title) LIKE lower(?) returns [1, 2] on SQLite and on PostgreSQL: the test now pins the product's rule (ignore case) on the engine you ship.Prefer real, then fake, then mock. Google's testing book: "A real implementation should be preferred over a test double. A fake is often the ideal solution if a real implementation can't be used" (Software Engineering at Google, ch. 13), and mocks sparingly. A test made of mocks restates the implementation, so it passes when the code is wrong and fails when the code is refactored correctly. Code design's Review lab has a real example: a mock-only test that still passes with the function it claims to test broken.
The interaction is the behaviour: "a payment is charged exactly once", "the alert is sent", "we never call the provider when the cache hits". Mock at the boundary you own (your PaymentGateway wrapper), not deep inside third-party libraries.
Mocking the database, then asserting the SQL string was passed. Mocking requests.post to return a dict that the real API never returns. Mocking a function in the same module you are testing. Each passes forever while production breaks.
A fake drifts: the real service changes a field name and your fake does not. A contract test checks the agreement between two sides directly. In consumer-driven contract testing (Pact, "a code-first consumer-driven contract testing tool"; pact-python 3.4.1, 2026-09-17), each side tests alone, yet a breaking change is caught before deploy:
Cost and when not to: it needs a place to share pacts (the Pact Broker or PactFlow) and buy-in from both teams. For a third-party API you do not control (a model provider), the provider will never run your pacts; use recorded responses and schema checks instead (section 7), and an OpenAPI document as the contract when one exists (Service APIs, section 3).
An integration test runs your code with a real dependency (the actual database engine, a real Redis, a real HTTP stack) and catches the bugs that live between components: SQL a different engine reads differently, a transaction that does not roll back, a type the driver converts. A common shortcut is SQLite in memory in tests while production runs PostgreSQL. What that shortcut cost, measured:
experiments/integ/: the same test against SQLite and PostgreSQL def search_chats(conn, owner, text):
"""Chats of this owner whose title contains `text`, ignoring case (the product spec)."""
rows = conn.execute(q(conn, "SELECT id FROM chats WHERE owner = ? AND title LIKE ? ORDER BY id"),
(owner, f"%{text}%")).fetchall()
return [r[0] for r in rows]
@pytest.mark.parametrize("db", ["sqlite_conn", "pg_conn"])
def test_search_ignores_case(db, request):
conn = request.getfixturevalue(db)
seed(conn) # "Trip planning for Lisbon", "trip budget spreadsheet" (ada); "Trip ideas" (bob)
assert search_chats(conn, "ada", "trip") == [1, 2]
SQLite's LIKE ignores case for ASCII letters by default (SQLite docs); PostgreSQL's LIKE is case-sensitive and offers ILIKE for the other behaviour (PostgreSQL docs). So the SQLite suite was green while production users searching "trip" never saw "Trip planning for Lisbon". The fix, lower(title) LIKE lower(?), passes on both; at scale you would add a trigram index (Topic: databases owns that depth).
The usual objection is speed: here a real PostgreSQL costs well under a second of startup per test run and a couple of milliseconds per test, so a suite of 500 such tests adds about a second. A little time for tests that use the engine you ship.
Keeping tests independent. Tests sharing a database leak state into each other. The cheapest isolation is a transaction rolled back after each test (the pg_conn fixture in section 3's pytest block). When the code under test commits on its own, truncate the tables after each test, or clone a prepared database per test with CREATE DATABASE t1 TEMPLATE base. With parallel workers (pytest-xdist), give each worker its own database. When not to: logic that does not touch the dependency (pricing rules, parsing, retry decisions) belongs in fast unit tests; integration tests are for the seams: queries, transactions, migrations, serialisation, configuration.
| Option | How | Cost |
|---|---|---|
| pgserver (used here) | PostgreSQL binaries inside a pip wheel; pgserver.get_server(dir) starts one. No Docker. | PostgreSQL only; version fixed by the wheel ( in ). |
| testcontainers-python | Starts a throwaway Docker container per session: with PostgresContainer("postgres:17") as pg:. Also Kafka, Redis, MinIO, LocalStack. | Needs Docker; first pull is slow; seconds per start. Any image and version, so it can match production exactly. |
| CI service containers | The CI system starts the database next to the job (services: in GitHub Actions, section 11). | Only in CI; locally you still need one of the above. |
Measured on 2026-10-04 (median of 50 runs each, experiments/integ/test_timing.py): per test, create a table, 3 inserts, 1 search. pytest's verdict: FAILED test_search.py::test_search_ignores_case[pg_conn] - assert [2] == [1, 2].
An example-based test checks the inputs you thought of; bugs live in the ones you did not (the empty string, the one-character document, the emoji, the negative number). A property is a statement that must hold for every valid input, such as "cutting a document into chunks and gluing them back gives the document". A property-based test states the property, and a library generates hundreds of inputs trying to break it. The idea comes from Haskell's QuickCheck (Claessen and Hughes, 2000); in Python the library is Hypothesis.
experiments/hyp/test_chunking_property.pyfrom hypothesis import given, strategies as st
from chunking import chunk, unchunk
@st.composite
def chunk_args(draw): # a custom strategy: valid (size, overlap) pairs
size = draw(st.integers(min_value=1, max_value=50))
overlap = draw(st.integers(min_value=0, max_value=size - 1))
return size, overlap
@given(text=st.text(), args=chunk_args())
def test_round_trip_loses_nothing(text, args):
size, overlap = args
assert unchunk(chunk(text, size, overlap), overlap) == text
A strategy describes how to generate one kind of value (st.text(), st.integers(1, 50), your own with @st.composite). Shrinking is what happens after a failure: Hypothesis keeps trying simpler versions of the failing input (shorter strings, smaller numbers, simpler characters) and keeps any that still fail, so the report is text='0', size=2, overlap=0 instead of a random 30-character unicode string. A one-character document with a two-character window: the bug, in one line.
Predict before it plays: the three examples of section 3 pass; how many generated inputs does the property need before its first failure? Fig. 3 replays the real Hypothesis run (seed , every one of its calls to the test logged) on the buggy chunk() from section 3: each call lands on the space of inputs (text length across, window size in depth); in front, the current call's characters as cubes and its windows as glass plates over them, a red cube a character the round trip lost.
chunk() returns no windows at all and the round trip gives back ''. The red floor shows why it came so soon: with overlap 0 an input fails unless its windows fit exactly, so most random documents trip it.'00', which still fails at size 3; sizes 1 and 2 pass.'0' with size 3 fails, size 1 passes, size 2 fails: the smallest failure so far (glowing). The empty text passes again.text='0', args=(2, 0), a one-character document with a two-character window. Of the calls, 14 failed.Across runs. Hypothesis is random, so the search differs from run to run. Over fixed seeds it found the bug in every run, always within the first generated inputs, because most random documents trip it. Shrinking ended at the true minimum ('0', size 2, overlap 0) in of runs; the others stopped at slightly larger inputs such as '0000' with size 3, which are just as readable. Shrinking is a local search: it guarantees that no simpler variant it tried still fails, not that no smaller failing input exists.
The fix starts a window wherever there is text the previous window did not cover: range(0, max(len(text) - overlap, 1), step), plus an early return for empty text. The same property then passed 5,000 generated cases (experiments/hyp/test_fixed_property.py, 2.3 s). It also cures a second symptom the examples never hit: the tail of any document whose length does not line up with the step, such as the last character of "abcde" with size 4 and overlap 1.
Determinism in CI. Hypothesis saves each failing input in a local example database (.hypothesis/examples) and replays it first next time. A CI machine starts with that folder empty, so Hypothesis now defaults to derandomize=True on CI ("If running on CI, the default is True"): every CI run tries the same inputs, so a red build reproduces, and new inputs are explored on developers' machines (or keep randomness in CI and cache the database between runs). Pin a found bug as a permanent regression case with @example(text="0", args=(2, 0)) above @given.
Some bugs need a particular sequence of calls. A stateful test lists the operations (rules), and Hypothesis runs random sequences of them against your code and a simple trusted model, comparing after each step. Here it tests the least-recently-used cache that holds embeddings by text hash: it should keep the two most recently used keys, but get forgets to mark a key as used. Hypothesis shrank random sequences to this five-step recipe:
Writing that sequence by hand requires already knowing the bug.
experiments/hyp/test_lru_stateful.pyclass LRUMatchesModel(RuleBasedStateMachine):
def __init__(self):
super().__init__()
self.cache = LRUCache(capacity=2)
self.model = OrderedDict() # the obviously-correct reference
@rule(k=keys, v=st.integers())
def put(self, k, v):
self.cache.put(k, v)
self.model[k] = v
self.model.move_to_end(k)
if len(self.model) > 2:
self.model.popitem(last=False)
@rule(k=keys)
def get(self, k):
expected = self.model.get(k)
if k in self.model:
self.model.move_to_end(k)
assert self.cache.get(k) == expected
TestLRU = LRUMatchesModel.TestCasef(f(x)) == f(x).What it costs, and when not to use it. Each property runs 100 examples by default, so it is slower than one example (seconds, not milliseconds). Thinking of a true property is the hard part; a property that restates the implementation proves nothing, and a strategy narrower than real inputs gives false confidence. Keep a few readable example tests as documentation, and add properties where the input space is large: parsers, serialisers, numeric transforms, data structures, anything with an inverse.
The old page's example property, @given(hnp.arrays(dtype=np.float32, shape=st.integers(1, 1000))) asserting that min-max normalisation produces no NaN, fails at once. Two reasons. First, by default the float strategy also generates NaN and infinity, so the test partly checks its own inputs; restrict them with elements=st.floats(-1e6, 1e6, width=32). Second, with finite inputs it still fails, and Hypothesis shrinks to x = array([0.]): a constant column makes max - min zero, and 0/0 is NaN. A real bug in every naive min-max scaler, found in under a second (experiments/mlt/test_normalize.py).
hypothesis.extra.numpy and hypothesis.extra.pandas generate arrays and data frames directly. Build domain objects with st.builds or @st.composite and reuse them across tests as a library of typed inputs.
A fuzz test is the "never crashes" property run for hours instead of 100 examples, with inputs mutated towards new code paths by coverage feedback; Google's OSS-Fuzz runs such entry points continuously for open-source libraries. However long it runs, it still samples. The rung above proves the property for every input: in October 2026 Anthropic's Frontier Red Team and Theorem had Claude write machine-checked Rocq proofs that 239 OSS-Fuzz entry points across 123 libraries never crash, fail an assertion or hit a memory-safety error for any input under 64 MB (Anthropic, Formal verification at scale). The existing fuzz test became the specification ("this test always passes"), the library and the test were compiled to a RISC-V binary, and the proof is about those instructions, not the source; about 180 million lines of Rocq in all, and the effort found and patched hundreds of bugs, among them a counter underflow that needed a roughly 20 MB input, the kind sampling rarely reaches.
What the proof does not cover is as important. It assumes a single-threaded static binary linked against musl, a fixed memory budget and a modelled Linux process, while most deployments run x86 or ARM with glibc and threads; it trusts the RISC-V and OS models, the theorem statements and the proof checker; and it says nothing a fuzz test does not ask, such as wrong output. The authors put it plainly: "'Formally verified' does not mean 'bug-free.'" One failure mode is specific to a model doing the proving: Claude "could make any theorem provable by rewriting the program into one that trivially never crashes", so patches were penalised, logged and audited (the same patch-to-pass shortcut as on Reward Hacking). For your own code the order stays: examples, then properties, then fuzzing for parsers and decoders that take untrusted bytes; proof is now within reach where a crash is a security bug.
A fuzzer or property test only finds bugs past the input checks if its generator builds inputs that pass them. Random bytes, or random mutations of a valid file, mostly take a decoder's rejection path; when Dan Luu had a coding agent fuzz the Zstd decoder it wrote (section 13), unguided fuzzers and property tests did exactly that, while the 10 of 160 fuzzing runs that generated structured inputs found real bugs about half the time (How well do agents use test/verification techniques?). Write the generator for the format, not for bytes.
An LLM feature is ordinary code wrapped around a call whose answer varies. Split it accordingly: the code around the call (building the prompt, parsing the answer, retrying, falling back) is tested like any code, fast and exactly, with the model replaced; the model's quality is measured by evals. Mixing the two gives slow, flaky, expensive unit tests that still do not tell you whether the model is good.
Deterministic seams. Make every source of variation something the caller passes in: the HTTP or SDK client (so a test supplies a fake), the clock as a function (so a test advances it instantly instead of sleeping), the random generator seeded (section 9's jitter fix). With all three injected, a test of the code around the model is as deterministic as a test of a pure function.
The highlighted box is the seam: the HTTP client is passed in, so a test can put a fake server or a recorded cassette behind it without editing the code. Everything left and right of it is our code and gets exact tests on every push; only the model's quality needs a statistical eval.
When model output feeds other code, the boundary needs a contract: a schema the output must satisfy, checked on every response. In Python that is a pydantic model. Structured-output modes (JSON mode, JSON schema, tool calling) and constrained decoding make valid output much more likely; validate anyway. Put semantic rules in the schema too: enum fields really in the enum, numbers within bounds, ids that resolve, citation indices in range.
experiments/llm/extract.py with pydantic , httpx class Ticket(BaseModel):
category: Literal["billing", "bug", "account", "other"]
priority: int = Field(ge=1, le=4)
summary: str = Field(min_length=1, max_length=200)
def extract_ticket(client: httpx.Client, message: str, retries: int = 1) -> Ticket:
prompt = f"Return JSON with category, priority (1-4) and summary for: {message}"
for attempt in range(retries + 1):
r = client.post("/v1/chat/completions", json={
"model": "small", "temperature": 0,
"response_format": {"type": "json_object"},
"messages": [{"role": "user", "content": prompt}]})
r.raise_for_status()
text = r.json()["choices"][0]["message"]["content"]
try:
return Ticket.model_validate_json(text)
except ValidationError as e: # repair: one retry with the error appended
prompt += f"\nYour last answer was invalid: {e.errors()[0]['msg']}. Return valid JSON only."
raise ValueError("model output failed validation after retries")
The repair loop retries once with the validation error in the prompt, then gives up and lets the caller fall back. Count how often it fires: a rising repair rate is an early signal that a model or prompt change has regressed.
httpx.MockTransport routes requests to a Python function in the same process: a fake chat-completions server that returns scripted replies and records what it was sent (a fake and a spy at once).
experiments/llm/test_extract.py (3 passed in 0.18 s)def fake_llm(*replies):
"""A fake chat-completions server: returns the given replies in order and records requests."""
seen = []
def handler(request: httpx.Request) -> httpx.Response:
seen.append(json.loads(request.content))
content = replies[min(len(seen) - 1, len(replies) - 1)]
return httpx.Response(200, json={"choices": [{"message": {"content": content}}]})
return httpx.Client(base_url="http://fake-llm", transport=httpx.MockTransport(handler)), seen
def test_out_of_range_priority_is_repaired_once():
client, seen = fake_llm('{"category": "bug", "priority": 7, "summary": "App crashes"}',
'{"category": "bug", "priority": 4, "summary": "App crashes"}')
assert extract_ticket(client, "the app crashes on login").priority == 4
assert len(seen) == 2 and "invalid" in seen[1]["messages"][0]["content"]
def test_gives_up_after_one_repair():
client, seen = fake_llm('not json at all')
with pytest.raises(ValueError):
extract_ticket(client, "hello")
assert len(seen) == 2
These tests pin what matters to the rest of the system (valid output passes through, one repair, then a clean failure, temperature=0 and JSON mode are actually sent) and run in milliseconds with no API key. The same fake can be a small local HTTP server (FastAPI or http.server) when the code under test builds its own client.
A fake returns what you think the provider returns. A recorded response test captures what it really returned once: vcrpy intercepts HTTP, saves request and response to a YAML cassette, and replays it on later runs without a network; pytest-recording wraps it as a marker. Here the "provider" is a local server so the run is self-contained; with a real provider the steps are the same.
Costs: cassettes go stale when the provider changes its API, so re-record on a schedule and when upgrading the SDK; they can capture secrets and user data, so filter headers and use synthetic inputs; and a cassette replays one sample of a nondeterministic model, so assert on structure, not on exact wording. Record modes decide what happens on a miss: once (vcrpy's default) records if the cassette does not exist and replays otherwise; none never touches the network, which pytest-recording uses by default "to prevent unintentional network requests"; new_episodes and all record more.
experiments/llm/test_vcr.py with vcrpy , pytest-recording @pytest.fixture(scope="module")
def vcr_config():
return {"filter_headers": ["authorization"]} # never write API keys into the cassette
@pytest.mark.vcr
def test_password_reset_is_an_account_ticket(provider_url):
with httpx.Client(base_url=provider_url, headers={"authorization": "Bearer sk-secret"}) as client:
t = extract_ticket(client, "I can't reset my password")
assert t.category == "account"
Some outputs are too big to write by hand in a test: the full message list sent to the model, a rendered email, a transformed data frame. A snapshot test (also golden test) records the output once into a file, you review that file like code, and every later run compares against it; any difference fails and shows a diff. Here it pinned the exact prompt the chat product sends; someone changed max_turns=2 to max_turns=1, and the snapshot failed with a diff.
SYSTEM = "You are a helpful assistant for Acme. Answer briefly."
def build_messages(history, user_msg, max_turns=2):
"""The exact message list sent to the model: system prompt, the last few turns, the new message."""
return [{"role": "system", "content": SYSTEM}] + history[-2 * max_turns:] + [{"role": "user", "content": user_msg}]
def test_prompt_is_stable(snapshot): # syrupy's fixture
assert build_messages(HISTORY, "refund?") == snapshot
The change dropped a whole turn of conversation from every prompt; a snapshot makes that visible in review, where an assertion on "the last message is the user's" would not. Use it for prompt assembly, rendered templates, API response shapes and data transforms checked against a reviewed golden file; never for live model output, which needs an eval with a tolerance, not equality. The danger is the update flag: --snapshot-update and commit, and the test now blesses the bug, so read a snapshot diff like a code change.
Treat a snapshot diff as a code change and read it in review. Scrub values that change on every run (timestamps, generated ids) or the test is flaky. Snapshot a small, meaningful view, not huge outputs nobody will read. inline-snapshot writes the value into the test file itself, which keeps small snapshots next to the code that checks them.
A unit test asks "is this exactly right?" and expects yes every time. For model quality ("are tickets categorised correctly?") the honest answer is a rate ("on 94% of cases", say), so the check is an eval: a versioned set of cases, scored, compared with the current production configuration, with a threshold and per-slice results (Production eval engineering, Eval harnesses). The split: tests (exact, every push, fake model) for prompt assembly, output parsing, schema validation, repair and fallback logic, retries, streaming, token counting, cost accounting and the gateway's routing rules; evals (statistical, on merge or nightly, real model) for answer quality, categorisation accuracy, refusal behaviour, tone and groundedness, run on every model, prompt, temperature or provider change. A few deterministic assertions sit in between and can run on real model output in the eval job: the output parses, the tool call is valid, no forbidden string appears. Treat prompts as code: versioned, reviewed, and every edit runs the eval. Runtime checks on live traffic are Guardrails.
An ML system has three things to test, and they behave differently:
The code between raw data and model input (cleaning, joining, feature computation, tokenisation, prompt assembly) is where most ML bugs live, and it is plain deterministic code. Use tiny literal fixtures (a few rows built inline, golden files for bigger cases); invariants, not only examples (row count preserved or changed by exactly the filtered rows, no NaN introduced, dtypes stable, keys unique, output values in the expected set); and the edge inputs production will send (an empty frame, one row, an all-null column, unicode, maximum-length strings, duplicate keys). Tokenisation and prompt assembly are transforms too: assert round trips where the tokenizer promises them, render templates with empty, huge and injection-shaped fields, and assert exact token counts on cost-critical paths.
experiments/mlt/test_transform.py (3 passed in 0.48 s)def clean_chats(df):
"""Drop duplicate chat ids (keep the latest), strip whitespace, drop empty messages."""
out = (df.sort_values("ts").drop_duplicates("chat_id", keep="last")
.assign(text=lambda d: d["text"].str.strip()))
return out[out["text"] != ""].sort_values("chat_id").reset_index(drop=True)
def test_keeps_latest_duplicate_and_drops_blank():
df = pd.DataFrame({"chat_id": ["a", "a", "b", "c"], "ts": [1, 2, 1, 1],
"text": ["old", " new ", "hi", " "]})
want = pd.DataFrame({"chat_id": ["a", "b"], "ts": [2, 1], "text": ["new", "hi"]})
pdt.assert_frame_equal(clean_chats(df), want)
def test_empty_frame_stays_empty_with_same_columns():
df = pd.DataFrame({"chat_id": pd.Series(dtype=str), "ts": pd.Series(dtype=int),
"text": pd.Series(dtype=str)})
out = clean_chats(df)
assert out.empty and list(out.columns) == ["chat_id", "ts", "text"]
Tests check code on inputs you chose; production data arrives without asking. A data schema states what valid data looks like (columns, types, ranges, allowed values, uniqueness), and a validation step rejects or quarantines a batch that breaks it before it reaches training or a dashboard.
Run on a bad batch with pandera , one pass flagged a duplicate id, an unknown language, a zero token count and a missing latency. Validate where data crosses a boundary: on ingest, before training, before publishing a partition; track the distribution over time (drift) in monitoring (Observability).
import pandera.pandas as pa
schema = pa.DataFrameSchema({
"chat_id": pa.Column(str, unique=True),
"lang": pa.Column(str, pa.Check.isin(["en", "fr", "de", "es"])),
"input_tokens": pa.Column(int, pa.Check.in_range(1, 128_000)),
"latency_ms": pa.Column(float, pa.Check.ge(0), nullable=False),
}, strict=True) # strict: unexpected columns are errors too
schema.validate(bad, lazy=True) # lazy: report every failure, not just the first
Great Expectations (1.23.2) does the same at a larger scale: suites of "expectations" run against tables in warehouses, with generated HTML reports for the people who own the data. pandera is a library call inside your pipeline; Great Expectations is closer to a service. Tutorials written for its old 0.x API (such as the Made With ML lesson's ge.dataset.PandasDataset) no longer run on 1.x.
Most "ML testing" failures come from testing only the code. Eugene Yan's How to Test Machine Learning Code and Systems (2020) splits model tests into pre-train tests (shapes, the loss goes down, no label leakage) and post-train tests ("Post-train tests check if the learned logic is expected"); Google's ML Test Score (Breck et al., 2017) lists "28 specific tests and monitoring needs" across data, model development, infrastructure and monitoring, still the best checklist for production readiness.
ML code is full of randomness (shuffles, initialisation, dropout, sampling). Pass a seeded generator in (rng = np.random.default_rng(0)) rather than using global state, and set seeds for random, NumPy and PyTorch in a fixture. Even then, exact equality on floats is the wrong check:
The same million float32 numbers, summed forwards and backwards, give different answers, because floating-point addition is not associative. Parallel hardware sums in whatever order its threads finish, so GPU results can change between runs and versions: PyTorch states that "completely reproducible results are not guaranteed across PyTorch releases, individual commits, or different platforms", and offers torch.use_deterministic_algorithms(True) at some speed cost (PyTorch reproducibility notes). So numeric tests assert with a tolerance chosen for the precision: np.testing.assert_allclose(got, want, rtol=1e-5) for float32, looser for bf16, and never ==.
Unit tests cannot see wiring bugs in a training loop: labels shuffled separately from inputs, the wrong tensor detached, a loss that is computed but never back-propagated. The cheapest catch is a smoke test: train on ten examples for a few hundred steps and assert the model memorises them.
experiments/mlt/test_smoke.pydef test_overfits_ten_examples():
losses = train(*ten_examples())
assert losses[-1] < 0.1 * losses[0] # a correct loop memorises 10 examples
def test_smoke_catches_shuffled_labels():
losses = train(*ten_examples(), bug=True) # labels shuffled apart from their inputs
assert not losses[-1] < 0.1 * losses[0] # the broken loop cannot
With a real model, use the smallest configuration that exercises the code path (two layers, a tiny vocabulary, or a 0.5B-parameter checkpoint), on CPU if possible, in seconds. It runs on every pull request; the full training run never does.
Loss over 500 steps on 10 examples, a tiny NumPy logistic regression standing in for a real model (experiments/mlt/smoke_out.json). The test's threshold is 10% of the starting loss.
Behavioural test sets borrow unit-test ideas for models. CheckList (Ribeiro et al., ACL 2020) names three kinds: minimum functionality tests (simple cases the model must get right), invariance tests ("label-preserving perturbations": a paraphrase or a swapped name must not change the answer) and directional tests (adding "answer in French" must change the language). Because a model passes them statistically, they are scored with a threshold and per-slice results, versioned with the prompt, and wired in as a merge gate; that machinery is on Production eval engineering.
Bad test data is a quiet source of bad tests: fixtures nobody understands, copies of production that leak personal data, shared files one test edits and another depends on. The options, from smallest to largest:
| Source | Use it for | Watch out for |
|---|---|---|
| Literal inputs in the test (a 3-row data frame, a dict) | Almost every unit test: the expected result can be checked by eye. | Copying the same 30-line literal into many tests; move it to a fixture. |
Factories and builders: a function make_chat(**overrides) with sensible defaults | Domain objects with many fields, where each test cares about one or two. | Defaults that hide what the test depends on: pass the field the test is about explicitly. |
| Generated inputs (Hypothesis strategies) | Large input spaces (section 6). | Strategies narrower than real data. |
| Golden files: a reviewed input and expected output on disk | Transforms over bigger data, rendered outputs (section 7). | Files nobody reviews when they change. |
| Recorded traffic (VCR cassettes) | Third-party APIs (section 7). | Secrets and personal data in the recording; recordings going stale. |
| Sampled production data | Realistic edge cases nobody would invent; eval sets. | Personal data: anonymise or synthesise, and record where it came from and when. |
Two rules keep it sane. Each test creates what it needs and leaves nothing behind (the rollback fixture, tmp_path for files), so tests can run in any order and in parallel. Large datasets are versioned, not copied: keep them out of git (DVC, Git LFS or object storage with a version in the path), pin the version the test uses, and keep a tiny sample in the repository for the fast tests.
A flaky test passes and fails on the same code. It is worse than no test: every red build might be noise, so people learn to press "rerun" until it is green, and then a real failure gets rerun away too. At Google's scale, "about 1.5% of all test runs" reported a flaky result and "almost 16% of our tests have some level of flakiness" (Micco, Google Testing Blog, 2016).
Luo, Hariri, Eloussi and Marinov studied 201 fixes of flaky tests in 51 open-source projects and classified 161 (FSE 2014). Async wait: the test sleeps or polls instead of waiting for the thing it needs. Test order dependency: one test relies on state another leaves behind. "Other" is derived (161 - 74 - 32 - 19 = 36, several smaller categories). In ML code add unseeded randomness, real network calls and exact asserts on floats.
Two of these, built and measured:
def full_jitter(attempt, rng=None):
rng = rng or random
return rng.uniform(0, backoff_delay(attempt))
def test_jitter_waits_a_bit():
# attempt 3: uniform in [0, 2.0] seconds
assert full_jitter(3) >= 0.1 # false 5% of the timedef test_jitter_stays_within_bounds():
rng = random.Random(1234) # same draws every run
for attempt in range(1, 8):
for _ in range(1000):
d = full_jitter(attempt, rng)
assert 0 <= d <= backoff_delay(attempt)Each square is one run of the flaky test (pytest --count=2000, run by run from a JUnit XML report); red ones failed.
The fix does two things. It seeds the generator, so a failure always reproduces. And it asserts the real contract (the wait lies between 0 and the cap), which is true on every draw; "waits at least 0.1 s" was never part of the contract, and no seed makes an untrue assertion correct.
def test_default_model():
assert build_request("hi")["model"] == "small"
def test_large_model_override():
settings_mod.CONFIG["model"] = "large" # never restored
assert build_request("hi")["model"] == "large"def test_large_model_override(monkeypatch):
monkeypatch.setitem(settings_mod.CONFIG, "model", "large")
assert build_request("hi")["model"] == "large"
# monkeypatch undoes the change after the testA chat backend is mostly async code: functions declared async def that pause at await while waiting on the network, so one process can serve many requests at once. pytest itself cannot run an async def test; a plugin such as pytest-asyncio (or AnyIO's pytest plugin) runs it in an event loop. The rules that keep async tests deterministic:
await asyncio.sleep(0.1) "so the background task finishes" is the classic flaky test. Await the task, or wait on an event the code sets.TestClient or httpx.AsyncClient with an ASGI transport calls your app without a network; Building a backend API has the service.In pytest-asyncio's default strict mode each async test needs @pytest.mark.asyncio.
experiments/asy/test_async.py with pytest , pytest-asyncio async def first_token(stream, timeout):
"""Wait for the first token of a streamed reply, give up after `timeout` seconds."""
return await asyncio.wait_for(anext(stream), timeout)
async def slow_stream(delay):
await asyncio.sleep(delay)
yield "Hello"
@pytest.mark.asyncio
async def test_first_token_arrives():
assert await first_token(slow_stream(0.01), timeout=1) == "Hello"
@pytest.mark.asyncio
async def test_slow_model_times_out():
with pytest.raises(TimeoutError):
await first_token(slow_stream(10), timeout=0.05)
async def test_no_marker(): # forgot the marker
assert await first_token(slow_stream(0), 1) == "WRONG"
The unmarked test asserts something false, and it fails here only because pytest refuses to run it. In older pytest versions an async test with no plugin was skipped with a warning, so a suite could show green while its async tests never ran; current pytest fails it instead (pytest 8.4.0 changelog, 2025-06-02: "Async tests will now fail, instead of warning+skipping, if you don't have any suitable plugin installed."). If your project pins an old pytest, check the warnings summary.
Find them on purpose. pytest-randomly shuffles test order on every run and resets random.seed, printing the seed so a failing order can be replayed with -p randomly --randomly-seed=N; run it in CI and order dependencies surface in days instead of months. pytest-xdist (-n auto) runs tests in parallel processes, which finds shared files and ports. pytest-repeat's --count reruns a suspect test hundreds of times, as above.
Measure them. A test's flakiness is the share of runs on the same commit where it failed and then passed on retry. CI systems that keep test history (Buildkite Test Engine, Datadog, Trunk, or a script over JUnit XML reports) can compute it per test and rank the worst.
Quarantine, then fix or delete. Google built "a tool that monitors the flakiness of tests and if the flakiness is too high, it automatically quarantines the test. Quarantining removes the test from the critical path and files a bug for developers to reduce the flakiness" (same post). By hand: move it out of the blocking job, give the bug an owner and a deadline, then fix it or delete it. Automatic retry (pytest-rerunfailures, --reruns 2) keeps the build green but hides real intermittent bugs (a race in your code looks exactly like a flaky test) and slows the suite; if you use it, record every rerun and review the list. Never let "rerun until green" become the culture.
Code coverage measures which code ran during the tests: line coverage counts executed lines; branch coverage also checks that every if went both ways. coverage.py measures both (coverage run --branch -m pytest, then coverage report -m lists the lines that never ran). That list is valuable: code no test executes is certainly untested. The reverse does not hold: coverage records that a line ran, not that any test checked what it did.
Mutation testing asks the better question: if the code had a bug, would a test fail? A tool makes many small changes to the code, one at a time (each change is a mutant: >= becomes >, 2 becomes 3, - 1 becomes + 1), and runs the tests against each. A mutant is killed if some test fails and survives if every test still passes: a bug your suite would not notice. The mutation score is the share killed.
Retry-After floored at 1 instead of 0), and 10 of the 16 kills are mutants that simply crash, which any test that runs the line kills. The figure shows coverage saturating at the third test.experiments/mut/tests/test_weak.pydef test_should_retry():
assert should_retry(503, attempt=1)
assert not should_retry(503, attempt=3)
def test_backoff_delay():
assert backoff_delay(1) > 0
def test_parse_retry_after():
assert parse_retry_after("2") == 2.0
assert parse_retry_after(None) is None
assert parse_retry_after("soon") is None
The weak suite has 100% line and branch coverage and lets planted bugs through, every one a wrong value; of its kills were mutants that crash (min(None, ...)). The improved suite (exact delays for attempts 1 to 6, a custom cap, every retryable and non-retryable status, the boundary at the last allowed attempt, negative and zero headers) kills all . Try it below.
Tests added one at a time: the weak suite's 3 test functions, then the improved suite's 7. Statements covered out of 15 and mutants killed out of 23, from the real per-test coverage (coverage.py dynamic contexts) and kill matrix (every mutant run against every test case, src/experiments/killmatrix.py), measured on 2026-10-04 with mutmut 3.8.0.
The retry policy, its two real suites, and all mutants mutmut generated for it. Tick tests on and off and watch both numbers; click a mutant for its line and a test that kills it. The challenge: the fewest tests that kill everything.
mutmut's own verdicts (weak /, improved /) match the per-test matrix. Module-level lines (the import, the RETRYABLE constant and the def lines) run on import and count as covered for any selection.
RETRYABLE = frozenset({408, 429, 500, 502, 503, 504}) produced no mutants at all, so mutmut could not tell you that the weak suite never checks which statuses are retryable. The improved suite covers it by naming every status explicitly. Keep important constants inside functions or test them directly.What it costs. One run of the suite per mutant: here mutants at mutants per second, under a second, but a large service has tens of thousands of mutants and a suite that takes minutes. So run it on changed code only (as Google does), nightly, or on the modules that matter most (pricing, permissions, retries). Some mutants are equivalent: they change the code but not its behaviour, cannot be killed, and need a human to dismiss them. Skip it for glue code and prototypes; use it where a silent wrong value is expensive.
[tool.mutmut] source_paths = ["src/"] pytest_add_cli_args_test_selection = ["tests/test_weak.py"] $ mutmut run # generate mutants, run the suite against each $ mutmut results # list survivors $ mutmut show retrypolicy.x_backoff_delay__mutmut_9 # the diff of one mutant
Continuous integration (CI) runs the checks automatically on every push and pull request, on a clean machine, and blocks the merge if any fail. It turns "the tests pass on my laptop" into "the tests pass, from scratch, for everyone". The design problem is time: developers wait for CI, so the order and split of the checks matter as much as the checks.
Fig. 4 is the job graph of the workflow in the closed block below (written for this page on 2026-10-04 and parsed as valid YAML, not run on GitHub). Block sizes are not measurements; the durations in the step text are the order of magnitude each tier should aim for.
static (ruff check, ruff format, mypy: seconds), unit (minutes), integration (minutes), then review and merge. Each job runs only if the one before it passed (needs:).static in seconds, and unit and integration never start: the cheapest check gives the fastest feedback and saves the rest of the run.pytest -m "not slow and not gpu" -n auto -p randomly; fail-fast: false lets every version report.postgres:17, started by GitHub Actions as a service container next to it and health-checked with pg_isready before the tests run.concurrency with cancel-in-progress: true cancels the older run, which was worthless anyway.schedule: cron "0 3 * * *" starts gpu-nightly on a gpu-t4 runner (smoke training, slow tests, evals), where hours are fine.@pytest.mark.slow, gpu, integration) so laptops and CI select with -m.concurrency with cancel-in-progress: true cancels it (workflow syntax).pytest -n auto (pytest-xdist) inside a job, and a matrix across Python versions; set fail-fast: false on a matrix when you want every version to report rather than stop at the first failure.# .github/workflows/ci.yml (written 2026-10-04; action versions checked on GitHub that day)
name: ci
on:
pull_request:
push:
branches: [main]
schedule:
- cron: "0 3 * * *" # nightly: slow and GPU tiers
concurrency: # a new push cancels the older run of the same branch
group: ci-${{{ github.ref }}
cancel-in-progress: true
jobs:
static: # seconds: fail fast on the cheapest checks
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: astral-sh/setup-uv@v10.2.0 # no floating @v10 tag since v8: pin a release or a SHA
with: { enable-cache: true }
- run: uv sync --locked
- run: uv run ruff check . && uv run ruff format --check .
- run: uv run mypy src
unit: # minutes at most: every push
needs: static
runs-on: ubuntu-latest
strategy:
fail-fast: false # let every Python version report
matrix: { python: ["3.12", "3.13"] }
steps:
- uses: actions/checkout@v7
- uses: astral-sh/setup-uv@v10.2.0
with: { enable-cache: true, python-version: "${{{ matrix.python }}" }
- run: uv sync --locked
- run: uv run pytest -m "not slow and not gpu" -n auto -p randomly --junitxml=unit.xml
integration: # real PostgreSQL as a service container
needs: unit
runs-on: ubuntu-latest
services:
postgres:
image: postgres:17
env: { POSTGRES_PASSWORD: test }
ports: ["5432:5432"]
options: >-
--health-cmd pg_isready --health-interval 2s --health-timeout 5s --health-retries 20
env:
DATABASE_URL: postgresql://postgres:test@localhost:5432/postgres
steps:
- uses: actions/checkout@v7
- uses: astral-sh/setup-uv@v10.2.0
with: { enable-cache: true }
- run: uv sync --locked
- run: uv run pytest -m "integration" --junitxml=integration.xml
gpu-nightly: # smoke training run and evals on a GPU runner
if: github.event_name == 'schedule'
runs-on: gpu-t4 # the name you gave your GPU larger runner
steps:
- uses: actions/checkout@v7
- uses: astral-sh/setup-uv@v10.2.0
with: { enable-cache: true }
- run: uv sync --locked
- run: uv run pytest -m "gpu or slow"
actions/checkout is at v7 (v7.0.1, 2026-07-20); many examples online still show v4. astral-sh/setup-uv stopped publishing floating major tags at v8.0.0 ("You won't be able to use @v8 or @v8.0 any longer", release notes), so @v10 does not resolve: pin a full release such as v10.2.0, or a commit SHA, which is the safer habit for every third-party action.Some code paths (CUDA kernels, mixed precision, a serving engine) only run on a GPU. Whatever runs on GPUs: cache model weights on the runner, use the smallest model that exercises the code, assert numeric results with tolerances (section 8), and keep full-size evals in the nightly tier.
| Option | What you get | Cost and catch |
|---|---|---|
| Avoid needing one | CPU runs of the smallest model that exercises the path, or a fake engine. | Free; misses GPU-only bugs. |
| GitHub-hosted GPU runner | 4 vCPU, one NVIDIA T4 (16 GB), 28 GB RAM. | $0.052 per minute on Linux, GitHub Team or Enterprise Cloud only (runner pricing, 2026-10-04). A T4 is old and small: fine for smoke tests, not for a 70B model. |
| Self-hosted runner on your own GPU machine | Any GPU, weights cached on local disk. | You run and secure it; never attach one to a public repository, where anyone's pull request could run code on it. |
| Ephemeral cloud GPU from a CPU job (Modal, SkyPilot, a cloud batch API) | A large GPU for the minutes the test needs. | Pay per second; needs credentials in CI; cold starts add minutes. |
Static analysis (ruff for lint, mypy or pyright for types) reads the code and catches whole classes of bugs before anything runs: type errors (passing a str where an int is expected), misspelled names, unused imports, unreachable code, a missing await. It misses anything about values at run time: a wrong formula type-checks fine. It costs seconds for a whole repository, which is why it is the first CI job and a pre-commit hook in the figure above.
Code review is the human check: a second engineer reads the change before it merges. As a quality practice it covers what no automated check can: whether the tests would fail if the code were wrong (read the tests first), whether the public surface and the error paths changed on purpose, and whether the change was needed at all. Google's mutants as review comments (section 10) make the first question visible to the reviewer.
How to write types (hints, checkers, dataclasses against pydantic, protocols) and how to give and take a review are Code design's (types and checkers in its closed "Depth: types and tooling" block, review as a craft in section 13), with its measured checker runs; this page places them in the pipeline.
A green suite says the behaviours someone thought to test still hold. It says nothing about the rest, and a big change travels straight through the rest. Nous Research's refactor of its Hermes agent codebase is a measured example: about nineteen active hours, 1,393 subagents (up to 218 at once) working on a repository of 1,063,826 non-test Python lines, cutting non-test source by 34.4% for about $19,300 in model costs for the main run (roughly $25k with follow-ups). Per-agent worktrees and a frozen baseline made the parallel edits integrable. Community review then caught public names that had been removed and a suppress() rewrite that changed exception handling at about 65 sites: "These were real regressions the existing tests had missed" (Nous Research, 2026). What closes that gap:
__all__, public classes, function signatures) before and after, and fail on any removal or signature change the change does not declare. Tests cover what someone called; the public surface is the promise.pytest.raises(RateLimited) on the 429 path), not only that an error happens. Broadened or swallowed exceptions are exactly the change a happy-path suite cannot see.The same rules apply to one AI-written pull request: read the tests first, and check they would fail if the code were wrong. An agent's own tests are where that check fails most often. In Dan Luu's 4,800 single-turn runs of GPT-5.6 Sol writing a Zstd decoder from its spec, agents fed four identical streams to a decoder that reads four, tested a backwards bitstream read with palindromic data, and wrote expected values that encoded the code's own wrong answer, so the tests passed on wrong code; naming a technique in the prompt (TDD, property tests, fuzzing, a proof tool) did not change that (one model, one task; How well do agents use test/verification techniques?). Code design (section 13 and its Review lab) covers reviewing AI-written code.
| Concern | Common choice (2026-10-04) |
|---|---|
| Runner and plugins | pytest with pytest-xdist (parallel), pytest-randomly (order), pytest-asyncio or AnyIO (async), pytest-recording or vcrpy (HTTP), syrupy or inline-snapshot (snapshots). |
| Inputs | Literal fixtures and factories; Hypothesis for parsers, transforms and data structures. |
| Real dependencies | testcontainers or CI service containers for PostgreSQL, Redis and Kafka; in-memory fakes for third-party APIs; Pact where both sides are your teams. |
| Static checks | ruff for lint and format, mypy or pyright for types, in pre-commit and as the first CI job. |
| Data | pandera schemas inside pipelines, Great Expectations for warehouse tables, drift monitoring in production. |
| ML and LLM | Seeded, tolerance-based numeric tests; a training smoke test per pull request; pydantic contracts on model output; fake model servers; evals as a separate gate. |
| Suite health | Coverage reported on every pull request (no mandate on the number); mutation testing on critical modules or changed lines; flaky tests tracked, quarantined and owned. |
| CI | GitHub Actions (or GitLab CI, Buildkite) with uv caching, cheapest checks first, a merge queue, nightly slow and GPU tiers. |
One request to an LLM chat product followed from 1 user to 10M; the map these children hang from. Its tabs: Scale simulator, Numbers to know, Case files. 25 min
"One content update, pushed to everyone at once, crashed 8.5 million PCs" (CrowdStrike, 2024); "A config file that doubled in size crashed the proxy worldwide" (Cloudflare, 2025); "Three serving bugs quietly made Claude's answers worse" (Anthropic, 2025); "Deleted the wrong database, then found the backups did not work" (GitLab, 2017). Each is a test that was missing. 15 min
Characterization tests and refactoring under test (section 9); the Review lab's mock-only test that passes with the function broken; reviewing AI-written code. About 37 min.
The service these tests would protect (OpenAPI as a contract is Service APIs, section 3). About 32 min.
Retries, backoff and jitter (the policy tested here), deployment safety, incidents. About 40 min.
What catches the bugs tests miss, in production. About 39 min.
Load testing, which this page leaves out. About 39 min.
Delivery semantics and idempotent consumers, measured on a real PostgreSQL. About 40 min.
Including what Jepsen-style testing finds in databases. About 46 min.
The gateway, fallbacks and model rollouts that LLM tests protect. About 28 min.
Worked designs from requirements to bottlenecks. About 41 min.
Golden sets, regression gates in CI, shadow and A/B tests. 30 min
lm-eval-harness, Inspect, HELM, promptfoo, Braintrust. 26 min
How many cases a gate needs; paired tests; error bars. 25 min
Runtime checks on live model traffic. 39 min
Engines, indexes and the SQL behaviour integration tests guard. 29 min
Fixtures, parametrize, markers: the substrate everything here runs on. 1 h for the how-to pages
Quick start, strategies, stateful testing, the numpy and pandas extras. 45 min
Testing overview, unit testing, test doubles, larger tests; free online. 2 h
Ham Vocke on martinfowler.com: every layer with real code. 45 min
Martin Fowler; the classic on test doubles and the two schools of TDD. 30 min
Eugene Yan (2020); pre-train and post-train tests with worked code. 30 min
Goku Mohandas; code, data and model tests with pytest. Its Great Expectations code uses the old 0.x API. 40 min
Breck et al., Google (2017): 28 tests and monitoring needs; still the best checklist. 45 min
Petrović et al.: mutants in code review at Google. 40 min
Luo et al., FSE 2014: the causes, with fixes. 40 min
Inozemtseva and Holmes, ICSE 2014. 30 min
Ribeiro et al., ACL 2020: behavioural testing of models. 40 min
Anthropic (2026): a port at about 98% of its tests matched about a quarter of production inputs, so the running Python API became the verifier; read for the replay design and the weakened tests it found. 17 min, plus 1 in closed details
Dan Luu (2026): 26 testing instructions and 4 skills given to a coding agent, none measurably better than none; read the transcripts section for what agent-written tests miss. Our article page adds the significance tests. 23 min, plus 5 in closed details
Nous Research: what a green suite missed in a million-line refactor. 20 min
The two tools behind the mutation lab in section 10. 20 min
src/, rebuilt 2026-10-24 to the teaching contract; experiments and raw outputs are in src/experiments/ and src/inputs/.