Python: using doctests for classes

Instead of instantiating the object in every method, you can use the extraglobs argument:

class Test:
    def multiply_by_2(self):
        """
        >>> t.multiply_by_2()
        10
        """
        return self._number*2

if __name__ == '__main__':
    import doctest
    doctest.testmod(extraglobs={'t': Test()})

You're missing the code to actually run the doctests at the bottom of the file:

class Test:
    <snip>

if __name__ == "__main__":
    import doctest
    doctest.testmod()

As for where to put the tests:

  • If it's testing the class as a whole, I'd put them in the class' docstring.
  • If it's testing the constructor, I'd put them in the constructor's docstring.
  • If it's testing a method (as it seems to be in this case), I'd actually put it them in that method's docstring.

The doctest module looks for any docstrings in a file and executes any embedded code in it, so yes it is possible to use doctest for classes.

As for whether it is better to put the doctests in the class's docstring or the constructor, I think that depends on what exactly you are documenting.

If the docstring gives a general overview of the class and how to use it then I think it is better to put it in the class.

If the docstring is specifically about how to create instances of the class then it should go in the __init__ method.

Remember the intent of doctests is primarily to have self-validating example code in documentation, so IMHO the documentation aspect should take priority over the testing aspect.

Edit:

In your example above there is no code to execute the doctest - running python test.py -v will execute the main python code which just defines the class.

You need to add this to the end of the file:

if __name__ == "__main__":
    import doctest
    doctest.testmod()

Alternatively If you are using Python 2.6 or later run it with:

python -m doctest -v test.py