Why is assertDictEqual needed if dicts can be compared by `==`?

Issue

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?

Solution

Basically, it allows unittest to give you more information about why the test failed ("diagnostics", to use the language from "Growing Object-Oriented Software Guided by Tests" by Steve Freeman and Nat Pryce). 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.

Answered By – jonrsharpe

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published