介绍
coverage 在单元测试中可以显示覆盖率,显示更清晰的数据
- 支持python 2.6-python3.X
- pip install coverage安装
测试代码
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测试
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()
- 命名运行
coverage run test_mymath.py
coverage report -m
- 结果
更多高级用法:http://www.blog.pythonlibrary.org/2016/07/20/an-intro-to-coverage-py/