测试带有浮点的元组的断言 [英] Test assertions for tuples with floats

查看:164
本文介绍了测试带有浮点的元组的断言的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数返回一个元组,其中包含一个浮点值。通常我使用 assertAlmostEquals 来比较这些元素,但这不适用于元组。此外,元组也包含其他数据类型。目前我正在断言元组中的每个元素,但是对于这样的元组列表来说太多了。有没有什么好的方法来写这种情况下的断言?
考虑这个函数:

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

现在我想写一个测试:

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

这将失败,因为 1.0 / 2 不完全是 0.5 。任何人都可以推荐一种以可读的方式编写这种断言的好方法吗?

编辑:其实 1.0 / 2 确切地说是 0.5 ,但是你明白了我的意思。

解决方案<那么如何拉伸你的功能与几个拉链:

  def testF(self):$ b $ (f(range)(1,3)),[(1.0,2),(0.5,4)]):
for zip1(tuple1,tuple2)中的val1,val2:
如果type(val2)是float:
self.assertAlmostEquals(val1,val2,5)
else:
self.assertEquals(val1,val2)


$ b我的前提是最好在循环中使用多个断言,以获取断点处的确切值,单一断言所有()。



ps。如果你有其他的数字类型你想使用assertAlmostEquals for,你可以把上面的if改成例如如果在[float,decimal.Decimal]中键入(val2):


I have a function that returns a tuple that, among others, contains a float value. Usually I use assertAlmostEquals to compare those, but this does not work with tuples. Also, the tuple contains other data-types as well. Currently I am asserting every element of the tuple individually, but that gets too much for a list of such tuples. Is there any good way to write assertions 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 fail because the result of 1.0/2 is not exactly 0.5. Can anyone recommend a good way of writing such an assertion in a readable way?

Edit: Actually 1.0/2 is exactly 0.5, but you get my meaning.

解决方案

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]:

这篇关于测试带有浮点的元组的断言的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆