Skip to article frontmatterSkip to article content
Site not loading correctly?

This may be due to an incorrect BASE_URL configuration. See the MyST Documentation for reference.

Module 13: Testing with pytest

Objectives: LO-13.1, LO-13.2, LO-13.3, LO-13.4
Prerequisites: Module 9, Module 10, and Module 12
Time: about 5.5 hours: 2 for this reading, 2 for Lab 13, and 1.5 for the practice

Since Module 5 you have tested functions with assert lines at the bottom of a script, and run them by running the script. This module moves those tests into files of their own and runs them with pytest, a testing tool that finds every test in a project, runs each one separately, and reports exactly which failed and why. You will decide what to test, test many cases with little code, write tests before the code they test, and have GitHub run your tests every time you push.

A first test file

A test is a function that calls the code under test with an input whose answer you know, and checks the result with assert. pytest is already in your course environment (setup, step 7). Make a folder m13 inside py101, and save this module in it as temps.py:

"""Temperature helpers for a weather station."""


def c_to_f(celsius):
    """Return a Celsius temperature in degrees Fahrenheit."""
    return celsius * 9 / 5 + 32


def mean(values):
    """Return the mean of a list of numbers, which must not be empty."""
    if not values:
        raise ValueError("mean of an empty list")
    return sum(values) / len(values)

Save the tests next to it, as test_temps.py:

from temps import c_to_f


def test_freezing_point():
    assert c_to_f(0) == 32


def test_boiling_point():
    assert c_to_f(100) == 212

The test file imports the functions it tests, as any module would (Module 9), and holds nothing but tests: no print, and no calls at the bottom. Run pytest from m13, with python -m pytest (python stands for your environment’s Python, run by its path, as in Module 9):

python -m pytest
============================= test session starts ==============================
platform linux -- Python 3.12.3, pytest-9.2.0, pluggy-1.7.0
rootdir: /home/ada/py101/m13
plugins: nbmake-1.5.5, anyio-4.16.0, platformdirs-4.14.8
collected 2 items

test_temps.py ..                                                         [100%]

============================== 2 passed in 0.01s ===============================

The first lines describe the run: the platform and the versions, the root directory (the folder pytest treats as the project’s top), and the plugins, which are extensions that other packages installed. Those lines differ from computer to computer. pytest then collects the tests, which means it finds them, and here it found two. Each test prints one character as it runs: . for a pass. The last line counts the results and the time they took.

pytest finds tests by their names, so the names matter:

Each test runs separately: one that fails doesn’t stop the rest. pytest lets a test file import the modules in its own folder, which is why from temps import c_to_f finds temps.py. python -m pytest runs the pytest installed in the environment of the Python you start, as python -m pip runs that environment’s pip (Module 9). pytest also makes a .pytest_cache folder, for its own records; the folder holds its own .gitignore, so Git leaves it out without your help.

Reading a failure

A body temperature of 38.1 °C is a fever: 100.58 °F. Add a third test:

def test_body_temperature():
    assert c_to_f(38.1) == 100.58
============================= test session starts ==============================
platform linux -- Python 3.12.3, pytest-9.2.0, pluggy-1.7.0
rootdir: /home/ada/py101/m13
plugins: nbmake-1.5.5, anyio-4.16.0, platformdirs-4.14.8
collected 3 items

test_temps.py ..F                                                        [100%]

=================================== FAILURES ===================================
____________________________ test_body_temperature _____________________________

    def test_body_temperature():
>       assert c_to_f(38.1) == 100.58
E       assert 100.58000000000001 == 100.58
E        +  where 100.58000000000001 = c_to_f(38.1)

test_temps.py:13: AssertionError
=========================== short test summary info ============================
FAILED test_temps.py::test_body_temperature - assert 100.58000000000001 == 10...
========================= 1 failed, 2 passed in 0.02s ==========================

The F marks the failed test, and the FAILURES section explains it:

pytest also ends with an exit status (Module 9): 0 when every test passed, and 1 when any failed. That status is how other tools, such as GitHub later in this module, learn the result.

When a test fails, either the code is wrong or the test is. Here neither is: as Module 2 showed, floats are stored in binary and are often a tiny bit off, so 38.1 * 9 / 5 + 32 comes out 100.58000000000001. Comparing calculated floats with == is the bug in the test.

Comparing floats with pytest.approx

Module 2 compared floats with math.isclose. In a test, use pytest.approx instead, which reports both values when the comparison fails. import pytest at the top of the test file, and change the third test:

import pytest

from temps import c_to_f


def test_body_temperature():
    assert c_to_f(38.1) == pytest.approx(100.58)

Now all three pass. By default, pytest.approx accepts a value within one part in a million of the expected one, that is, a relative tolerance of 1e-6. To give an absolute tolerance, a fixed distance either way, pass abs: pytest.approx(8.667, abs=0.001) accepts anything from 8.666 to 8.668. Use approx for every float a function calculates. Whole numbers, strings, and floats the code doesn’t calculate, such as 4.0 returned unchanged, can still use ==.

What to test

The three tests of c_to_f above check one input each. A function has far too many inputs to try them all, so choose cases that each could catch a different mistake:

For mean, that gives tests like these:

CaseInputExpected
Typical[8.5, 11.0, 6.5]about 8.667
Edge: one value[4.0]4.0
Edge: negative values[-2.5, -0.5]-1.5
Error: no values[]ValueError
from temps import c_to_f, mean


def test_mean_of_several_values():
    assert mean([8.5, 11.0, 6.5]) == pytest.approx(8.667, abs=0.001)


def test_mean_of_one_value():
    assert mean([4.0]) == 4.0


def test_mean_of_negative_values():
    assert mean([-2.5, -0.5]) == -1.5

Name each test for the case it checks. When test_mean_of_one_value fails, its name alone tells you which case broke.

Testing errors with pytest.raises

mean promises a ValueError for an empty list. A test of that promise passes only if the exception happens, so it can’t call mean([]) plainly, which would stop the test with the exception. pytest.raises catches it instead, in a with block:

def test_mean_of_empty_list_raises():
    with pytest.raises(ValueError, match="empty list"):
        mean([])

The test passes when the code inside the block raises a ValueError whose message contains empty list. match is a regular expression, a pattern language for text that Python’s re module implements; letters, digits, and spaces match themselves, but characters such as ., (, and ? have special meanings, so keep the pattern to a few plain words from the message. The test fails in three other situations. If mean returns 0 for an empty list:

>       with pytest.raises(ValueError, match="empty list"):
E       Failed: DID NOT RAISE ValueError

If it raises a ValueError with another message, such as no values:

E       AssertionError: Regex pattern did not match.
E         Expected regex: 'empty list'
E         Actual message: 'no values'

And if it raises a different exception, pytest.raises doesn’t catch it, so it fails the test as any other exception would. Without its if not values check, mean([]) divides by zero:

E       ZeroDivisionError: division by zero

temps.py:11: ZeroDivisionError

Put only the call that should raise inside the with block: any line after the call, inside the block, never runs, because the exception leaves the block.

Many cases with parametrize

The three tests of c_to_f differ only in their numbers. @pytest.mark.parametrize writes one test and gives it a list of cases. Replace the three with this, and add the case where both scales agree, −40:

@pytest.mark.parametrize(
    "celsius, fahrenheit",
    [
        (0, 32),
        (100, 212),
        (-40, -40),
        (38.1, 100.58),
    ],
)
def test_c_to_f(celsius, fahrenheit):
    assert c_to_f(celsius) == pytest.approx(fahrenheit)

A line that starts with @ above a function is a decorator, which changes or labels the function below it; Module 16 shows how decorators work. This one labels the test to run once for each case. Its first argument names the test function’s parameters, in a string with commas between the names, and its second is a list with a tuple for each case, in the same order. pytest runs the test once per tuple, and counts each run as its own test. With -v:

test_temps.py::test_c_to_f[0-32] PASSED                                  [ 10%]
test_temps.py::test_c_to_f[100-212] PASSED                               [ 20%]
test_temps.py::test_c_to_f[-40--40] PASSED                               [ 30%]
test_temps.py::test_c_to_f[38.1-100.58] PASSED                           [ 40%]

The part in brackets is the case’s ID, made from its values, so a failure names the case that failed. Use parametrize when several cases check the same thing in the same way; keep separate tests when the cases check different things, as the error test does.

Fixtures

Tests often need the same starting data. A fixture is a function that prepares something a test needs; a test asks for it by naming it as a parameter, and pytest calls the fixture and passes in what it returns. Add a week of readings:

@pytest.fixture
def week():
    """Seven days of temperatures at one station, in degrees Celsius."""
    return [8.5, 11.0, 6.5, 7.0, 9.5, 10.0, 12.5]


def test_mean_of_week(week):
    assert mean(week) == pytest.approx(9.29, abs=0.01)

@pytest.fixture is the decorator that makes week a fixture. pytest calls the fixture again for every test that asks for it, so each test gets a new list. A test that changes its list, as Lab 12’s median did when it sorted its argument in place, can’t affect the next test.

tmp_path: a folder for each test

pytest comes with fixtures of its own. tmp_path gives each test a new, empty temporary folder, as a pathlib.Path (Module 11), so a test of code that writes files never touches your real files, and never sees what an earlier test left behind. Add a function to temps.py that writes a report:

def write_report(path, readings):
    """Write each station's mean temperature to a text file, one station per line."""
    with open(path, "w", encoding="utf-8") as file:
        for station, temps in readings.items():
            file.write(f"{station}: {mean(temps):.1f}\n")

The test asks for two fixtures, tmp_path and week, writes the report into the temporary folder, and reads it back:

from temps import c_to_f, mean, write_report


def test_write_report(tmp_path, week):
    path = tmp_path / "report.txt"
    write_report(path, {"Harbor": week, "Hilltop": [4.0]})
    assert path.read_text(encoding="utf-8") == "Harbor: 9.3\nHilltop: 4.0\n"

Comparing the whole file also checks the details a reader would notice: the order of the lines, the rounding, and the newline at the end. When a test that uses tmp_path fails, its report shows the folder’s path as the value of tmp_path, so you can look inside; pytest keeps the folders of its last three runs and deletes older ones. With these tests, the whole file runs 10 tests, and all pass.

Write the test first

So far each test came after its code. Writing the test first has two benefits. It makes you decide exactly what the code should do before you write it, edge cases included. And you see the test fail before the code exists, which proves the test can fail: a test that has never failed may not be testing anything.

The station’s website labels each day’s rain: dry for 0 mm, light below 5 mm, moderate from 5 mm to below 20 mm, and heavy from 20 mm. Negative rain is a mistake in the data. Write the tests first, in test_rain.py, with a case on each side of each boundary:

import pytest

from rain import rain_label


@pytest.mark.parametrize(
    "mm, label",
    [
        (0, "dry"),
        (0.2, "light"),
        (4.9, "light"),
        (5, "moderate"),
        (19.9, "moderate"),
        (20, "heavy"),
        (85.5, "heavy"),
    ],
)
def test_rain_label(mm, label):
    assert rain_label(mm) == label


def test_negative_rain_raises():
    with pytest.raises(ValueError, match="negative"):
        rain_label(-0.1)

Run them, with python -m pytest test_rain.py, before rain.py exists. pytest can’t even import the test file, so it reports an error while collecting, and the run ends there:

test_rain.py:3: in <module>
    from rain import rain_label
E   ModuleNotFoundError: No module named 'rain'
=========================== short test summary info ============================
ERROR test_rain.py
!!!!!!!!!!!!!!!!!!!! Interrupted: 1 error during collection !!!!!!!!!!!!!!!!!!!!
=============================== 1 error in 0.13s ===============================

That failure is the expected one. Now write rain.py. This first try has a mistake that is easy to make:

"""Labels for a day's rain."""


def rain_label(mm):
    """Return dry, light, moderate, or heavy for a day's rain in millimeters."""
    if mm < 0:
        raise ValueError(f"rain can't be negative: {mm}")
    if mm == 0:
        return "dry"
    if mm <= 5:
        return "light"
    if mm < 20:
        return "moderate"
    return "heavy"
test_rain.py ...F....                                                    [100%]

=================================== FAILURES ===================================
_________________________ test_rain_label[5-moderate] __________________________

mm = 5, label = 'moderate'

The section goes on to show the test and ends with the comparison. For strings, pytest shows how they differ, with - before the expected text and + before the actual one:

>       assert rain_label(mm) == label
E       AssertionError: assert 'light' == 'moderate'
E         
E         - moderate
E         + light

The case at exactly 5 mm caught the <= that should be <. Change it, and all eight tests pass. This rhythm is called test-driven development: write a failing test, write the least code that passes it, then tidy the code while the tests stay green (passing), and repeat.

Capture a bug in a test before you fix it

When you find a bug, write a test that fails because of it before you change the code. The test proves that you understood the bug, tells you when the fix works, and stays in the project afterward, so the bug can’t come back unnoticed. A test kept for this reason is a regression test: it catches a regression, a bug that returns after it was fixed.

Module 12’s median gave 9.75 for [8.5, 11.0, 6.5, 7.0] instead of 7.75. Add it to temps.py as it was before the fix:

def median(values):
    """Return the middle value of values, or the mean of the two middle ones."""
    ordered = sorted(values)
    middle = len(ordered) // 2
    if len(ordered) % 2 == 0:
        return (ordered[middle] + ordered[middle + 1]) / 2
    return ordered[middle]

Then turn the bug report and Module 12’s smaller cases into tests in test_temps.py, with median added to the import line, and run python -m pytest test_temps.py:

@pytest.mark.parametrize(
    "values, expected",
    [
        ([8.5, 11.0, 6.5, 7.0], 7.75),
        ([1, 2], 1.5),
        ([3, 1, 2], 2),
    ],
)
def test_median(values, expected):
    assert median(values) == expected
=========================== short test summary info ============================
FAILED test_temps.py::test_median[values0-7.75] - assert 9.75 == 7.75
FAILED test_temps.py::test_median[values1-1.5] - IndexError: list index out o...
========================= 2 failed, 11 passed in 0.04s =========================

The two even-length cases fail, one with the wrong answer and one with an exception, and the odd-length case passes, as Module 12 found. (A list doesn’t make a short ID, so pytest names that case after the parameter and its position, values0.) Now fix the line, as Module 12 did:

        return (ordered[middle - 1] + ordered[middle]) / 2

Run every test again, not only the new ones, to check that the fix broke nothing else. All 21 pass, across both files.

Running tests on every push with GitHub Actions

Tests protect you only when someone runs them. Continuous integration (CI) is the practice of checking every change automatically, on another computer, as soon as it reaches the shared repository. A broken change is then noticed at once, even when you forgot to run the tests, or your computer differs from everyone else’s. GitHub’s service for this is GitHub Actions. Its terms:

Running workflows on GitHub’s standard runners is free in public repositories; GitHub’s billing pages give the limits for private ones.

Tests for the dice roller

Module 10 published dice-roller, with Module 9’s dice.py. Its main guard (Module 9) lets a test import roll without rolling any dice or reading any arguments. Add test_dice.py to the repository:

import random

from dice import roll


def test_roll_gives_one_result_per_roll():
    assert len(roll(6, 5)) == 5


def test_rolls_are_between_1_and_sides():
    for result in roll(6, 1000):
        assert 1 <= result <= 6


def test_same_seed_gives_same_rolls():
    random.seed(9)
    first = roll(6, 3)
    random.seed(9)
    assert roll(6, 3) == first

Random results can’t be compared with fixed answers, so these tests check what must hold for any roll: how many results come back, their range, and that a seed repeats a run. Run them, and they pass. The runner needs pytest too, so add requirements.txt, as Module 9 wrote it:

pytest==9.2.0

The workflow file

A workflow is written in YAML, a format for settings and data, like JSON (Module 11) but without the brackets and braces:

Make the folders .github and .github/workflows in dice-roller (the first name starts with a dot), and save this as .github/workflows/tests.yml:

name: "Tests"

on: [push]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - name: "Check out the repository"
        uses: actions/checkout@v7
      - name: "Set up Python"
        uses: actions/setup-python@v7
        with:
          python-version: "3.12"
      - name: "Install the requirements"
        run: python -m pip install -r requirements.txt
      - name: "Run the tests"
        run: python -m pytest

Line by line:

Both actions are GitHub’s own. Before you use an action that someone else published, read GitHub’s security advice on third-party actions: an action runs with access to your repository.

Reading the result

Commit the three new files and push (Module 10):

git add test_dice.py requirements.txt .github/workflows/tests.yml
git commit -m "Run the tests on every push"
git push

Then open the repository on GitHub:

  1. Select the Actions tab. Each push gets a run of the workflow. The page lists the runs, newest first, each titled with its commit message, and the left sidebar lists the workflows by name, to show one workflow’s runs.

  2. Select the run, then the job, test. Each step has a line, with a green check mark when it succeeded and a red X when it failed. Expand a step to read everything it printed.

  3. When the run finishes, GitHub shows its check mark or X next to the commit too, on the repository’s main page and in the commit history.

GitHub adds steps of its own around yours, such as Set up job at the start and Complete job at the end. Expand Run the tests to see the same pytest output as on your computer.

To see a failure, break the code on purpose: change random.randint(1, sides) in dice.py to random.randint(0, sides). Run the tests on your computer first, as you always should:

>           assert 1 <= result <= 6
E           assert 1 <= 0

test_dice.py:12: AssertionError
=========================== short test summary info ============================
FAILED test_dice.py::test_rolls_are_between_1_and_sides - assert 1 <= 0
========================= 1 failed, 2 passed in 0.03s ==========================

Then commit and push it anyway, to see what GitHub does. pytest ends with exit status 1, so the Run the tests step fails, the job and the run fail, and the run shows the error Process completed with exit code 1. A failed step also stops the job: any step after it is skipped. Expand the step to read pytest’s report, which names the test and the values, as it did on your computer. Fix the code, commit, and push again, and the next run passes. A run that failed for a reason outside your code, such as a network error, can be repeated with Re-run jobs, on the run’s page.

A run that fails on GitHub but passes on your computer usually means the runner doesn’t have something you do: a file you never committed, or a package missing from requirements.txt.

Common misconceptions

MisconceptionWhat’s trueAn example that breaks it
All the tests pass, so the code is correctTests check only the cases they tryModule 12’s median passes every test of odd-length lists
A test that passes has tested somethingA test can be unable to fail, or never runIn test_checks.py, a function named check_mean isn’t collected: pytest reports no tests ran and exits with status 5
Floats can be compared with == in a testCalculated floats are often a tiny bit offc_to_f(38.1) == 100.58 fails; pytest.approx passes
pytest.raises passes when anything goes wrongIt passes only for the exception it namespytest.raises(ValueError) around a ZeroDivisionError fails the test
Tests that pass on my computer pass on GitHubThe runner has only what the repository holdsA test that reads a data file you never committed fails with FileNotFoundError

Summary

Self-check

  1. pytest reports this. What does the test check, which value is wrong, and where is the test?

    _______________________________ test_week_total ________________________________
    
        def test_week_total():
    >       assert total([2.4, 0, 12.0]) == pytest.approx(14.4)
    E       assert 12.0 == 14.4 ± 1.4e-05
    E         
    E         comparison failed
    E         Obtained: 12.0
    E         Expected: 14.4 ± 1.4e-05
    
    test_rain.py:7: AssertionError

    Answer

    It checks that total([2.4, 0, 12.0]) is 14.4, within pytest.approx’s tolerance: one part in a million of 14.4, which is the ± 1.4e-05. The function returned 12.0, which is 0 plus 12.0, so it seems to leave out the first value. The test is on line 7 of test_rain.py.

  2. parse_time("7:05") returns (7, 5), and raises ValueError with a message that contains HH:MM for text without a colon. Write one test that checks three good inputs, and one that checks the error.

    Answer

    @pytest.mark.parametrize(
        "text, expected",
        [
            ("7:05", (7, 5)),
            ("00:00", (0, 0)),
            ("23:59", (23, 59)),
        ],
    )
    def test_parse_time(text, expected):
        assert parse_time(text) == expected
    
    
    def test_parse_time_without_colon_raises():
        with pytest.raises(ValueError, match="HH:MM"):
            parse_time("705")

    The three good cases cover a typical time and both ends of the day. Other good choices work too, as long as they include the edges.

  3. This test passes, although mean([1, 2]) is 1.5. Why?

    def test_mean():
        mean([1, 2]) == 2

    Answer

    It has no assert. The comparison gives False, which the test throws away, and a test that raises nothing passes. Seeing each new test fail first, with the code broken or not written yet, catches a test like this one.

  4. Why does test_write_report use tmp_path instead of writing report.txt in the current folder?

    Answer

    tmp_path is a new, empty folder for each test, so the test can’t overwrite a real file, and can’t pass because of a report.txt that an earlier run left behind. The folder is also the same kind of object, a pathlib.Path, that the code under test expects.

  5. A workflow run’s Run the tests step shows a red X, and the step after it, which builds a report, shows no check mark either. What happened, and where do you look first?

    Answer

    pytest found a failing test and ended with exit status 1, so GitHub marked the step failed and skipped the steps after it. Expand Run the tests and read pytest’s report, as you would on your computer: the FAILURES section names the test, the line, and the values. Then run the tests on your computer, fix the cause, and push again.

Further reading