Foundations to Frontier
Tests
C. Programming, Tools and HPC › C2 Software Engineering for Research

Testing with pytest and Property-Based Testing

Tests are executable claims about what your code does. This topic covers unit, integration and regression tests; pytest's conventions (test discovery, plain assert, fixtures, parametrize, approx, raises); what to test in numerical code (known values, invariants, conservation laws, edge cases, tolerances); property-based testing with Hypothesis (random generation plus shrinking to minimal counterexamples); coverage vs mutation testing as measures of test quality; and running tests in CI. In the exercises you build a miniature pytest (discovery, parametrize, approx) that exposes a subtle interpolation bug, then a property-based tester with shrinking and a mutation-testing harness that grades three test suites.

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.

Property-based testing: random inputs, then shrink the failure
property: median(xs) equals the true median
random inputs tried (1)
✗ [-102, -64]
shrinking the failure (7 steps)
found [-102, -64]
shrunk [0, -64]
shrunk [0, -32]
shrunk [0, -16]
shrunk [0, -8]
shrunk [0, -4]
shrunk [0, -2]
shrunk [0, -1]
minimal counterexample: [0, -1]
Example-based tests check the cases you thought of; properties check rules that must hold for every input, and the generator finds the cases you didn't think of (empty lists, even lengths, big gaps). Shrinking repeatedly tries smaller variants (halves, removing elements, numbers closer to zero) that still fail, so the report is the essence of the bug rather than a random mess. This is what Hypothesis does for pytest.
Why engineers care

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.

📝 Quick check (Level 0)
0/3 answered
  1. 1. A unit test…
  2. 2. Property-based tests check…
  3. 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.

📝 Quick check (Level 1)
0/3 answered
  1. 1. How do you compare 0.1 + 0.2 with 0.3 in pytest?
  2. 2. @pytest.mark.parametrize runs a test…
  3. 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.

🐍 Exercise 1: a miniature pytest finds a bug
Implement approx, a parametrize decorator and a test runner that discovers test_* functions and runs each parameter set, reporting pass/fail. Write tests for a calibration-table interpolator (known points, clamping, staying within bounds), then show they pass for the correct version and catch a version that uses one slope everywhere.
📝 Quick check (Level 2)
0/3 answered
  1. 1. A good invariant test for an orbit propagator is…
  2. 2. A regression test…
  3. 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 > vmax vs v >= vmax when 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.

📝 Quick check (Level 3)
0/3 answered
  1. 1. 100% line coverage guarantees…
  2. 2. An equivalent mutant…
  3. 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.

🐍 Exercise 2 (research): shrinking counterexamples and grading test suites
Build a property-based checker that generates random integer lists and shrinks failures (halves, single and pair deletions, simpler numbers); use it to find a minimal counterexample for a buggy median. Then generate AST mutants of a clamping function and compute the mutation scores of an example suite, a boundary-value suite and a property-based suite, identifying the equivalent mutants.

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

  1. pytest documentation (docs.pytest.org): fixtures, parametrize, approx.
  2. D. R. MacIver, Z. Hatfield-Dodds et al. (2019). “Hypothesis: a new approach to property-based testing.” Journal of Open Source Software, 4(43).
  3. K. Claessen, J. Hughes (2000). “QuickCheck: a lightweight tool for random testing of Haskell programs.” ICFP.
  4. Y. Jia, M. Harman (2011). “An analysis and survey of the development of mutation testing.” IEEE Transactions on Software Engineering, 37(5).
  5. NASA (2022). NPR 7150.2D, NASA Software Engineering Requirements.