Time for action – executing doctests
Let's write a simple example that is supposed to calculate the well-known factorial, but doesn't cover all the possible boundary conditions. In other words some tests will fail.
The docstring will look like text you would see in a Python shell (including a prompt). We will rig one of the tests to fail, just to see what will happen.
""" Test for the factorial of 3 that should pass. >>> factorial(3) 6 Test for the factorial of 0 that should fail. >>> factorial(0) 1 """
We will write the following line of NumPy code to compute the factorial:
return np.arange(1, n+1).cumprod()[-1]
We want this code to fail from time to time for demonstration purposes.
We can run the
doctest
by calling therundocs
function of thenumpy.testing
module for instance in the Python shell.>>>from numpy.testing import rundocs >>>rundocs('docstringtest.py') Traceback (most recent call last): File "<stdin>", line 1, in <module...