Search code examples
pythondjangotestingassert

assertEqual two dicts except one key


I need to test a function which will return an dict with rest_framework.test.APITestCase's assertEqual in django. The dict is something like this:

{
    "first_name": "John",
    "last_name": "Doe",
    "random": some random number
}

How can I check the returned dict with my suitable result except the random key?

I mean assertEqual(a, result) should return True if these two dicts are passed:

a = {
        "first_name": "John",
        "last_name": "Doe",
        "random": 12
    }

result = {
        "first_name": "John",
        "last_name": "Doe",
        "random": 24
    }

Is there anyway to make this kind of exceptions in assertEqual or I have to use assert?

UPDATE:

Thanks to everyone, I got great solutions, But what if I got a list containing those dicts, like:

assertEqual(list_of_dicts, expected_result_list)

I mean in these two lists:

list1 = [
 d1,
 d2,
 d3
]

list2 = [
 d1,
 d2,
 d3
]

should be equal without considering the random key in each dict

Do I have to loop through the list and compare dicts one by one or there is a fastest solution for that as well?


Solution

  • You can create a copy of the dictionaries and pop the random number from there

    a_copy = a.copy()
    a_copy.pop("random")
    result_copy = result.copy()
    result_copy.pop("random")
    
    assertEqual(a_copy, result_copy)
    

    If you don't want to preserve the original use pop() directly on the existing dictionaries.

    If you have two lists of dicts you can iterate over both with zip and compare each pair

    for l, r in zip(copy.deepcopy(list_of_dicts), copy.deepcopy(expected_result_list)):
        l.pop("random")
        r.pop("random")
        assertEqual(l, r)