单元测试-断言列表中的一组项目包含(或不包含)在另一个列表中

Rub*_*ane 6 python unit-testing assert list python-2.7

您好,我是编程和尝试进行测试的新手,它检查项目列表中的任何项目是否存在于另一个列表中(在Python 2.7中使用unittest)。

例如,如果我有一个列表[[dog],“ cat”,“ frog],而我要测试的方法的结果是[” tiger“,” lion“,” kangaroo“,” frog],我希望测试失败,因为它包含上一个列表中的一项(“青蛙”)。我还希望测试告诉我两个列表都有哪些单词(即,哪些单词导致测试失败)。

我试过了:

self.assertIn(["cat", "dog"], method("cat dog tiger"))
Run Code Online (Sandbox Code Playgroud)

该方法的结果为[“ cat”,“ dog”,“ tiger”],但测试结果为失败,并显示:

AssertionError: ['cat', 'dog'] not found in ['cat', 'dog', 'tiger']
Run Code Online (Sandbox Code Playgroud)

我希望此测试返回“确定”,因为第二个列表中存在“猫”和“狗”。这似乎assertIn没有做什么,我还以为它会做(我认为这是检查是否有任何一个存在于b)。

反之亦然,当我希望它失败时会通过assertNotIn传递。

我已经搜索了一段时间,但是因为我不确定要查找的内容而很难找到。

谢谢您的阅读,我希望这是有道理的。

编辑:我已经放弃了克里斯的解决方案,它可以按我的意愿工作:

def myComp(list1, list2):
    section = list(set(list1).intersection(list2))
Run Code Online (Sandbox Code Playgroud)

为了获取错误消息中重叠(即触发失败)的单词列表,我从此处添加了以下代码。如何在Python AssertionError中更改消息?

try:
    assert(len(section)==0)
except AssertionError as e:
    e.args += ('The following are present in the processed text', 
    section)
    raise
Run Code Online (Sandbox Code Playgroud)

结果正是我想要的:

AssertionError: ('The following are pressent in the processed text', ['dog', 
'cat'])
Run Code Online (Sandbox Code Playgroud)

Ale*_*lex 11

您可以遍历您的列表 and assertIn,或者使用sets 并且您可以执行类似self.assertTrue(set(a).issuperset(set(b))).


Chr*_*ris 7

你应该看看这个问题,然后你可以很容易地看到类似的东西:

def myComp(list1, list2):
  section = list(set(list1).intersection(list2))
  return ((len(section)==0), section)
Run Code Online (Sandbox Code Playgroud)

此函数将返回一个带有布尔值的元组,指示失败或成功,以及两个列表中出现的项目列表。

如果您真的想在断言语句中执行此操作,则只需使用该元组的第一个元素...


小智 5

self.assertTrue(any(animal in method("cat dog tiger") for animal in ("cat", "dog")))
Run Code Online (Sandbox Code Playgroud)