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 of 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). 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 """
- Write the following line of NumPy code:
return np.arange(1, n+1).cumprod()[-1]
We want this code to fail from time to time for demonstration purposes.
- 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...