Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 733
trikoder_beta Avatar asked Dec 22 '15 11:12

trikoder_beta


People also ask

How do I check if two dictionaries are equal in Python?

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.


1 Answers

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.

like image 157
jonrsharpe Avatar answered Sep 29 '22 14:09

jonrsharpe