Testing with pytest
Be able to write unit tests, understand fixtures and interpret a failing test report.
Prerequisites
Intuition
A test is code that calls your code and checks the result with assert. A test library (pytest) finds every test_* function, runs them and reports.
Why? So that you can change code without fear. An ML project without tests breaks silently: one change in the data loading and suddenly the model is training on the wrong column — with no error message, just worse numbers three hours later.
Test: the normal case, edge cases (empty, zero, one element), error cases (should raise an exception).
Code
# test_normalise.py
import pytest
from normalise import normalise
def test_mean_zero_std_one():
out = normalise([1.0, 2.0, 3.0])
assert abs(sum(out) / 3) < 1e-9
@pytest.mark.parametrize("x", [[], [5.0]])
def test_degenerate(x):
with pytest.raises(ValueError):
normalise(x)
@pytest.fixture
def data():
return [10.0, 20.0, 30.0, 40.0]
def test_order_preserved(data):
out = normalise(data)
assert out == sorted(out)
Run pytest -q. A failing line shows assert 0.3 < 1e-9 with the values — read which expression failed, not just that something did.
Mastery means
- Writes unit tests with pytest, including edge cases
- Uses fixtures and parametrize
- Interprets a failing test report
Sign in to do the exercises and build your mastery up.