Skip to content

Instantly share code, notes, and snippets.

@soxofaan

soxofaan/ignore_order.py

Last active Nov 3, 2020
Embed
What would you like to do?
Order ignoring list/tuple comparison asserts for pytest
from typing import Union
class IgnoreOrder:
"""
pytest helper to test equality of lists/tuples ignoring item order
E.g., these asserts pass:
>>> assert [1, 2, 3, 3] == IgnoreOrder([3, 1, 2, 3])
>>> assert {"foo": [1, 2, 3]} == {"foo": IgnoreOrder([3, 2, 1])}
"""
def __init__(self, items: Union[list, tuple], key=None):
self.items = items
self.key = key
def __eq__(self, other):
return type(other) == type(self.items) and sorted(other, key=self.key) == sorted(self.items, key=self.key)
def __repr__(self):
return '{c}({v!r})'.format(c=self.__class__.__name__, v=self.items)
def test_ignore_order_basic_lists():
assert [1, 2, 3] == IgnoreOrder([1, 2, 3])
assert IgnoreOrder([1, 2, 3]) == [1, 2, 3]
assert [1, 2, 3] == IgnoreOrder([3, 1, 2])
assert IgnoreOrder([3, 1, 2]) == [1, 2, 3]
assert [1, 2, 3, 3] == IgnoreOrder([3, 1, 2, 3])
assert IgnoreOrder([3, 1, 2, 3]) == [1, 2, 3, 3]
def test_ignore_order_basic_tuples():
assert (1, 2, 3) == IgnoreOrder((1, 2, 3))
assert IgnoreOrder((1, 2, 3)) == (1, 2, 3)
assert (1, 2, 3) == IgnoreOrder((3, 1, 2))
assert IgnoreOrder((3, 1, 2)) == (1, 2, 3)
assert (1, 2, 3, 3) == IgnoreOrder((3, 1, 2, 3))
assert IgnoreOrder((3, 1, 2, 3)) == (1, 2, 3, 3)
def test_ignore_order_basic_list_vs_tuples():
assert [1, 2, 3] != IgnoreOrder((1, 2, 3))
assert (1, 2, 3) != IgnoreOrder([1, 2, 3])
assert IgnoreOrder((1, 2, 3)) != [1, 2, 3]
assert IgnoreOrder([1, 2, 3]) != (1, 2, 3)
def test_ignore_order_nesting():
assert {"foo": [1, 2, 3]} == {"foo": IgnoreOrder([3, 2, 1])}
assert {"foo": [1, 2, 3], "bar": [4, 5]} == {"foo": IgnoreOrder([3, 2, 1]), "bar": [4, 5]}
assert {"foo": [1, 2, 3], "bar": [4, 5]} != {"foo": IgnoreOrder([3, 2, 1]), "bar": [5, 4]}
def test_ignore_order_key():
assert [{"f": "b"}, {"x": "y:"}] == IgnoreOrder([{"x": "y:"}, {"f": "b"}], key=repr)
@soxofaan

This comment has been minimized.

Copy link
Owner Author

@soxofaan soxofaan commented Nov 3, 2020

Also see https://github.com/utapyngo/pytest-unordered for a nicely packaged version of this

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment