Python 单元测试中是否有针对子列表的断言?

Is there an assert for sublists in Python unit testing?

对于Python 2.7:

list1 = [1, 2]

self.assertIn(1, list1)
self.assertIn(2, list1)

有什么方法可以让我更轻松地做到这一点?类似于:

self.assertIn((1,2), list1)  # I know this is wrong, just an example

尝试

self.assertTrue(all(x in list1 for x in [1,2]))

如果可以使用 pytest-django 则可以使用本机断言语句:

assert all(x in in list1 for x in [1,2])

我相信您已经弄明白了,但您可以为此使用一个循环:

tested_list = [1, 2, 3]
checked_list = [1, 2]

# check that every number in checked_list is in tested_list:
for num in checked_list:
    self.assertIn(num, tested_list)

这在 tested_list 中缺少的特定号码上失败,因此您立即知道问题出在哪里。

对于这样的东西,我特别喜欢 hamcrest 库。

您可以像这样编写测试:

from hamcrest import assert_that, has_items, contains_inanyorder

assert_that([1, 2], has_items(2, 1)) # passes

assert_that([1, 2, 3], has_items(2, 1)) # also passes - the 3 is ignored
assert_that([1, 2], has_items(3, 2, 1)) # fails - no match for 3
assert_that([1, 2], contains_inanyorder(2, 1)) # passes
assert_that([1, 2, 3], contains_inanyorder(2, 1)) # fails, no match for 3

稍微难看一点,可读性差一些,但会显示所有缺失的元素,而不仅仅是第一个失败的元素:

actual = [1, 2]
expected = set([1, 2, 3, 4])
self.assertEqual(set(actual) & expected, expected)

输出:

AssertionError: Items in the second set but not the first:
3
4