一. 安装coverage
直接执行命令
$ sudo easy_install coverage
二. 一个计算器项目的单测以及覆盖率生成的方式
$ mkdir src
$ mkdir test
$ vim src/Calc.py
class Calc():
def sum(self, a, b):
c = a + b
return c
def minus(self, a, b):
c = a - b
return c
def multi(self, a, b):
c = a * b
return c
def div(self, a, b):
c = None
if 0 != b:
c = a / b
return c
def absolute(self, a, b):
c = 0
if a >= b:
c = a - b
else:
c = b - a
return c
$ vim test/TestCalc.py
import unittest
import sys
sys.path.append('./src')
import Calc
class TestCalc(unittest.TestCase):
def setUp(self):
self.calc = Calc.Calc()
def test_sum(self):
self.assertEqual(3, self.calc.sum(1, 2))
def test_multi(self):
self.assertEqual(6, self.calc.multi(2, 3))
def test_absolute(self):
self.assertEqual(8, self.calc.absolute(10, 2))
if __name__ == '__main__':
unittest.main()
生成覆盖率统计数据
$ coverage run --branch --source=src/ test/TestCalc.py #生成.coverage文件,可以使用命令$ coverage report在命令行上查看统计数据
$ coverage html -d covhtml #将.coverage转化为html统计信息
三. 效果展示