inadaze
inadaze

Reputation: 181

ignoring an element from a dict when asserting in pytest

I was wondering if there is a way to ignore an element in a dict when doing an assert in pytest. We have an assert which will compare a list containing a last_modified_date. The date will always be updated so there is no way to be sure that the date will be equal to the date originally entered.

For example:

{'userName':'bob','lastModified':'2012-01-01'}

Thanks Jay

Upvotes: 17

Views: 5374

Answers (4)

vidstige
vidstige

Reputation: 13085

There is an excellent symbol called ANY in the system library unittest.mock that can be used as a wildcard. Try this

from unittest.mock import ANY
actual = {'userName': 'bob', 'lastModified': '2012-01-01'}
expected = {'userName': 'bob', 'lastModified': ANY}
assert actual == expected

Upvotes: 26

Leonardo
Leonardo

Reputation: 318

def test_compare_dicts():
    dict1 = {'userName':'bob','lastModified':'2012-01-01'}
    dict2 = {'userName':'bob','lastModified':'2013-01-01'}

    excluded_fields = ['lastModified']

    assert {k: v for k, v in dict1.items() if k not in excluded_fields} == {k: v for k, v in dict2.items() if k not in excluded_fields}

Upvotes: 0

Artimi
Artimi

Reputation: 351

I solved this issue by creating object that equals to everything:

class EverythingEquals:
    def __eq__(self, other):
        return True

everything_equals = EverythingEquals()

def test_compare_dicts():
    assert {'userName':'bob','lastModified':'2012-01-01'} == {'userName': 'bob', 'lastModified': everything_equals}

This way it will be compared as the same and also you will check that you have 'lastModified' in your dict.

EDIT:

Now you can use unittest.mock.ANY instead of creating your own class.

Upvotes: 22

kindall
kindall

Reputation: 184345

Make a copy of the dict and remove the lastModified key from the copy, or set it to a static value, before asserting. Since del and dict.update() and the like don't return the dict, you could write a helper function for that:

def ignore_keys(d, *args):
    d = dict(d)
    for k in args:
        del d[k]
    return d

assert ignore_keys(myDict, "lastModified") == {"userName": "bob")

Upvotes: 1

Related Questions