Python代码覆盖率工具coverage.py其实是一个第三方的包,同时支持Python2和Python3版本。
安装也非常简单,直接运行:
pip install coverage
首先我们编写一个简易计算器的程序:
#mymath.py
defadd(a, b):return a +bdefsubtract(a, b):return a -bdefmultiply(a, b):return a *bdefdivide(numerator, denominator):return float(numerator) / denominator
接着来编写基于unittest的单元测试用例:
#test_mymath.py
importmymathimportunittestclassTestAdd(unittest.TestCase):"""Test the add function from the mymath library"""
deftest_add_integers(self):"""Test that the addition of two integers returns the correct total"""result= mymath.add(1, 2)
self.assertEqual(result,3)deftest_add_floats(self):"""Test that the addition of two floats returns the correct result"""result= mymath.add(10.5, 2)
self.assertEqual(result,12.5)deftest_add_strings(self):"""Test the addition of two strings returns the two string as one
concatenated string"""result= mymath.add('abc', 'def')
self.assertEqual(result,'abcdef')if __name__ == '__main__':
unittest.main()
下面打开CMD命令窗口并进入代码文件所在目录。
1.使用coverage命令运行测试用例
coverage run test_mymath.py
2.生成覆盖率报告
coverage report -m
-m参数表示显示有哪些行没有被覆盖。
可以看到计算器程序mymath.py的测试覆盖率是62%,其中13,17,21行未运行。
3.生成HTML报告
coverage html
运行后在代码文件所在目录生成了htmlcov文件夹,打开index.html查看报告
点击报告中的mymath.py,可以打开该文件的覆盖详情,会飘红展示哪些代码未被运行。
因为我们的单元测试代码只是测试了mymath.add(),所以其他函数里的代码未被覆盖,这时就需要我们补充测试用例了。
--------------------------------------------------------------------------------
关注微信公众号(测试工程师小站)即可在手机上查阅,并可接收更多测试分享,发送【测试资料】更可获取百G测试教程~