如何解决如何使用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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。