The doctest
module is one of the most useful modules within Python. It allows you to combine documenting your code with tests to make sure that it keeps working as it is supposed to.
Let's start with a quick example: a function that squares the input. The following example is a fully functional command-line application, containing not only code but also functioning tests. The first few tests cover how the function is supposed to behave when executing normally, followed by a few tests to demonstrate the expected errors:
def square(n): ''' Returns the input number, squared >>> square(0) 0 >>> square(1) 1 >>> square(2) 4 >>> square(3) 9 >>> square() Traceback (most recent call last): ... TypeError: square() missing 1 required positional argument: 'n' >>> square('x') Traceback (most recent call last): ... TypeError...