【问题标题】:Unit Test in Python involving two listsPython中的单元测试涉及两个列表
【发布时间】:2015-08-18 18:11:46
【问题描述】:

我正在 Python 中执行单元测试,我试图检查两个列表中的元素是否在一定范围内。我正在考虑的两个列表是yieldslist_of_yields,并且正在考虑做self.assertEqual(round(yields-list_of_yields, 7), 0)。但是- 是列表不受支持的类型,所以我的两个问题是如何检查元素是否在某个范围内以及如何对多个元素执行assert,因为我被告知有多个asserts是不好的做法。我看到了this answer,但我的问题略有不同。

谢谢

【问题讨论】:

  • 元素的顺序是什么?假设我们有以下列表 [a, b, c][x, y, z] 以及一个返回 true 的接近函数,如 def close(item1, item2)。您是否只想按照它们在列表中的索引顺序检查元素,例如:all(( close(a,x), close(b,y), close(c, z) ))?或者您只是想看看两个列表中是否有任何可以满足条件的选择排列?
  • any([ abs(x - y) > 7 for x, y in zip(yields, list_of_yields) ])?

标签: python unit-testing


【解决方案1】:

如果要按照元素出现的确切顺序比较元素,您可以创建一个实用函数,该函数接受参数并检查它们是否满足某些条件:

def close_round(item1, item2, rounding_param):
    """Determines closeness for our test purposes"""
    return round(item1, rounding_param) == round(item2, rounding_param)

然后你可以在这样的测试用例中使用它:

assert len(yields1) == len(list_of_yields)
index = 0
for result, expected in zip(yields, list_of_yields):
    self.assertTrue(close_round(result, expected, 7),
                    msg="Test failed: got {0} expected {1} at index {2}".format(result, expected, index))
    index+=1

您可能会发现这种类型的模式很有用,在这种情况下您可以创建一个执行此操作的函数:

def test_lists_close(self, lst1, lst2, comp_function):
    """Tests if lst1 and lst2 are equal by applying comp_function
    to every element of both lists"""
    assert len(lst1) == len(lst2)
    index = 0
    for result, expected in zip(yields, list_of_yields):
        self.assertTrue(comp_function(result, expected),
                        msg="Test failed: got {0} expected {1} at index {2}".format(result, expected, index))
        index+=1

如果你经常使用它,你可能也想测试这个功能。

【讨论】:

    【解决方案2】:

    这是一个函数式方法

    assert(0 == (reduce(lambda a,b:a+b, map(lambda c:round(c[0]-c[1], 7), zip(yields, list_of_yeilds))))
    

    分解: 取yieldslist_of_yieldszip 以获取对列表:

    [(yields[0], list_of_yields[0]), (yields[1], list_of_yields[1]), ...]
    

    然后map 函数lambda c:round(c[0]-c[1], 7) 在每一对上得到yieldslist_of_yields 的成对差异,四舍五入到小数点后7位。

    [round(yields[0] - list_of_yields[0], 7), round(yields[1] - list_of_yields[1], 7), ...]
    

    最后一步是检查此列表中的任何元素是否非零(在这种情况下,列表不够接近)。只需通过加法减少并检查 0 即可。

    0 == round(yields[0] - list_of_yields[0], 7) + round(yields[1] - list_of_yields[1], 7) + ...
    

    【讨论】:

      猜你喜欢
      • 2019-05-02
      • 2013-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-02
      相关资源
      最近更新 更多