Simple testing in Python

Author: Kushal Das
Date: 2012-08-01

What we should test ?

If possible everything in our codebase.

Unit testing

A method by which individual units of source code.

For now you can think like each function.

unittest module

In python we have unittest module to help us.

Factorial code

You can see the code here

$ python 5

Which function to test ?

As you can see fact(n) is function which is doing all calculations, so we should test that at least.

Our first testcase contains our first test.

Run the test:

$ python
Ran 1 test in 0.000s



We are importing unittest module first and then the required functions which we want to test.

A testcase is created by subclassing unittest.TestCase.

Now open the test file and change 120 to 121 and see what happens :)

Different assert statements

Method Checks that New in
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 2.7
assertIsNot(a, b) a is not b 2.7

Different assert statements

Method Checks that New in
assertIsNone(x) x is None 2.7
assertIsNotNone(x) x is not None 2.7
assertIn(a, b) a in b 2.7
assertNotIn(a, b) a not in b 2.7
assertIsInstance(a, b) isinstance(a, b) 2.7
assertNotIsInstance(a, b) not isinstance(a, b) 2.7

Testing exceptions

If we call div(0) in , we can see if raises an exception.

We can also test these exceptions, like:

self.assertRaises(ZeroDivisionError, div, 0)

Full code

Here we have only one function mount_details() doing the parsing and printing mount details.

Before refactoring

After refactoring

Now we refactored the code and have one new function parse_mount which we can test easily.

After refactoring and the test code

$ python
Ran 2 tests in 0.001s


Test coverage

Test coverage is a simple way to find untested parts of a codebase. It does not tell you how good your tests are.

In Python we already have a nice coverage tool to help us. You can install it in Fedora

# yum install python-coverage

Coverage Example

$ coverage -x
<OUTPUT snipped>

$ coverage -rm
Name        Stmts   Miss  Cover   Missing
mounttab2      21      7    67%   16, 24-29, 33
mounttest      14      0   100%
TOTAL          35      7    80%