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:
pytest --pdb
You can also manually trigger a breakpoint inside a test or application code using pdb.set_trace():
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:
| 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 |
Introduction
pytest is rarely used in isolation. In most real-world testing environments, it acts as a central test runner while integrating smoothly with debugging tools, coverage analyzers, mocking libraries, environment managers and even other testing frameworks. This interoperability is one of pytest’s strongest advantages.
Coverage.py
Code coverage is a metric that indicates how much of an application’s source code is executed when the test suite runs, typically expressed as a percentage of the codebase exercised by the tests. pytest is commonly used together with Coverage.py tool to measure code coverage. While Coverage.py can be used on its own, pytest users typically rely on the pytest-cov plugin, which provides seamless integration.
