Writing unit tests with doctest
It is a widely adopted practice to provide concrete examples of classes and functions in docstrings. As shown in the preceding example, we can provide the following kind of example text in a docstring:
>>> p_1 = Point(22, 7) >>> p_2 = Point(20, 5) >>> round(p_1.dist(p_2),4) 2.8284
A concrete example has many benefits. The goal of Python code is to be beautiful and readable. If the code sample is obscure or confusing, this is a design problem that really should be resolved. Writing more words in comments to try to explain bad code is a symptom of a deeper problem. A concrete example should be as clear and expressive as the code itself.
An additional benefit of concrete examples is that they are test cases. The doctest
module can scan each docstring to locate these examples, build, and execute test cases. This will confirm that the output in the example matches the actual output.
One common approach to using doctest
is to include the...