Title: Testable Documentation
Slug: testable_documentation
Summary: Testable Documentation in Python.
Date: 2016-01-23 12:00
Category: Python
Tags: Testing
Authors: Chris Albon
Interesting in learning more? Here are some good books on unit testing in Python: Python Testing: Beginner's Guide and Python Testing Cookbook.
In [1]:
import doctest
In [16]:
def summation(a, b):
"""
Takes two inputs and outputs their sum.
Tests:
>>> summation(5, 4)
9
>>> summation(4, 3)
7
>>> summation('foo','bar')
'foobar'
>>> summation(3,'d')
Traceback (most recent call last):
...
TypeError: unsupported operand type(s) for +: 'int' and 'str'
"""
return a + b
Notice that in the last test, we are making sure the function outputs the correct error.
In [17]:
doctest.testmod(verbose=True)
Out[17]: