覆盖率参考
安装与基础用法
pip install pytest-cov
# 运行测试并生成覆盖率
pytest --cov=myapp tests/
# 指定源包和输出格式
pytest --cov=src --cov-report=term-missing tests/
# 开启分支覆盖
pytest --cov=myapp --cov-branch tests/
# 覆盖率低于阈值时失败
pytest --cov=myapp --cov-fail-under=85 tests/
coverage.ini / .coveragerc / pyproject.toml
# .coveragerc
[run]
source = myapp
branch = True
omit =
*/migrations/*
*/tests/*
*/conftest.py
[report]
show_missing = True
fail_under = 85
[html]
directory = htmlcov
title = 我的应用覆盖率
---
# pyproject.toml(现代写法)
[tool.coverage.run]
source = ["myapp"]
branch = true
omit = ["*/migrations/*", "*/tests/*"]
[tool.coverage.report]
fail_under = 85
show_missing = true
分支覆盖
# 启用分支覆盖 — 测量 if/else 路径覆盖
pytest --cov=myapp --cov-branch tests/
# 输出示例:
# Name Stmts Miss Branch BrPart Cover
# ---------------------------------------------------------
# myapp/utils.py 20 2 8 3 82%
# 排除特定分支
def _internal(x):
if x is None: # pragma: no branch
raise ValueError("x 不能为 None")
覆盖率报告
# 终端报告(显示缺失行号)
pytest --cov=myapp --cov-report=term-missing tests/
# HTML 报告(可在浏览器中查看)
pytest --cov=myapp --cov-report=html tests/
# 输出:htmlcov/index.html
# XML 报告(用于 CI/SonarQube)
pytest --cov=myapp --cov-report=xml tests/
# 同时生成多种报告
pytest --cov=myapp \
--cov-report=term-missing \
--cov-report=html:htmlcov \
--cov-report=xml:coverage.xml \
tests/
排除模式与 pragma: no cover
# .coveragerc 排除模式
[run]
omit =
*/site-packages/*
*/migrations/versions/*
*/tests/*
myapp/dev_tools.py
# 代码中排除特定行或块
def unreachable(): # pragma: no cover
pass
[report]
exclude_lines =
pragma: no cover
def __repr__
if TYPE_CHECKING:
raise NotImplementedError
CI 集成
| CI 系统 | 集成方式 |
|---|---|
| GitHub Actions | codecov/codecov-action@v4 上传 coverage.xml |
| GitLab CI | 设置 coverage: '/TOTAL.*\s+(\d+%)$/' 正则 |
| Codecov | 测试后执行 codecov --token=TOKEN |
| SonarQube | 配置 sonar.python.coverage.reportPaths=coverage.xml |