Tom J Muthirenthi
Tom J Muthirenthi

Reputation: 3340

unittest - compare list irrespective of order

I am doing a unit test on two list of list values:

self.assertEqual(sale, [['1',14], ['2',5], ['3',7], ['4',1]])

But it gives the below error:

AssertionError: Lists differ: [['1', 14], ['4', 1], ['2', 5], ['3', 7]] != [['1'
, 14], ['2', 5], ['3', 7], ['4', 1]]

First differing element 1:
['4', 1]
['2', 5]

- [['1', 14], ['4', 1], ['2', 5], ['3', 7]]
+ [['1', 14], ['2', 5], ['3', 7], ['4', 1]]

How can I make this scenario pass, Prevent the assertEqual function to avoid checking the order of the elements in the list.

Upvotes: 13

Views: 4720

Answers (2)

Tim Tisdall
Tim Tisdall

Reputation: 10382

You want assertCountEqual.

For assertCountEqual(a, b), it passes if:

a and b have the same elements in the same number, regardless of their order.

Upvotes: 9

AndrewHK
AndrewHK

Reputation: 96

Since Python lists keep track of order, you'll need some way to make sure the items are in the same order.

A set might work, if all items are unique. If they aren't unique you'll lose information on the duplicates.

Sorting the lists before you compare them will probably be your best bet. It will keep all the data intact, and put them in the same order in each list.

Here is a link to the different built in sorting methods for lists in Python 3. https://docs.python.org/3/howto/sorting.html

Upvotes: 7

Related Questions