Book Image

Learning NumPy Array

By : Ivan Idris
Book Image

Learning NumPy Array

By: Ivan Idris

Overview of this book

Table of Contents (14 chapters)
Learning NumPy Array
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Performing Unit tests


Unit tests are automated tests that test a small piece of code, usually a function or method. Python has the PyUnit API for unit testing. As NumPy users, we can make use of the assert functions that we saw in action before.

We will write tests for a simple factorial function. The tests will check for the so-called happy path (regular conditions and is expected to always pass) and for abnormal conditions:

  1. We start by writing the factorial function:

    def factorial(n):
       if n == 0:
          return 1
    
       if n < 0:
          raise ValueError, "Unexpected negative value"
    
       return np.arange(1, n+1).cumprod()

    The code is using the arange and cumprod functions that we have already seen to create arrays and calculate the cumulative product, but we added a few checks for boundary conditions.

  2. Now we will write the unit test. Let's write a class that will contain the unit tests. It extends the TestCase class from the unittest module, which is a part of standard Python. We test for calling...