Sub topic 3
Running pytest and reading the output
This chapter assumes you can write a test function and that pytest finds it by name, as covered in the previous chapter. It also assumes you have pytest installed in an active virtual environment. Here you will run pytest in several ways, read what it prints, and use its exit codes.
The shape of a run
A run has three phases. Pytest first collects tests by walking the directories you pass, importing matching files, and building a list of test items. It then runs each item in order. Finally it prints a report and exits with a status code.
Collection and execution fail differently, so it helps to know which phase broke. An ImportError in a test file is a collection error, and pytest reports it before any test runs.
Running the basics
Use this module under test and its tests:
# cart.py
def total(prices, tax_rate=0.0):
if tax_rate < 0:
raise ValueError("tax_rate must be non-negative")
return sum(prices) * (1 + tax_rate)# test_cart.py
import pytest
from cart import total
def test_total_without_tax():
assert total([10, 20]) == 30
def test_total_with_tax():
assert total([10, 20], tax_rate=0.1) == pytest.approx(33.0)
def test_negative_tax_rate_is_rejected():
with pytest.raises(ValueError, match="non-negative"):
total([1], tax_rate=-0.5)Run pytest in the directory that holds both files. You can also run python -m pytest. The second form adds the current directory to sys.path, which helps when from cart import total fails with ModuleNotFoundError.
============================= test session starts ==============================
platform linux -- Python 3.12.3, pytest-8.3.2, pluggy-1.5.0
rootdir: /home/user/project
collected 3 items
test_cart.py ... [100%]
============================== 3 passed in 0.01s ===============================The header lists the platform, the Python and pytest versions, and the rootdir. The rootdir is the base directory pytest uses for configuration and test IDs. The line collected 3 items confirms how many tests were found. If it says collected 0 items, check your file and function names first.
Each character after the file name is one test result. The percentage on the right shows progress through the whole run.
| Symbol | Meaning |
|---|---|
| `.` | The test passed |
| `F` | An assertion failed or the test raised an exception |
| `E` | An error happened outside the test body, such as in a fixture |
| `s` | The test was skipped |
| `x` | The test failed as expected (xfail) |
| `X` | The test was expected to fail but passed (xpass) |
The difference between F and E matters when you debug. F points at the test body or the code it calls. E points at setup or teardown, so look at your fixtures.
Reading a failure
Change the first assertion to assert total([10, 20]) == 31 and run again.
================================== FAILURES ===================================
____________________________ test_total_without_tax ____________________________
def test_total_without_tax():
> assert total([10, 20]) == 31
E assert 30 == 31
E + where 30 = total([10, 20])
test_cart.py:7: AssertionError
=========================== short test summary info ============================
FAILED test_cart.py::test_total_without_tax - assert 30 == 31
========================= 1 failed, 2 passed in 0.02s ==========================Read it from the top:
- The underscore banner names the failing test.
- Source lines show the test code. The
>marker sits on the line that failed. - Lines starting with
Eshow what went wrong. Pytest rewritesassertstatements so it can show the values of sub-expressions. That is why you see30 = total([10, 20])without writing any message. - The last line of the block gives
file:lineand the exception type. - The short test summary repeats each failure on one line, using the test's node ID.
A node ID such as test_cart.py::test_total_without_tax uniquely names one test. You can paste it back into the command line to rerun only that test.
Choosing what to run
You can narrow a run by location, by name, or by marker.
pytest test_cart.py
pytest test_cart.py::test_total_with_tax
pytest -v
pytest -k total --maxfail=1
pytest -m "not slow"
pytest --cov=cart --cov-report=term-missing- By location. A file, a directory, or a node ID limits collection to that target.
-vprints one line per test with its name and result instead of dots.-k totalruns tests whose names contain the expression. It supportsand,or, andnot, so-k "total and not tax"works.--maxfail=1stops after the first failure.-xis a shorthand for the same thing.-m "not slow"selects by marker. Markers are covered in a later chapter.--covreports coverage but only works if thepytest-covplugin is installed. It is also covered later.
Some other options you will use constantly:
| Option | Effect |
|---|---|
| `-q` | Quieter output, fewer header lines |
| `-s` | Show `print` output instead of capturing it |
| `--tb=short` | Shorter tracebacks (`long`, `short`, `line`, `no` are also valid) |
| `--lf` | Rerun only the tests that failed in the last run |
| `--ff` | Run the previous failures first, then the rest |
| `--collect-only` | List what would run without running it |
| `-ra` | Add a summary line for every outcome except passes |
Pytest captures standard output by default and shows it only for failing tests. This keeps passing runs clean. Use -s when you want live prints while debugging.
Exit codes
Pytest returns a numeric exit code. Continuous integration systems read this code, not the printed text.
| Code | Meaning |
|---|---|
| 0 | All collected tests passed |
| 1 | Some tests failed |
| 2 | The run was interrupted, for example with Ctrl+C |
| 3 | An internal error occurred |
| 4 | The command line was used incorrectly |
| 5 | No tests were collected |
Code 5 surprises many people. A typo in a -k expression selects nothing, and the run fails even though no test failed. In a shell, check the code with echo $? right after the run.
Common errors when running
ModuleNotFoundErrorfor your own module. The directory holding your code is not onsys.path. Runpython -m pytestfrom the project root, or install the project in editable mode withpip install -e ..collected 0 items. Files must matchtest_*.pyor*_test.py. Functions must start withtest. Classes must start withTestand have no__init__method.import file mismatch. Two test files share the same base name in directories without__init__.py. Rename one, or add the package files.- Failures hidden by output capture. Rerun with
-s, or read the "Captured stdout call" section pytest prints under a failure. - Stale results from an old run. Remove the
.pytest_cachedirectory if--lfbehaves oddly. It is safe to delete.
Exercise
You run pytest -k totl by mistake, with a typo. No test name contains "totl". What does pytest report, and what exit code does it return?
Show answer
Pytest collects the tests, deselects all of them, and prints a line such as "3 deselected" followed by "no tests ran". It exits with code 5, which means no tests were collected. No test failed, but the code is non-zero so a CI job would notice the problem.
Exercise
A test output shows test_cart.py E. for a file with two tests. What does the E tell you about where to look, and how would you rerun only that test?
Show answer
E means an error occurred outside the test body, most likely in a fixture's setup or teardown. Look at the fixtures the first test requests. To rerun only that test, copy its node ID from the short test summary (for example test_cart.py::test_name) and pass it to pytest, or use pytest --lf to rerun the last failures.