I would like to use a doctest comment block to demonstrate the usage of a particular base class, but either this cannot be done with doctest or I am doing something wrong. Here is my simple demo code.
class MyClass(object):
'''
>>> m = MyClass()
>>> print m.x
1
>>> class A(MyClass):
>>> def __init__(self):
>>> super(A,self).__init__()
>>>
>>> a = A()
>>> print a.x
1
'''
def __init__(self):
self.x = 1
if __name__ == "__main__":
import doctest
doctest.testmod()
The code doesn't run. Here's the first error issued:
Failed example:
class A(MyClass):
Exception raised:
Traceback (most recent call last):
File "C:\Python27\lib\doctest.py", line 1254, in __run
compileflags, 1) in test.globs
File "<doctest __main__.MyClass[2]>", line 1
class A(MyClass):
^
SyntaxError: unexpected EOF while parsing
The Doctest Module finds patterns in the docstring that looks like interactive shell commands. The input and expected output are included in the docstring, then the doctest module uses this docstring for testing the processed output.
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.
The following is a mathematical example of a doctest for a function such as add (a, b) that adds two numbers together: In this example we have a line of explanation, and one example of the add () function with two integers for input values.
DocTestParser: Creates a DocTest object from a string (such as an object’s docstring). DocTestRunner: Executes the examples in a DocTest, and uses an OutputChecker to verify their output. OutputChecker: Compares the actual output from a doctest example with the expected output, and decides whether they match.
Try it out in the interpreter; it uses ...
to show continuation lines. >>>
is only for a new statement or expression, while a class
in incomplete until you've had an empty ...
continuation line:
>>> class A(MyClass):
... def __init__(self):
... super(A, self).__init__()
...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With