Creating separate test modules and packages
We can do any kind of unit testing in docstring examples. There are some things, however, which can become extremely tedious when done this way.
The unittest
module allows us to step beyond simple examples. These tests rely on test case class definitions. A subclass of TestCase
can be used to write very complex and sophisticated tests; these can be simpler than the same test done as doctest examples.
The unittest
module also allows us to package tests outside the docstrings. This can be helpful for particularly complex tests of corner cases that aren't as helpful when placed in the documentation. Ideally, doctest cases illustrate the happy path – the most common use cases. It's common to use unittest
for test cases which are off the happy path.
How can we create more sophisticated tests?
Getting ready
A test can often be summarized by a three-part Given-When-Then story:
- GIVEN: Some unit in an initial state or context
- WHEN: A behavior is requested
- THEN...