Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ignoring an element from a dict when asserting in pytest

Tags:

python

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

like image 418
inadaze Avatar asked Aug 05 '13 17:08

inadaze


People also ask

How does assert work in pytest?

Assertions in PyTest Pytest assertions are checks that return either True or False status. In Python Pytest, if an assertion fails in a test method, then that method execution is stopped there. The remaining code in that test method is not executed, and Pytest assertions will continue with the next test method.

Should I use assert in Python?

Assert should only be used for testing and debugging — not in production environments. Because assert statements only run when the __debug__ variable is set to True , a Python interpreter can disable them.

What happens when the Python O command is run on a file?

Running Python with the -O or -OO command-line option makes your compiled bytecode smaller. Additionally, if you have several assertions or if __debug__: conditionals, then these command-line options can also make your code faster.


3 Answers

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.

like image 179
Artimi Avatar answered Oct 06 '22 00:10

Artimi


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
like image 42
vidstige Avatar answered Oct 05 '22 23:10

vidstige


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")
like image 35
kindall Avatar answered Oct 06 '22 00:10

kindall