Knowpapa.com - a developer's blog

Unit Testing In Python with doctest

What is doctest ?
A doctest is an inbuilt standard function in Python that lets the programmer check the validity of part(s) of program by giving results for some common test variables.

In other words, doctest is in the in-built python module and tool for unit testing which lets the program verify, if a given piece of code is doing its work as intended.

Usage in Python: Doctests codes are written inside triple quotes on the first line of the body of a function or script. A doctest statement begins with >>> followed by the function to be tested and some sample parameter(s) for the function.

So a typical doctest command would look like:

"""
>>> my_function (some sample parameters)
the expected output for the given sample parameter
"""
# all your actual program goes here

# followed by these lines of code which make the doctest execute
if __name__ == '__main__':
import doctest
doctest.testmod(verbose=True)

When you run the program and python comes across the line “”” followed by >>>, it knows it has to do the doctesting . The doctest module then creates a sample interpreter sessions and automatically runs to compare the following line with the output from the interpreter.

Let’s say, one of the functions in your program is intended to check¬†whether or not a number is divisible by 3.

def is_divisible_by_3(x):
"""
>>> is_divisible_by_3(7)
False
"""
return True

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

Because our sample parameter 7 is not divisible by 3, running this program gives me a failed test error like:

File “test.py”, line 4, in __main__.is_divisible_by_3
Failed example:
is_divisible_by_3(7)
Expected:
True
Got nothing
**********************************************************************
1 items had failures:
1 of 1 in __main__.is_divisible_by_3
***Test Failed*** 1 failures.

If I change the function parameter in the doctest to say 9 (any number divisible by 3) – the test will pass and i will get no error message.