In this post we’ll see the basic commands to apply unit testing and analyze coverage in Python. We will consider an example python class (Stack). Let’s assume the implementation is in a file named “stack.py”

The first test would be to create and empty Stack and check that is empty

test_stack_unittest.py”

import unittest
from stack import *

class TestStack(unittest.TestCase):

  def setUp(self):
    pass

  def testInit(self):
    s = Stack()
    self.assertTrue(s.is_empty())

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

We can now run it:

python3 test_stack_unittest.py

The output should look as follows:


.

----------------------------------------------------------------------

Ran 1 test in 0.000s

OK

The first dot represents the test passing (when it fails it shows “E” for errors)

Then the time taken and the summary (OK) appears.

Given this initial test we can check for coverage:

coverage run test_stack_unittest.py
coverage report -m

The output looks similar to this:


Name                     Stmts   Miss  Cover   Missing

------------------------------------------------------

stack.py                    20     11    45%   13-18, 21-23, 26-30

test_stack_unittest.py      10      0   100%

------------------------------------------------------

TOTAL                       30     11    63%

In the next post, we will combine these ideas to obtain 100% (statement) coverage of stack.py

Advertisements