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