0
0
PytestHow-ToBeginner ยท 3 min read

How to Generate Coverage Report with pytest

To generate a coverage report with pytest, install the pytest-cov plugin and run pytest --cov=your_package. Add --cov-report=term or --cov-report=html to see coverage in the terminal or as an HTML report.
๐Ÿ“

Syntax

Use the pytest command with the --cov option to specify the package or module to measure coverage. Add --cov-report to choose the report format.

  • --cov=PATH: Path to the code to measure coverage.
  • --cov-report=term: Show coverage summary in the terminal.
  • --cov-report=html: Generate an HTML report in a htmlcov folder.
bash
pytest --cov=your_package --cov-report=term
pytest --cov=your_package --cov-report=html
๐Ÿ’ป

Example

This example shows how to run pytest with coverage on a sample package named myapp. It runs tests and prints a coverage summary in the terminal and also creates an HTML report.

python
[test_sample.py]

def add(a, b):
    return a + b


def test_add():
    assert add(2, 3) == 5


# Run this command in terminal:
# pytest --cov=myapp --cov-report=term --cov-report=html
Output
============================= test session starts ============================= collecting ... collected 1 item test_sample.py . [100%] ---------- coverage: platform linux, python 3.x.x ---------- Name Stmts Miss Cover ---------------------------------- myapp.py 3 0 100% ============================== 1 passed in 0.03s ============================== # An HTML report is created in the htmlcov directory.
โš ๏ธ

Common Pitfalls

Common mistakes when generating coverage reports include:

  • Not installing pytest-cov plugin, so --cov option is not recognized.
  • Forgetting to specify the correct package or module path in --cov=.
  • Running tests without coverage options, so no report is generated.
  • Expecting coverage for code not imported or executed during tests.
bash
Wrong:
pytest

Right:
pytest --cov=myapp --cov-report=term
๐Ÿ“Š

Quick Reference

OptionDescription
--cov=PATHMeasure coverage for the specified path
--cov-report=termShow coverage summary in terminal
--cov-report=htmlGenerate HTML coverage report
--cov-report=xmlGenerate XML coverage report for CI tools
--cov-fail-under=MINFail test if coverage is below MIN%
โœ…

Key Takeaways

Install pytest-cov plugin to enable coverage reporting with pytest.
Use --cov=your_package to specify which code to measure.
Add --cov-report=term or --cov-report=html to see coverage results.
Ensure tests execute the code you want coverage for.
Use --cov-fail-under to enforce minimum coverage thresholds.