Unit Testing
As a final best practice, we want to consider unit testing. Among the different testing
approaches, unit testing can indeed be considered a best practice because it tests Python
code on a rather fundamental level — i.e., the single units. What it does not test, however,
is the integration of the single units. Typically, such units are functions, classes, or
methods of classes. As a pretty simple example of a Python function that is also easily
testable, consider the one in Example A-5.
Example A-5. A rather simple Python function
Simple function to calculate
the square of the square root
of a positive number
simple_function.py
from math import sqrt
def f(x):
”’ Function to calculate the square of the square root.
Parameters
==========
x : float or int
input number
Returns
=======
fx : float
square of the square root, i.e. sqrt(x) ** 2
Raises
======
TypeError
if argument is neither float nor integer
ValueError
if argument is negative
Examples
========
>>> f(1)
1
>>> f(10.5)
10.5
”’
if type(x) != float and type(x) != int:
raise TypeError(“Input has not the right type.”)
if x < 0 :
raise ValueError(“Number negative.”)
fx = sqrt(x) ** 2
return fx
There are many tools available that help support unit tests. We will make use of nose in
what follows. Example A-6 contains a small test suite for the simple function f from
Example A-5.
Example A-6. A test suite for the function f
Test suite for simple function f
nose_test.py
import nose.tools as nt
from simple_function import f
def test_f_calculation():