Replies: 2 comments 2 replies
-
def assert_contains(container, items):
matching_items = [item for item in items if item in container]
assert matching_items == items Oh, just realised that this of course requires the items to be in the same order, which is not what I want. But I don't want to use I want to do only a single |
Beta Was this translation helpful? Give feedback.
0 replies
-
The unordered plugin provides orders defying helpers for those cases |
Beta Was this translation helpful? Give feedback.
2 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Does anyone know of a good way to assert that a container contains each one of several items, while ignoring the order and also ignoring other items that the container might contain?
The obvious way to write it is like this:
This test will fail because
result
contains neither4
nor5
. Note that result does contain2
and3
, which are not inexpected_items
, but this would not cause the test to fail:2
and3
should be ignored.The above code works fine but it doesn't produce an ideal error message. Because we've used multiple
assert
's in afor
loop, the error message only reports about the first item that was missing (4
).Ideally it would report that
5
is also missing. I guess you could do something like this:This results in a better failure message:
Note that I'm trying to avoid things like requiring the items to be sortable (to use
sorted()
) or hashable (to useset()
).That's a bit much to write if you have a lot of tests that need to do this type of assertion. You could write a global helper function for it:
That's better but it does make the failure messages a bit longer because the failing assertion is actually in the
assert_contains()
helper (which would probably be in some other file likeconftest.py
or somewhere):Is there a better way, or am I on the right track?
Thanks
Beta Was this translation helpful? Give feedback.
All reactions