doctest annoyance/puzzle
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Sun Sep 5 11:30:29 EDT 2010
I'm writing a "literate programming" document, example.txt, which mixes
text and code in ReST format:
This is my excellent module for making spam. It has
one public function, ``make_spam``, which takes a
single argument for how much spam to make:
>>> from module import make_spam
>>> make_spam(3)
'spam spam spam'
If you ask for too little spam, you get a bonus:
>>> make_spam(-3)
'spam spam spam GLORIOUS SPAM!!!'
I run the doctests with:
python2.6 -m doctest examples.txt
and the first example passes, but the second fails with NameError:
make_spam not defined.
I have a work-around, I do an import at the start of *every* doctest
block, but that's ugly. More complex (realistic) examples sometimes need
setup code, which I'd like to survive from one block to the next:
>>> it = iter(make_spam(5).split())
>>> next(it)
'spam'
text goes here
>>> next(it)
'spam'
but of course that also fails. This surprises me, because doctests in
functions or classes can mix descriptive text between tests without this
problem.
Am I doing something wrong, or is doctest fundamentally broken when
executing tests in a text file?
--
Steven
More information about the Python-list
mailing list