Measuring Test Coverage with 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.
After installing the plugin, coverage measurement becomes part of the normal pytest workflow:
pytest --cov=my_package
This command runs all tests and reports how much of my_package was covered.
You can also generate more detailed reports, such as an HTML report:
pytest --cov=my_package --cov-report=html
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.
mock
pytest does not ship its own mocking library, but it works extremely well with unittest.mock, which is part of the Python standard library. This allows you to replace external dependencies, network calls, or expensive operations with controlled mock objects. Mock objects are sometimes called test doubles, spies, fakes or stubs. By combining pytest’s monkeypatch fixture with the unittest.mock module, you can cover nearly all common test double use cases.
