Code coverage

suggest change

Code coverage measures how much of your Python source code is executed when your automated test suite runs. It identifies untested execution paths, dead code, and untested conditional branches. The standard tool for measuring code coverage in Python is coverage.py, typically paired with the pytest-cov plugin.


1. Installing coverage.py and pytest-cov

pip install coverage pytest-cov

2. Running Coverage with unittest and coverage run

If your project uses Python's standard unittest framework:

# Execute tests under coverage measurement
coverage run -m unittest discover

# Display the summary report with missing lines
coverage report -m

Sample report output:

Name                      Stmts   Miss  Cover   Missing
-------------------------------------------------------
src/__init__.py               0      0   100%
src/calculator.py            18      2    89%   24-25
src/user_service.py          42      0   100%
-------------------------------------------------------
TOTAL                        60      2    97%

The Missing column indicates exact line numbers that were not reached during test execution.


3. Running Coverage with pytest and pytest-cov

For projects using pytest, the pytest-cov plugin provides tight integration:

# Run pytest with coverage for the 'src' package
pytest --cov=src --cov-report=term-missing

# Generate an interactive HTML report
pytest --cov=src --cov-report=html

# Enforce a minimum coverage threshold (fails with exit code 1 if below)
pytest --cov=src --cov-fail-under=90

The HTML report is written to htmlcov/index.html. Opening it in a browser provides line-by-line syntax-highlighted views showing green (executed), red (missed), and yellow (partial branch) lines.


4. Branch Coverage

Line coverage (statement coverage) only verifies that a line was touched; it does not check if every boolean decision (if/else) was exercised. Branch coverage ensures both True and False outcomes of conditional statements are tested:

# src/discount.py
def apply_discount(price: float, is_vip: bool) -> float:
    if is_vip and price > 100:  # Branch test
        price = price * 0.8
    return price

If your tests only ever pass is_vip=True with price=150, line coverage will report 100%, even though the path where the condition is false (jumping straight to return price) was never taken! Branch coverage reports it as a partial branch (2->4 in the Missing column). Note that coverage.py measures branches between lines, not each sub-condition of and/or.

Enable branch coverage using the --cov-branch flag (or branch = true in config):

pytest --cov=src --cov-branch --cov-report=term-missing

5. Configuration via pyproject.toml or .coveragerc

Configure coverage rules in your project's pyproject.toml so team members and CI pipelines use consistent options automatically:

[tool.coverage.run]
branch = true
source = ["src"]
omit = [
    "tests/*",
    "src/migrations/*",
]

[tool.coverage.report]
# Fail if overall coverage drops below 85%
fail_under = 85
show_missing = true

# Regex patterns of lines to exclude from coverage metrics
exclude_lines = [
    # Standard exclusion pragma
    "pragma: no cover",

    # Ignore debug representations
    "def __repr__",

    # Ignore abstract methods
    "raise NotImplementedError",

    # Ignore typing-only blocks
    "if TYPE_CHECKING:",

    # Ignore main invocation blocks
    "if __name__ == .__main__.:",
]

Excluding Unreachable Lines with pragma: no cover

When defensive code or platform-specific fallbacks cannot be reached in standard tests, annotate them with # pragma: no cover to avoid artificially lowering metrics:

import sys

if sys.platform == "win32":  # pragma: no cover
    import msvcrt
else:
    import termios

6. Continuous Integration (CI) and Coverage Badges

In CI workflows (such as GitHub Actions), export coverage data in XML format for automated ingestion by services like Codecov or Coveralls:

pytest --cov=src --cov-report=xml:coverage.xml

GitHub Actions workflow snippet:

- name: Run Tests & Measure Coverage
  run: |
    pytest --cov=src --cov-report=xml --cov-fail-under=85

- name: Upload coverage to Codecov
  uses: codecov/codecov-action@v5
  with:
    files: ./coverage.xml
    token: ${{ secrets.CODECOV_TOKEN }}

Best Practices

  1. Don't Confuse 100% Coverage with Quality: High code coverage guarantees your tests ran the code; it does not guarantee they made meaningful assertions or tested edge cases (e.g. empty inputs, zero values, network timeouts).
  2. Always Enable Branch Coverage: Branch coverage exposes hidden untested boolean paths that statement coverage misses.
  3. Set Realistic Thresholds: Aim for 80%–90% coverage for core business logic, rather than chasing 100% on trivial boilerplate (getters, simple wrappers, configurations).

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents