Unit testing in Python

What is unit testing?

When doing unit testing, you break your codes into small units (mostly functions), and test if each unit works as expected. Generally the tests are written in the form of functions that will determine whether a returned value equals the value you were expecting when you wrote the function.

Unit testing framework in Python

Let’s say I write a simple math library called Math.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
"""A simple math library"""
class Math(object):
"""An example class for unit testing"""
def __init__(self):
pass
def multiply(self, multiplier, multiplicand):
"""Multipy two numbers
Args:
multiplier: int, float or long.
multiplicand: int, float or long
Returns:
The result of the multiplication.
"""
return multiplier * multiplicand
def isLessThan(self, n, m):
"""Compare two numbers.
Args:
n, m: int, floar or long
Returns:
True if n is less than m, otherwise false.
"""
return n < m

Then I write another file called test_math.py for unit testing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
"""An unit testing example for the simple math library"""
import unittest
from math import Math
class MathTest(unittest.TestCase):
def setUp(self):
self.math = Math()
def tearDown(self):
pass
def test_multiply_int(self):
self.assertEqual(self.math.multiply(3, 5), 15)
def test_multipy_float(self):
self.assertEqual(self.math.multiply(3.0, 5.0), 15.0)
def test_is_less_than(self):
self.assertTrue(self.math.isLessThan(4, 18))
if __name__ == '__main__':
unittest.main()

For creating test cases, we need to define our own class by subclassing unittest.TestCase.

The setUp() and tearDown() methods allow you to define instructions that will be executed before and after each test method. So in our MathTest class, before each test method, a self.math will be created and after the excution of the test method, the tearDown method will be called. If you donnot have a class to test, you may drop the setUp() and tearDown() methods and simply run test methods.

The test method must start with test_.

Now run the test file in terminal.

1
2
3
4
5
6
int3@int3:~/Changsong$ python test_math.py
...
----------------------------------------------------------------------
Ran 3 tests in 0.000s
OK

We can see that the three tests are ran and passed!

The TestCase class provides several assert methods to check for and report failures. The following table lists the most commonly used methods.

Method Checks that
assertEqual(a, b) a == b
assertNotEqual(a, b) a != b
assertTrue(x) bool(x) is True
assertFalse(x) bool(x) is False
assertIs(a, b) a is b
assertIsNot(a, b) a is not b
assertIsNone(x) x is None
assertIsNotNone(x) x is not None
assertIn(a, b) a in b
assertNotIn(a, b) a not in b
assertIsInstance(a, b) isinstance(a, b)
assertNotIsInstance(a, b) not isinstance(a, b)

When should you perform unit testing?

As often as possible.

Test every function you write in the development process.