Coverage
Pytest · Reference cheat sheet
Coverage
Pytest · Reference cheat sheet
📋 Overview
pytest-cov integrates coverage.py: measure line/branch coverage, fail under thresholds, and emit terminal/HTML/XML reports for CI.
🔧 Core concepts
| Flag | Meaning |
|---|---|
--cov=pkg | Measure package |
--cov-report= | term, html, xml |
--cov-fail-under=N | Exit non-zero if below |
--cov-branch | Branch coverage |
omit / include | Scope in .coveragerc |
Run from project root so paths resolve correctly.
💡 Examples
CLI:
pytest --cov=myapp --cov-report=term-missing
pytest --cov=myapp --cov-report=html --cov-report=xml
pytest --cov=myapp --cov-fail-under=85 --cov-branchpyproject.toml:
[tool.coverage.run]
source = ["myapp"]
branch = true
omit = ["*/tests/*", "*/migrations/*"]
[tool.coverage.report]
show_missing = true
skip_covered = false
fail_under = 85
[tool.pytest.ini_options]
addopts = "--cov=myapp --cov-report=term-missing"HTML: open htmlcov/index.html.
CI: publish coverage.xml to Codecov/Sonar; keep thresholds realistic for new projects.
⚠️ Pitfalls
- Measuring tests or virtualenv paths — set
source/omit. - 100% line coverage with zero meaningful assertions.
- Combining xdist without
pytest-covconcurrency support configured. - Dynamic imports /
# pragma: no coverabused to hide gaps. - Different coverage between local and CI due to optional extras.