衡量Unit Test(单元测试)是否充分, 覆盖率是一个必要指标, 是检验单元测试的重要依据, 这里针对python unittest 的单元测试覆盖率coverage进行分享.html
来自官方的解释:python
Coverage.py runs on many versions of Python:正则表达式
CPython 2.6, 2.7 and 3.3 through alpha 3.8.数据库
PyPy2 6.0 and PyPy3 6.0.浏览器
Jython 2.7.1, though not for reporting.微信
IronPython 2.7.7, though not for reporting.app
注: Coverage支持丰富的python版本框架
Install Coverageide
pip install coverage工具
不管是Windows, Linux 仍是Mac os,安装都很是方便, 若是提示pip command not found, 请看这里或者自行百度.
测试代码:
咱们如今已经installed coverage, 须要使用它, 让咱们来建立一个Module 而后调用mymath.py, 代码以下:
这个module里咱们定义了4个方法, 分别是add, subtract, multiply, divide(+,-,*,/)
让咱们来测试这模块, 在call以前先要import咱们的module,下面是咱们的测试代码
Use coverage run to run your progame and gather data:
而后咱们就可使用Coverage 进行验证了
coverage run test_mymath.py
执行上面命令:
若是你的Module有参数,你可使用下面方法
coverage run test.py arg1 arg2
Use coverage report to report on the results:
For a nice presentation, use coverage html to get annotated HTML lisitings detailing missed lines:
coverage html
使用上述命令会在目录下生成htmlcov文件, 包含了详细的测试报告.
浏览器查看报告详情
从中不难发现, 在test_mymath.py中咱们只调用了mymath.py的add 方法, 另外3个方法没有调用,所以代码覆盖率没有达到100%, report中用红色标注提示咱们, 而 test_mymath.py 所有代码都被彻底Coverage, 覆盖率100%.
这么一个傻瓜式工具使用很是easy, 经过这个实例实战, 让咱们比较直观的了解单元测试代码覆盖率的重要性, 平时的工做中可能被各类业务和框架缠绕, 没有把中心放在这上面, 但它倒是很是重要的, 用事实和数听说话抵过千言万语.
注: Java也有相应的Coverage工具 jacoco, EMMA等.
参考文献: https://pypi.org/project/coverage/
今日精选推荐
咨询工做加微信
扫描二维码
欢迎自荐和推荐, 须要的微信推送简历!
请猛戳下面二维码了解更多