Sometimes, you want to ignore parts of your code when checking test coverage. This helps focus on important code and avoid false alarms.
0
0
Excluding code from coverage in PyTest
Introduction
When you have debug or logging code that does not affect program logic.
When you include code that runs only on specific platforms or environments.
When you have code that is hard to test or not worth testing, like error handlers for impossible cases.
When you want to exclude generated code or third-party code from coverage reports.
Syntax
PyTest
# Use comment # pragma: no cover after the line you want to exclude some_code() # pragma: no cover
The comment # pragma: no cover tells coverage tools to ignore that line.
This works well with pytest and coverage.py tools.
Examples
This line will not be counted in coverage reports.
PyTest
def example(): print("This runs") # pragma: no cover
Exclude code that runs only when the script is executed directly.
PyTest
if __name__ == '__main__': # pragma: no cover main()
Exclude debug code from coverage.
PyTest
def debug(): # This function is for debugging only print("Debug info") # pragma: no cover
Sample Program
This example shows a simple function add tested by test_add. The debug_log function is excluded from coverage using # pragma: no cover.
PyTest
def add(a, b): return a + b def debug_log(): print("Debug info") # pragma: no cover def test_add(): assert add(2, 3) == 5 # Run tests with coverage: pytest --cov=. # The debug_log function line is excluded from coverage report.
OutputSuccess
Important Notes
Use # pragma: no cover only on lines you really want to exclude.
Coverage tools ignore these lines when calculating coverage percentage.
Remember to run coverage with pytest using --cov option.
Summary
Use # pragma: no cover comment to exclude code lines from coverage.
This helps keep coverage reports focused and accurate.
Works well with pytest and coverage.py tools.