Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 995
Saša Kalaba Avatar asked Aug 10 '15 13:08

Saša Kalaba


2 Answers

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])
like image 125
Sebastian Wozny Avatar answered Oct 13 '22 11:10

Sebastian Wozny


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.

like image 22
geckon Avatar answered Oct 13 '22 12:10

geckon