Doctest
The simplest, easiest and funniest way to "home-test" code
The name is short for "document testing" or "testable document".
Doctest are great for non-production usage, small projects, tasks and for documentation purposes
Ideally, doctest
informs human readers, and tells the computer what to expect at the same time
Mixing tests and documentation helps us:
Keeps the documentation up-to-date with reality
Make sure that the tests express the intended behavior
Reuse some of the efforts involved in the documentation and test creation
Syntax
Lines that start with a
>>>
prompt are sent to a Python interpreter.Lines that start with a
...
prompt are sent as continuations of the code from the previous line, allowing you to embed complex block statements into your doctests.Finally, any lines that don't start with
>>>
or...
, up to the next blank line or>>>
prompt, represent the output expected from the statement.
We can test anything that can be typed in interactive Python shell:
Doctests can be keeped in plain txt files
The doctest module ignores anything in the file that isn't part of a test
Doctests can be keeped in docstrings in:
modules
functions
classes
class methods
The simplest way to start using doctest:
Simplest testing ever!
test_example.py
Expecting exceptions
Exception tracebacks tend to contain many details that are not relevant to the test, but that can change unexpectedly.
The doctest module deals with this by ignoring the traceback entirely: it's only concerned with the first line:
which tells it that you expect an exception, and the part after the traceback, which tells it which exception you expect.
The doctest module only reports a failure if one of these parts does not match.
🪄 Code >>> and 📟 Output:
Expecting blank lines
The doctest handles this situation by matching a line that contains only the text <BLANKLINE>
in the expected output with a real blank line in the actual output.
🪄 Code >>> and 📟 Output:
Directives
A directive comment begins with # doctest:
after which comes a comma-separated list of options that either enable or disable various behaviors.
To enable a behavior, write a +(plus symbol) followed by the behavior name. To disable a behavior, white a – (minus symbol) followed by the behavior name.
+ELLIPSIS
- treat the text...
as a wildcard that will match any text+NORMALIZE_WHITESPACE
– ignore white space+SKIP
– skip the test+IGNORE_EXCEPTION_DETAIL
🪄 Code >>> and 📟 Output:
🪄 Code >>> and 📟 Output:
Trick
Last updated