Doc tests in Python

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Thu Jun 19 08:56:01 CEST 2008


En Thu, 19 Jun 2008 02:46:15 -0300, J-Burns <arslanburney at gmail.com>  
escribió:

> Hello. Im new to using doctests in python. Could some1 tel me how to
> use doctests if i have a constructor in my code?

Just construct the desired objects inside the doctest. See the difflib  
module for a couple examples.
If it's hard/undesirable/annoying to construct the objects for every test,  
you may use the "globs" or "extraglobs" argument to doctest.testmod.  
Something like this:

class SomeClass:
     def __init__(self, a, lot, of arguments, are, required):
         ...

     def some_method(self, arg):
         """Does this and that...

         In the test below, obj refers to the
         already created instance (below, in _test)

         >>> obj.some_method(self, 123)
         True
         >>> obj.some_method(self, "hi")
         False
         """
         ...

def _test():
     import doctest
     obj = SomeClass(create, the instance, using, a, lot, of, arguments)
     doctest.testmod(extraglobs={'obj': obj})

if __name__=='__main__':
     _test()

But I prefer to keep the doctests self-contained whenever possible.

-- 
Gabriel Genellina




More information about the Python-list mailing list