Python Pytest Coverage with pytest-cov
Measure Python code coverage with pytest-cov: set thresholds, exclude selected code, and generate terminal, HTML, and XML reports.

When you run pytest, you often want to know how much of your code is actually exercised by your tests. The pytest-cov plugin integrates coverage.py with pytest, so you can measure coverage for the packages you specify and turn the results into terminal, HTML, or XML reports.
Installing pytest-cov and Running Your First Coverage Report
Start by installing the plugin into your environment:
pip install pytest-covThen run pytest with the --cov flag and point it at the package or module you want to measure:
pytest --cov=myprojectThis executes your test suite and prints a coverage summary to the terminal. The summary shows the number of executed statements, the number missed, and the coverage percentage for each file:
Name Stmts Miss Cover
----------------------------------------
myproject/__init__.py 10 2 80%
myproject/core.py 50 5 90%
----------------------------------------
TOTAL 60 7 88%To include the actual missing line numbers in the terminal report, use the term-missing report type:
pytest --cov=myproject --cov-report=term-missingThe --cov option accepts a package, module, or directory. You can measure multiple locations by repeating the flag:
pytest --cov=myproject --cov=myproject.utilsIf you omit the value, pytest-cov measures everything it can see, which usually includes third-party libraries and is rarely what you want. Specify the code you own.
Understanding Coverage Report Formats
By default, pytest-cov prints a terminal report. Use --cov-report to control the output. The most common report types are term, html, and xml; coverage.py also supports additional formats depending on your installed version.
To generate an HTML report you can open in a browser:
pytest --cov=myproject --cov-report=htmlThis creates an htmlcov/ directory with an index.html file. The HTML report highlights covered and missed lines, which helps when you need to inspect specific branches or statements.
For CI systems, an XML report is often useful because tools such as SonarQube or Codecov can ingest it:
pytest --cov=myproject --cov-report=xmlThe XML file is written to coverage.xml by default. You can combine report formats in a single run:
pytest --cov=myproject --cov-report=term --cov-report=htmlThis prints the terminal summary and writes the HTML report at the same time.
Using a Configuration File for Consistent Coverage Settings
Typing the same --cov flags on every command is error-prone. Store them in a pytest configuration file so that a plain pytest invocation picks them up automatically.
In pytest.ini:
[pytest]
addopts = --cov=myproject --cov-report=term --cov-report=htmlIn pyproject.toml, add a [tool.pytest.ini_options] section:
[tool.pytest.ini_options]
addopts = "--cov=myproject --cov-report=term --cov-report=html"With this configuration, every test run produces both the terminal summary and an HTML report. You can still pass additional flags on the command line, but the defaults are consistent across your team and CI.
Setting Coverage Thresholds
A coverage percentage alone does not guarantee quality, but a threshold gives you a concrete gate for regressions. The --cov-fail-under option makes pytest exit with a non-zero status if total coverage falls below a percentage you specify:
pytest --cov=myproject --cov-fail-under=80If total coverage is below 80%, pytest exits with a failure status, which can cause a CI build to fail. You can also set the threshold in a configuration file:
[pytest]
addopts = --cov=myproject --cov-fail-under=80Choose a threshold carefully. In a large legacy codebase, a very high threshold may push you toward testing code that is not worth testing, while a very low threshold can create a false sense of security.
Excluding Code from Coverage
Not every line needs to be covered. Debug-only branches, version-compatibility shims, or code that runs only under one interpreter version may be impractical to test. coverage.py provides two ways to exclude code.
First, add a # pragma: no cover comment to a line:
def debug_only_function():
if __debug__:
print("Debugging output") # pragma: no coverFor a whole block, place the comment on the if or def line:
def platform_specific_behavior(): # pragma: no cover
if sys.platform == "win32":
return "Windows"
else:
return "Linux"Second, configure exclusions in a .coveragerc file or in the [tool.coverage.report] section of pyproject.toml. For example, to skip debug-only branches and lines that deliberately raise AssertionError:
[tool.coverage.report]
exclude_lines = ["if __debug__:", "raise AssertionError"]Excluding code should be a deliberate decision. If you exclude too much, your coverage number becomes meaningless. Use pragmas sparingly and document why a particular block is excluded.
Combining Coverage Across Multiple Test Runs
In a large project, you might split your test suite into several invocations, such as running unit tests and integration tests separately. By default, each pytest run starts with a clean coverage state. To accumulate coverage across runs, use the --cov-append flag:
pytest --cov=myproject tests/unit
pytest --cov=myproject --cov-append tests/integrationThe second run appends its data to the file left by the first. This is useful when different test directories require different fixtures or database setups.
Be aware that --cov-append only works if both runs use the same coverage data file. By default, pytest-cov writes to .coverage in the current directory. If you run tests from different directories, set the COVERAGE_FILE environment variable to a shared path.
Operational Considerations: Performance and CI Integration
Coverage measurement adds overhead to every test run because the interpreter must track which lines are executed. For large or slow suites, this can be noticeable, so reserve coverage measurement for full CI runs and use plain pytest for quick smoke tests.
Branch coverage, enabled with --cov-branch, provides a more detailed view of which branches were taken, but it increases overhead further. Use it when you need to understand edge cases in complex conditionals.
In CI, you typically want a single command that produces a report and enforces a threshold. A common pattern is:
pytest --cov=myproject --cov-report=xml --cov-report=term --cov-fail-under=80This generates an XML artifact for external tools and fails the build if coverage drops below 80%. Keep the threshold in your configuration file so local runs match CI behavior.
Generated files such as .coverage, htmlcov/, and coverage.xml should be added to .gitignore.
Finally, remember that coverage measures which lines were executed, not whether assertions were meaningful. A high coverage percentage does not guarantee that your tests catch bugs. Use coverage as one signal among many, and combine it with mutation testing or property-based testing when you need stronger guarantees.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.