如何使用Pytest声明列表的元素?

问题描述

我正在写Pytest,它有两个返回两个列表的函数。如何使用 assert 并比较Python 3.7中的两个无序列表?我想比较一下每个元素(子网)都存在于Expected_list中,最好使用表驱动测试

expected_list= ['subnet-123','subnet-456','subnet-789','subnet-000']

second_list= ['subnet-789','subnet-123','subnet-000']

def test_subnet_exist():
    expected_list = get_expected_list()
    second_list = get(second_list)
    for expected_list in second_list:
        assert second_list,"subnet {} not found".format(subnet)

由于列表的顺序,将导致“ AssertionError”。使用断言排序是一种方法,但是我很想知道是否有可能检查second_list的每个元素是否存在于Expected_list中

解决方法

旁注:get_expected_list()get(second_list)是一种奇怪的选择,不会像写的那样出现在问题中。

如果您的元素不可哈希,不可排序或除了定义相等性之外没有其他方法,那么IIRC不能比O(n^2)做得更好,因此我将假设哈希性(对于大多数合理的对象定义了相等性的代码,您也可以子类化并定义自定义__hash__(self)方法(如有必要)。

只要您的元素是可哈希的,您就可以依靠内置函数来测试成员资格。

def test_subnet_exists():
    assert set(get_expected_list()).issubset(get(second_list))

如果出于任何原因(例如,为了详细记录缺少的元素而需要循环),则可能仍需要使用集合来使过程高效。

def test_subnet_exists():
    # if hashability is impossible,leave this as `outer = get(second_list)`
    # and accept the O(n^2) performance impact
    outer = set(get(second_list))

    for item in get_expected_list():
        assert item in outer
,

由于您必须遍历列表,而且我们知道它们不是唯一的(123次出现两次,而789秒出现两次,因此您可以遍历它们,对吗?

顺便说一句,似乎“期望列表”是关键,而您想确保第二个列表中的值全部出现在“期望列表”中,而不是相反。

>
expected_list= ['subnet-123','subnet-456','subnet-789','subnet-123','subnet-wrong']

second_list= ['subnet-789','subnet-789']

def test_subnet_exist():
    expected = expected_list
    second = second_list
    for element in expected:
        assert element in second,f"{element} not found"
    print ("All elements found")

test_subnet_exist()

>>>AssertionError: subnet-wrong not found