[TIP] Best way to do setup/teardown on a per-test basis using doctest?

Brett Cannon brett at python.org
Sun Jul 1 20:08:03 PDT 2007

On 7/1/07, Titus Brown <titus at caltech.edu> wrote:
> -> But I am willing to give a doctest a shot.  To learn it I have a need
> -> to write some regression tests for __import__.  But because it is
> -> testing something that has a lot of file I/O I have a need to
> -> temporarily create some files, run the tests, and then delete the
> -> created files.
> ->
> -> I read about the Unittest API, but I would like to be able to specify
> -> what files to create on a per-test basis.  Normally I would use a
> -> try/finally or develop a context manager, but that would suppress the
> -> output from expression evaluation and thus kill the testing (if I
> -> understand how doctest works).
> ->
> -> So what is the best way to approach this?
> I didn't spot any replies to the actual question ;).

There weren't any.  =)

> Short answer: I don't know.  The setup/teardown part of doctests
> is, IMO, quite annoying.  There was some mention a few months back on
> this list of using reST-style footnotes to specify setup and teardown
> code (related to Zope, I believe).  That would be a good solution to
> try.
> Right now I would approach your problem by developing a utils module
> that contains functions to do the setup/teardown, and then I'd call
> them explicitly in the doctests.

But how do I guarantee that the teardown is called?  If do something like::

"""Here are some tests
  >>> with setup():
  ...   test1
  ...   test2


That won't test anything from my understanding of doctest as that
would be executed as a single statement and not a bunch of indivudal
expressions to verify the output.

This just might be a situation where unittest is just a better fit.


More information about the testing-in-python mailing list