Skip to content
BIASED

Testing

Block 1 of 8~2 min

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 bug

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

Answers are saved on the server and tied to this browser until you sign in.