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
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.
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.
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.
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.
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
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With