To be honest I have always used assertDictEqual, because sometime when I didn't use it I got information, that equal dicts are not the same.
But... I know that dicts can be compared by == operator:
>>> {'a':1, 'b':2, 'c': [1,2]} == {'b':2, 'a':1, 'c': [1,2]} True Where I actually may need assertDictEqual?
The simplest technique to check if two or multiple dictionaries are equal is by using the == operator in Python. You can create the dictionaries with any of the methods defined in Python and then compare them using the == operator. It will return True the dictionaries are equals and False if not.
Basically, it allows unittest to give you more information about why the test failed. Compare these two tests:
class DemoTest(unittest.TestCase): D1 = {'a': 1, 'b': 2, 'c': [1, 2]} D2 = {'a': 1, 'b': 2, 'c': [1]} def test_not_so_useful(self): self.assertTrue(self.D1 == self.D2) def test_useful(self): self.assertDictEqual(self.D1, self.D2) And their outputs:
Failure Traceback (most recent call last): File "...x.py", line 86, in test_not_so_useful self.assertTrue(self.D1 == self.D2) AssertionError: False is not true vs.
Failure Traceback (most recent call last): File "...x.py", line 80, in test_useful self.assertDictEqual(self.D1, self.D2) AssertionError: {'a': 1, 'c': [1, 2], 'b': 2} != {'a': 1, 'c': [1], 'b': 2} - {'a': 1, 'b': 2, 'c': [1, 2]} ? --- + {'a': 1, 'b': 2, 'c': [1]} In the latter, you can see exactly what the difference was, you don't have to work it out yourself. Note that you can just use the standard assertEqual instead of assertDictEqual, with the same result; per the docs
...it’s usually not necessary to invoke these methods directly.
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