Unit testing with the unittest module
The unittest
module allows us to step beyond the examples used by doctest
. Each test case can have one more scenario built as a subclass of the unittest.TestCase
class. These use result checks that are more sophisticated than the literal text matching used by the doctest
tool.
The unittest
module also allows us to package tests outside docstrings. This can be helpful for tests for edge cases that might be too detailed to be helpful documentation. Often, doctest
cases focus on the happy path—the most common use cases, where everything works as expected. We can use the unittest
module to define test cases that are both on as well as off the happy path.
This recipe will show how we can use the unittest
module to create more sophisticated tests. It will step beyond simple text comparison to use the more sophisticated assertion methods of the unittest.TestCase
class.
Getting ready
It's sometimes helpful to summarize...