tags:

views:

20

answers:

1

I'd like to have several of the doctests in a file share test data and/or functions. Is there a way to do this without locating them in an external file or within the code of the file being tested?

update

"""This is the docstring for the module ``fish``.

I've discovered that I can access the module under test
  from within the doctest, and make changes to it, eg


>>> import fish
>>> fish.data = {1: 'red', 2: 'blue'}
"""

def jef():
    """
    Modifications made to the module will persist across subsequent tests:

    >>> import fish
    >>> fish.data[1]
    'red'
    """
    pass

def seuss():
    """
    Although the doctest documentation claims that
      "each time doctest finds a docstring to test,
       it uses a shallow copy of M‘s globals",
      modifications made to the module by a doctest
      are not imported into the context of subsequent docstrings:

    >>> data
    Traceback (most recent call last):
      ...
    NameError: name 'data' is not defined
    """
    pass

So I guess that doctest copies the module once, and then copies the copy for each docstring?

In any case, importing the module into each docstring seems usable, if awkward.

I'd prefer to use a separate namespace for this, to avoid accidentally trampling on actual module data that will or will not be imported into subsequent tests in an possibly undocumented manner.

It's occurred to me that it's (theoretically) possible to dynamically create a module in order to contain this namespace. However as yet I've not gotten any direction on how to do that from the question I asked about that a while back. Any information is quite welcome! (as a response to the appropriate question)

In any case I'd prefer to have the changes be propagated directly into the namespace of subsequent docstrings. So my original question still stands, with that as a qualifier.

+1  A: 

This is the sort of thing that causes people to turn away from doctests: as your tests grow in complexity, you need real programming tools to be able to engineer your tests just as you would engineer your product code.

I don't think there's a way to include shared data or functions in doctests other than defining them in your product code and then using them in the doctests.

You are going to need to use real code to define some of your test infrastructure. If you like doctests, you can use that infrastructure from your doctests.

Ned Batchelder