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.
assertDictEqual ()- Tests that two dictionaries are equal. Now that we’ve discussed all these, you can go check the code once again. We used the methods assertEqual (), assertTrue (), assertFalse (), and assertRaises (). This delivers a command-line interface to the test script.
Now, let’s take a look at what methods we can call within Unit testing with Python: assertEqual ()- Tests that the two arguments are equal in value. assertNotEqual ()- Tests that the two arguments are unequal in value.
This is used to validate that each unit of the software performs as designed. The unittest test framework is python’s xUnit style framework. White Box Testing method is used for Unit testing.
To see which function it is talking about and which arguments were using for invoking it follow the stack trace: at Object.<anonymous> (sum.spec.js:25:36) . At the indicated line and column you should
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
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:
What failed one says:
Therefore assertCountEqual
should be used for OP's case.
This test was done in PyCharm latest version and Python 3.5
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With