6.6 Testing Code
155
In [6]: rel_diff
Out[6]: -1.9073486327552798e-16
Clearly, diff here would certainly not be smaller than a tolerance of 1E − 15 (as
we used above). So, to check whether a and b are equal, we should rather proceed
as
In [7]: tol = 1E-15
In [8]: rel_diff < tol
Out[8]: True
6.6.4 Constructing Unit Tests and Writing Test Functions
Python has several frameworks for automatic testing of software. By just one
command, you can get Python to run through a (potentially) very large number of
tests for various parts of your software. This is an extremely useful feature during
program development: whenever you have done some changes to one or more files,
launch the test command and make sure nothing is broken because of your edits.
The test frameworks nose and py.test are particularly attractive, since they are
very easy to use. Tests are placed in special test functions that the frameworks can
recognize and run for you. The requirements to a test function are simple:
• the name must start with test_
• the test function cannot have any arguments
• the tests inside test functions must be boolean expressions
• a boolean expression b must be tested in an assert statement of the form assert
b, msg. When b is true, nothing happens. However, if b is false, msg is written
out, where msg is an optional object (string or number).
Suppose we have written a function
def add(a, b):
return a + b
A corresponding test function can then be
def test_add():
expected = 2
computed = add(1, 1)
assert computed == expected, ’1+1={:g}’.format(computed)
Test functions can be in any program file or in separate files, typically with names
starting with test. You can also collect tests in subdirectories: running py.test
-s -v will actually run all tests in all test*.py files in all subdirectories, while
nosetests -s -v restricts the attention to subdirectories whose names start with
test or end with _test or _tests.
As long as we add integers, the equality test in the test_add function is
appropriate, but if we try to call add(0.1, 0.2) instead, we will face the rounding
Précédent

- 176/350

Suivant