如何在Python中获得100%的代码覆盖率?

时间:2014-07-01 19:32:32

标签: python tdd code-coverage coverage.py python-coverage

learning.py

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

def addition(a, b):
    return a + b

test_learning.py

import unittest

from learning import *

class Test(unittest.TestCase):
    def test_multiply(self):
        self.assertEqual( multiply(3,4), 12)

    def test_addition(self):
        self.assertEqual( addition(5,10), 15)       

if __name__ == '__main__':
    unittest.main()

50%的代码覆盖率

虽然两种方法都经过测试,但代码覆盖率为50%

C:\>coverage run learning.py test_learning.py

C:\>coverage report

Name       Stmts   Miss  Cover
------------------------------
learning       4      2    50%

1 个答案:

答案 0 :(得分:4)

您想要的coverage命令是:

coverage run test_learning.py

您正在做的是使用参数learning.py运行test_learning.py,该参数仅执行2 def个语句并且从不运行测试(或执行2个已定义函数的内容)。