Few doctest notes

bearophile bearophileHUGS at lycos.com
Mon Nov 22 20:04:09 EST 2004


doctest module is quite useful; and I've also tried the simpler docex:
http://aima.cs.berkeley.edu/python/docex.html
http://aima.cs.berkeley.edu/python/docex.py
(docex isn't perfect, there are problems with functions without a
return, and with functions with prints inside, but it can be useful,
easy to use, and it produces very short docs.)


Looking at docex I think doctest usage can be simplified a little, and
the doctest output can be shortened, because this can become a bit
long:
Running example.__doc__
0 of 0 examples failed in example.__doc__
Running example._test.__doc__
0 of 0 examples failed in example._test.__doc__
Running example. ...


>From doctest Library Reference:
>For example, when printing a dict, Python doesn't guarantee that the
key-value pairs will be printed in any particular order, so a test
like<
docex solves similar problems not using a string comparison, but
executing the output too, and then with a comparison of the resulting
objects (but in some special cases the output cannot be executed, like
where there is a Traceback, or ... or ==>)


I think "..." can also be used at the end of very long output lines,
this time a string comparison is used because such objects cannot be
executed.


docex uses a ==> syntax, like:
Ex: sqrt(4) ==> 2
This can be useful in doctest too for simple functions, to make
shorter docs, but it can also be triky to implement correctly.


>From doctest Library Reference:
>Expected output cannot contain an all-whitespace line, since such a
line is taken to signal the end of expected output.<
Then maybe to distinguish such cases it can added a "tag" at the start
of every output line, like "< " or "<<< ". (but such symbols probably
have to be added by hand...). Example:

This is a useless comment:
>>> foo(2)
<<< 2
<<< 2
This is a second useless comment:
>>> foo(3)
<<< 3
<<< 3
<<< 3
foo(0) prints a number with thousands of digits:
>>> foo(0)
<<< 555126219729759572912...
An error:
>>> foo(-1)
<<< AssertionError: foo(n): n cannot be negative.

Hugs,
Bearophile



More information about the Python-list mailing list