Skip to content

Commit a54b781

Browse files
authored
feat(matchers): add ListMatching to match sub-lists (#261)
1 parent 99af642 commit a54b781

File tree

2 files changed

+58
-0
lines changed

2 files changed

+58
-0
lines changed

decoy/matchers.py

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -250,6 +250,41 @@ def DictMatching(values: Mapping[str, Any]) -> Any:
250250
return _DictMatching(values)
251251

252252

253+
class _ListMatching:
254+
_values: List[Any]
255+
256+
def __init__(self, values: List[Any]) -> None:
257+
self._values = values
258+
259+
def __eq__(self, target: object) -> bool:
260+
"""Return true if target matches all given values."""
261+
if not hasattr(target, "__iter__"):
262+
return False
263+
264+
return all(
265+
any(item == target_item for target_item in target) for item in self._values
266+
)
267+
268+
def __repr__(self) -> str:
269+
"""Return a string representation of the matcher."""
270+
return f"<ListMatching {self._values!r}>"
271+
272+
273+
def ListMatching(values: List[Any]) -> Any:
274+
"""Match any list with the passed in values.
275+
276+
Arguments:
277+
values: Values to check.
278+
279+
!!! example
280+
```python
281+
value = [1, 2, 3]
282+
assert value == matchers.ListMatching([1, 2])
283+
```
284+
"""
285+
return _ListMatching(values)
286+
287+
253288
class _StringMatching:
254289
_pattern: Pattern[str]
255290

tests/test_matchers.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,29 @@ def test_dict_matching_matcher() -> None:
106106
assert [] != matchers.DictMatching({"hello": "world"})
107107

108108

109+
def test_list_matching_matcher() -> None:
110+
"""It should have a "contains this sub-list" matcher."""
111+
assert [1, 2, 3] == matchers.ListMatching([1])
112+
assert [1, 2, 3] == matchers.ListMatching([1, 2])
113+
assert [1, 2, 3] == matchers.ListMatching([1, 2, 3])
114+
assert [1, 2, 3] != matchers.ListMatching([1, 2, 3, 4])
115+
assert [1] != matchers.ListMatching([1, 2])
116+
117+
assert [{"hello": "world"}, {"yoo": "man"}] == matchers.ListMatching(
118+
[{"hello": "world"}]
119+
)
120+
assert [{"hello": "world"}, {"yoo": "man"}] == matchers.ListMatching(
121+
[{"yoo": "man"}]
122+
)
123+
assert [{"hello": "world"}, {"yoo": "man"}] != matchers.ListMatching(
124+
[{"yoo": "mann"}]
125+
)
126+
127+
assert 1 != matchers.ListMatching([1])
128+
129+
assert str(matchers.ListMatching([1])) == "<ListMatching [1]>"
130+
131+
109132
def test_string_matching_matcher() -> None:
110133
"""It should have an "any string that matches" matcher."""
111134
assert "hello" == matchers.StringMatching("ello")

0 commit comments

Comments
 (0)