Welcome, guest | Sign In | My Account | Store | Cart

a test case to use with an interval insted of a single value

Python, 32 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
import unittest

class IntervalTestCase( unittest.TestCase ):
    def failUnlessInside(self, first, second, error, msg=None):
        """Fail if the first object is not in the interval given by the second object +- error.
        """
        if (first > second + error) or (first < second - error):
            raise self.failureException, \
                  (msg or '%s != %s (+-%s)' % (`first`, `second`, `error`))

    def failIfInside(self, first, second, error, msg=None):
        """Fail if the first object is in the interval given by the second object +- error.
        """
        if (first <= second + error) and (first >= second - error):
            raise self.failureException, \
                  (msg or '%s == %s (+-%s)' % (`first`, `second`, `error`))

    assertInside = failUnlessInside

    assertNotInside = failIfInside

class IntegerArithmenticTestCase( IntervalTestCase ):
    def testAdd(self):  ## test method names begin 'test*'
        self.assertInside((1 + 2), 3.3, 0.5)
        self.assertInside(0 + 1, 1.1, 0.01)
        
    def testMultiply(self):
        self.assertNotInside((0 * 10), .1, .05)
        self.assertNotInside((5 * 8), 40.1, .2)

if __name__ == '__main__':
    unittest.main()

if you are implementing aproximation to functions or are studying numerical analysis like me, you'll find it usefull

1 comment

Christos Georgiou 16 years, 3 months ago  # | flag

Take advantage of chained comparisons. This:

(first &lt;= second + error) and (first >= second - error)

can be rewritten as

second - error &lt;= first &lt;= second + error

And this:

(first > second + error) or (first &lt; second - error)

can be rewritten as

not (second - error &lt;= first &lt;= second + error)
Created by Javier Burroni on Sun, 2 Nov 2003 (PSF)
Python recipes (4591)
Javier Burroni's recipes (3)

Required Modules

Other Information and Tasks