Reputation: 720
I wrote a custom assert function to compare items in two lists such that the order is not important, using pytest_assertrepr_compare. This works fine and reports a failure when the content of the lists differ.
However, if the custom assert passes, it fails on the default '==' assert because item 0 of one list is unequal to item 0 of the other list.
Is there a way to prevent the default assert to kick in?
assert ['a', 'b', 'c'] == ['b', 'a', 'c'] # custom assert passes
# default assert fails
The custom assert function is:
def pytest_assertrepr_compare(config, op, left, right):
equal = True
if op == '==' and isinstance(left, list) and isinstance(right, list):
if len(left) != len(right):
equal = False
else:
for l in left:
if not l in right:
equal = False
if equal:
for r in right:
if not r in left:
equal = False
if not equal:
return ['Comparing lists:',
' vals: %s != %s' % (left, right)]
Upvotes: 2
Views: 3912
Reputation: 2362
I found easiest way to combinate py.test & pyhamcrest. In your example it is easy to use contains_inanyorder
matcher:
from hamcrest import assert_that, contains_inanyorder
def test_first():
assert_that(['a', 'b', 'c'], contains_inanyorder('b', 'a', 'c'))
Upvotes: 3
Reputation: 29
You could use a python set
assert set(['a', 'b', 'c']) == set(['b', 'a', 'c'])
This will return true
Upvotes: 2