Level 0: Foundation
★☆☆☆☆ Introductory⏱ 5 minGeneral audience. No mathematics required.Code that checks your code
A test is a small program that runs your code and checks the answer: “interpolating halfway between 10 and 20 must give 15”. Run hundreds of these after every change, and you find out within seconds if you broke something. pytest is Python’s most popular testing tool. Property-based testing goes further: instead of checking the cases you thought of, it generates thousands of random cases and checks rules that must always hold (“sorting never changes the length”). When one fails, it shrinks the input to the smallest example that still breaks.
Flight software is tested to the hilt (NASA’s NPR 7150.2 and DO-178C demand it), and research code that feeds design decisions deserves the same discipline at a smaller scale. A unit-conversion test or a conservation-law check catches the kind of error that has lost real spacecraft.
- 1. A unit test…
- 2. Property-based tests check…
- 3. Shrinking a failing input means…
Level 1: Beginner
★★☆☆☆ Basic⏱ 25 minSecondary-school mathematics: arithmetic and elementary algebra.pytest basics
# tests/test_interp.py
import pytest
from mylib.interp import interp_table
def test_midpoint():
assert interp_table(0.5, [0, 1], [10, 20]) == pytest.approx(15)
@pytest.mark.parametrize("x, expected", [(0, 10), (1, 20), (-5, 10)])
def test_known_points(x, expected):
assert interp_table(x, [0, 1], [10, 20]) == pytest.approx(expected)
def test_rejects_unsorted():
with pytest.raises(ValueError):
interp_table(0.5, [1, 0], [10, 20])Run pytest (or pytest -q tests/test_interp.py::test_midpoint). Any function named test_* in a test_*.py file is discovered. A plain assert gives a rich failure message. Compare floats with pytest.approx, never ==.
Fixtures
@pytest.fixture functions provide shared setup (a sample dataset, a temporary directory via tmp_path, a seeded RNG). Tests request them by naming them as parameters.
- 1. How do you compare 0.1 + 0.2 with 0.3 in pytest?
- 2. @pytest.mark.parametrize runs a test…
- 3. The tmp_path fixture gives…
Level 2: Intermediate
★★★☆☆ Intermediate⏱ 40 minUndergraduate students and practising engineers.What to test in scientific code
- Known values: analytic solutions and textbook cases.
- Invariants: energy or momentum conservation, symmetry, monotonicity, bounds.
- Edge cases: empty input, length 1, NaN, endpoints, degenerate geometry.
- Round trips:
parse(format(x)) == x,inverse(f(x)) ≈ x. - Regression tests: freeze a known-good output for a fixed seed and compare.
- Tolerances that reflect the algorithm (relative 1e-9 for exact formulas, looser for iterative solvers).
Property-based testing with Hypothesis
from hypothesis import given, strategies as st
@given(st.lists(st.floats(allow_nan=False, allow_infinity=False, width=32), min_size=1))
def test_median_bounds(xs):
m = median(xs)
assert min(xs) <= m <= max(xs)Hypothesis generates inputs (biased toward edge cases), and on failure shrinks them and stores the example in a database so it is retried next run.
- 1. A good invariant test for an orbit propagator is…
- 2. A regression test…
- 3. Hypothesis remembers failing examples…
Level 3: Advanced
★★★★☆ Advanced⏱ 30 minGraduate level, with full derivations and proofs.Measuring test quality
- Line and branch coverage (
pytest --cov) shows which code ran, not whether the assertions would catch a bug. - Mutation testing (mutmut, cosmic-ray) makes small changes to your code (flip
>to>=, negate, add 1) and checks whether the tests fail. The mutation score is killed mutants over all non-equivalent mutants. - Equivalent mutants behave identically on every input (e.g.
v > vmaxvsv >= vmaxwhen both branches return vmax at equality) and can never be killed.
Why shrinking works
The failure set is usually “monotone-ish”: small examples that fail exist near large ones. Greedy shrinking (try halves, deletions, pairs of deletions, simpler numbers, and keep the first that still fails) reaches a local minimum, an input where every listed simplification passes. The candidate set matters: if a bug only appears for even lengths, deleting one element never keeps it failing, so pair deletions are needed.
Tests in CI
Run the full suite on every pull request (GitHub Actions), across supported Python versions and with pinned dependencies. Fast unit tests on every push, slower integration tests nightly.
- 1. 100% line coverage guarantees…
- 2. An equivalent mutant…
- 3. Greedy shrinking returns…
Level 4: Expert
★★★★★ Expert⏱ 30 minResearchers: original papers and open problems.Test quality, measured
Exercise 1. The 8 test cases (5 known points, 2 clamping cases, 1 bounds sweep) all pass for the correct interpolator. The buggy version, which uses the first segment’s slope everywhere, fails test_known_points[2.0,10.0] and the bounds sweep, but passes the points in the first segment and the clamped ends. Tests only catch what they probe.
Exercise 2. Random testing finds the even-length median bug within the first few lists, and shrinking reduces it to a two-element list such as [0, −1]. Single-element deletion alone gets stuck at length 6, which is why the shrinker also tries pairs. Mutation testing of a speed-clamping function produces 7 mutants, 2 of them equivalent:
| suite | mutation score |
|---|---|
| two “typical” examples | 0.43 |
| + boundary values (±vmax, 0, negative) | 0.71 |
| 200 random property checks | 0.71 |
0.71 is 5/7, every killable mutant. Both the boundary suite and the property suite are complete here.
Testing in AI, robotics and aerospace
- Unit tests for frames, units and conversions: the cheapest insurance against catastrophic errors.
- Property tests for geometry (rotation matrices orthonormal, quaternion norms 1) and estimators (covariances symmetric PSD).
- Regression tests for ML pipelines with fixed seeds and tolerance bands.
- Hardware-in-the-loop and simulation tests in CI for robots and flight software.
References
- pytest documentation (docs.pytest.org): fixtures, parametrize, approx.
- D. R. MacIver, Z. Hatfield-Dodds et al. (2019). “Hypothesis: a new approach to property-based testing.” Journal of Open Source Software, 4(43).
- K. Claessen, J. Hughes (2000). “QuickCheck: a lightweight tool for random testing of Haskell programs.” ICFP.
- Y. Jia, M. Harman (2011). “An analysis and survey of the development of mutation testing.” IEEE Transactions on Software Engineering, 37(5).
- NASA (2022). NPR 7150.2D, NASA Software Engineering Requirements.