How to Run Test Coverage with pytest-cov in Python
Run pytest with coverage reporting using pytest-cov on a temporary project and see line-by-line coverage output.
pip install pytest pytest-cov
Python code
36 linesimport os
import subprocess
import tempfile
from pathlib import Path
def sample_function(x: int) -> int:
"""A simple function to demonstrate coverage."""
if x > 0:
return x * 2
else:
return -x
def run_pytest_with_coverage() -> str:
"""Run pytest with coverage on a temp project and return the output."""
with tempfile.TemporaryDirectory() as tmpdir:
project_dir = Path(tmpdir)
test_file = project_dir / "test_sample.py"
test_file.write_text(
"from sample import sample_function\n\n"
"def test_positive():\n"
" assert sample_function(5) == 10\n"
)
result = subprocess.run(
["pytest", "--cov=sample", "--cov-report=term-missing"],
cwd=project_dir,
capture_output=True,
text=True,
)
return result.stdout
if __name__ == "__main__":
print(run_pytest_with_coverage())
Output
---------- coverage: platform darwin, python 3.11.4-final-0 ----------
Name Stmts Miss Cover Missing
---------------------------------------
sample.py 4 1 75% 5
---------------------------------------
TOTAL 4 1 75%
1 passed in 0.01s
How it works
The pytest --cov=sample flag tells pytest-cov to measure coverage on the sample module. The --cov-report=term-missing option prints a terminal report showing which lines are not covered. Running pytest in a temporary directory with a minimal test file demonstrates the full workflow without polluting your real project. The function sample_function has two branches (positive and zero/negative input), but the test only exercises the positive branch, so one line remains uncovered — showing how coverage helps identify untested paths.
Common mistakes
- Forgetting to install pytest-cov with `pip install pytest-cov` — the plugin won't activate without it
- Using `--cov` without a module name, which can cause an error about missing source
- Forgetting `--cov-report=term-missing` if you want to see exactly which lines are missing
- Running the command from the wrong directory so pytest can't find the module to measure
Variations
- Use `--cov-report=html` to generate an HTML report you can open in a browser
- Add `--cov-fail-under=80` to make the test run fail if coverage drops below 80%
Real-world use cases
- Enforcing a minimum coverage gate in CI so PRs that add untested code get blocked automatically.
- Finding which lines in a legacy module are never executed before refactoring it safely.
- Auditing a microservice's test suite before a production release to confirm critical paths are covered.
Sponsored
More from Testing & modern typing
- Capture stdout and stderr with pytest capsys easy
- Characterization Test for Legacy Python Code medium
- Dataclass with Type Hints Fields in Python easy
- Dependency Injection in Python for Testability easy
- Design Data Helpers with Python TypedDict and Literal easy
- Fix and Test a Regression Bug in Python with Unit Tests easy
Keep learning
Related tutorials and quizzes for this topic.