dimanche 26 janvier 2020

Python 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?

Aucun commentaire:

Enregistrer un commentaire