Testing
Why automated tests; pytest tests and assertion rewriting, fixtures and temporary files, parametrize and expected exceptions, doctests, property-based tests with Hypothesis, tolerances and seeds for numerical code.
Right types, wrong answer
The topic Type hints ended with a limit. A checker such as mypy reads the annotations and confirms that every call passes the right kinds of values. It cannot confirm that the value that comes back is right. This mean has perfect annotations and a bug:
# metrics.py
def mean(values: list[float]) -> float:
if not values:
raise ValueError("mean of an empty sequence")
return sum(values) / (len(values) + 1) # a bugmypy --strict metrics.py prints Success: no issues found in 1 source file, and mean([0.9, 0.5, 0.4]) returns 0.45 instead of 0.6. Only running the code on a known input and comparing the result catches this. The Reliable code module starts here.
You could check by hand in the REPL. That check is not saved, it covers only the inputs you happened to type, and a person decides whether the number "looks right". An automated test is code that does the checking: it calls the function with a fixed input and compares the result with what it must be. A collection of tests, a test suite, runs in seconds, so it runs after every change. A change that breaks something is found minutes after it was made, not weeks later.
A unit test checks one small unit, usually one function, in isolation. It runs in milliseconds and, when it fails, points at that function. An integration test runs several parts together, say reading a metrics file, cleaning it and fitting a model, and catches the errors that live between the parts. A project needs both; this topic is about unit tests.
Python's own tool for a check is assert expr: if expr is false, it raises AssertionError. That is a start, but the report shows the line and not the value mean returned, and python -O strips every assert from the program. The rest of the topic uses pytest, the test runner of most Python projects, NumPy and pandas included. It is a third-party package: install it with uv add --dev pytest, as in the topic Modules, packages and environments. The outputs below come from Python 3.14.7, pytest 9.2 and Hypothesis 6.170.
A first pytest test
With the bug fixed (/ len(values)), here is a test file for metrics.py, with one wrong expectation on purpose:
# test_metrics.py
from metrics import mean
def test_mean_of_three():
assert mean([1, 2, 3]) == 2.0
def test_mean_of_four():
assert mean([1, 2, 3, 4]) == 2 # wrong on purposeA pytest test is an ordinary function with a plain assert. pytest finds tests by name:
- Starting from the folders given on the command line (the current folder by default), it collects files named
test_*.pyor*_test.py. - It imports each file and collects module-level functions named
test*, and methods namedtest*of classes namedTest*that have no__init__. - It runs each test separately. A test passes if it returns and fails if it raises, an
AssertionErroror anything else.
$ python -m pytest
============================= test session starts ==============================
platform darwin -- Python 3.14.7, pytest-9.2.0, pluggy-1.7.0
rootdir: ...
collected 2 items
test_metrics.py .F [100%]
=================================== FAILURES ===================================
______________________________ test_mean_of_four _______________________________
def test_mean_of_four():
> assert mean([1, 2, 3, 4]) == 2 # wrong on purpose
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
E assert 2.5 == 2
E + where 2.5 = mean([1, 2, 3, 4])
test_metrics.py:7: AssertionError
=========================== short test summary info ============================
FAILED test_metrics.py::test_mean_of_four - assert 2.5 == 2
========================= 1 failed, 1 passed in 0.02s ==========================The header and the time depend on the machine. In the progress line each dot is a passed test and each F a failed one, in file order. Read a failure from the line marked >, the failing line. The E lines show the comparison with its values filled in, 2.5 == 2, and where 2.5 came from. When anything fails, the command exits with status 1, which is what a continuous-integration service checks.
How pytest knows the values
A plain assert raises a bare AssertionError. pytest can print 2.5 because it does not run your test file as written. When it imports a test module, an import hook reads the source, parses it into a syntax tree and replaces every assert with code that saves each subexpression in a temporary variable and, on failure, formats those values into the message. The rewritten module is compiled and cached in __pycache__ like any other. The topic How CPython runs code shows that same syntax tree from the compiler's side.
Rewriting applies to test modules and conftest.py files only. A helper module that the tests import keeps plain asserts unless it is registered with pytest.register_assert_rewrite.
An assert can carry a message after a comma, and pytest shows it next to the values:
> assert loss < 0.1, "loss too high"
E AssertionError: loss too high
E assert 0.5 < 0.1Rewriting does not change what assert checks. It still tests the truth of the one expression after it, by the truthiness rules from the topic Control flow.
The worst test is one that cannot fail, because a green run hides it. A function named check_mean instead of test_mean, or a file named checks.py, is never collected. If nothing is collected at all, pytest prints no tests ran and exits with status 5, but one uncollected test among a hundred collected ones goes unnoticed. The habit that guards against all of this: make each new test fail once on purpose, by changing the expected value, before you trust it.
Fixtures: what a test needs
A test often needs something prepared: a file to read, a small dataset, a model with known weights. A fixture is a function decorated with @pytest.fixture. A test asks for it by naming it as a parameter, and pytest calls the fixture and passes in its return value. tmp_path is a built-in fixture: a fresh, empty folder as a pathlib.Path, different for every test, so tests cannot see each other's files. Here read_losses(path) reads the loss column of a metrics CSV with csv.DictReader, as in the topic Files and exceptions:
import pytest
from metrics import read_losses
@pytest.fixture
def metrics_file(tmp_path):
path = tmp_path / "metrics.csv"
path.write_text("epoch,loss\n1,0.9\n2,0.5\n", encoding="utf-8")
return path
def test_read_losses(metrics_file):
assert read_losses(metrics_file) == [0.9, 0.5]pytest matches each parameter name to a fixture of the same name: in the test file, in a conftest.py in the same folder or above, or built in. A fixture can ask for fixtures (metrics_file asks for tmp_path), so fixtures form a graph, and pytest sets them up in dependency order before it calls the test. If a fixture raises during setup, the test is reported as an error, not a failure.
A fixture that must clean up uses yield instead of return: the code after yield runs after the test, whether it passed or failed. The scope says how long a value lives: "function" (the default, a fresh value per test), "module" or "session". With import pytest at the top:
@pytest.fixture(scope="module")
def tracker():
yield {"runs": 0} # one dict for the whole file
@pytest.fixture
def run(tracker):
tracker["runs"] += 1
yield "run-1"
tracker["runs"] -= 1 # undo after the test
def test_one(run, tracker):
assert tracker["runs"] == 1
def test_two(run, tracker):
assert tracker["runs"] == 1$ python -m pytest --setup-show -q test_order.py
SETUP M tracker
SETUP F run (fixtures used: tracker)
test_order.py::test_one (fixtures used: run, tracker) .
TEARDOWN F run
SETUP F run (fixtures used: tracker)
test_order.py::test_two (fixtures used: run, tracker) .
TEARDOWN F run
TEARDOWN M tracker
2 passed in 0.00sM marks the module-scoped fixture, set up once; F marks the function-scoped one, set up and torn down around each test. State shared between tests is the usual reason a test passes alone and fails in the full suite, which is why the default scope is the shortest one.
Many cases and expected exceptions
Tests that differ only in their data are one test with a table. @pytest.mark.parametrize takes the argument names as one string and a list of tuples, and pytest makes one test per tuple:
import pytest
from metrics import mean
@pytest.mark.parametrize("values, expected", [
([5], 5.0),
([1, 3], 2.0),
([1, 2, 3, 4], 2.0), # wrong row, on purpose
([-1, 0, 1], 0.0),
])
def test_mean_cases(values, expected):
assert mean(values) == expected$ python -m pytest -v
...
test_metrics.py::test_mean_cases[values0-5.0] PASSED [ 20%]
test_metrics.py::test_mean_cases[values1-2.0] PASSED [ 40%]
test_metrics.py::test_mean_cases[values2-2.0] FAILED [ 60%]
test_metrics.py::test_mean_cases[values3-0.0] PASSED [ 80%]
test_metrics.py::test_mean_of_empty_raises PASSED [100%]
...
========================= 1 failed, 4 passed in 0.02s ==========================Each case gets an id in brackets built from its values (a list becomes values0, a number its value) and passes or fails on its own. A loop inside one test would stop at the bad row and hide the rows after it. Two parametrize decorators on one test give every combination of their values, which suits a grid of hyperparameters. -v prints one line per test, and -k cases would run only tests whose names contain cases.
The last line of that run is a test of the contract for the empty list, which must raise ValueError. It uses pytest.raises as a context manager:
def test_mean_of_empty_raises():
with pytest.raises(ValueError, match="empty"):
mean([])The test passes if the block raises the given type or a subclass of it, with a message in which re.search finds the pattern match. If the block finishes normally, the test fails with DID NOT RAISE. An exception of another type passes through and fails the test as usual. Keep the block to the one call that should raise: a ten-line block passes if any line raises that type, including one you did not mean.
Doctests and properties
A doctest is an example in a docstring, written as a REPL session, that a tool runs and compares with the output shown:
def mean(values: list[float]) -> float:
"""Return the arithmetic mean of a non-empty list.
>>> mean([1, 2, 3])
2.0
>>> mean([])
Traceback (most recent call last):
...
ValueError: mean of an empty sequence
"""python -m doctest -v metrics.py ends with 2 passed. and Test passed.; python -m pytest --doctest-modules runs the same examples as one test, metrics.py::metrics.mean. For an exception only the first and last lines are compared, and ... stands for the frames. A doctest keeps documentation honest, since an example that stopped being true fails. It is poor at everything else, because it compares printed text character by character, not values: 0.30000000000000004 against 0.3, or a memory address inside a repr, breaks it. Keep a few illustrative doctests and write real tests in test files.
Every test so far checks examples that someone chose, and the bugs that survive live in inputs nobody thought of. A property is a statement that must hold for every input of some kind; a property-based test generates many inputs and checks it on each. Take the batching generator from the topic Iteration, comprehensions and generators, written with a bug:
# loader.py
def batches(items, size):
for start in range(0, len(items) - size + 1, size):
yield items[start:start + size]The example list(batches([1, 2, 3, 4], 2)) == [[1, 2], [3, 4]] passes. The property is that batching loses nothing: the batches, joined, give back items. The library Hypothesis generates the inputs from a strategy that describes their kind:
from hypothesis import given, strategies as st
from loader import batches
@given(st.lists(st.integers()), st.integers(min_value=1, max_value=8))
def test_batches_keep_every_item(items, size):
flat = [x for batch in batches(items, size) for x in batch]
assert flat == items$ python -m pytest -q test_loader.py
...
E assert [] == [0]
...
E Failing test case: test_batches_keep_every_item(
E items=[0],
E size=2,
E )Hypothesis tries 100 inputs by default (the max_examples setting), biased towards edge cases. When one fails, it shrinks it: it tries simpler versions and reports the simplest input that still fails, here one item and a batch of two. The bug is the dropped last partial batch; range(0, len(items), size) fixes it. Failing inputs are saved in a local .hypothesis folder and tried first on the next run. A loop over random.Random(0) draws gives the same idea by hand, without shrinking or memory.
Properties worth looking for: a round trip (encode then decode, save then load), an invariant (sorting keeps the same elements), and agreement with a slow but obviously correct version of the same function.
Numbers with a tolerance
Floating-point arithmetic rounds every result to the nearest representable number, so a computed value is rarely exactly the value the mathematics gives (the topic Values, types and names met 0.1 + 0.2). An exact == on floats tests the rounding, not the formula:
E assert 0.19999999999999998 == 0.2
E + where 0.19999999999999998 = mean([0.1, 0.2, 0.3])Rounding can even break an obvious invariant: mean([0.1, 0.1, 0.1]) returns 0.10000000000000002, larger than every element. The rule is to compare with a tolerance:
>>> import math, pytest
>>> from metrics import mean
>>> x = mean([0.1, 0.2, 0.3])
>>> x == 0.2
False
>>> math.isclose(x, 0.2)
True
>>> x == pytest.approx(0.2)
True
>>> pytest.approx(0.2)
0.2 ± 2.0e-07The two tools follow slightly different rules. math.isclose(a, b, rel_tol=1e-09, abs_tol=0.0) is true when
with = rel_tol and = abs_tol. actual == pytest.approx(expected, rel=1e-6, abs=1e-12) is true when
with the actual value, the expected one, = rel and = abs. pytest.approx also compares lists, dicts and NumPy arrays element by element: a plain-Python softmax([0.0, math.log(3)]) returns [0.25, 0.7500000000000001], and == pytest.approx([0.25, 0.75]) is True. For arrays, NumPy has numpy.testing.assert_allclose.
A tolerance should come from the computation, not be loosened until the test passes. A sum of numbers can gather an error of about times the unit roundoff , relative to the size of the terms; an iterative solver stops at its own tolerance; a random estimate has a standard error. A tolerance of on a value that should be exact to cannot catch a bug in the third digit.
Seeds and what comes next
Code that draws random numbers gives a different answer on every run. Its test either fails at random or is so loose that it checks nothing. The rule is to pass the generator in and seed it in the test: random.Random(42) for the standard library, numpy.random.default_rng(42) in the topic NumPy arrays. The same seed gives the same sequence, so the test is repeatable and a failure can be replayed:
import random
import pytest
from metrics import mean
def bootstrap_means(values, n_resamples, rng):
k = len(values)
return [mean([values[rng.randrange(k)] for _ in range(k)])
for _ in range(n_resamples)]
def test_bootstrap():
data = [2.0, 4.0, 4.0, 5.0, 9.0]
first = bootstrap_means(data, 200, random.Random(42))
assert first == bootstrap_means(data, 200, random.Random(42))
assert mean(first) == pytest.approx(mean(data), abs=0.3)The second check is statistical, and its tolerance comes from the spread. The data have a standard deviation of about , so the mean of 200 bootstrap means has a standard error of about , and abs=0.3 is about four of them. Over 2000 different seeds it never fails. The machine-learning courses seed every run for the same reason.
What tests cannot do:
- They show the presence of bugs, not their absence. A green suite says that the checked cases work. Coverage tools such as
pytest-covshow which lines ran, not whether they were checked well. - Tests are code. A wrong expected value is a bug that the suite now protects.
- Fakes drift.
unittest.mockreplaces a database or a network service with a fast fake, and the fake can stop matching the real thing. Some integration tests against the real thing are still needed. - pytest is not the only runner. The standard library's
unittestuses classes andself.assertEqual; pytest runs those tests too.
A failing test says that something is wrong and where the check failed. It does not always say why: the wrong value may have been computed three calls earlier, or only on the ten-thousandth row of the data. The next topic, Debugging and profiling, is about finding the cause: reading chained tracebacks, stopping a running program with breakpoint() to look at its variables, logging what a long run does, and, when the code is correct but slow, measuring where the time and memory go.
Check your understanding
The same questions as in Pulse. Answers are shared between modes.
Answers are saved on the server and tied to this browser until you sign in.