0
0
PyTesttesting~5 mins

pytest-cov setup

Choose your learning style9 modes available
Introduction

We use pytest-cov to check how much of our code is tested. It helps find parts that need more tests.

You want to see which parts of your code are tested by your tests.
You want to improve your test coverage to catch more bugs.
You need to generate a coverage report for your project.
You want to check coverage automatically during continuous integration.
You want to find untested code before releasing your software.
Syntax
PyTest
pip install pytest-cov

pytest --cov=your_package_name

# Optional: generate HTML report
pytest --cov=your_package_name --cov-report=html

Replace your_package_name with the folder or module you want to check coverage for.

The --cov-report=html option creates a nice report you can open in a browser.

Examples
This installs the pytest-cov plugin so pytest can measure coverage.
PyTest
pip install pytest-cov
Runs tests and shows coverage for the myapp folder in the terminal.
PyTest
pytest --cov=myapp
Runs tests, shows coverage, and creates an HTML report in the htmlcov folder.
PyTest
pytest --cov=myapp --cov-report=html
Sample Program

This simple test checks the add function. Running pytest with coverage shows which lines ran.

PyTest
# test_sample.py

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

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

# Run in terminal:
# pytest --cov=. --cov-report=term-missing
OutputSuccess
Important Notes

Always install pytest-cov in the same environment where you run pytest.

Use --cov-report=term-missing to see which lines are not covered in the terminal.

Coverage reports help you find untested code to improve your tests.

Summary

pytest-cov measures how much code your tests cover.

Install it with pip install pytest-cov and run pytest with --cov.

You can create reports in the terminal or as HTML files.