Test assertions for tuples with floats

|▌冷眼眸甩不掉的悲伤 提交于 2019-12-04 05:16:40

Well how about pimping up your function with couple of zips:

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 here is that it is better to use multiple asserts in a loop as to get the exact values where it breaks, vs. using single assert with all().

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

I'll 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 it will assert (1, 2) and [1, 2] are equal.)

What I have done in the past is to write a custom-function that establishes validity for a complicated data type, and then used assert( IsFooValid( foo ) ). The validity function can simply return true/false, but it's usually better for it to raise AssertionError with an appropriate message.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!