pythontddcode-coveragecoverage.pypython-coverage

How to get 100% code coverage in Python?


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% code coverage

Although both methods have been tested, the code coverage is 50%

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

C:\>coverage report

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

Solution

  • The coverage command you want is:

    coverage run test_learning.py
    

    What you're doing is running learning.py with the argument test_learning.py, which only executes the 2 def statements and never runs the tests (or executes the contents of the 2 defined functions).