Reputation: 3015
I'm writing a unit test for a function that returns a list of dictionaries. What is the best way to check if the output is as expected? Here, "as expected" means the dictionaries in the lists have the same keys and values, irrespective of the order of keys within the dictionary, or of the dictionary's order within the list. So something like this:
expect_output = [ {"c":4} , {"a" : 4 , "b" : 3}]
actual_ouput = [{"b" : 3, "a" : 4 }, {"c":4}]
# some function that would return true in this case.
Upvotes: 24
Views: 19262
Reputation: 1313
Here I've done a simple comparison between assertEqual
and assertCountEqual
as a value addition.
For assertEqual
-> order of the list is important.
For assertCountEqual
-> order of the list is not important.
def test_swapped_elements_1(self):
self.assertEqual([{"b": 1}, {"a": 1, "b": 1}], [{"b": 1, "a": 1}, {"b": 1}])
def test_swapped_elements_2(self):
self.assertCountEqual([{"b": 1}, {"a": 1, "b": 1}], [{"b": 1, "a": 1}, {"b": 1}])
def test_non_swapped_elements_1(self):
self.assertEqual([{"a": 1, "b": 1}, {"b": 1}], [{"b": 1, "a": 1}, {"b": 1}])
def test_non_swapped_elements_2(self):
self.assertCountEqual([{"a": 1, "b": 1}, {"b": 1}], [{"b": 1, "a": 1}, {"b": 1}])
Above results in:
Therefore assertCountEqual
should be used for OP's case.
This test was done in PyCharm latest version and Python 3.5
Upvotes: 4
Reputation: 531693
If you are using unittest
, there is a method for this:
self.assertItemsEqual(actual_output, expected_output)
In Python-3, this method is renamed to assertCountEqual
Upvotes: 25