Book Image

NumPy: Beginner's Guide

By : Ivan Idris
Book Image

NumPy: Beginner's Guide

By: Ivan Idris

Overview of this book

Table of Contents (21 chapters)
NumPy Beginner's Guide Third Edition
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
NumPy Functions' References
Index

Time for action – writing a unit test


We will write tests for a simple factorial function. The tests will check for the so-called happy path and abnormal conditions.

  1. Start by writing the factorial function:

    import numpy as np
    import unittest
    
    
    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 uses the arange() and cumprod() functions 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 part of standard Python. Test for calling the factorial function with the following three attributes:

    • a positive number, the happy path

    • boundary condition 0

    • negative numbers, which should result in an error

      class FactorialTest(unittest.TestCase):
         def test_factorial(self):
            #Test for the factorial...