Python 测试覆盖率
coverage 工具测量代码被测试覆盖的程度,识别测试盲点。
安装与基本使用
Bash
pip install coverage
# 运行测试并收集覆盖率
coverage run -m unittest discover
# 生成报告
coverage report
# 生成 HTML 报告
coverage html
命令行使用
Bash
# 运行测试
coverage run test_module.py
# 或使用 pytest
coverage run -m pytest
# 查看覆盖率报告
coverage report -m
# 输出示例
Name Stmts Miss Cover Missing
-------------------------------------------------------
myapp/__init__.py 5 0 100%
myapp/core.py 20 5 75% 15-20
myapp/utils.py 10 2 80% 8, 12
-------------------------------------------------------
TOTAL 35 7 80%
配置文件
toml
# pyproject.toml 或 .coveragerc
[tool.coverage.run]
source = ["myapp"]
omit = ["tests/*", "*/__init__.py"]
[tool.coverage.report]
exclude_lines = [
"pragma: no cover",
"if __debug__:",
"raise NotImplementedError",
]
fail_under = 80 # 覆盖率低于80%失败
HTML 报告
Bash
coverage html
# 打开 htmlcov/index.html 查看
# 绿色:已覆盖
# 红色:未覆盖
# 黄色:部分覆盖(分支)
pytest 集成
Bash
pip install pytest-cov
# 运行 pytest 并显示覆盖率
pytest --cov=myapp tests/
# HTML 报告
pytest --cov=myapp --cov-report=html tests/
# 只显示未覆盖代码
pytest --cov=myapp --cov-report=term-missing tests/
API 使用
Python
import coverage
# 启动覆盖率收集
cov = coverage.Coverage()
cov.start()
# 运行代码
import myapp
myapp.main()
# 停止收集
cov.stop()
cov.save()
# 生成报告
cov.report()
cov.html_report(directory='htmlcov')
排除代码
Python
# 使用 pragma 排除特定行
def debug_only():
if __debug__: # pragma: no cover
print("调试信息")
# 排除整个函数
def placeholder(): # pragma: no cover
pass
分支覆盖率
Bash
# 启用分支覆盖
coverage run --branch test_module.py
# 或配置
[tool.coverage.run]
branch = true
Python
# 分支覆盖示例
def check(value):
if value > 0: # 需测试 value > 0 和 value <= 0
return True
return False
覆盖率报告解读
| 字段 | 说明 |
|---|---|
| Stmts | 语句总数 |
| Miss | 未执行语句数 |
| Cover | 覆盖百分比 |
| Missing | 未覆盖行号 |
设置覆盖率目标
toml
[tool.coverage.report]
fail_under = 90 # 要求90%覆盖率
# 命令行
coverage report --fail-under=90
CI/CD 集成
YAML
# GitHub Actions 示例
- name: Run tests with coverage
run: pytest --cov=myapp --cov-report=xml
- name: Upload coverage
uses: codecov/codecov-action@v3
with:
file: coverage.xml
覆盖率最佳实践
| 实践 | 建议 |
|---|---|
| 目标覆盖率 | 80-90% 合理目标 |
| 排除代码 | 测试无关代码可排除 |
| 分支覆盖 | 启用分支覆盖率更全面 |
| 持续监控 | CI/CD 集成覆盖率检查 |
| 定期审查 | 检查未覆盖代码是否需补充测试 |
要点总结
coverage run收集覆盖率数据coverage report显示覆盖率报告coverage html生成可视化 HTML 报告- pytest-cov 插件与 pytest 无缝集成
--branch启用分支覆盖率pragma: no cover排除特定代码fail_under设置最低覆盖率要求- 覆盖率帮助识别测试盲点,指导测试完善
📝 发现内容有误?点击此处直接编辑