Unit Tests · 22 min

Build a test suite with pytest

Discover tests, parameterize cases, and check for expected exceptions.

Jump to the automation lab

Put tests in a file named test_duration.py and start each test function name with test_. Run python -m pytest from the project root. Pytest discovers the tests and reports failing expressions with their values.

pytest.approx() is useful for floats. pytest.raises() verifies the expected exception type and can match its message. Add a zero case as well as a negative case so a mistaken cutoff is visible.

Move the implementation into an importable module as the suite grows. In the browser example, the last lines call the tests directly. On your computer, the commands below run them through pytest’s discovery.

Follow the example

Choose an input outside the valid range.

Worked examples

Run table-driven tests from a separate file

Save the two files side by side. Pytest runs the parameterized test once for each pair, then separately tests the invalid case.

duration.py
def hours(minutes):
    if minutes < 0:
        raise ValueError("minutes must be nonnegative")
    return minutes / 60
test_duration.py
import pytest

from duration import hours


@pytest.mark.parametrize("minutes, expected", [(0, 0), (1, 1 / 60), (90, 1.5)])
def test_hours(minutes, expected):
    assert hours(minutes) == pytest.approx(expected)


def test_negative_minutes():
    with pytest.raises(ValueError, match="nonnegative"):
        hours(-1)
Terminal
python -m pip install pytest
python -m pytest -q

Run the example and practice

Add test_zero, which checks that hours(0) equals 0. Call all three tests, then update the printed count.

Target output

3 tests passed
Show a hint

Keep the boundary check in its own test and call test_zero() before printing.

Output

Ready

Run your code to see the output here.

Check output also tests your code with additional cases.

The first run downloads Python. Code runs in your browser. Progress and drafts are stored on this device.

Show one solution
import pytest

def hours(minutes):
    if minutes < 0:
        raise ValueError("minutes must be nonnegative")
    return minutes / 60

def test_fraction():
    assert hours(90) == pytest.approx(1.5)

def test_invalid():
    with pytest.raises(ValueError, match="nonnegative"):
        hours(-1)

def test_zero():
    assert hours(0) == 0

test_fraction()
test_invalid()
test_zero()
print("3 tests passed")

Automation lab

Test a delivery-fee rule

Protect the free-delivery threshold and check that an invalid basket raises an error.

Output

Ready

Run the example to see the output here.

Temporarily change the threshold comparison to > and see which check catches it.

Further reading in Automate the Boring Stuff with Python by Al Sweigart