Tests and Exceptions


In this lesson we will look at how to make your code more reliable by writing tests. Tests when used cleverly can give you a lot of confidence in your code and therefore your results!

Lets start with our (broken) square function from the last lesson:

def square(x):
    return x**3

Tests can take many forms, they can compare your code against known results i.e. ones in a published paper, or they can just test that the result of some function returns the type of object you expect or even just check that your code results always stays the same, so you know if something breaks.

A simple test for our square function we defined above might look like:

def test_square():
    assert square(10) == 10*10

The `assert` statement

As we will see later, the way to make a test fail is to raise an error. Therefore the assert statement in Python is a useful shortcut when writing tests.

The assert statement will raise an error if a condition is not satisfied. The general form of the assert statement is:

assert condition, "message"


assert 5 == 6, "Five is not equal to six"

We can run our test function the same way that we run any other function. Although this dosent scale very well to thousands of tests!

AssertionError                            Traceback (most recent call last)
<ipython-input-3-5351b87f150c> in <module>()
----> 1 test_square()

<ipython-input-2-0fd7f2671b21> in test_square()
      1 def test_square():
----> 2     assert square(10) == 10*10


Writing Tests

The following function has bugs in it. Write some tests below the function to find all the bugs.

def quadratic(a, b, c):
    return ((-1* b) * np.sqrt(b**2 - 4*a*c) / (2 * a))
import numpy as np
def test_quadratic():
    assert(quadratic(1,1,-1)) == -1.118033988749895


Running Tests Automatically with pytest

Once you have a few test functions written, you will probably start getting bored with typing out their names and running them one-by-one. There are a few different modules to help you write and run tests. The one we will be using is called pytest.

For the next section of this session we will be using the two Python (.py) files named askdl.py and lsadkj.py.