remotivelabs.topology.testing.hamcrest.matchers

  1from __future__ import annotations
  2
  3from hamcrest.core.base_matcher import BaseMatcher, Description, Matcher, T
  4
  5L = list[T]
  6
  7
  8class HasLastElement(BaseMatcher[L]):
  9    """Matcher that passes if the last element of a list satisfies a nested matcher."""
 10
 11    def __init__(self, matcher: Matcher[T]) -> None:
 12        self.matcher = matcher
 13
 14    def _matches(self, item: L) -> bool:
 15        if not item:
 16            return False
 17        item_last = item[-1]
 18        return self.matcher.matches(item_last)
 19
 20    def describe_to(self, description: Description) -> None:
 21        description.append_text("a list with last element").append_description_of(self.matcher)
 22
 23
 24def has_last_element(matcher: Matcher) -> HasLastElement:
 25    """Return a matcher that passes if the last element of a list satisfies `matcher`."""
 26    return HasLastElement(matcher)
 27
 28
 29class EndsWithSequence(BaseMatcher[L]):
 30    """Matcher that passes if a list ends with the given sequence."""
 31
 32    def __init__(self, sequence: L) -> None:
 33        self.sequence = sequence
 34
 35    def _matches(self, item: L) -> bool:
 36        if not item:
 37            return False
 38        # Check if the last n elements of the item match the given sequence
 39        return item[-len(self.sequence) :] == self.sequence
 40
 41    def describe_to(self, description: Description) -> None:
 42        description.append_text(f"a list ending with {self.sequence}")
 43
 44
 45def ends_with_signal_value_sequence(sequence: L) -> EndsWithSequence:
 46    """Return a matcher that passes if a list ends with `sequence`."""
 47    return EndsWithSequence(sequence)
 48
 49
 50class ContainsContiguousSublist(BaseMatcher[L]):
 51    """Matcher that passes if a list contains the given values as a contiguous subsequence.
 52
 53    Consecutive duplicate values in the observed list are collapsed before matching,
 54    unless the expected sublist itself contains consecutive duplicates.
 55    """
 56
 57    def __init__(self, *sublist: T) -> None:
 58        self.sublist = list(sublist)
 59
 60    def _has_consecutive_duplicates(self, seq: list) -> bool:
 61        return any(a == b for a, b in zip(seq, seq[1:]))
 62
 63    def _matches(self, item: L) -> bool:
 64        if not item:
 65            return False
 66
 67        if not self._has_consecutive_duplicates(self.sublist):
 68            filtered = [item[0]] if item else []
 69            for v in item[1:]:
 70                if v != filtered[-1]:
 71                    filtered.append(v)
 72        else:
 73            filtered = item
 74
 75        sublist_len = len(self.sublist)
 76        if sublist_len > len(filtered):
 77            return False
 78
 79        for i in range(len(filtered) - sublist_len + 1):
 80            if filtered[i : i + sublist_len] == self.sublist:
 81                return True
 82        return False
 83
 84    def describe_to(self, description: Description) -> None:
 85        description.append_text(f"a list containing the contiguous sublist {self.sublist}")
 86
 87
 88def contains_signal_value_sequence(*sublist: T) -> ContainsContiguousSublist:
 89    """Return a matcher that passes if a list contains `sublist` as a contiguous subsequence."""
 90    return ContainsContiguousSublist(*sublist)
 91
 92
 93class ContainsContiguousSubdict(BaseMatcher[dict[str, L] | dict[str, dict[str, L]]]):
 94    """Matcher that passes if each key in a dict maps to a list containing the expected subsequence."""
 95
 96    def __init__(self, expected: dict[str, L] | dict[str, dict[str, L]]) -> None:
 97        self.expected = expected
 98
 99        self.matchers: dict[str, BaseMatcher] = {
100            key: ContainsContiguousSubdict(subdict_or_sublist)
101            if isinstance(subdict_or_sublist, dict)
102            else contains_signal_value_sequence(*subdict_or_sublist)
103            for key, subdict_or_sublist in expected.items()
104        }
105
106    def _matches(self, actual: dict[str, L] | dict[str, dict[str, L]]) -> bool:
107        for key, matcher in self.matchers.items():
108            if key not in actual or not matcher.matches(actual[key]):
109                return False
110        return True
111
112    def describe_to(self, description: Description) -> None:
113        description.append_text("a dict where each value contains its corresponding contiguous sublist: ")
114        description.append_text(str(self.expected))
115
116
117def contains_signal_value_sequences(expected: dict[str, L] | dict[str, dict[str, L]]) -> ContainsContiguousSubdict:
118    """Return a matcher that passes if each key in a dict contains its expected subsequence."""
119    return ContainsContiguousSubdict(expected)
L = list[~T]
class HasLastElement(hamcrest.core.base_matcher.BaseMatcher[list[~T]]):
 9class HasLastElement(BaseMatcher[L]):
10    """Matcher that passes if the last element of a list satisfies a nested matcher."""
11
12    def __init__(self, matcher: Matcher[T]) -> None:
13        self.matcher = matcher
14
15    def _matches(self, item: L) -> bool:
16        if not item:
17            return False
18        item_last = item[-1]
19        return self.matcher.matches(item_last)
20
21    def describe_to(self, description: Description) -> None:
22        description.append_text("a list with last element").append_description_of(self.matcher)

Matcher that passes if the last element of a list satisfies a nested matcher.

HasLastElement(matcher: hamcrest.core.matcher.Matcher[~T])
12    def __init__(self, matcher: Matcher[T]) -> None:
13        self.matcher = matcher
matcher
def describe_to(self, description: hamcrest.core.description.Description) -> None:
21    def describe_to(self, description: Description) -> None:
22        description.append_text("a list with last element").append_description_of(self.matcher)

Generates a description of the object.

The description may be part of a description of a larger object of which this is just a component, so it should be worded appropriately.

Parameters
  • description: The description to be built or appended to.
def has_last_element( matcher: hamcrest.core.matcher.Matcher) -> HasLastElement:
25def has_last_element(matcher: Matcher) -> HasLastElement:
26    """Return a matcher that passes if the last element of a list satisfies `matcher`."""
27    return HasLastElement(matcher)

Return a matcher that passes if the last element of a list satisfies matcher.

class EndsWithSequence(hamcrest.core.base_matcher.BaseMatcher[list[~T]]):
30class EndsWithSequence(BaseMatcher[L]):
31    """Matcher that passes if a list ends with the given sequence."""
32
33    def __init__(self, sequence: L) -> None:
34        self.sequence = sequence
35
36    def _matches(self, item: L) -> bool:
37        if not item:
38            return False
39        # Check if the last n elements of the item match the given sequence
40        return item[-len(self.sequence) :] == self.sequence
41
42    def describe_to(self, description: Description) -> None:
43        description.append_text(f"a list ending with {self.sequence}")

Matcher that passes if a list ends with the given sequence.

EndsWithSequence(sequence: list[~T])
33    def __init__(self, sequence: L) -> None:
34        self.sequence = sequence
sequence
def describe_to(self, description: hamcrest.core.description.Description) -> None:
42    def describe_to(self, description: Description) -> None:
43        description.append_text(f"a list ending with {self.sequence}")

Generates a description of the object.

The description may be part of a description of a larger object of which this is just a component, so it should be worded appropriately.

Parameters
  • description: The description to be built or appended to.
def ends_with_signal_value_sequence( sequence: list[~T]) -> EndsWithSequence:
46def ends_with_signal_value_sequence(sequence: L) -> EndsWithSequence:
47    """Return a matcher that passes if a list ends with `sequence`."""
48    return EndsWithSequence(sequence)

Return a matcher that passes if a list ends with sequence.

class ContainsContiguousSublist(hamcrest.core.base_matcher.BaseMatcher[list[~T]]):
51class ContainsContiguousSublist(BaseMatcher[L]):
52    """Matcher that passes if a list contains the given values as a contiguous subsequence.
53
54    Consecutive duplicate values in the observed list are collapsed before matching,
55    unless the expected sublist itself contains consecutive duplicates.
56    """
57
58    def __init__(self, *sublist: T) -> None:
59        self.sublist = list(sublist)
60
61    def _has_consecutive_duplicates(self, seq: list) -> bool:
62        return any(a == b for a, b in zip(seq, seq[1:]))
63
64    def _matches(self, item: L) -> bool:
65        if not item:
66            return False
67
68        if not self._has_consecutive_duplicates(self.sublist):
69            filtered = [item[0]] if item else []
70            for v in item[1:]:
71                if v != filtered[-1]:
72                    filtered.append(v)
73        else:
74            filtered = item
75
76        sublist_len = len(self.sublist)
77        if sublist_len > len(filtered):
78            return False
79
80        for i in range(len(filtered) - sublist_len + 1):
81            if filtered[i : i + sublist_len] == self.sublist:
82                return True
83        return False
84
85    def describe_to(self, description: Description) -> None:
86        description.append_text(f"a list containing the contiguous sublist {self.sublist}")

Matcher that passes if a list contains the given values as a contiguous subsequence.

Consecutive duplicate values in the observed list are collapsed before matching, unless the expected sublist itself contains consecutive duplicates.

ContainsContiguousSublist(*sublist: ~T)
58    def __init__(self, *sublist: T) -> None:
59        self.sublist = list(sublist)
sublist
def describe_to(self, description: hamcrest.core.description.Description) -> None:
85    def describe_to(self, description: Description) -> None:
86        description.append_text(f"a list containing the contiguous sublist {self.sublist}")

Generates a description of the object.

The description may be part of a description of a larger object of which this is just a component, so it should be worded appropriately.

Parameters
  • description: The description to be built or appended to.
def contains_signal_value_sequence( *sublist: ~T) -> ContainsContiguousSublist:
89def contains_signal_value_sequence(*sublist: T) -> ContainsContiguousSublist:
90    """Return a matcher that passes if a list contains `sublist` as a contiguous subsequence."""
91    return ContainsContiguousSublist(*sublist)

Return a matcher that passes if a list contains sublist as a contiguous subsequence.

class ContainsContiguousSubdict(hamcrest.core.base_matcher.BaseMatcher[dict[str, list[~T]] | dict[str, dict[str, list[~T]]]]):
 94class ContainsContiguousSubdict(BaseMatcher[dict[str, L] | dict[str, dict[str, L]]]):
 95    """Matcher that passes if each key in a dict maps to a list containing the expected subsequence."""
 96
 97    def __init__(self, expected: dict[str, L] | dict[str, dict[str, L]]) -> None:
 98        self.expected = expected
 99
100        self.matchers: dict[str, BaseMatcher] = {
101            key: ContainsContiguousSubdict(subdict_or_sublist)
102            if isinstance(subdict_or_sublist, dict)
103            else contains_signal_value_sequence(*subdict_or_sublist)
104            for key, subdict_or_sublist in expected.items()
105        }
106
107    def _matches(self, actual: dict[str, L] | dict[str, dict[str, L]]) -> bool:
108        for key, matcher in self.matchers.items():
109            if key not in actual or not matcher.matches(actual[key]):
110                return False
111        return True
112
113    def describe_to(self, description: Description) -> None:
114        description.append_text("a dict where each value contains its corresponding contiguous sublist: ")
115        description.append_text(str(self.expected))

Matcher that passes if each key in a dict maps to a list containing the expected subsequence.

ContainsContiguousSubdict(expected: dict[str, list[~T]] | dict[str, dict[str, list[~T]]])
 97    def __init__(self, expected: dict[str, L] | dict[str, dict[str, L]]) -> None:
 98        self.expected = expected
 99
100        self.matchers: dict[str, BaseMatcher] = {
101            key: ContainsContiguousSubdict(subdict_or_sublist)
102            if isinstance(subdict_or_sublist, dict)
103            else contains_signal_value_sequence(*subdict_or_sublist)
104            for key, subdict_or_sublist in expected.items()
105        }
expected
matchers: dict[str, hamcrest.core.base_matcher.BaseMatcher]
def describe_to(self, description: hamcrest.core.description.Description) -> None:
113    def describe_to(self, description: Description) -> None:
114        description.append_text("a dict where each value contains its corresponding contiguous sublist: ")
115        description.append_text(str(self.expected))

Generates a description of the object.

The description may be part of a description of a larger object of which this is just a component, so it should be worded appropriately.

Parameters
  • description: The description to be built or appended to.
def contains_signal_value_sequences( expected: dict[str, list[~T]] | dict[str, dict[str, list[~T]]]) -> ContainsContiguousSubdict:
118def contains_signal_value_sequences(expected: dict[str, L] | dict[str, dict[str, L]]) -> ContainsContiguousSubdict:
119    """Return a matcher that passes if each key in a dict contains its expected subsequence."""
120    return ContainsContiguousSubdict(expected)

Return a matcher that passes if each key in a dict contains its expected subsequence.