Testing your software in Python

We’ll follow the concise Software Carpentry Testing Tutorial, but today we will only cover the following sections:

Note: the contents of this notebook are taken from the above tutorials, and are thus licensed according to the same terms, under the Creative Commons Attribution license (CC BY 4.0).

A simple, testable mean

Let’s checkpoint here with a directory that should have:

%%writefile mean.py

def mean(num_list):
    try:
        return sum(num_list)/len(num_list)
    except ZeroDivisionError :
        return 0
    except TypeError as detail :
        msg = "The algebraic mean of an non-numerical list is undefined.\
               Please provide a list of numbers."
        raise TypeError(detail.__str__() + "\n" +  msg)
%%writefile test_mean.py

from mean import *

def test_ints():
    num_list = [1, 2, 3, 4, 5]
    obs = mean(num_list)
    exp = 3
    assert obs == exp

def test_zero():
    num_list=[0,2,4,6]
    obs = mean(num_list)
    exp = 3
    assert obs == exp

def test_double():
    # This one will fail in Python 2
    num_list=[1,2,3,4]
    obs = mean(num_list)
    exp = 2.5
    assert obs == exp

def test_long():
    big = 100000000
    obs = mean(range(1,big))
    exp = big/2.0
    assert obs == exp

def test_complex():
    # given that complex numbers are an unordered field
    # the arithmetic mean of complex numbers is meaningless
    num_list = [2 + 3j, 3 + 4j, -32 - 2j]
    obs = mean(num_list)
    exp = NotImplemented
    assert obs == exp
from test_mean import *

test_ints()
test_zero()
test_double()
test_long()
test_complex()  ## This might fail. You'll get an error message showing which tests failed