Framework Mode - Excluding code from coverage
Folder Structure
project-root/ ├── src/ │ └── my_module.py ├── tests/ │ ├── test_feature.py │ └── conftest.py ├── .coveragerc ├── pytest.ini └── requirements.txt
Jump into concepts and practice - no test required
project-root/ ├── src/ │ └── my_module.py ├── tests/ │ ├── test_feature.py │ └── conftest.py ├── .coveragerc ├── pytest.ini └── requirements.txt
.coveragerc for coverage settings, pytest.ini for pytest options.conftest.py to support tests.To exclude code from coverage reports in pytest, use the .coveragerc file with coverage.py settings.
Example .coveragerc content:
[run]
omit =
src/excluded_module.py
src/*_deprecated.py
[report]
exclude_lines =
# Exclude lines with this comment
pragma: no cover
if __name__ == '__main__':
In your source code, mark lines or blocks to exclude with # pragma: no cover comment.
Example in my_module.py:
def helper_function():
# This function is only for debugging
print("Debug info") # pragma: no cover
Run tests with coverage using:
pytest --cov=src
pytest-cov plugin to generate coverage reports.
name: Python Tests
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Set up Python
uses: actions/setup-python@v4
with:
python-version: '3.12'
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install pytest pytest-cov
- name: Run tests with coverage
run: pytest --cov=src --cov-report=xml
- name: Upload coverage to Codecov
uses: codecov/codecov-action@v3
# pragma: no cover comments to exclude specific lines or blocks that are not relevant for coverage (e.g., debug prints, platform-specific code)..coveragerc to omit entire files or folders that should not be counted in coverage (e.g., legacy code, generated files).Where in this framework structure would you add a new file to exclude from coverage reporting?
# pragma: no cover in your Python test code when using pytest and coverage.py?# pragma: no cover tells coverage.py to ignore that line when measuring test coverage.# pragma: no cover exactly as written.def func(x):
if x > 0:
return x
else:
return -x # pragma: no cover
What will coverage.py report about the line with return -x if it is never executed?# pragma: no cover tells coverage.py to ignore that line regardless of execution.def example():
print('Start') # pragma no cover
print('End')But coverage.py still counts the first print line as uncovered. What is the likely problem?# pragma: no cover. Missing colon causes coverage.py to ignore the comment.# pragma: no cover only works line-by-line. Which approach correctly excludes multiple lines without affecting other code?# pragma: no cover comment excludes coverage only for the line it is on, so each line must have it to be excluded.if False: changes code behavior or testability; partial comments on first and last lines do not exclude intermediate lines.