Skip to content

代码覆盖率

安装依赖

shell
pip install coverage

运行测试并生成覆盖率报告

python run_tests.py
case3_test % python run_tests.py
.....
----------------------------------------------------------------------
Ran 5 tests in 0.000s

OK

Coverage Summary:
Name            Stmts   Miss  Cover
-----------------------------------
calculator.py      17      0   100%
run_tests.py       14     14     0%
-----------------------------------
TOTAL              31     14    55%

查看报告

在 htmlcov 目录下会生成详细的 HTML 报告

image-20250118161023702

使用coverage

shell
coverage run -m unittest discover
coverage report
coverage html
case3_test % coverage run -m unittest discover
.....
----------------------------------------------------------------------
Ran 5 tests in 0.000s

OK

case3_test % coverage report
Name            Stmts   Miss  Cover
-----------------------------------
calculator.py      17      0   100%
run_tests.py       14     14     0%
-----------------------------------
TOTAL              31     14    55%


case3_test % coverage html
Wrote HTML report to htmlcov/index.html

查看案例

https://gitee.com/PatrickW/flask-web/blob/master/src/case3_test

目录结构

shell
case3_test % tree -l 2 .
2  [error opening dir]
.
├── __pycache__
│   ├── calculator.cpython-38.pyc
│   └── test_calculator.cpython-38.pyc
├── calculator.py
├── htmlcov
│   ├── calculator_py.html
│   ├── class_index.html
│   ├── coverage_html_cb_6fb7b396.js
│   ├── favicon_32_cb_58284776.png
│   ├── function_index.html
│   ├── index.html
│   ├── keybd_closed_cb_ce680311.png
│   ├── run_tests_py.html
│   ├── status.json
│   └── style_cb_8e611ae1.css
├── run_tests.py
└── test_calculator.py

2 directories, 15 files