1 Python Testing Cheat Sheet
2 ==========================
7 Using an assertion to ensure input is acceptable:
11 # ... continue safe in knowledge that x > 0
13 Adding an explanatory message to the assertion:
15 assert x >= 0, "Function not defined for negative x."
17 Alternatively, raise an exception to indicate what the problem is:
21 raise TypeError, "Function not defined for negative x."
25 Unit testing with Nose
26 ----------------------
28 To run tests, at the shell prompt, type
34 * look for test functions that have a name starting with `test`
35 * look for them in files with names starting with `test`
36 * look for such files in the current working directory, and in subdirectories with names starting with `test`
38 There are some additional rules, and you can configure your own, but this should be enough to get started.
42 from nose.tools import assert_equal
44 from mystatscode import mean
46 def test_single_value():
47 observed = mean([1.0])
49 assert_equal(observed, expected)
53 Nose provides a range of assertions that can be used when a test is not just checking a simple equality, e.g.
55 from nose.tools import assert_items_equal
57 from mycode import find_factors
60 observed = find_factors(6)
62 assert_items_equal(observed, expected) # order of factors is not guaranteed
64 ### Floating point tests
66 When comparing floating-point numbers for equality, allow some tolerance for small differences due to
67 the way values are represented and rounded.
69 from nose.tools import assert_almost_equal
71 from mycode import hypotenuse
73 def test_hypotenuse_345():
74 observed = hypotenuse(3.0, 4.0)
76 assert_almost_equal(observed, expected)
78 ### Testing exceptions
80 Testing that a method raises the appropriate exception when the input is invalid:
82 from nose.tools import raises
84 from mystatscode import mean
87 def test_not_a_list():
92 A *fixture* is what the test function uses as input, e.g. values, objects and arrays.
94 To set up a fixture once before any tests are run, define a method called `setup` in the same files
95 as the test functions. This can assign values to global variables for use in the test functions.
101 # append more values to long_list...
103 If the global variables assigned in `setup` might be modified by some of the test functions, the set-up
104 step must be executed once before each test function is called:
106 from nose.tools import with_setup
108 from mycode import mean, clear
114 # append more values to long_list...
116 @with_setup(setup_each)
117 def test_mean_long_list():
118 observed = mean(long_list)
120 assert_equal(observed, expected)
122 @with_setup(setup_each)
123 def test_clear_long_list():
125 assert_equal(len(long_list), 0)