Page - 155 - in Programming for Computations β Python - A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
Image of the Page - 155 -
Text of the Page - 155 -
6.6 TestingCode 155
In [6]: rel_diff
Out[6]: -1.9073486327552798e-16
Clearly,diffhere would certainly not be smaller than a tolerance of 1Eβ15 (as
we used above). So, to check whethera andb are equal, we should rather proceed
as
In [7]: tol = 1E-15
In [8]: rel_diff < tol
Out[8]: True
6.6.4 ConstructingUnitTestsandWritingTestFunctions
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
programdevelopment:wheneveryouhavedonesomechanges tooneormorefiles,
launch the test commandandmakesurenothingisbrokenbecauseofyouredits.
Thetest frameworksnoseandpy.testareparticularlyattractive,since theyare
very easy to use. Tests are placed in special test functions that the frameworks can
recognizeand runforyou.The requirements toa test functionare simple:
β’ thenamemust start withtest_
β’ the test functioncannothaveanyarguments
β’ the tests inside test functionsmust bebooleanexpressions
β’ abooleanexpressionbmustbe tested inanassert statementof the formassert
b, msg. Whenb is true, nothing happens. However, ifb is false,msg is written
out,wheremsg is anoptionalobject (stringornumber).
Supposewehavewrittena function
def add(a, b):
return a + b
Acorrespondingtest functioncan thenbe
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: runningpy.test
-s -vwill actually run all tests in all test*.pyfiles in all subdirectories, while
nosetests -s -v restricts the attention to subdirectories whose names start with
testorendwith_testor_tests.
As long as we add integers, the equality test in the test_add function is
appropriate,but ifwe try tocalladd(0.1, 0.2) instead,wewill face therounding
Programming for Computations β Python
A Gentle Introduction to Numerical Simulations with Python 3.6, Volume Second Edition
- Title
- Programming for Computations β Python
- Subtitle
- A Gentle Introduction to Numerical Simulations with Python 3.6
- Volume
- Second Edition
- Authors
- Svein Linge
- Hans Petter Langtangen
- Publisher
- Springer Open
- Date
- 2020
- Language
- English
- License
- CC BY 4.0
- ISBN
- 978-3-319-32428-9
- Size
- 17.8 x 25.4 cm
- Pages
- 356
- Keywords
- Programmiersprache, Informatik, programming language, functional, imperative, object-oriented, reflective
- Category
- Informatik