对于Python 2.7:
vTest = Source.objects.get(id=self.id).state
有没有办法让我更轻松?类似的东西:
$stateParam
答案 0 :(得分:5)
尝试
self.assertTrue(all(x in list1 for x in [1,2]))
如果可以使用pytest-django,则可以使用本机断言语句:
assert all(x in in list1 for x in [1,2])
答案 1 :(得分:5)
我确定你已经弄明白但是你可以使用循环:
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
中缺少的特定号码失败,因此您可以立即知道问题所在。
答案 2 :(得分:3)
对于这样的东西,我特别喜欢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