Python for Finance: Analyze Big Financial Data

(Elle) #1

”’ Tests if function f calculates correctly. ”’
nt.assert_equal(f(4.), 4.)
nt.assert_equal(f( 1000 ), 1000 )
nt.assert_equal(f(5000.5), 5000.5)


def test_f_type_error():
”’ Tests if type error is raised. ”’
nt.assert_raises(TypeError, f, ‘test string’)
nt.assert_raises(TypeError, f, [ 3 , ‘string’])


def test_f_value_error():
”’ Tests if value error is raised. ”’
nt.assert_raises(ValueError, f, - 1 )
nt.assert_raises(ValueError, f, -2.5)


def test_f_test_fails():
”’ Tests if function test fails. ”’
nt.assert_equal(f(5.), 10 )


Table A-2 describes the test functions that are implemented.


Table A-2. Test functions for simple function f


Function Description

test_f_calculation

Tests if the function generates correct results

test_f_type_error

Checks if the function raises a type error when expected

test_f_value_error

Checks if the function raises a value error when expected

test_f_test_fails

Tests if the calculation test fails as expected (for illustration)

From the command line/shell, you can run the following tests:


$   nosetests   nose_test.py
...F
======================================================================
FAIL: Test if function test fails.
–––––––––––––––––––––––-
Traceback (most recent call last):
File “/Library/anaconda/lib/python2.7/site-packages/nose/case.py”,
line 197, in runTest self.test(*self.arg)
File “//Users/yhilpisch/Documents/Work/Python4Finance/python/nose_test.py”,
line 30, in test_f_test_fails
nt.assert_equal(f(5.), 10)
AssertionError: 5.000000000000001 != 10

–––––––––––––––––––––––-
Ran 4 tests in 0.002s

FAILED  (failures=1)
$

Obviously, the first three tests are successful, while the last one fails as expected. Using


such tools — and more importantly, implementing a rigorous approach to unit testing —


may require more effort up front, but you and those working with your code will benefit in


the long run.

Free download pdf