Saša Kalaba
Saša Kalaba

Reputation: 4421

Is there an assert for sublists in Python unit testing?

For Python 2.7:

list1 = [1, 2]

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

Is there a way I can do this easier? Something like:

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

Upvotes: 7

Views: 5194

Answers (3)

Sebastian Wozny
Sebastian Wozny

Reputation: 17506

Try

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

If you can use pytest-django you can use the native assert statement:

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

Upvotes: 7

Dunes
Dunes

Reputation: 40833

For stuff like this I particularly like the hamcrest library.

You can write your test something like this:

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

Slightly more ugly, and less readable, but shows all the missing elements, rather than just the first element to fail:

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

Outputs:

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

Upvotes: 3

geckon
geckon

Reputation: 8774

I'm sure you figured it out but you can use a loop for that:

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)

This fails on a particular number that is missing in tested_list so you immediately know where the problem is.

Upvotes: 6

Related Questions