全部学科
Python全栈
python
NodeJS全栈
nodejs
小程序首页
📅 2026-05-19 8 分钟 ✍️ juanwangdev

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 设置最低覆盖率要求
  • 覆盖率帮助识别测试盲点,指导测试完善

📝 发现内容有误?点击此处直接编辑

← 上一篇 Python 日志最佳实践
下一篇 → Python C扩展加速
想查看更多题目和详细解析?
小程序提供完整的题库、模拟考试和详细解析
马上就来

长按或扫描二维码,立即体验

扫码体验小程序
马上就来
使用微信扫描二维码
立即体验完整题库