Working of doctest Module
Let's find out how doctest module works.
The doctest
module works by examining the docstrings in the module, from
the module level to the function, class and method levels. It will not
look at imported modules though.
For most of the part, we can use just copy-and-paste an interactive console session, and doctest
module will work fine with it.
doctest
will look for output following the final >>> or …
line that contains code. Said output will only extend to the next
>>> or all-whitespace line.
Here are a few gotcha’s to watch out for.
- If we continue a line using a backslash, then we want to use a raw docstring (i.e. r""“This is raw”"") to preserve the backslash. Otherwise it will be considered a part of the string and will probably raise an error.
- Tracebacks usually contain exact file path and line numbers which change when we’re developing and the paths will certainly change across machines. So this will cause issues too.
Fortunately,
doctest
is pretty flexible with tracebacks. We only need the Traceback line and the actual Exception line to make the test pass. Just change the example from before to this:
Get hands-on with 1200+ tech skills courses.