Interactive Debugging with pdb
pytest integrates naturally with Python’s built-in debugger, pdb, making it easy to inspect failing tests interactively. When a test fails, you can instruct pytest to drop into a debugging session at the point of failure.
Running pytest with the --pdb option automatically invokes the debugger whenever a test fails:
shell
pytest --pdbYou can also manually trigger a breakpoint inside a test or application code using pdb.set_trace():
python
def test_division():
import pdb; pdb.set_trace()
result = 10 / 2
assert result == 5Once execution reaches the breakpoint, pytest pauses and hands control to the pdb shell.
The table below summarizes some of the most commonly used commands in the pdb interactive shell:
| Command | Description |
|---|---|
l or list | Shows the source code around the current line |
n or next | Executes the next line, stepping over function calls |
s or step | Steps into a function call |
c or continue | Continues execution until the next breakpoint or failure |
p <expr> | Prints the value of an expression |
pp <expr> | Pretty-prints the value of an expression |
w or where | Displays the current stack trace |
u | Moves one level up in the call stack |
d | Moves one level down in the call stack |
q or quit | Exits the debugger and aborts execution |
