How can I improve code coverage of Python3

Viewed 1437

With unittest and Coverage.py,

def add_one(num: int):
    num = num + 1
    return num
from unittest import TestCase

from add_one import add_one


class TestAddOne(TestCase):

    def test_add_one(self):
        self.assertEqual(add_one(0), 1)
        self.assertNotEqual(add_one(0), 2)

and here is the coverage:

code coverage 33%

How can I test the whole file?

2 Answers

Assuming that your test file is called test_one.py run this command in the same directory:

coverage run  -m unittest test_one.py && coverage report

Result should look similar to this:

.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
Name          Stmts   Miss  Cover
---------------------------------
add_one.py        3      0   100%
test_one.py       6      0   100%
---------------------------------
TOTAL             9      0   100%

You never call the test_add_one method.

Note how the function definition is executed, but not the body. To run your test, add a __main__ check and a TestSuite/TextTestRunner (https://docs.python.org/3/library/unittest.html)

from unittest import TestCase, TestSuite, TextTestRunner
from add_one import add_one


class TestAddOne(TestCase):

    def test_add_one(self):
        self.assertEqual(add_one(0), 1)
        self.assertNotEqual(add_one(0), 2)

if __name__ == "__main__":
    suite = TestSuite()
    suite.addTest(TestAddOne("test_add_one"))

    TextTestRunner().run(suite)

The result of

coverage run <file.py>
coverage html
# OR
coverage report -m

is all lines tested.

Related