码迷,mamicode.com
首页 > 编程语言 > 详细

Python代码覆盖率工具coverage使用教程

时间:2020-06-26 12:55:14      阅读:109      评论:0      收藏:0      [点我收藏+]

标签:library   基于   命令   src   cmd   addition   公众   line   install   

Python代码覆盖率工具coverage.py其实是一个第三方的包,同时支持Python2和Python3版本。
安装也非常简单,直接运行:

pip install coverage

 

首先我们编写一个简易计算器的程序:

# mymath.py
def add(a, b):
    return a + b

def subtract(a, b):
    return a - b

def multiply(a, b):
    return a * b

def divide(numerator, denominator):
    return float(numerator) / denominator

 

接着来编写基于unittest的单元测试用例:

# test_mymath.py
import mymath
import unittest

class TestAdd(unittest.TestCase):
    """
    Test the add function from the mymath library
    """
    def test_add_integers(self):
        """
        Test that the addition of two integers returns the correct total
        """
        result = mymath.add(1, 2)
        self.assertEqual(result, 3)

    def test_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)

    def test_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测试教程~

技术图片

Python代码覆盖率工具coverage使用教程

标签:library   基于   命令   src   cmd   addition   公众   line   install   

原文地址:https://www.cnblogs.com/songzhenhua/p/13194232.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!