Testing

Assertions

Learning Objectives

  • Assertions are one line tests embedded in code.
  • Assertions can halt execution if something unexpected happens.
  • Assertions are the building blocks of tests.

Assertions are the simplest type of test. They are used as a tool for bounding acceptable behavior during runtime. The assert keyword in python has the following behavior:

>>> assert True == False
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  AssertionError
  >>> assert True == True
  >>>

That is, assertions halt code execution instantly if the comparison is false. It does nothing at all if the comparison is true. These are therefore a very good tool for guarding the function against foolish (e.g. human) input:

def mean(num_list):
    assert len(num_list) != 0
    return sum(num_list)/len(num_list)

The advantage of assertions is their ease of use. They are rarely more than one line of code. The disadvantage is that assertions halt execution indiscriminately and the helpfulness of the resulting error message is usually quite limited.

Also, input checking may require decending a rabbit hole of exceptional cases. What happens when the input provided to the mean function is a string, rather than a list of numbers?

Insert an Assertion

  1. Open an IPython Notebook
  2. Create the following function:
def mean(num_list):
  return sum(num_list)/len(num_list)
  1. In the function, insert an assertion that checks whether the input is actually a list.

Hint: Use the isinstance function.

Assertions are also helpful for catching abnormal behaviors, such as those that arise with floating point arithmetic.

Almost Equal

Assertions are also helpful for catching abnormal behaviors, such as those that arise with floating point arithmetic. Using the assert keyword, how could you test whether some value is almost the same as another value?

  • My package, mynum, provides the number a.
  • Use the assert keyword to check whether the number a is greater than 2.
  • Use the assert keyword to check that a is equal to 2 within an error of 0.003.
from mynum import a
# greater than 2 assertion here
# 0.003 assertion here

NumPy

The NumPy numerical computing library has a built-in function assert_allclose for comparing numbers within a tolerance:

from numpy.testing import assert_allclose
from mynum import a
assert_allclose(a, 2, atol=0.003, rtol=0)