python coverage--单元测试覆盖图

上一篇 / 下一篇  2018-04-10 10:28:27 / 个人分类:其它

python coverage--单元测试覆盖图
https://www.jianshu.com/p/ed7ba052ccab

介绍

coverage 在单元测试中可以显示覆盖率,显示更清晰的数据

  • 支持python 2.6-python3.X
  • pip install coverage安装

测试代码

defadd(a, b):returna + bdefsubtract(a, b):returna - bdefmultiply(a, b):returna * bdefdivide(numerator, denominator):returnfloat(numerator) / denominator
  • unittest测试
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()
  • 命名运行
coverageruntest_mymath.pycoveragereport-m

作者:望月成三人
链接:https://www.jianshu.com/p/ed7ba052ccab
來源:简书



Coverage简介

Coverage是一种用于统计Python代码覆盖率的工具,通过它我们可以检测测试代码的有效性,即测试case对被测代码的覆盖率如何。
Coverage支持分支覆盖率统计,可以生成HTML/XML报告。XML报告可以集成入Jenkins和Sonar。
官方文档:http://coverage.readthedocs.org/en/latest/

Coverage安装(Ubuntu)

sudo pipinstallcoverage

目前最新的版本是4.0。

Coverage使用

Coverage支持2种运行方式,一种是命令行方式,另一种是在代码中调用Coverage的API,可以灵活地控制哪些代码需要测试。
关于这2种方式,可以看以下文档:
命令行方式:http://coverage.readthedocs.org/en/latest/cmd.html
API方式:http://coverage.readthedocs.org/en/latest/api.html

分析Web项目的代码覆盖率

关于以Python启动的web项目的代码覆盖率统计,请见:

关于WSGI项目的覆盖率统计,这方面的文档较少,需要一定地摸索,请见:


TAG:

 

评分:0

我来说两句

Open Toolbar