|
1 | 1 | import asyncio |
| 2 | +import contextlib |
2 | 3 | import json |
3 | 4 | import time |
4 | 5 |
|
@@ -124,6 +125,60 @@ async def test_a_server_error_is_retried(monkeypatch): |
124 | 125 | assert batches[-1].events == [{"i": 0}] |
125 | 126 |
|
126 | 127 |
|
| 128 | +@contextlib.asynccontextmanager |
| 129 | +async def _following(agent: _Agent, stop: asyncio.Event, *, poll_interval_seconds: float): |
| 130 | + """A follower of ``agent``'s task, yielded once it has made its first read; cancelled on the way out |
| 131 | + if it is still running, so a failing test leaves no follower behind.""" |
| 132 | + |
| 133 | + async def sink(batch: TrajectoryBatch) -> None: |
| 134 | + pass |
| 135 | + |
| 136 | + async def follow() -> None: |
| 137 | + async with agent.client() as client: |
| 138 | + await follow_trajectory( |
| 139 | + _ENDPOINT, "task-1", sink, poll_interval_seconds=poll_interval_seconds, stop=stop, client=client |
| 140 | + ) |
| 141 | + |
| 142 | + follower = asyncio.create_task(follow()) |
| 143 | + try: |
| 144 | + async with asyncio.timeout(5): |
| 145 | + while not agent.afters: |
| 146 | + await asyncio.sleep(0.01) |
| 147 | + yield follower |
| 148 | + finally: |
| 149 | + follower.cancel() |
| 150 | + await asyncio.wait({follower}) |
| 151 | + |
| 152 | + |
| 153 | +@pytest.mark.asyncio |
| 154 | +async def test_a_follower_cancelled_as_it_is_stopped_ends(): |
| 155 | + """A step's teardown sets ``stop`` and cancels its follower in the same tick. The agent keeps |
| 156 | + answering, so only the cancel can end the follower; on Python 3.11 ``asyncio.wait_for`` dropped it.""" |
| 157 | + agent = _Agent(*[httpx.Response(200, json=_page(0, [], "running"))] * 100) |
| 158 | + stop = asyncio.Event() |
| 159 | + async with _following(agent, stop, poll_interval_seconds=30) as follower: |
| 160 | + stop.set() |
| 161 | + follower.cancel() |
| 162 | + |
| 163 | + done, _ = await asyncio.wait({follower}, timeout=2) |
| 164 | + |
| 165 | + assert done == {follower} |
| 166 | + assert follower.cancelled() |
| 167 | + |
| 168 | + |
| 169 | +@pytest.mark.asyncio |
| 170 | +async def test_an_agent_that_fails_after_the_turn_ends_ends_following(): |
| 171 | + agent = _Agent(httpx.Response(200, json=_page(0, [], "running")), *[httpx.Response(503)] * 100) |
| 172 | + stop = asyncio.Event() |
| 173 | + async with _following(agent, stop, poll_interval_seconds=30) as follower: |
| 174 | + stop.set() |
| 175 | + |
| 176 | + async with asyncio.timeout(2): |
| 177 | + await follower |
| 178 | + |
| 179 | + assert agent.afters == [0, 0] |
| 180 | + |
| 181 | + |
127 | 182 | @pytest.mark.asyncio |
128 | 183 | async def test_a_task_the_agent_no_longer_knows_ends_following(): |
129 | 184 | agent = _Agent(httpx.Response(404, json={"detail": "Unknown task"})) |
|
0 commit comments