作者:kmv2145234 | 来源:互联网 | 2023-09-17 04:42
代码覆盖率是什么?为什么要统计代码覆盖率?
- 代码覆盖率指的是在统计时间段内哪些代码被执行过或者被调用过,它会统计从代码开始执行到结束执行一共执行了多少代码比例。
- 为什么要统计?比如我们有一个测试需求,按业务等设计了测试case,但是我们并不清楚自己的测试case到底有没有覆盖所有业务场景,这个时候coverage就可以派上用场
coverage 统计python代码覆盖率
pip install coverage -i http://pypi.douban.com/simple/ --trusted-host pypi.douban.com
测试代码
这里我们先写一个简单的场景,然后去执行,主要是查看coverage具体是怎么使用的。这里我们从菜鸟上面找到一篇判断字符串是否是数字的代码。
def is_number(s):try:float(s)return Trueexcept ValueError:passtry:import unicodedataunicodedata.numeric(s)return Trueexcept (TypeError, ValueError):passreturn Falseprint(is_number(10))返回结果:
C:/Users/hzxy/PycharmProjects/work/test.py
TrueProcess finished with exit code 0
开始覆盖率统计执行
执行如下命令:
coverage run test.py
coverage report -m
生成 reportcoveragehtml报告
coverage html
coverage html -d reportcoveragehtml
命令执行之后,他会生成一个 reportcoveragehtml 的文件夹,然后我们在文件夹中找到以我们运行文件开头生成的html文件,然后再浏览器中打开
打开之后,报告生成是这个样子的~
统计结果文件,红色底色的行表示没有执行。