Testing claims for float tuples

I have a function that returns a tuple that, among other things, contains a float value. I usually use assertAlmostEquals for comparison, but this does not work with tuples. In addition, the tuple contains other data types. Currently, I approve each element of a tuple individually, but this is too much for a list of such tuples. Is there a good way to write statements for such cases? Consider this function:

 def f(a): return [(1.0/x, x * 2) for x in a] 

Now I want to write a test for it:

 def testF(self): self.assertEqual(f(range(1,3)), [(1.0, 2), (0.5, 4)]) 

This will not succeed, because the result of 1.0/2 does not correspond to 0.5 . Can anyone recommend a good way to write such a statement in a readable way?

Edit : Actually 1.0/2 exactly 0.5 , but you will get my value.

+5
python floating-point assert unit-testing tuples
source share
3 answers

Ok, how about pulling your function with a couple of zip codes:

 def testF(self): for tuple1, tuple2 in zip(f(range(1,3)), [(1.0, 2), (0.5, 4)]): for val1, val2 in zip(tuple1, tuple2): if type(val2) is float: self.assertAlmostEquals(val1, val2, 5) else: self.assertEquals(val1, val2) 

My premise is that it is better to use several statements in a loop to get the exact values ​​where it breaks, and also use a single assert with all ().

ps. If you have other numeric types for which you want to use assertAlmostEquals, you can change the if value above, for example. if type(val2) in [float, decimal.Decimal]:

+7
source share

I will probably define a recursive function.

 from collections import Iterable; def recursiveAssertAlmostEqual(testCase, first, second, *args, **kwargs): if isinstance(first, Iterable) and isinstance(second, Iterable): for a, b in zip(first, second): recursiveAssertAlmostEqual(testCase, a, b, *args, **kwargs) else: testCase.assertAlmostEqual(first, second, *args, **kwargs) 

(Note that he will argue that (1, 2) and [1, 2] are equal.)

+3
source share

What I did in the past is to write a user-defined function that sets validity for a complex data type, and then assert( IsFooValid( foo ) ) . The validity function may just return true / false, but it is usually better to raise an AssertionError with the appropriate message.

+2
source share

All Articles