Skip to content

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 --pdb

You 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 == 5

Once 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:

CommandDescription
l or listShows the source code around the current line
n or nextExecutes the next line, stepping over function calls
s or stepSteps into a function call
c or continueContinues 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 whereDisplays the current stack trace
uMoves one level up in the call stack
dMoves one level down in the call stack
q or quitExits the debugger and aborts execution