Python Unit Testing


If you build a car, you will build a lot of sub components such as the engine, the wheels, the brakes and so on. All these components have requirements.

Without testing, we wouldn’t know if a car would drive after putting the components together.

modular system
Without Testing, can you guarantee it will drive?

Software is similar, it consists of different components. We can test all of the components before putting the whole software package together.

Software quality is no better than the quality of the least tested component.

Unit Testing – unittest module

The module unittest is a complete unit testing framework.
Lets define a simple function:

def valuePlusOne(x):
    return x+1

Then we can test it using the assertEquals method:

import unittest
 
def valuePlusOne(x):
    return x+1
 
class Tests(unittest.TestCase):
 
    def test(self):
        self.assertEqual( valuePlusOne(2), 3)
 
    def test_neg(self):
        self.assertEqual( valuePlusOne(-1),0)
 
if __name__ == '__main__':
    unittest.main()

Running the program will show:

----------------------------------------------------------------------
Ran 2 tests in 0.000s
 
OK

Unit Testing – py.test

An alternative to the unittest module is pytest.
Install using:

pip install pytest

Create a simple program like:

def valuePlusOne(x):
    return x+1
 
def test_value():
    assert( valuePlusOne(2) == 3)
python-unit-test
Unit Test with Python

Lets make a test fail, change the code to:

def valuePlusOne(x):
    return x+2
 
def test_value():
    assert( valuePlusOne(2) == 3)
unit-testing-python
Unit Testing Python

Testing modules

There are several other unit testing modules: Nose, Tox, unittest2 and unittest.mock.