【发布时间】:2018-01-25 22:48:57
【问题描述】:
您好,我是编程新手,并尝试进行测试以检查项目列表中的 任何 项目是否存在于另一个列表中(在 Python 2.7 中使用 unittest)。
例如,如果我有一个列表 ["dog", "cat", "frog] 并且我正在测试的方法的结果是 ["tiger", "lion", "kangaroo", "frog] 我想要测试失败,因为它包含上一个列表中的一项(“frog”)。我还希望测试告诉我两个列表都有哪些单词(即哪些单词导致测试失败)。
我试过了:
self.assertIn(["cat", "dog"], method("cat dog tiger"))
方法的结果是 ["cat", "dog", "tiger"] 但测试的结果是失败并说:
AssertionError: ['cat', 'dog'] not found in ['cat', 'dog', 'tiger']
我希望此测试返回正常,因为“猫”和“狗”出现在第二个列表中。似乎 assertIn 没有做我认为它会做的事情(我认为它是检查 b 中是否存在任何 a)。
反之亦然,当我希望它失败时,assertNotIn 就会通过。
我一直在寻找一段时间,但因为我不确定我在寻找什么,所以很难找到。
感谢您的阅读,我希望这是有道理的。
编辑:我采用了 Chris 的解决方案,它可以按我的意愿工作:
def myComp(list1, list2):
section = list(set(list1).intersection(list2))
为了获取错误消息中重叠的单词列表(即触发失败),我从这里添加了以下代码How to change the message in a Python AssertionError?:
try:
assert(len(section)==0)
except AssertionError as e:
e.args += ('The following are present in the processed text',
section)
raise
结果正是我想要的:
AssertionError: ('The following are pressent in the processed text', ['dog',
'cat'])
【问题讨论】:
-
列表
['cat', 'dog']未在列表['cat', 'dog', 'tiger']中找到在提示符中尝试print ['a'] in ['a']- 这是错误的,因为列表不在列表中,并且它不执行元素-明智的比较。
标签: python python-2.7 list unit-testing assert