How can you test that two dictionaries are equal with pytest in python

39,006

Solution 1

Don't spend your time writing this logic yourself. Just use the functions provided by the default testing library unittest

from unittest import TestCase
TestCase().assertDictEqual(expected_dict, actual_dict)

Solution 2

pytest's magic is clever enough. By writing

assert {'a': 1} == {'a': 1}

you will have a nested test on equality.

Solution 3

I guess a simple assert equality test should be okay:

>>> d1 = {n: chr(n+65) for n in range(10)}
>>> d2 = {n: chr(n+65) for n in range(10)}
>>> d1 == d2
True
>>> l1 = [1, 2, 3]
>>> l2 = [1, 2, 3]
>>> d2[10] = l2
>>> d1[10] = l1
>>> d1 == d2
True
>>> class Example:
    stub_prop = None
>>> e1 = Example()
>>> e2 = Example()
>>> e2.stub_prop = 10
>>> e1.stub_prop = 'a'
>>> d1[11] = e1
>>> d2[11] = e2
>>> d1 == d2
False

Solution 4

General purpose way is to:

import json

# Make sure you sort any lists in the dictionary before dumping to a string

dictA_str = json.dumps(dictA, sort_keys=True)
dictB_str = json.dumps(dictB, sort_keys=True)

assert dictA_str == dictB_str
Share:
39,006
John Mike
Author by

John Mike

Updated on August 31, 2021

Comments

  • John Mike
    John Mike over 2 years

    Trying to assert that two dictionaries that have nested contents are equal to each other (order doesn't matter) with pytest. What's the pythonic way to do this?