Doctests are comment strings embedded in Python code that resemble interactive sessions. These strings can be used to test certain assumptions or just provide examples. We need to use the doctest
module to run these tests.
Let's write a simple example that is supposed to calculate the factorial but doesn't cover all possible boundary conditions. In other words, some tests will fail.
Write the
docstring
with a test that will pass and another test that will fail. Thedocstring
text should look like what you would normally see in a Python shell:""" 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 NumPy code:
return np.arange(1, n+1).cumprod()[-1]
We want this code to fail on purpose—sometimes. It will create an array of sequential numbers, calculate the cumulative product of the array, and return the last element.