remotivelabs.topology.testing
Utilities for validating network communication.
Capturing frames
Use remotivelabs.topology.testing.frames.capture_frames to subscribe to CAN frames from a
namespace and assert on the received frames and signal values:
from remotivelabs.broker import BrokerClient
from remotivelabs.topology.testing.frames import capture_frames
async def test_hazard_light_sequence(broker_client: BrokerClient) -> None:
# Subscribe to frames published by the HazardLightControlUnit behavioral model
async with capture_frames(
(broker_client, "HazardLightControlUnit-DriverCan0"),
frames=["HazardLightButton"],
) as cap:
# Assert that the signal transitions 0 → 1 → 0 (button press and release)
await cap.wait_for_signal_values(
"HazardLightButton",
"HazardLightButton.HazardLightButton",
values=[0, 1, 0],
timeout=5.0,
)
Capturing SOME/IP events
Use remotivelabs.topology.testing.some_ip.capture_events to subscribe to SOME/IP events:
from remotivelabs.broker import BrokerClient
from remotivelabs.topology.testing.some_ip import capture_events
MY_SERVICE = "MyTestService"
SPEED_EVENT = (MY_SERVICE, "SpeedEvent")
async def test_speed_event_sequence(broker_client: BrokerClient) -> None:
async with capture_events(
(broker_client, "consuming_service", 99),
events=[SPEED_EVENT],
) as cap:
# Wait for the speed to reach 50, then drop back to 0
await cap.wait_for_event_parameter_values(SPEED_EVENT, "speed", values=[50, 0], timeout=5.0)
Polling assertions
For lower-level polling assertions, install the optional PyHamcrest extras:
pip install remotivelabs-topology[hamcrest]
remotivelabs.topology.testing.hamcrest.await_at_most provides a fluent retry API with signal
value matchers:
from remotivelabs.broker import BrokerClient, FrameSubscription, SignalValue
from remotivelabs.topology.namespaces.can import CanNamespace
from remotivelabs.topology.testing.hamcrest import await_at_most, contains_signal_value_sequence
async def test_signal_sequence(broker_client: BrokerClient) -> None:
async with CanNamespace("HazardLightControlUnit-DriverCan0", broker_client) as ns:
stream = await ns.subscribe_frames(FrameSubscription(name="HazardLightButton"))
values: list[SignalValue] = []
async def consume_next() -> list[SignalValue]:
frame = await anext(stream)
values.append(frame.signals["HazardLightButton.HazardLightButton"])
return values
# Assert the button transitions 0 → 1 → 0 within 5 seconds
await await_at_most(5).until(consume_next, contains_signal_value_sequence(0, 1, 0))
See remotivelabs.topology.testing.hamcrest for details.
1""" 2Utilities for validating network communication. 3 4## Capturing frames 5 6<!-- start-include --> 7Use `remotivelabs.topology.testing.frames.capture_frames` to subscribe to CAN frames from a 8namespace and assert on the received frames and signal values: 9 10```python 11.. include:: ../_docs/snippets/testing_capture_frames.py 12``` 13<!-- end-include --> 14 15## Capturing SOME/IP events 16 17<!-- start-include2 --> 18Use `remotivelabs.topology.testing.some_ip.capture_events` to subscribe to SOME/IP events: 19 20```python 21.. include:: ../_docs/snippets/testing_capture_events.py 22``` 23<!-- end-include2 --> 24 25## Polling assertions 26 27For lower-level polling assertions, install the optional 28[PyHamcrest](https://pypi.org/project/PyHamcrest/) extras: 29 30```bash 31pip install remotivelabs-topology[hamcrest] 32``` 33 34`remotivelabs.topology.testing.hamcrest.await_at_most` provides a fluent retry API with signal 35value matchers: 36 37```python 38.. include:: ../_docs/snippets/testing_hamcrest.py 39``` 40 41See `remotivelabs.topology.testing.hamcrest` for details. 42""" 43 44from remotivelabs.topology.testing import hamcrest 45from remotivelabs.topology.testing.capture import Capture 46from remotivelabs.topology.testing.frames import FrameCapture, capture_frames 47from remotivelabs.topology.testing.some_ip import SomeIPCapture, capture_events 48 49__all__ = [ 50 "hamcrest", 51 "Capture", 52 "FrameCapture", 53 "capture_frames", 54 "SomeIPCapture", 55 "capture_events", 56]
65class Capture(Generic[T]): 66 """ 67 Utility for capturing items from an async iterator in a background task. 68 69 The Capture instance is stateful: each successful call to a wait or retrieval method advances the internal position, so subsequent calls 70 operate on new items. This enables sequential, windowed assertions and waits within a single capture context. 71 """ 72 73 def __init__( 74 self, 75 iterator: AsyncIterator[T], 76 name: str | None = None, 77 subscribed_frames: list[str] | None = None, 78 ): 79 self._iterator = iterator 80 self._name = name or f"capture-{id(iterator):x}" 81 self._task: asyncio.Task[None] | None = None 82 self._cursor: int = 0 83 self._results: list[T] = [] 84 self._subscribed_frames = subscribed_frames 85 86 async def __aenter__(self) -> Capture[T]: 87 loop = asyncio.get_running_loop() 88 self._task = loop.create_task(self._consume()) 89 await asyncio.sleep(0) # Yield control to let task start 90 _logger.debug(f"Capture [{self._name}]: Started listening.") 91 return self 92 93 async def __aexit__(self, exc_type: Any, exc_val: Any, exc_tb: Any) -> None: 94 if self._task: 95 self._task.cancel() 96 try: 97 await self._task 98 except asyncio.CancelledError: 99 # Only propagate CancelledError if the context manager (main task, not self._task) is being cancelled. 100 # Since we cancelled self._task ourselves, we don't want to propagate its CancelledError 101 if exc_type is asyncio.CancelledError: 102 raise 103 _logger.debug(f"Capture [{self._name}]: Stopped listening. Total captured: {len(self._results)}.") 104 105 async def _consume(self) -> None: 106 async for item in self._iterator: 107 self._results.append(item) 108 109 @property 110 def results(self) -> list[T]: 111 """Return a list of all captured items.""" 112 return list(self._results) 113 114 def _raise_timeout(self, timeout: float, waiting_for: str) -> Never: 115 """Raise a CaptureTimeoutError with context.""" 116 raise CaptureTimeoutError( 117 name=self._name, 118 captured=self.results, 119 timeout=timeout, 120 subscribed_frames=self._subscribed_frames, 121 waiting_for=waiting_for, 122 ) from None 123 124 async def next(self, timeout: float = 1.0) -> T: 125 """ 126 Wait for and return the next captured item. 127 128 Resumes from the last read position. 129 """ 130 131 def check() -> T: 132 if self._cursor < len(self._results): 133 item = self._results[self._cursor] 134 self._cursor += 1 135 return item 136 raise ValueError("waiting for next item") 137 138 try: 139 return await retry(check, timeout=timeout) 140 except TimeoutError: 141 self._raise_timeout(timeout, "next item") 142 143 async def wait_for_item( 144 self, 145 predicate: Callable[[T], bool], 146 timeout: float = 1.0, 147 waiting_for: str = "item matching predicate", 148 ) -> T: 149 """ 150 Wait for an item matching a predicate. 151 152 Args: 153 predicate: Predicate to match items. 154 timeout: Maximum time to wait in seconds. 155 waiting_for: Description of what is being waited for (used in timeout error). 156 157 Returns: 158 The matching item. 159 160 Raises: 161 CaptureTimeoutError: If no matching item is received in time. 162 """ 163 164 def check() -> T: 165 while self._cursor < len(self._results): 166 item = self._results[self._cursor] 167 self._cursor += 1 168 if predicate(item): 169 return item 170 raise ValueError("waiting for item matching predicate") 171 172 try: 173 return await retry(check, timeout=timeout) 174 except TimeoutError: 175 self._raise_timeout(timeout, waiting_for) 176 177 async def wait_for_items( 178 self, 179 predicates: Sequence[Callable[[T], bool]], 180 timeout: float = 1.0, 181 ) -> list[T]: 182 """ 183 Wait for a sequence of items matching the predicates in order. 184 185 Items that do not match the current predicate are skipped. This is intentional for 186 interleaved sequences (e.g. waiting for frames A, B, A across a mixed stream), but 187 means unexpected values are silently ignored rather than causing immediate failure. 188 189 Note: 190 A future `strict` mode could fail immediately on mismatch using a private 191 exception that does not inherit from `Exception` (so it escapes the broad 192 `except Exception` in `retry`). 193 194 Args: 195 predicates: A sequence of predicate functions to match in order. 196 timeout: Maximum time to wait for the entire sequence. 197 198 Returns: 199 A list of items matching each predicate in order. 200 201 Raises: 202 CaptureTimeoutError: If the sequence is not received in time. 203 """ 204 205 matched: list[T] = [] 206 207 def check() -> list[T]: 208 while self._cursor < len(self._results) and len(matched) < len(predicates): 209 item = self._results[self._cursor] 210 self._cursor += 1 211 if predicates[len(matched)](item): 212 matched.append(item) 213 if len(matched) >= len(predicates): 214 return matched 215 raise ValueError(f"waiting for sequence, matched {len(matched)}/{len(predicates)}") 216 217 try: 218 return await retry(check, timeout=timeout) 219 except TimeoutError: 220 self._raise_timeout(timeout, f"sequence of {len(predicates)} items")
Utility for capturing items from an async iterator in a background task.
The Capture instance is stateful: each successful call to a wait or retrieval method advances the internal position, so subsequent calls operate on new items. This enables sequential, windowed assertions and waits within a single capture context.
73 def __init__( 74 self, 75 iterator: AsyncIterator[T], 76 name: str | None = None, 77 subscribed_frames: list[str] | None = None, 78 ): 79 self._iterator = iterator 80 self._name = name or f"capture-{id(iterator):x}" 81 self._task: asyncio.Task[None] | None = None 82 self._cursor: int = 0 83 self._results: list[T] = [] 84 self._subscribed_frames = subscribed_frames
109 @property 110 def results(self) -> list[T]: 111 """Return a list of all captured items.""" 112 return list(self._results)
Return a list of all captured items.
124 async def next(self, timeout: float = 1.0) -> T: 125 """ 126 Wait for and return the next captured item. 127 128 Resumes from the last read position. 129 """ 130 131 def check() -> T: 132 if self._cursor < len(self._results): 133 item = self._results[self._cursor] 134 self._cursor += 1 135 return item 136 raise ValueError("waiting for next item") 137 138 try: 139 return await retry(check, timeout=timeout) 140 except TimeoutError: 141 self._raise_timeout(timeout, "next item")
Wait for and return the next captured item.
Resumes from the last read position.
143 async def wait_for_item( 144 self, 145 predicate: Callable[[T], bool], 146 timeout: float = 1.0, 147 waiting_for: str = "item matching predicate", 148 ) -> T: 149 """ 150 Wait for an item matching a predicate. 151 152 Args: 153 predicate: Predicate to match items. 154 timeout: Maximum time to wait in seconds. 155 waiting_for: Description of what is being waited for (used in timeout error). 156 157 Returns: 158 The matching item. 159 160 Raises: 161 CaptureTimeoutError: If no matching item is received in time. 162 """ 163 164 def check() -> T: 165 while self._cursor < len(self._results): 166 item = self._results[self._cursor] 167 self._cursor += 1 168 if predicate(item): 169 return item 170 raise ValueError("waiting for item matching predicate") 171 172 try: 173 return await retry(check, timeout=timeout) 174 except TimeoutError: 175 self._raise_timeout(timeout, waiting_for)
Wait for an item matching a predicate.
Arguments:
- predicate: Predicate to match items.
- timeout: Maximum time to wait in seconds.
- waiting_for: Description of what is being waited for (used in timeout error).
Returns:
The matching item.
Raises:
- CaptureTimeoutError: If no matching item is received in time.
177 async def wait_for_items( 178 self, 179 predicates: Sequence[Callable[[T], bool]], 180 timeout: float = 1.0, 181 ) -> list[T]: 182 """ 183 Wait for a sequence of items matching the predicates in order. 184 185 Items that do not match the current predicate are skipped. This is intentional for 186 interleaved sequences (e.g. waiting for frames A, B, A across a mixed stream), but 187 means unexpected values are silently ignored rather than causing immediate failure. 188 189 Note: 190 A future `strict` mode could fail immediately on mismatch using a private 191 exception that does not inherit from `Exception` (so it escapes the broad 192 `except Exception` in `retry`). 193 194 Args: 195 predicates: A sequence of predicate functions to match in order. 196 timeout: Maximum time to wait for the entire sequence. 197 198 Returns: 199 A list of items matching each predicate in order. 200 201 Raises: 202 CaptureTimeoutError: If the sequence is not received in time. 203 """ 204 205 matched: list[T] = [] 206 207 def check() -> list[T]: 208 while self._cursor < len(self._results) and len(matched) < len(predicates): 209 item = self._results[self._cursor] 210 self._cursor += 1 211 if predicates[len(matched)](item): 212 matched.append(item) 213 if len(matched) >= len(predicates): 214 return matched 215 raise ValueError(f"waiting for sequence, matched {len(matched)}/{len(predicates)}") 216 217 try: 218 return await retry(check, timeout=timeout) 219 except TimeoutError: 220 self._raise_timeout(timeout, f"sequence of {len(predicates)} items")
Wait for a sequence of items matching the predicates in order.
Items that do not match the current predicate are skipped. This is intentional for interleaved sequences (e.g. waiting for frames A, B, A across a mixed stream), but means unexpected values are silently ignored rather than causing immediate failure.
Note:
A future
strictmode could fail immediately on mismatch using a private exception that does not inherit fromException(so it escapes the broadexcept Exceptioninretry).
Arguments:
- predicates: A sequence of predicate functions to match in order.
- timeout: Maximum time to wait for the entire sequence.
Returns:
A list of items matching each predicate in order.
Raises:
- CaptureTimeoutError: If the sequence is not received in time.
33class FrameCapture: 34 """ 35 Frame-specific capture with typed wait methods. 36 37 Wraps a `Capture[Frame]` and provides methods for waiting on specific frames 38 and signal values. Obtain an instance via `capture_frames`. 39 """ 40 41 def __init__(self, cap: Capture[Frame]) -> None: 42 self._cap = cap 43 44 async def next(self, timeout: float = 1.0) -> Frame: 45 """ 46 Wait for and return the next captured frame. 47 48 Resumes from the last read position. 49 """ 50 return await self._cap.next(timeout=timeout) 51 52 async def wait_for_frame( 53 self, 54 frame: str, 55 signals: dict[str, Any], 56 timeout: float = 1.0, 57 ) -> Frame: 58 """ 59 Wait for a frame matching the given name and signal values. 60 61 Args: 62 frame: The frame name to match. 63 signals: A mapping of signal name to expected value. 64 timeout: Maximum time to wait in seconds. 65 66 Returns: 67 The first matching frame. 68 69 Raises: 70 CaptureTimeoutError: If no matching frame is received in time. 71 """ 72 return await self._cap.wait_for_item( 73 _pred(frame, signals), 74 timeout=timeout, 75 waiting_for=f"frame '{frame}' with signals {signals}", 76 ) 77 78 async def wait_for_frames( 79 self, 80 sequence: Sequence[tuple[str, dict[str, Any]]], 81 timeout: float = 1.0, 82 ) -> list[Frame]: 83 """ 84 Wait for an ordered sequence of frames matching `(frame_name, signals)` pairs. 85 86 Unlike `wait_for_signal_values`, this supports sequences that span multiple different 87 frames interleaved in any order. Frames not matching the current expected pair are skipped. 88 89 Args: 90 sequence: An ordered list of `(frame_name, signals)` pairs to match in sequence. 91 timeout: Maximum time to wait for the entire sequence. 92 93 Returns: 94 A list of frames, one per pair, in order. 95 96 Raises: 97 CaptureTimeoutError: If the full sequence is not received in time. 98 99 Example: 100 ```python 101 await cap.wait_for_frames([ 102 ("TurnLightControl", {"TurnLightControl.LeftTurnLightRequest": 1}), 103 ("SpeedControl", {"SpeedControl.Speed": 0}), 104 ("TurnLightControl", {"TurnLightControl.LeftTurnLightRequest": 0}), 105 ]) 106 ``` 107 """ 108 return await self._cap.wait_for_items( 109 [_pred(name, signals) for name, signals in sequence], 110 timeout=timeout, 111 ) 112 113 async def wait_for_signal_values( 114 self, 115 frame: str, 116 signal: str, 117 values: Sequence[Any], 118 timeout: float = 1.0, 119 ) -> list[Frame]: 120 """ 121 Wait for a sequence of frames where a signal takes each value in order. 122 123 Each value in `values` must appear in a frame (in order). Frames not matching 124 the current expected value are skipped — unexpected values are not treated as failures. 125 126 Args: 127 frame: The frame name to match. 128 signal: The signal name (full path, e.g. `"FrameName.SignalName"`). 129 values: A sequence of expected signal values to observe in order. 130 timeout: Maximum time to wait for the entire sequence. 131 132 Returns: 133 A list of frames, one per value, in order. 134 135 Raises: 136 CaptureTimeoutError: If the full sequence is not received in time. 137 """ 138 return await self._cap.wait_for_items( 139 [_pred(frame, {signal: v}) for v in values], 140 timeout=timeout, 141 )
Frame-specific capture with typed wait methods.
Wraps a Capture[Frame] and provides methods for waiting on specific frames
and signal values. Obtain an instance via capture_frames.
44 async def next(self, timeout: float = 1.0) -> Frame: 45 """ 46 Wait for and return the next captured frame. 47 48 Resumes from the last read position. 49 """ 50 return await self._cap.next(timeout=timeout)
Wait for and return the next captured frame.
Resumes from the last read position.
52 async def wait_for_frame( 53 self, 54 frame: str, 55 signals: dict[str, Any], 56 timeout: float = 1.0, 57 ) -> Frame: 58 """ 59 Wait for a frame matching the given name and signal values. 60 61 Args: 62 frame: The frame name to match. 63 signals: A mapping of signal name to expected value. 64 timeout: Maximum time to wait in seconds. 65 66 Returns: 67 The first matching frame. 68 69 Raises: 70 CaptureTimeoutError: If no matching frame is received in time. 71 """ 72 return await self._cap.wait_for_item( 73 _pred(frame, signals), 74 timeout=timeout, 75 waiting_for=f"frame '{frame}' with signals {signals}", 76 )
Wait for a frame matching the given name and signal values.
Arguments:
- frame: The frame name to match.
- signals: A mapping of signal name to expected value.
- timeout: Maximum time to wait in seconds.
Returns:
The first matching frame.
Raises:
- CaptureTimeoutError: If no matching frame is received in time.
78 async def wait_for_frames( 79 self, 80 sequence: Sequence[tuple[str, dict[str, Any]]], 81 timeout: float = 1.0, 82 ) -> list[Frame]: 83 """ 84 Wait for an ordered sequence of frames matching `(frame_name, signals)` pairs. 85 86 Unlike `wait_for_signal_values`, this supports sequences that span multiple different 87 frames interleaved in any order. Frames not matching the current expected pair are skipped. 88 89 Args: 90 sequence: An ordered list of `(frame_name, signals)` pairs to match in sequence. 91 timeout: Maximum time to wait for the entire sequence. 92 93 Returns: 94 A list of frames, one per pair, in order. 95 96 Raises: 97 CaptureTimeoutError: If the full sequence is not received in time. 98 99 Example: 100 ```python 101 await cap.wait_for_frames([ 102 ("TurnLightControl", {"TurnLightControl.LeftTurnLightRequest": 1}), 103 ("SpeedControl", {"SpeedControl.Speed": 0}), 104 ("TurnLightControl", {"TurnLightControl.LeftTurnLightRequest": 0}), 105 ]) 106 ``` 107 """ 108 return await self._cap.wait_for_items( 109 [_pred(name, signals) for name, signals in sequence], 110 timeout=timeout, 111 )
Wait for an ordered sequence of frames matching (frame_name, signals) pairs.
Unlike wait_for_signal_values, this supports sequences that span multiple different
frames interleaved in any order. Frames not matching the current expected pair are skipped.
Arguments:
- sequence: An ordered list of
(frame_name, signals)pairs to match in sequence. - timeout: Maximum time to wait for the entire sequence.
Returns:
A list of frames, one per pair, in order.
Raises:
- CaptureTimeoutError: If the full sequence is not received in time.
Example:
await cap.wait_for_frames([ ("TurnLightControl", {"TurnLightControl.LeftTurnLightRequest": 1}), ("SpeedControl", {"SpeedControl.Speed": 0}), ("TurnLightControl", {"TurnLightControl.LeftTurnLightRequest": 0}), ])
113 async def wait_for_signal_values( 114 self, 115 frame: str, 116 signal: str, 117 values: Sequence[Any], 118 timeout: float = 1.0, 119 ) -> list[Frame]: 120 """ 121 Wait for a sequence of frames where a signal takes each value in order. 122 123 Each value in `values` must appear in a frame (in order). Frames not matching 124 the current expected value are skipped — unexpected values are not treated as failures. 125 126 Args: 127 frame: The frame name to match. 128 signal: The signal name (full path, e.g. `"FrameName.SignalName"`). 129 values: A sequence of expected signal values to observe in order. 130 timeout: Maximum time to wait for the entire sequence. 131 132 Returns: 133 A list of frames, one per value, in order. 134 135 Raises: 136 CaptureTimeoutError: If the full sequence is not received in time. 137 """ 138 return await self._cap.wait_for_items( 139 [_pred(frame, {signal: v}) for v in values], 140 timeout=timeout, 141 )
Wait for a sequence of frames where a signal takes each value in order.
Each value in values must appear in a frame (in order). Frames not matching
the current expected value are skipped — unexpected values are not treated as failures.
Arguments:
- frame: The frame name to match.
- signal: The signal name (full path, e.g.
"FrameName.SignalName"). - values: A sequence of expected signal values to observe in order.
- timeout: Maximum time to wait for the entire sequence.
Returns:
A list of frames, one per value, in order.
Raises:
- CaptureTimeoutError: If the full sequence is not received in time.
144@asynccontextmanager 145async def capture_frames( 146 source: GenericNamespace | tuple[BrokerClient, NamespaceName], 147 frames: Sequence[Frame | FrameInfo | str] | None = None, 148 name: str | None = None, 149) -> AsyncIterator[FrameCapture]: 150 """ 151 Async context manager to capture frames from a namespace. 152 153 The returned `FrameCapture` object is stateful: each successful call to a wait or retrieval 154 method advances the internal position, so subsequent calls resume from where the last 155 left off. 156 157 Args: 158 source: A `GenericNamespace`, or a `(broker_client, namespace_name)` tuple. 159 frames: Frames to subscribe to. If `None`, subscribes to all frames in the namespace. 160 name: Name for logging. If `None`, generates a unique name. 161 162 Yields: 163 A `FrameCapture` instance. 164 165 Example: 166 ```python 167 async with capture_frames((broker_client, "ecu_b"), ["FrameA"]) as cap: 168 frame = await cap.wait_for_frame("FrameA", {"FrameA.Signal": 1}) 169 ``` 170 """ 171 ns = source if isinstance(source, GenericNamespace) else GenericNamespace(name=source[1], broker_client=source[0]) 172 173 if frames is None: 174 frames = await ns.list_frame_infos() 175 176 frame_names = [f if isinstance(f, str) else f.name for f in frames] 177 subscriptions = [FrameSubscription(name=fn) for fn in frame_names] 178 iterator = await ns.subscribe_frames(*subscriptions) 179 async with Capture(iterator, name=name, subscribed_frames=frame_names) as cap: 180 yield FrameCapture(cap)
Async context manager to capture frames from a namespace.
The returned FrameCapture object is stateful: each successful call to a wait or retrieval
method advances the internal position, so subsequent calls resume from where the last
left off.
Arguments:
- source: A
GenericNamespace, or a(broker_client, namespace_name)tuple. - frames: Frames to subscribe to. If
None, subscribes to all frames in the namespace. - name: Name for logging. If
None, generates a unique name.
Yields:
A
FrameCaptureinstance.
Example:
async with capture_frames((broker_client, "ecu_b"), ["FrameA"]) as cap: frame = await cap.wait_for_frame("FrameA", {"FrameA.Signal": 1})
43class SomeIPCapture: 44 """ 45 SOME/IP-specific capture with typed wait methods. 46 47 Wraps a `Capture[SomeIPEvent]` and provides methods for waiting on specific events 48 and parameter values. Obtain an instance via `capture_events`. 49 """ 50 51 def __init__(self, cap: Capture[SomeIPEvent]) -> None: 52 self._cap = cap 53 54 async def next(self, timeout: float = 1.0) -> SomeIPEvent: 55 """ 56 Wait for and return the next captured event. 57 58 Resumes from the last read position. 59 """ 60 return await self._cap.next(timeout=timeout) 61 62 async def wait_for_event( 63 self, 64 event: SomeIPEventSpec, 65 parameters: dict[ParameterName, Any] | None = None, 66 timeout: float = 1.0, 67 ) -> SomeIPEvent: 68 """ 69 Wait for a SOME/IP event matching the given event spec and optional parameters. 70 71 Args: 72 event: A `(service_name, event_name)` tuple identifying the event to match. 73 parameters: A mapping of parameter name to expected value. If `None`, only the event identity is checked. 74 timeout: Maximum time to wait in seconds. 75 76 Returns: 77 The first matching `SomeIPEvent`. 78 79 Raises: 80 CaptureTimeoutError: If no matching event is received in time. 81 """ 82 service, event_name = event 83 waiting_for = f"event '{event_name}' from service '{service}'" 84 if parameters: 85 waiting_for += f" with parameters {parameters}" 86 return await self._cap.wait_for_item( 87 _pred(event, parameters), 88 timeout=timeout, 89 waiting_for=waiting_for, 90 ) 91 92 async def wait_for_events( 93 self, 94 sequence: Sequence[tuple[SomeIPEventSpec, dict[ParameterName, Any] | None]], 95 timeout: float = 1.0, 96 ) -> list[SomeIPEvent]: 97 """ 98 Wait for an ordered sequence of events matching `(event_spec, parameters)` pairs. 99 100 Unlike `wait_for_event_parameter_values`, this supports sequences that span multiple 101 different events interleaved in any order. Events not matching the current expected 102 pair are skipped. 103 104 Args: 105 sequence: An ordered list of `(event_spec, parameters)` pairs to match in sequence. 106 `parameters` may be `None` to match any event of that type. 107 timeout: Maximum time to wait for the entire sequence. 108 109 Returns: 110 A list of events, one per pair, in order. 111 112 Raises: 113 CaptureTimeoutError: If the full sequence is not received in time. 114 115 Example: 116 ```python 117 await cap.wait_for_events([ 118 (("MyService", "SpeedEvent"), {"speed": 0}), 119 (("MyService", "GearEvent"), {"gear": 1}), 120 (("MyService", "SpeedEvent"), {"speed": 50}), 121 ]) 122 ``` 123 """ 124 return await self._cap.wait_for_items( 125 [_pred(event, parameters) for event, parameters in sequence], 126 timeout=timeout, 127 ) 128 129 async def wait_for_event_parameter_values( 130 self, 131 event: SomeIPEventSpec, 132 parameter: ParameterName, 133 values: Sequence[SignalValue], 134 timeout: float = 1.0, 135 ) -> list[SomeIPEvent]: 136 """ 137 Wait for a sequence of SOME/IP events where a parameter takes each value in order. 138 139 Each value in `values` must appear in an event (in order). Events not matching 140 the current expected value are skipped — unexpected values are not treated as failures. 141 142 Args: 143 event: A `(service_name, event_name)` tuple identifying the event to match. 144 parameter: The parameter name to check. 145 values: A sequence of expected parameter values to observe in order. 146 timeout: Maximum time to wait for the entire sequence. 147 148 Returns: 149 A list of events, one per value, in order. 150 151 Raises: 152 CaptureTimeoutError: If the full sequence is not received in time. 153 """ 154 return await self._cap.wait_for_items( 155 [_pred(event, {parameter: v}) for v in values], 156 timeout=timeout, 157 )
SOME/IP-specific capture with typed wait methods.
Wraps a Capture[SomeIPEvent] and provides methods for waiting on specific events
and parameter values. Obtain an instance via capture_events.
54 async def next(self, timeout: float = 1.0) -> SomeIPEvent: 55 """ 56 Wait for and return the next captured event. 57 58 Resumes from the last read position. 59 """ 60 return await self._cap.next(timeout=timeout)
Wait for and return the next captured event.
Resumes from the last read position.
62 async def wait_for_event( 63 self, 64 event: SomeIPEventSpec, 65 parameters: dict[ParameterName, Any] | None = None, 66 timeout: float = 1.0, 67 ) -> SomeIPEvent: 68 """ 69 Wait for a SOME/IP event matching the given event spec and optional parameters. 70 71 Args: 72 event: A `(service_name, event_name)` tuple identifying the event to match. 73 parameters: A mapping of parameter name to expected value. If `None`, only the event identity is checked. 74 timeout: Maximum time to wait in seconds. 75 76 Returns: 77 The first matching `SomeIPEvent`. 78 79 Raises: 80 CaptureTimeoutError: If no matching event is received in time. 81 """ 82 service, event_name = event 83 waiting_for = f"event '{event_name}' from service '{service}'" 84 if parameters: 85 waiting_for += f" with parameters {parameters}" 86 return await self._cap.wait_for_item( 87 _pred(event, parameters), 88 timeout=timeout, 89 waiting_for=waiting_for, 90 )
Wait for a SOME/IP event matching the given event spec and optional parameters.
Arguments:
- event: A
(service_name, event_name)tuple identifying the event to match. - parameters: A mapping of parameter name to expected value. If
None, only the event identity is checked. - timeout: Maximum time to wait in seconds.
Returns:
The first matching
SomeIPEvent.
Raises:
- CaptureTimeoutError: If no matching event is received in time.
92 async def wait_for_events( 93 self, 94 sequence: Sequence[tuple[SomeIPEventSpec, dict[ParameterName, Any] | None]], 95 timeout: float = 1.0, 96 ) -> list[SomeIPEvent]: 97 """ 98 Wait for an ordered sequence of events matching `(event_spec, parameters)` pairs. 99 100 Unlike `wait_for_event_parameter_values`, this supports sequences that span multiple 101 different events interleaved in any order. Events not matching the current expected 102 pair are skipped. 103 104 Args: 105 sequence: An ordered list of `(event_spec, parameters)` pairs to match in sequence. 106 `parameters` may be `None` to match any event of that type. 107 timeout: Maximum time to wait for the entire sequence. 108 109 Returns: 110 A list of events, one per pair, in order. 111 112 Raises: 113 CaptureTimeoutError: If the full sequence is not received in time. 114 115 Example: 116 ```python 117 await cap.wait_for_events([ 118 (("MyService", "SpeedEvent"), {"speed": 0}), 119 (("MyService", "GearEvent"), {"gear": 1}), 120 (("MyService", "SpeedEvent"), {"speed": 50}), 121 ]) 122 ``` 123 """ 124 return await self._cap.wait_for_items( 125 [_pred(event, parameters) for event, parameters in sequence], 126 timeout=timeout, 127 )
Wait for an ordered sequence of events matching (event_spec, parameters) pairs.
Unlike wait_for_event_parameter_values, this supports sequences that span multiple
different events interleaved in any order. Events not matching the current expected
pair are skipped.
Arguments:
- sequence: An ordered list of
(event_spec, parameters)pairs to match in sequence.parametersmay beNoneto match any event of that type. - timeout: Maximum time to wait for the entire sequence.
Returns:
A list of events, one per pair, in order.
Raises:
- CaptureTimeoutError: If the full sequence is not received in time.
Example:
await cap.wait_for_events([ (("MyService", "SpeedEvent"), {"speed": 0}), (("MyService", "GearEvent"), {"gear": 1}), (("MyService", "SpeedEvent"), {"speed": 50}), ])
129 async def wait_for_event_parameter_values( 130 self, 131 event: SomeIPEventSpec, 132 parameter: ParameterName, 133 values: Sequence[SignalValue], 134 timeout: float = 1.0, 135 ) -> list[SomeIPEvent]: 136 """ 137 Wait for a sequence of SOME/IP events where a parameter takes each value in order. 138 139 Each value in `values` must appear in an event (in order). Events not matching 140 the current expected value are skipped — unexpected values are not treated as failures. 141 142 Args: 143 event: A `(service_name, event_name)` tuple identifying the event to match. 144 parameter: The parameter name to check. 145 values: A sequence of expected parameter values to observe in order. 146 timeout: Maximum time to wait for the entire sequence. 147 148 Returns: 149 A list of events, one per value, in order. 150 151 Raises: 152 CaptureTimeoutError: If the full sequence is not received in time. 153 """ 154 return await self._cap.wait_for_items( 155 [_pred(event, {parameter: v}) for v in values], 156 timeout=timeout, 157 )
Wait for a sequence of SOME/IP events where a parameter takes each value in order.
Each value in values must appear in an event (in order). Events not matching
the current expected value are skipped — unexpected values are not treated as failures.
Arguments:
- event: A
(service_name, event_name)tuple identifying the event to match. - parameter: The parameter name to check.
- values: A sequence of expected parameter values to observe in order.
- timeout: Maximum time to wait for the entire sequence.
Returns:
A list of events, one per value, in order.
Raises:
- CaptureTimeoutError: If the full sequence is not received in time.
160@asynccontextmanager 161async def capture_events( 162 source: SomeIPNamespace | tuple[BrokerClient, NamespaceName, int], 163 events: Sequence[SomeIPEventSpec], 164 name: str | None = None, 165) -> AsyncIterator[SomeIPCapture]: 166 """ 167 Async context manager to capture SOME/IP events from a namespace. 168 169 Args: 170 source: A `SomeIPNamespace`, or a `(broker_client, namespace_name, client_id)` tuple 171 that will be used to create a transient `SomeIPNamespace`. 172 events: A sequence of `(service_name, event_name)` tuples to subscribe to. 173 name: Name for logging. If `None`, generates a unique name. 174 175 Yields: 176 A `SomeIPCapture` instance. 177 178 Example: 179 ```python 180 async with capture_events( 181 some_ip_eth, 182 [("MyTestService", "ByteEncodedMessages")], 183 ) as cap: 184 event = await cap.wait_for_event(("MyTestService", "ByteEncodedMessages")) 185 ``` 186 """ 187 if isinstance(source, tuple): 188 broker_client, namespace_name, client_id = source 189 ns = SomeIPNamespace(name=namespace_name, broker_client=broker_client, client_id=client_id) 190 else: 191 ns = source 192 193 stream = await ns.subscribe(*((name, service) for service, name in events)) 194 async with Capture(stream, name=name) as cap: 195 yield SomeIPCapture(cap)
Async context manager to capture SOME/IP events from a namespace.
Arguments:
- source: A
SomeIPNamespace, or a(broker_client, namespace_name, client_id)tuple that will be used to create a transientSomeIPNamespace. - events: A sequence of
(service_name, event_name)tuples to subscribe to. - name: Name for logging. If
None, generates a unique name.
Yields:
A
SomeIPCaptureinstance.
Example:
async with capture_events( some_ip_eth, [("MyTestService", "ByteEncodedMessages")], ) as cap: event = await cap.wait_for_event(("MyTestService", "ByteEncodedMessages"))