Python 代码覆盖率统计工具 coverage.py

1、安装coverage

pip install coverage

安装完成后,会在Python环境下的Scripts下看到coverage.exe;

2、Coverage 命令行

coverage run 

运行一个.py的文件方式:python test.py

现在使用coverage执行.py的文件方式:coverage run test.py 

会自动生成一个覆盖率统计结果文件(data file):.coverage,这个文件在你的test.py的文件对应目录下。

coverage report

有了覆盖率统计结果文件,只需要再运行report参数,就可以在命令里看到统计的结果。

coverage html -d covhtml

生成html的测试报告。

输出结果意义

Stmts    总的有效代码行数(不包含空行和注释行)
Miss    未执行的代码行数(不包含空行和注释行)
Branch    总分支数
BrMiss    未执行的分支数
Cover    代码覆盖率
Missing    未执行的代码部分在源文件中行号

命令详解

coverage run --help   # 打印帮助信息
coverage run test_xxx.py                # 执行test_xxx.py文件,会自动生成一个覆盖率统计结果文件.coverage
coverage report -m(带有详细信息)                  # 查看coverage报告,读取.coverage文件并打印到屏幕上,可以在命令行里看到统计结果
coverage html -d report                # 生成显示整体的covergae html形式的报告 (在当前同路径下生成一个report文件夹,里面包含html形式的报告。通过查看report文件夹下的内容即可)

3、其他功能

除了使用命令行,还可以在python代码中直接调用coverage模块执行代码覆盖率的统计。使用方法也非常简单:

import coverage

cov = coverage.coverage()
cov.start()

# .. run your code ..

cov.stop()
cov.save()

文档:https://coverage.readthedocs.io/en/latest/cmd.html