本文目录导读:

在Python中测试覆盖率报告最常用的工具是 pytest-cov(基于 coverage.py),以下是几种生成覆盖率报告的方法:
安装工具
pip install pytest pytest-cov
命令行生成报告
终端显示报告
# 运行所有测试并显示覆盖率 pytest --cov=your_package tests/ # 显示更详细的报告(按文件) pytest --cov=your_package tests/ --cov-report=term-missing
生成HTML报告
pytest --cov=your_package tests/ --cov-report=html # 会在当前目录生成 htmlcov 文件夹 # 打开 index.html 查看详细的覆盖率报告
生成XML报告(适用于CI/CD)
pytest --cov=your_package tests/ --cov-report=xml # 生成 coverage.xml 文件
同时生成多种格式
pytest --cov=your_package tests/ \
--cov-report=term-missing \
--cov-report=html \
--cov-report=xml
配置文件方式
在项目根目录创建 .coveragerc 或 setup.cfg 文件:
.coveragerc
[run]
source = your_package
omit =
*/tests/*
*/__init__.py
*/setup.py
[report]
exclude_lines =
pragma: no cover
def __repr__
if __name__ == .__main__.:
pyproject.toml
[tool.coverage.run]
source = ["your_package"]
omit = ["*/tests/*", "*/__init__.py"]
[tool.coverage.report]
exclude_lines = [
"pragma: no cover",
"def __repr__",
"if __name__ == .__main__.:",
]
完整示例
项目结构
my_project/
├── my_package/
│ ├── __init__.py
│ ├── calculator.py
│ └── utils.py
├── tests/
│ ├── __init__.py
│ ├── test_calculator.py
│ └── test_utils.py
└── pyproject.toml
运行并生成报告
# 运行测试并生成HTML报告 pytest tests/ --cov=my_package --cov-report=html # 或者指定报告输出目录 pytest tests/ --cov=my_package --cov-report=html:coverage_report
在CI/CD中使用(GitHub Actions示例)
name: Test Coverage
on: [push, pull_request]
jobs:
test:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v2
- uses: actions/setup-python@v2
with:
python-version: '3.10'
- run: pip install pytest pytest-cov
- run: pytest tests/ --cov=my_package --cov-report=xml
- uses: codecov/codecov-action@v3
with:
file: ./coverage.xml
fail_ci_if_error: true
忽略特定代码行
def some_function():
# 这行不会被计入覆盖率
if DEBUG: # pragma: no cover
print("Debug message")
code_that_should_be_tested()
if __name__ == "__main__": # pragma: no cover
main()
常用选项总结
| 选项 | 说明 |
|---|---|
--cov=PACKAGE |
指定要检测覆盖率的包 |
--cov-report=term |
终端显示简单报告 |
--cov-report=term-missing |
终端显示未覆盖的行 |
--cov-report=html |
生成HTML报告 |
--cov-report=xml |
生成XML报告 |
--cov-report=annotate |
生成带注释的源码 |
--cov-fail-under=80 |
覆盖率低于80%则测试失败 |
可视化报告示例
生成的HTML报告包含:
- 总体覆盖率百分比
- 各个文件的覆盖率详情
- 源码高亮显示已覆盖/未覆盖的行
- 按目录组织的树形结构
这样你就能清楚地知道哪些代码已经被测试覆盖,哪些还没有被覆盖到。
版权声明:足球直播
足球直播
足球直播
足球直播
足球直播
中超直播
中超直播
中超直播
中超直播
中超直播
英超直播
英超直播
英超直播
英超直播
英超直播
德甲直播
德甲直播
德甲直播
德甲直播
德甲直播
西甲直播
西甲直播
西甲直播
西甲直播
西甲直播
意甲直播
意甲直播
意甲直播
意甲直播
意甲直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
足球直播
足球直播
足球直播
足球直播
足球直播
中超直播
中超直播
中超直播
中超直播
中超直播
英超直播
英超直播
英超直播
英超直播
英超直播
德甲直播
德甲直播
德甲直播
德甲直播
德甲直播
西甲直播
西甲直播
西甲直播
西甲直播
西甲直播
意甲直播
意甲直播
意甲直播
意甲直播
意甲直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播
足球直播
足球直播
足球直播
足球直播
足球直播
中超直播
中超直播
中超直播
中超直播
中超直播
英超直播
英超直播
英超直播
英超直播
英超直播
德甲直播
德甲直播
德甲直播
德甲直播
德甲直播
西甲直播
西甲直播
西甲直播
西甲直播
西甲直播
意甲直播
意甲直播
意甲直播
意甲直播
意甲直播
NBA直播
NBA直播
NBA直播
NBA直播
NBA直播
篮球直播
篮球直播
篮球直播
篮球直播
篮球直播