Sub topic 14
Debugging failing tests with pytest and pdb
This chapter assumes you can read a pytest failure report, run pytest from a terminal, and use the basic pdb commands (n, s, c, p, w, up, down). It also assumes you know what breakpoint() does. Here you will connect those tools to pytest. A failing test is a reproducible crash, which makes it a good place to use a debugger.
Why debug inside pytest
A failing test gives you a fixed input, a fixed call path, and a failure you can trigger again and again. You don't need to rebuild the situation by hand. You can also start the debugger exactly where the test fails, so you skip the printing, rerunning, and guessing.
pytest has three ways to start pdb. They differ in when the debugger starts.
| Option | When pdb starts | Typical use |
|---|---|---|
| `--pdb` | After a test fails or raises an unexpected error | You see a failure and want to inspect its state |
| `--trace` | Before each selected test runs, at its first line | You want to step through a test from the start |
| `breakpoint()` in code | When execution reaches that line | You know where to look before the failure happens |
A failing test to practice on
Create two files in an empty directory. The first holds the code under test.
# cart.py
def apply_discount(price, percent):
return price - price * percent / 100
def total(items, percent):
subtotal = sum(item["price"] * item["qty"] for item in items)
return apply_discount(subtotal, percent)The second holds the test. One item uses the key quantity where the code expects qty.
# test_cart.py
from cart import total
def test_total_with_discount():
items = [
{"price": 10.0, "qty": 2},
{"price": 5.0, "quantity": 1},
]
assert total(items, 10) == 22.5Running pytest prints a KeyError: 'qty' traceback. The traceback tells you where the error happened. It does not let you ask which item caused it or what the other values were. That is the job of the debugger.
Post-mortem on failure with `--pdb`
Run pytest with --pdb:
pytest --pdbWhen the test fails, pytest prints the usual failure report and then opens a (Pdb) prompt. This is the same post-mortem mode you used with pdb.post_mortem(). The frame you land in is the one where the exception was raised, not the test function. Here that is the generator expression inside total. The output below is abridged:
>>>>>>>>>> PDB post_mortem (IO-capturing turned off) >>>>>>>>>>
> /home/you/project/cart.py(7)<genexpr>()
-> subtotal = sum(item["price"] * item["qty"] for item in items)
(Pdb) p item
{'price': 5.0, 'quantity': 1}
(Pdb) up
> /home/you/project/cart.py(7)total()
-> subtotal = sum(item["price"] * item["qty"] for item in items)
(Pdb) p items
[{'price': 10.0, 'qty': 2}, {'price': 5.0, 'quantity': 1}]
(Pdb) up
> /home/you/project/test_cart.py(10)test_total_with_discount()
-> assert total(items, 10) == 22.5
(Pdb) cOne p item shows the cause: the second item has quantity instead of qty. The up commands move you outward through the stack, so you can compare the bad value with the data the test supplied.
A few details matter here:
- The state is frozen at the moment of failure. You can inspect it but you can't "fix and resume". Stepping with
nin a post-mortem session does not rerun the failed line. - With an assertion failure, you land in the test function at the
assertline. If the assertion calls other code that raised, you land in the deepest frame. --pdbonly triggers on failures and errors. It does not trigger on passing tests, skipped tests, or expected failures marked withxfail.cends the session for that test and pytest moves on. The next failing test opens a new session.qquits the debugger and also stops the whole pytest run. Usecif you want to see the remaining failures.
Controlling which failures you debug
On a large suite, --pdb alone can open dozens of sessions. Combine it with selection options:
# Stop at the first failure and debug it
pytest -x --pdb
# Rerun only the tests that failed last time
pytest --lf --pdb
# Run one test by node ID
pytest test_cart.py::test_total_with_discount --pdb
# Run tests whose names match an expression
pytest -k discount --pdb--lf (last failed) uses pytest's cache directory, so it works after a normal run that showed failures. -x stops after the first failure. --maxfail=3 stops after three, if you want a few.
Stopping before the failure with `--trace`
Sometimes the test fails with a wrong value rather than an exception, and you need to watch values change. The option --trace starts pdb at the first line of each selected test:
pytest --trace test_cart.py::test_total_with_discountYou are now at the top of the test function. Use s to step into total, n to move over lines, and display to watch an expression after every stop. Always select a single test with --trace. Otherwise you get a debugger prompt for every test in the run.
Using `breakpoint()` in tests and code
You can also put breakpoint() in the test or in the code under test, as you would in a script:
def total(items, percent):
breakpoint()
subtotal = sum(item["price"] * item["qty"] for item in items)
return apply_discount(subtotal, percent)pytest normally captures everything the test prints, which would make a debugger prompt unusable. To avoid that, pytest recognizes the default breakpoint() and pdb.set_trace() calls. It suspends output capture while the prompt is open and restores it when you continue. You don't need -s for this to work.
The option -s (short for --capture=no) turns capturing off completely. Use it when you want to see print() output as it happens, or when you use a custom debugger through PYTHONBREAKPOINT that pytest does not recognize:
PYTHONBREAKPOINT=ipdb.set_trace pytest -s test_cart.pyBecause breakpoint() runs only when execution reaches it, you can place it inside a branch to stop at one interesting case:
def total(items, percent):
for item in items:
if "qty" not in item:
breakpoint()
...This fits cases where a failure depends on one input out of many, such as one parametrized case.
Debugging a parametrized test
With @pytest.mark.parametrize, the same code runs for many inputs. A plain breakpoint() stops on every case. Two approaches help:
- Run one case by its node ID:
pytest "test_cart.py::test_total[10-22.5]" --trace. Usepytest --collect-only -qto list the exact IDs. - Use a conditional breakpoint. Start with
--trace, then at the first prompt typeb cart.py:6, percent == 50andc. The debugger stops only when that condition is true.
Which approach to choose
The diagram shows a sensible order of decisions.
The workflow matches the hypothesis-driven approach from earlier in this tutorial. Look at the failing state first, then state what you think went wrong, then use the prompt to confirm or reject that guess. Only then edit the code.
Using a different debugger class
pytest lets you replace pdb with a compatible debugger through --pdbcls:
pytest --pdb --pdbcls=IPython.terminal.debugger:TerminalPdbThe format is module:class. The class must be a subclass-compatible debugger. This example requires IPython to be installed. Use it when you want tab completion and syntax highlighting while keeping the same pdb commands.
Common errors and gotchas
- Debugger prompt with no echo or hanging output. This usually means capture is interfering with a custom debugger. Add
-s. - Forgotten
breakpoint()in committed code. In an automated run with no terminal attached, the prompt reads end-of-file and the test fails with an error instead of hanging. SetPYTHONBREAKPOINT=0in CI to make everybreakpoint()call do nothing, and add a check that rejects the string in code review. --pdbandxfailorskip. Neither opens a prompt. If you want to debug an expected failure, run it without the mark or use--runxfail.- Parallel runs. With plugins such as pytest-xdist, worker processes cannot share your terminal, so the debugger is not usable. Run the failing test alone in a normal process.
qaborts the whole run. If you only wanted to leave one session, usec.- Failures in fixtures. An error in a fixture is reported as a setup error.
--pdbstill opens, but the top frame is in the fixture, not the test.
Summary of commands
pytest --pdb # debug each failure after it happens
pytest -x --pdb # stop at the first failure
pytest --lf --pdb # only tests that failed last run
pytest --trace path::test_name # start at the first line of a test
pytest -s # no output capture
PYTHONBREAKPOINT=0 pytest # ignore every breakpoint() callExercise
You run pytest --pdb and a test fails with an exception raised inside a helper function that the test calls. At the (Pdb) prompt you want to see the arguments the test passed to the helper. Which frame are you in when the prompt opens, and which commands get you to the test's frame and show its local variables?
Show answer
The prompt opens in the frame where the exception was raised, which is the helper function (the deepest frame), not the test. Type up once, or as many times as needed, to move to the test function's frame. Then use pp locals() or p variable_name to see its values. w shows the whole stack and marks the current frame with >.
Exercise
A parametrized test has 40 cases and only the case with percent=50 fails with a wrong value, no exception. Describe a command sequence that stops only on that case without editing the code.
Show answer
Collect the IDs with pytest --collect-only -q, then run the single failing case with pytest "test_cart.py::test_total[...]" --trace, using its exact ID. You are now at the first line of that test and can step with s and n. Alternatively, run with --trace on the whole test function, set a conditional breakpoint such as b cart.py:6, percent == 50, and continue with c, so the debugger stops only when the condition is true.