Sub topic 14
Debugging failing tests with pytest and pdb
This chapter assumes you can write basic pytest tests and have read the earlier chapters on the (Pdb) prompt, breakpoint(), post-mortem mode, and stack navigation. Pytest integrates with pdb, so you can debug a failing test without changing how you write it.
Opening pdb on failure with --pdb
The --pdb option starts a post-mortem session whenever a test fails or raises an error. The session opens in the frame where the exception was raised. It does not open in the test function.
Consider this code under test:
# stats.py
def mean(values):
return sum(values) / len(values)
def summarize(groups):
return {name: mean(vals) for name, vals in groups.items()}And this test:
# test_stats.py
from stats import summarize
def test_summarize():
groups = {"a": [1, 2, 3], "b": []}
assert summarize(groups)["a"] == 2Run it with -x so pytest stops after the first failure:
pytest --pdb -xPytest prints the traceback, then shows a (Pdb) prompt inside mean:
(Pdb) p values
[]
(Pdb) w
(Pdb) u
(Pdb) p name
'b'
(Pdb) qp values shows the empty list that caused the ZeroDivisionError. u moves up one frame into the dict comprehension, where name shows which group was empty. The cause is the input data, so the fix belongs in mean or in the caller's handling of empty groups.
Using breakpoint() inside a test
You can also put breakpoint() in a test or in the code it calls. Pytest hooks into it, pauses its output capturing, and gives you a normal (Pdb) prompt. Use this when a test fails with a wrong value and no exception, so --pdb has nothing to catch.
def test_summarize_a():
groups = {"a": [1, 2, 3]}
result = summarize(groups)
breakpoint()
assert result["a"] == 2Pytest captures stdout by default, so anything your code prints is hidden unless the test fails. The -s option turns capturing off. Add it when you want to see print output while you step:
pytest -s test_stats.py::test_summarize_aNaming a single test with file::test_name keeps the session short and avoids stopping at unrelated breakpoints.
Other options worth knowing
| Option | Effect |
|---|---|
| `--pdb` | Open pdb post-mortem at each failure or error |
| `-x` | Stop after the first failure |
| `--lf` | Rerun only the tests that failed last time |
| `--trace` | Stop at the start of each selected test |
| `-s` | Do not capture output |
A common combination is pytest --lf -x --pdb. It reruns only what failed before, stops at the first failure, and opens the debugger there.
Common errors
- Debugger never opens. Check that the test actually fails. A passing test does not trigger
--pdb. - Prompt appears but input is garbled. Another plugin may be capturing the terminal. Try
-s, or run without-nfrom pytest-xdist, since debugging does not work across parallel workers. - Breakpoint left in the code. A forgotten
breakpoint()hangs a CI run. SettingPYTHONBREAKPOINT=0in CI disables every call. - Wrong frame.
--pdbstarts in the innermost frame. Usewanduto reach the test function.
Exercise
A test fails with an AssertionError because a function returned 4 instead of 5, and no exception comes from the code under test. You want to examine local variables inside the function while the test runs. Which approach works, and why is --pdb alone a poor fit?
Show answer
Put breakpoint() inside the function (or use pytest --trace to stop at the test's start and step in), then run only that test. --pdb opens only after a failure and starts in the frame where the exception was raised. For an assertion failure, that frame is the test's assertion line, which is after the function has already returned. You could not step through the function's execution.