|
| 1 | +# Copyright (c) Microsoft. All rights reserved. |
| 2 | + |
| 3 | +"""EventStream assertion helper for AG-UI regression tests.""" |
| 4 | + |
| 5 | +from __future__ import annotations |
| 6 | + |
| 7 | +from typing import Any |
| 8 | + |
| 9 | + |
| 10 | +class EventStream: |
| 11 | + """Wraps a list of AG-UI events with structured assertion methods. |
| 12 | +
|
| 13 | + Usage: |
| 14 | + events = [event async for event in agent.run(payload)] |
| 15 | + stream = EventStream(events) |
| 16 | + stream.assert_bookends() |
| 17 | + stream.assert_text_messages_balanced() |
| 18 | + """ |
| 19 | + |
| 20 | + def __init__(self, events: list[Any]) -> None: |
| 21 | + self.events = events |
| 22 | + |
| 23 | + def __len__(self) -> int: |
| 24 | + return len(self.events) |
| 25 | + |
| 26 | + def __iter__(self): |
| 27 | + return iter(self.events) |
| 28 | + |
| 29 | + def types(self) -> list[str]: |
| 30 | + """Return ordered list of event type strings.""" |
| 31 | + return [self._type_str(e) for e in self.events] |
| 32 | + |
| 33 | + def get(self, event_type: str) -> list[Any]: |
| 34 | + """Filter events matching the given type string.""" |
| 35 | + return [e for e in self.events if self._type_str(e) == event_type] |
| 36 | + |
| 37 | + def first(self, event_type: str) -> Any: |
| 38 | + """Return the first event matching the given type, or raise.""" |
| 39 | + matches = self.get(event_type) |
| 40 | + if not matches: |
| 41 | + raise ValueError(f"No event of type {event_type!r} found. Available: {self.types()}") |
| 42 | + return matches[0] |
| 43 | + |
| 44 | + def last(self, event_type: str) -> Any: |
| 45 | + """Return the last event matching the given type, or raise.""" |
| 46 | + matches = self.get(event_type) |
| 47 | + if not matches: |
| 48 | + raise ValueError(f"No event of type {event_type!r} found. Available: {self.types()}") |
| 49 | + return matches[-1] |
| 50 | + |
| 51 | + def snapshot(self) -> dict[str, Any]: |
| 52 | + """Return the latest StateSnapshotEvent snapshot dict.""" |
| 53 | + return self.last("STATE_SNAPSHOT").snapshot |
| 54 | + |
| 55 | + def messages_snapshot(self) -> list[Any]: |
| 56 | + """Return the latest MessagesSnapshotEvent messages list.""" |
| 57 | + return self.last("MESSAGES_SNAPSHOT").messages |
| 58 | + |
| 59 | + # ── Structural assertions ── |
| 60 | + |
| 61 | + def assert_bookends(self) -> None: |
| 62 | + """Assert first event is RUN_STARTED and last is RUN_FINISHED.""" |
| 63 | + types = self.types() |
| 64 | + assert types, "Event stream is empty" |
| 65 | + assert types[0] == "RUN_STARTED", f"Expected RUN_STARTED first, got {types[0]}" |
| 66 | + assert types[-1] == "RUN_FINISHED", f"Expected RUN_FINISHED last, got {types[-1]}" |
| 67 | + |
| 68 | + def assert_has_run_lifecycle(self) -> None: |
| 69 | + """Assert RUN_STARTED is first and RUN_FINISHED exists (may not be last). |
| 70 | +
|
| 71 | + Use this instead of assert_bookends() for workflow resume streams where |
| 72 | + _drain_open_message() can emit TEXT_MESSAGE_END after RUN_FINISHED. |
| 73 | + """ |
| 74 | + types = self.types() |
| 75 | + assert types, "Event stream is empty" |
| 76 | + assert types[0] == "RUN_STARTED", f"Expected RUN_STARTED first, got {types[0]}" |
| 77 | + assert "RUN_FINISHED" in types, f"Expected RUN_FINISHED in stream. Types: {types}" |
| 78 | + |
| 79 | + def assert_strict_types(self, expected: list[str]) -> None: |
| 80 | + """Assert exact type sequence match.""" |
| 81 | + actual = self.types() |
| 82 | + assert actual == expected, f"Event type mismatch.\nExpected: {expected}\nActual: {actual}" |
| 83 | + |
| 84 | + def assert_ordered_types(self, expected: list[str]) -> None: |
| 85 | + """Assert expected types appear as a subsequence (in order, not necessarily contiguous).""" |
| 86 | + actual = self.types() |
| 87 | + actual_idx = 0 |
| 88 | + for expected_type in expected: |
| 89 | + found = False |
| 90 | + while actual_idx < len(actual): |
| 91 | + if actual[actual_idx] == expected_type: |
| 92 | + actual_idx += 1 |
| 93 | + found = True |
| 94 | + break |
| 95 | + actual_idx += 1 |
| 96 | + if not found: |
| 97 | + raise AssertionError( |
| 98 | + f"Expected subsequence type {expected_type!r} not found after index {actual_idx}.\n" |
| 99 | + f"Expected subsequence: {expected}\n" |
| 100 | + f"Actual types: {actual}" |
| 101 | + ) |
| 102 | + |
| 103 | + def assert_text_messages_balanced(self) -> None: |
| 104 | + """Assert every TEXT_MESSAGE_START has a matching TEXT_MESSAGE_END with the same message_id.""" |
| 105 | + starts: dict[str, int] = {} |
| 106 | + ends: set[str] = set() |
| 107 | + for i, event in enumerate(self.events): |
| 108 | + t = self._type_str(event) |
| 109 | + if t == "TEXT_MESSAGE_START": |
| 110 | + mid = event.message_id |
| 111 | + assert mid not in starts, f"Duplicate TEXT_MESSAGE_START for message_id={mid}" |
| 112 | + starts[mid] = i |
| 113 | + elif t == "TEXT_MESSAGE_END": |
| 114 | + mid = event.message_id |
| 115 | + assert mid in starts, f"TEXT_MESSAGE_END for unknown message_id={mid}" |
| 116 | + assert mid not in ends, f"Duplicate TEXT_MESSAGE_END for message_id={mid}" |
| 117 | + ends.add(mid) |
| 118 | + |
| 119 | + unclosed = set(starts.keys()) - ends |
| 120 | + assert not unclosed, f"Unclosed text messages: {unclosed}" |
| 121 | + |
| 122 | + def assert_tool_calls_balanced(self) -> None: |
| 123 | + """Assert every TOOL_CALL_START has a matching TOOL_CALL_END with the same tool_call_id.""" |
| 124 | + starts: dict[str, int] = {} |
| 125 | + ends: set[str] = set() |
| 126 | + for i, event in enumerate(self.events): |
| 127 | + t = self._type_str(event) |
| 128 | + if t == "TOOL_CALL_START": |
| 129 | + tid = event.tool_call_id |
| 130 | + assert tid not in starts, f"Duplicate TOOL_CALL_START for tool_call_id={tid}" |
| 131 | + starts[tid] = i |
| 132 | + elif t == "TOOL_CALL_END": |
| 133 | + tid = event.tool_call_id |
| 134 | + assert tid in starts, f"TOOL_CALL_END for unknown tool_call_id={tid}" |
| 135 | + assert tid not in ends, f"Duplicate TOOL_CALL_END for tool_call_id={tid}" |
| 136 | + ends.add(tid) |
| 137 | + |
| 138 | + unclosed = set(starts.keys()) - ends |
| 139 | + assert not unclosed, f"Unclosed tool calls: {unclosed}" |
| 140 | + |
| 141 | + def assert_no_run_error(self) -> None: |
| 142 | + """Assert no RUN_ERROR events exist.""" |
| 143 | + errors = self.get("RUN_ERROR") |
| 144 | + if errors: |
| 145 | + messages = [getattr(e, "message", str(e)) for e in errors] |
| 146 | + raise AssertionError(f"Found {len(errors)} RUN_ERROR event(s): {messages}") |
| 147 | + |
| 148 | + def assert_has_type(self, event_type: str) -> None: |
| 149 | + """Assert at least one event of the given type exists.""" |
| 150 | + assert event_type in self.types(), f"Expected {event_type!r} in stream. Available: {self.types()}" |
| 151 | + |
| 152 | + def assert_message_ids_consistent(self) -> None: |
| 153 | + """Assert TEXT_MESSAGE_CONTENT events reference valid, open message_ids.""" |
| 154 | + open_messages: set[str] = set() |
| 155 | + for event in self.events: |
| 156 | + t = self._type_str(event) |
| 157 | + if t == "TEXT_MESSAGE_START": |
| 158 | + open_messages.add(event.message_id) |
| 159 | + elif t == "TEXT_MESSAGE_END": |
| 160 | + open_messages.discard(event.message_id) |
| 161 | + elif t == "TEXT_MESSAGE_CONTENT": |
| 162 | + mid = event.message_id |
| 163 | + assert mid in open_messages, f"TEXT_MESSAGE_CONTENT references message_id={mid} which is not open" |
| 164 | + |
| 165 | + # ── Internal ── |
| 166 | + |
| 167 | + @staticmethod |
| 168 | + def _type_str(event: Any) -> str: |
| 169 | + """Extract event type as a plain string.""" |
| 170 | + t = getattr(event, "type", None) |
| 171 | + if t is None: |
| 172 | + return type(event).__name__ |
| 173 | + if isinstance(t, str): |
| 174 | + return t |
| 175 | + return getattr(t, "value", str(t)) |
0 commit comments