Archive for the ‘doctest’ tag
Doctests in Python
This post is due for a long time since my post on Singular form of a word program and here it is - Doctests in Python. From the python library reference,
The doctest module searches for pieces of text that look like interactive Python sessions, and then executes those sessions to verify that they work exactly as shown.
Doctests are an easy way to test small functions by specifying the output of the function in docstrings. In python you can (should) write docstrings for classes and methods which can be used to generate the documentation for the module. In those docstrings, you just specify calls to the function with the return string specified. The doctest module automatically asserts the output and verifies whether the test passes or fails.
Lets see an example of doctest and how to run them. Lets create a function which adds two numbers.
def add(x, y):
"""Adds two numbers/strings together
>>> add(1,2)
3
>>> add('foo','bar')
'foobar'
"""
return x+y
Here we have written the docstrings and have four lines which look like the python shell. There we call the function with various arguments and also specify how the function will return.
So, how do we run the test? Just include these lines in the module and run the file directly. This is the usual way we run doctest (in the __main__ part of the file).
def _test():
import doctest
doctest.testmod()
if __name__ == "__main__":
_test()
You just have to call the doctest.testmod() function and it will search for all such tests in the docstrings and outputs nothing if the tests pass. If you want to get more verbose output, run the file as python filename.py -v
There are many advantages of doctests (wikipedia has a lot more):
- Easy to understand what a function is going to do if called
- Tests and code together - easy to update the test if code changes
- Most of the times I execute my functions on the shell - so I just have to copy-paste the output from the shell to the code
Once you start using doctests, you would find yourself trying to use it in all possible places. For more elaborate testing, you should probably use pyunit.
Is there any other programming language which has tests written directly in the documentations? If you were to design such a testing module for you favourite language, how would you do it (especially if it doesn’t have a interactive shell)? Do explain your views on it below.

