zoukankan      html  css  js  c++  java
  • Python代码覆盖率工具coverage使用教程

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

  • 相关阅读:
    Jenkins 主备master-slave模式搭建
    vbox 相关
    jenkins 常见问题汇总
    linux git patch 和patch以及git diff 命令
    Linux中的free命令
    MySQL Show命令的使用
    MySQL 加锁处理分析 转
    共享锁【S锁】 排他锁【X锁】
    MySQL分库分表环境下全局ID生成方案 转
    mysql性能的检查和调优方法
  • 原文地址:https://www.cnblogs.com/songzhenhua/p/13194232.html
Copyright © 2011-2022 走看看