Using doctest to define test cases
The doctest
module provides us with a simpler form of testing than the unittest
module. There are many cases where a simple interaction can be shown in the docstring and the test can be automated via doctest
. This will combine the documentation and test cases into one tidy package.
The doctest
cases are written into the docstring for a module, class, method, or function. A doctest
case shows us the interactive Python prompt >>>
, statements and responses. The doctest
module contains an application that looks for these examples in docstrings. It runs the given examples and compares the expected results shown in the docstrings with the actual outputs.
For larger and more complex class definitions, this can be challenging. In some cases, we may find that simple, printable results are difficult to work with, and we need more sophisticated comparisons to be made available from unittest
.
With careful design of an API, we can create a class that can be used...