Testing and quality: unit, property-based, data and model tests, CI

Reading: 46 min, plus 18 in closed details. How to know your code works, and keep knowing it while you change it, with real pytest code run on 2026-10-04 against pieces of the LLM chat product from Topic: swe-and-system-design. Data as of October 2026.

The idea in one screen

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.

  1. Nets stacked cheapest first. A change meets static checks first (the whole repository in seconds: type errors, typos, a missing await), then unit and property tests, contract tests and fakes, integration tests, end-to-end tests and, on top, evals. Plate widths are the pyramid's proportions, not measurements.
  2. Unit and property: the chunker. The chunker drops short documents: 3 examples pass, the property fails within 5 generated inputs and shrinks to one character (section 6). Nothing above a unit test is needed, but only a generated input finds it.
  3. Contract and fakes: the model-output parser. Out-of-range model output: exactly one repair request, then a clean failure. 3 tests in 0.18 s, no API key (section 7).
  4. Integration: chat search. Chat search green on SQLite, wrong on PostgreSQL: [2] instead of [1, 2]. ms a test, x SQLite. It cannot be caught below a real PostgreSQL (section 5).
  5. The top layers. End-to-end: a few critical journeys after each deploy (send a message, get a streamed reply); not built here. Evals ask whether the model is good: a rate with a threshold, not yes or no, measured on Production eval engineering.
  6. Testing the nets. 100% coverage still let 7 of 23 planted bugs through: the weak suite runs every line of the retry policy (100% line and branch coverage), yet it killed only 16 of 23, and the 7 wrong values rise straight through the net (section 10). A test with unseeded randomness failed 4.7% of 12,000 runs (section 9). The suite itself needs testing.

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.

Unit, integration, end-to-end
one function in one process; your code with a real dependency; the deployed system driven like a user
Test double: fake, stub, mock
a stand-in for a dependency: a small working implementation; canned answers; expected calls checked
Property-based test
a statement true for every valid input, checked on hundreds of generated inputs, with failures shrunk to the smallest
Fuzz test, formal proof
"never crashes" checked on millions of mutated inputs; the same property proved by a checker for every input
Contract test
checks the agreement between two sides (a provider's responses, a model's structured output) directly
Seam
a place where a test can replace a dependency without editing the code: an injected client, clock or random generator
Flaky test
passes and fails on the same code
Coverage, mutation score
the share of lines and branches the tests ran; the share of planted bugs (mutants) some test noticed

1. What a test buys, and what it cannot

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.

Checked: "a bug costs 100 times more in production" (the number is weaker than it sounds)

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.

2. Layers: what each catches, what it costs

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).

Pyramid and trophy agree on the top; they differ on how wide the middle is

Band widths are the shapes' proportions, not measurements. Click a band for what that layer catches, misses and costs on this page.

3. Unit tests that survive refactoring

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:

real experiments/hyp/chunking.py
def 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:])
real experiments/hyp/test_chunking_examples.py
from 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
$ pytest -q test_chunking_examples.py ... [100%] 3 passed in 0.53s

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.

Test behaviour, not implementation

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.

brittle tests the implementation

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.RETRYABLE

robust tests the behaviour

def 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:

  • Arrange, act, assert: build the inputs, call the code once, check the result. If a test needs three acts, it is three tests.
  • One reason to fail, and a name that says the behaviour: test_retry_preserves_idempotency_key, not test_retry_2. When it goes red in CI, the name is the bug report.
  • Tiny literal inputs written in the test itself, so the expected output can be checked by eye.
  • Write the failing test before fixing a bug. It proves you reproduced the bug and stops it coming back (a regression test). Every production incident should leave one behind; for model behaviour the equivalent is a new case in the golden set (Production eval engineering).
  • Design for testing: a function that takes its inputs as arguments and returns a value (a pure function) needs no setup at all. Anything that touches S3, a database or the clock goes behind an interface a test can replace. Code design (sections 7 and 5: functional core, dependency injection) shows the refactoring on a real handler.
pytest in one screen (runner, fixtures, parametrisation, errors, floats, markers, a starting config)

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.

CommandWhat it does
pytest -qRun everything under the current folder, one character per test.
pytest tests/test_search.py::test_search_ignores_caseRun 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 --lfStop 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=10List 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:

real 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:

real 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.
  • Markers label tests: @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",
]
A test tied to the how fails on a correct refactor and passes a real bug

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).

4. Test doubles: prefer real, then fake, then 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).

  1. The seam. 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.
  2. A mock of the connection. It records the call, and the test asserts 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.
  3. SQLite in memory, a stand-in. Playing the fake's role, it returns [1, 2], because its 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).
  4. Real PostgreSQL . Its 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.
  5. The fix, on both. 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.

Where a mock is the right tool

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.

Where a mock lies

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.

Contract tests: keeping fakes honest

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).

Consumer-driven contracts: the consumer writes the expectations, the provider's CI replays them

5. Integration tests against the engine you ship

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:

real 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.

Three ways to get the real thing (pgserver, testcontainers, CI service containers)
OptionHowCost
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-pythonStarts 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 containersThe 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.
Same query, same rows, two engines: PostgreSQL misses the capitalised title

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].

6. Property-based testing: let the computer pick the inputs

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.

real experiments/hyp/test_chunking_property.py
from 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
$ pytest -q test_chunking_property.py E AssertionError: assert '' == '0' E Failing test case: test_round_trip_loses_nothing( E text='0', E args=(2, 0), E ) 1 failed in 1.81s

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.

  1. Generating (calls 1 and 2). Hypothesis draws a text and a valid (size, overlap). Call 1 is the empty text; call 2 has 2 characters with size 1. Both round-trip: pass.
  2. First failure (call 3). 2 characters, size 16, overlap 7: the text is shorter than one window, so 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.
  3. Shrinking starts (calls 4 to 10). Hypothesis now tries simpler variants and keeps any that still fail. Overlap 7 becomes 0: still fails. It also tries two other failing texts (10 and 3 characters); size 1 always passes (one-character windows always fit), so the shrinker throws those away.
  4. Smaller windows (calls 11 to 15). Back on the 2-character text, size 16 halves to 8 and then 4: still failing. The empty text and size 2 (two characters fit one window exactly) pass.
  5. Size 3, plainer characters (calls 16 to 20). Size 3 still fails; the two exotic code points become '00', which still fails at size 3; sizes 1 and 2 pass.
  6. Shorter text (calls 21 to 24). '0' with size 3 fails, size 1 passes, size 2 fails: the smallest failure so far (glowing). The empty text passes again.
  7. The report (call 25). Nothing simpler fails, so Hypothesis runs the smallest failure once more to print its error report: 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.

Stateful testing: random sequences of operations

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:

E AssertionError: assert 0 == None E Failing test case: E state = LRUMatchesModel() E state.put(k='b', v=0) E state.put(k='a', v=0) E state.get(k='b') # b is now the most recently used E state.put(k='c', v=0) # so a should be evicted, but the cache evicts b E state.get(k='a') 1 failed in 0.14s

Writing that sequence by hand requires already knowing the bug.

The stateful test's code (a RuleBasedStateMachine against an OrderedDict model)
real experiments/hyp/test_lru_stateful.py
class 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.TestCase

Properties that pay off, especially in ML code

  • Round trip: decode(encode(x)) == x; config to YAML and back; a tokenizer where it promises it.
  • Invariants: shape and dtype preserved; row count preserved (or changed by exactly the filtered rows); no NaN introduced; output vocabulary within the expected set; probabilities sum to 1.
  • Idempotence: normalising twice equals normalising once, f(f(x)) == f(x).
  • Equivalence to a slow reference: the vectorised implementation equals a plain loop on every input (a test oracle).
  • Monotonicity: a higher score never ranks lower.
  • Never crashes: a parser for model output returns a value or raises your own error type, for any string.

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.

Checked: the old page's NumPy example, run as written (it fails, twice)

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.

Above sampling: fuzzing, then proof

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.

7. Testing code that calls an LLM

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.

One LLM feature, four checks: three exact tests on our code, one eval on the model

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.

Contract tests on structured output

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.

real 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.

A fake model server

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).

real 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.

Record and replay (VCR)

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.

The recorded test and its three runs (record, replay offline, fail without the cassette)
real 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"
$ pytest --record-mode=once test_vcr.py # provider up: records the cassette 1 passed in 1.29s $ PROVIDER_DOWN=1 pytest --record-mode=none test_vcr.py # nothing listening: replays it 1 passed in 0.14s $ (cassette deleted) PROVIDER_DOWN=1 pytest --record-mode=none test_vcr.py 1 failed in 0.14s # the saved cassette: method, URL, request body, response body, no authorization header

Golden outputs: snapshot the prompt

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.

The snapshot test and its failing diff (syrupy)
real experiments/snap/ with syrupy
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
$ pytest --snapshot-update # first run: writes __snapshots__/test_prompt_snapshot.ambr 1 snapshot generated. # someone changes max_turns=2 to max_turns=1 $ pytest E AssertionError: assert [+ received] == [- snapshot] E - dict({ E - 'content': 'price?', E - 'role': 'user',... 1 snapshot failed.

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.

Snapshot hygiene (scrubbing, size, inline snapshots)

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.

When an eval replaces a test

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.

8. Testing data and ML code

An ML system has three things to test, and they behave differently:

Transforms are ordinary code: test them like it

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.

A transform and its tests (pandas, 3 passed in 0.48 s)
real 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"]

Data validation: a schema the data must pass

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).

The schema, its report, and Great Expectations (pandera code; when to use the bigger tool)
real experiments/mlt/pandera_demo.py with pandera
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
column check failure_case index chat_id field_uniqueness a1 0 chat_id field_uniqueness a1 1 lang isin(['en', 'fr', 'de', 'es']) pt 1 input_tokens in_range(1, 128000) 0 1 latency_ms not_nullable NaN 1

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.

Code is checked exactly, data against a schema, the model statistically

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.

Seeds and tolerances: deterministic enough to test

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 ==.

The training smoke test

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.

The smoke test's code and output
real experiments/mlt/test_smoke.py
def 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.

A correct loop memorises ten examples; a loop with shuffled labels cannot

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.

Model behaviour: where tests end and evals begin

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.

Where test inputs come from (literals, factories, generated, golden files, cassettes, sampled production data)

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:

SourceUse it forWatch 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 defaultsDomain 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 diskTransforms 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 dataRealistic 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.

9. Flaky 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).

Almost half of fixed flaky tests waited on something asynchronously

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:

1. Unseeded randomness

flaky

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 time

fixed

def 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.

2. Test order dependency

flaky

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"

fixed

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 test

The top cause: waiting on async code

A 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:

  • Do not sleep to wait for something. 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.
  • Timeouts belong in async tests: a hung await hangs CI forever. Give every network wait a timeout in the code, and test it with a delay far beyond the timeout (10 s against 0.05 s below) so the test is not flaky.
  • Time-dependent logic (rate limiters, cache expiry, retries with backoff): pass the clock in as a function, and give the test a fake clock it can advance instantly, instead of sleeping for real.
  • Test web endpoints in-process: FastAPI's TestClient or httpx.AsyncClient with an ASGI transport calls your app without a network; Building a backend API has the service.
Async tests in code, and a trap that used to pass silently (pytest-asyncio, pytest 8.4)

In pytest-asyncio's default strict mode each async test needs @pytest.mark.asyncio.

real 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"
PASSED test_async.py::test_first_token_arrives PASSED test_async.py::test_slow_model_times_out FAILED test_async.py::test_no_marker - Failed: async def functions are not natively supported.

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, measure, quarantine

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.

10. Coverage and mutation testing: is the suite any good?

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.

Predict: the weak suite below calls every function of the retry policy, so line and branch coverage are 100%. Of the 23 mutants mutmut makes, how many does it kill?
real experiments/mut/tests/test_weak.py
def 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 coverage report and mutmut's survivors (terminal output)

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.

Coverage hits 100% at the third test; the mutation score keeps climbing

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.

Mutation lab: which tests notice which bugs?

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.

src/retrypolicy.py: green edge, a line some selected test runs; red, a line none runs; yellow, the selected mutant's line.
All 23 mutants (kind, original and mutated line, killed or survived under your selection; click one)
Kind: crash mutants raise an error (any test that runs the line kills them); value mutants return a wrong value (only a test that checks the value kills them).

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.

A gap measured here: what mutmut 3 does not mutate
mutmut 3 only mutates code inside functions; its README says to use mutmut 2 "if you want to mutate code outside of functions". The module-level 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 the research and practice say

  • Inozemtseva and Holmes measured 31,000 test suites over five Java systems and found "a low to moderate correlation between coverage and effectiveness when the number of test cases in the suite is controlled for", effectiveness being mutants killed (ICSE 2014). Coverage is a floor detector, not a goal.
  • Google's guidance treats "60% as 'acceptable', 75% as 'commendable' and 90% as 'exemplary'", while adding "There is no 'ideal code coverage number' that universally applies to all products" and "We should not be obsessing on how to get from 90% code coverage to 95%" (Google Testing Blog, 2020).
  • Google runs mutation testing incrementally, "mutating only changed code during code review", showing at most one mutant per line as a review comment; "82% of all surfaced mutants with feedback were labeled as productive by developers" (Petrović et al., 2021). Developers exposed to it "write more tests, and actively improve their test suites" (Petrović et al., ICSE 2021).

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.

Running mutmut (configuration and commands)
real mutmut , configured in pyproject.toml
[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

11. CI: fast feedback, cheapest checks first

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.

  1. Jobs in needs: order. pre-commit on the laptop (ruff, optionally the fast tests, before each commit), then on every push 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:).
  2. A bad change stops at the first job. A lint error (illustrative) fails static in seconds, and unit and integration never start: the cheapest check gives the fastest feedback and saves the rest of the run.
  3. The unit matrix. A good change fans out into one unit job per Python version (3.12 and 3.13), each running pytest -m "not slow and not gpu" -n auto -p randomly; fail-fast: false lets every version report.
  4. Integration with a real database. The job talks to postgres:17, started by GitHub Actions as a service container next to it and health-checked with pg_isready before the tests run.
  5. Cancel stale runs. A newer push to the same branch arrives; concurrency with cancel-in-progress: true cancels the older run, which was worthless anyway.
  6. Merge, and the nightly tier. A human reads the tests first and the change merges. The slow tiers run on their own trigger: schedule: cron "0 3 * * *" starts gpu-nightly on a gpu-t4 runner (smoke training, slow tests, evals), where hours are fine.
  • Cheapest first, fail fast. Lint and type checks take seconds and catch a large share of mistakes; run them first and stop there if they fail. Then unit tests (aim for a few minutes), then integration tests, then the slow tiers.
  • Tiers by cost. Unit on every push; integration with real services and fakes on every pull request; GPU, full-model and eval tiers on the merge queue or nightly. Mark tests (@pytest.mark.slow, gpu, integration) so laptops and CI select with -m.
  • Cache dependencies. Resolving and downloading packages can take longer than the tests; uv with its cache restores an environment in seconds.
  • Cancel stale runs. A new push to the same branch makes the previous run worthless; concurrency with cancel-in-progress: true cancels it (workflow syntax).
  • Parallelise with 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.
  • Same checks locally. pre-commit hooks run ruff (and optionally the fast tests) before each commit, so CI is rarely the first to find a lint error.
The complete GitHub Actions workflow (experiments/ci/ci.yml, dated 2026-10-04, with the version pins checked that day)
# .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"
Version pins, checked 2026-10-04
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.

GPU tests in CI

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.

Four ways to get a GPU into CI (CPU stand-ins, GitHub's T4 runner and its price, self-hosted, ephemeral cloud GPUs)
OptionWhat you getCost and catch
Avoid needing oneCPU runs of the smallest model that exercises the path, or a fake engine.Free; misses GPU-only bugs.
GitHub-hosted GPU runner4 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 machineAny 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.

12. Static analysis, types and review: the checks that are not tests

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.

13. Very large and AI-written changes: where tests are silent

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:

  • Public-API diffing as a merge gate. List the exported surface (__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.
  • Exception-contract tests. Assert the exception type and the condition that raises it (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.
  • Frozen baselines. Compare behaviour against the pinned pre-change commit, not a moving main branch; run the old and new code on the same recorded inputs and diff the outputs. When the old system keeps changing and its replies are nondeterministic, the running old system is the baseline: call the model once, replay its output to both versions, compare every intermediate step, and log only where the first difference is. Anthropic's port of its Messages API from Python to Rust needed exactly that, since the port passed about 98% of its integration tests while only about a quarter of shadowed production inputs matched (Migrating our Messages API to Rust).
  • Review by surface, not by file. Nobody reads a million-line diff. Spend human attention on the public interface, the error paths and the deleted code; mutation testing on the changed lines shows where the tests are silent.

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.

Reference

What pros run in production (the common choice per concern, 2026-10-04)
ConcernCommon choice (2026-10-04)
Runner and pluginspytest with pytest-xdist (parallel), pytest-randomly (order), pytest-asyncio or AnyIO (async), pytest-recording or vcrpy (HTTP), syrupy or inline-snapshot (snapshots).
InputsLiteral fixtures and factories; Hypothesis for parsers, transforms and data structures.
Real dependenciestestcontainers or CI service containers for PostgreSQL, Redis and Kafka; in-memory fakes for third-party APIs; Pact where both sides are your teams.
Static checksruff for lint and format, mypy or pyright for types, in pre-commit and as the first CI job.
Datapandera schemas inside pipelines, Great Expectations for warehouse tables, drift monitoring in production.
ML and LLMSeeded, 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 healthCoverage reported on every pull request (no mandate on the number); mutation testing on critical modules or changed lines; flaky tests tracked, quarantined and owned.
CIGitHub Actions (or GitLab CI, Buildkite) with uv caching, cheapest checks first, a merge queue, nightly slow and GPU tiers.
Glossary (every term this page defines, linked to where it is defined)