Testing
Last updated
How do you know your fine rules still work after you change them? You run them and check the answers. In this lesson you'll make Python do the checking with assert, write test functions, run them all with pytest, read the report when a test fails, and test that a function raises the error it should.
By the end of this lesson you can
- Check a result with
assert, and read anAssertionError - Write test functions in a
test_file and run them withpytest - Read pytest’s report for a failing test and find the bug it points to
- Test that a function raises an error, with
pytest.raises
Checking with assert
assert is followed by something that should be true. If it is, nothing happens and the program carries on. If it's false, the program stops with an error.
Here fine_for is the rule from the Stage 1 project. Each assert checks one answer we already know: on time is free, 3 days cost 75 cents, and fines stop at 500.
Checking by eye means reading the output every time and remembering what it should be. An assert remembers for you.
When a check fails
The second check on line 11 is wrong on purpose: 4 days late should be 100 cents, not 75. Press Run and read the error.
AssertionError: 4 days late should cost 4 times 25. The text after the comma on line 11 is an optional message, shown when the check fails. Line 10 passed, so nothing else was printed.
Here the check was wrong, so fix the check: change 75 to 100. When a correct check fails, the code is wrong, and that's the bug the test caught for you.
Tests are functions
A few loose assert lines get messy, and the first one that fails stops all the rest. So tests are written as functions, one for each thing to check, with names that say what's being checked. A test function takes no arguments, starts with test_, and passes if it ends without an error.
The fine rules now live in their own module: click the fines.py tab. main.py holds the tests, like a file called test_fines.py would. At the bottom, it calls each test by hand.
Calling every test by hand gets tedious, and it's easy to write a new test and forget to call it. The next step hands that job to a tool.
Running them with pytest
pytest is the most widely used testing tool for Python. Install it into your project’s virtual environment, as in lesson 2.9:
(.venv) > python -m pip install pytestpytest finds tests by their names: files called test_something.py, and functions inside them called test_something. So the project folder looks like this, and test_fines.py is the code from step 3 without the three calls at the bottom:
library/
fines.py
test_fines.pyFrom the project folder, run pytest. It finds the file, calls every test function, and reports:
(.venv) > python -m pytest
============================= test session starts =============================
collected 3 items
test_fines.py ... [100%]
============================== 3 passed in 0.02s ==============================(Two lines naming your Python version and folder are left out here.) Each dot is a test that passed. Add -v to see each test’s name instead.
Reading a failing test
Someone tidied fines.py and took out the lines that stop a fine at 500. Click the fines.py tab to see the change, then press Run.
The page’s Python stops at the first failure. pytest runs every test and reports each one that failed:
(.venv) > python -m pytest
============================= test session starts =============================
collected 3 items
test_fines.py ..F [100%]
================================== FAILURES ===================================
_________________________ test_fine_stops_at_the_cap __________________________
def test_fine_stops_at_the_cap():
> assert fine_for(40) == 500
E assert 1000 == 500
E + where 1000 = fine_for(40)
test_fines.py:13: AssertionError
=========================== short test summary info ===========================
FAILED test_fines.py::test_fine_stops_at_the_cap - assert 1000 == 500
========================= 1 failed, 2 passed in 0.08s =========================Read it from the top. ..F: two tests passed, the third failed. Under FAILURES, the test’s name says what broke: the cap. The > marks the line that failed, and the E lines show both sides of the check: fine_for(40) gave 1000, but the test wanted 500.
The test is right, so the bug is in fines.py. In the fines.py tab, put back the two lines after fine = days_late * FINE_PER_DAY:
if fine > MAX_FINE:
fine = MAX_FINERun it again, and all three tests pass.
Testing an error
In lesson 2.6, fine_for learned to raise a ValueError when it's given a negative number of days. That behaviour needs a test too. In pytest you write
import pytest
from fines import fine_for
def test_negative_days_is_an_error():
with pytest.raises(ValueError):
fine_for(-1)The test passes only if the lines inside the with raise a ValueError. If they raise nothing, or a different error, it fails. Here’s what pytest.raises does for you, written by hand with try and except:
And here’s a fine_for that forgets to raise. Press Run: the test catches it.
With the ValueError test added to test_fines.py, pytest reports:
(.venv) > python -m pytest
...
test_fines.py .... [100%]
============================== 4 passed in 0.02s ==============================Check what you learned
Four questions. Pick or type an answer, then check it.
Sources
Every example on this page was run with Python 3.14, and its output and error messages are copied from it. These pages cover the same ground in more depth.
- The Python Language Reference: The assert statement
- Built-in Exceptions: AssertionError
- unittest: Basic example: test methods start with test, and checks that a call raises an error
- The Python Tutorial: Raising Exceptions
- The Python Tutorial: Handling Exceptions: the try and except a hand-written error test uses