Skip to content

feat(matchers): add ListMatching to match sub-lists #261

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Jun 7, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
35 changes: 35 additions & 0 deletions decoy/matchers.py
Original file line number Diff line number Diff line change
Expand Up @@ -250,6 +250,41 @@ def DictMatching(values: Mapping[str, Any]) -> Any:
return _DictMatching(values)


class _ListMatching:
_values: List[Any]

def __init__(self, values: List[Any]) -> None:
self._values = values

def __eq__(self, target: object) -> bool:
"""Return true if target matches all given values."""
if not hasattr(target, "__iter__"):
return False

return all(
any(item == target_item for target_item in target) for item in self._values
)

def __repr__(self) -> str:
"""Return a string representation of the matcher."""
return f"<ListMatching {self._values!r}>"


def ListMatching(values: List[Any]) -> Any:
"""Match any list with the passed in values.

Arguments:
values: Values to check.

!!! example
```python
value = [1, 2, 3]
assert value == matchers.ListMatching([1, 2])
```
"""
return _ListMatching(values)


class _StringMatching:
_pattern: Pattern[str]

Expand Down
23 changes: 23 additions & 0 deletions tests/test_matchers.py
Original file line number Diff line number Diff line change
Expand Up @@ -106,6 +106,29 @@ def test_dict_matching_matcher() -> None:
assert [] != matchers.DictMatching({"hello": "world"})


def test_list_matching_matcher() -> None:
"""It should have a "contains this sub-list" matcher."""
assert [1, 2, 3] == matchers.ListMatching([1])
assert [1, 2, 3] == matchers.ListMatching([1, 2])
assert [1, 2, 3] == matchers.ListMatching([1, 2, 3])
assert [1, 2, 3] != matchers.ListMatching([1, 2, 3, 4])
assert [1] != matchers.ListMatching([1, 2])

assert [{"hello": "world"}, {"yoo": "man"}] == matchers.ListMatching(
[{"hello": "world"}]
)
assert [{"hello": "world"}, {"yoo": "man"}] == matchers.ListMatching(
[{"yoo": "man"}]
)
assert [{"hello": "world"}, {"yoo": "man"}] != matchers.ListMatching(
[{"yoo": "mann"}]
)

assert 1 != matchers.ListMatching([1])

assert str(matchers.ListMatching([1])) == "<ListMatching [1]>"


def test_string_matching_matcher() -> None:
"""It should have an "any string that matches" matcher."""
assert "hello" == matchers.StringMatching("ello")
Expand Down
Loading