unittest module
Date: January 14th 2016
Last updated: January 14th 2016
The unittest module is pythons built-in testing framework. There are also modules that extend the capability of unittest. Here I will only look at a simple scenario using the example from doctest module.
The initial difference between unittest and doctest is that the code goes in its own script. A good starting point is to create a test module that lives in the same directory as your script.
Project
├── test_vowels.py
└── vowels.py
The test module is shown below. Start by importing unittest and the module for testing (A). The test class inherits methods from unittest. The definition name of each function is prefixed with test. The methods that are executed start with either assert or fail.
# test_vowels.py
"""
This module tests the count_vowels method from the module from vowels.py
"""
import unittest
import vowels # A: Initial directory structure
#from vowels import vowels # B: modified directory structure
class VowelsTest(unittest.TestCase):
def testNormalCase(self):
self.assertEqual(vowels.count_vowels('this is a test'), 4)
if __name__ == '__main__':
unittest.main()
Then execute the script as usual from the command line (i.e. >> python test_module). For each test the output will produce a . (dot) for each method it checks, a summary line, and a final line saying "OK".
>>> python test_vowels.py
.
--------------------
Ran 1 test in 0.000s
OK
Caution, you get the OK message even if you haven't tested any methods!!!
Convention has it that the test script goes in a subdirectory called test which sits next to the module (e.g. vowels.py). The test script gets the same name as the module, prefixed with test_ (e.g. test/test_vowels.py).
Project
├── test
│ └── test_vowels.py
└── vowels.py
I found this to be tricky on my first attempt. If you run the module now it will fail because the test script won't find the source file siting in the parent directory. That is, python doesn't know it exists.
The easiest way (I think) is to add a few things into the file structure (see this forum discussion for other options). Create another subdirectory for the source file to sit in (e.g. vowels). In both folders include an empty __init__ file to make them modules. In the test script include from vowels import vowels (B), which will import the vowels module that is buried in the sister subdirectory.
Project
├── test
│ ├── __init__.py # make test_vowels.py a module
│ └── test_vowels.py
└── vowels
├── __init__.py # make vowels.py a module
└── vowels.py # used in doctest example
To run the test module, navigate to project and run the following line:
python -m unittest test.test_vowels
Done! Now populate test_vowels.py with a complete list of tests.