|
| 1 | +import asyncio |
| 2 | +from collections.abc import Generator |
| 3 | +from typing import Any |
| 4 | + |
| 5 | +import pytest |
| 6 | + |
| 7 | +from agents.agent import Agent |
| 8 | +from agents.run import AgentRunner |
| 9 | + |
| 10 | + |
| 11 | +@pytest.fixture |
| 12 | +def fresh_event_loop_policy() -> Generator[asyncio.AbstractEventLoopPolicy, None, None]: |
| 13 | + policy_before = asyncio.get_event_loop_policy() |
| 14 | + new_policy = asyncio.DefaultEventLoopPolicy() |
| 15 | + asyncio.set_event_loop_policy(new_policy) |
| 16 | + try: |
| 17 | + yield new_policy |
| 18 | + finally: |
| 19 | + asyncio.set_event_loop_policy(policy_before) |
| 20 | + |
| 21 | + |
| 22 | +def test_run_sync_reuses_existing_default_loop(monkeypatch, fresh_event_loop_policy): |
| 23 | + runner = AgentRunner() |
| 24 | + observed_loops: list[asyncio.AbstractEventLoop] = [] |
| 25 | + |
| 26 | + async def fake_run(self, *_args, **_kwargs): |
| 27 | + observed_loops.append(asyncio.get_running_loop()) |
| 28 | + return object() |
| 29 | + |
| 30 | + monkeypatch.setattr(AgentRunner, "run", fake_run, raising=False) |
| 31 | + |
| 32 | + test_loop = asyncio.new_event_loop() |
| 33 | + fresh_event_loop_policy.set_event_loop(test_loop) |
| 34 | + |
| 35 | + try: |
| 36 | + runner.run_sync(Agent(name="test-agent"), "input") |
| 37 | + assert observed_loops and observed_loops[0] is test_loop |
| 38 | + finally: |
| 39 | + fresh_event_loop_policy.set_event_loop(None) |
| 40 | + test_loop.close() |
| 41 | + |
| 42 | + |
| 43 | +def test_run_sync_creates_default_loop_when_missing(monkeypatch, fresh_event_loop_policy): |
| 44 | + runner = AgentRunner() |
| 45 | + observed_loops: list[asyncio.AbstractEventLoop] = [] |
| 46 | + |
| 47 | + async def fake_run(self, *_args, **_kwargs): |
| 48 | + observed_loops.append(asyncio.get_running_loop()) |
| 49 | + return object() |
| 50 | + |
| 51 | + monkeypatch.setattr(AgentRunner, "run", fake_run, raising=False) |
| 52 | + |
| 53 | + fresh_event_loop_policy.set_event_loop(None) |
| 54 | + |
| 55 | + runner.run_sync(Agent(name="test-agent"), "input") |
| 56 | + created_loop = observed_loops[0] |
| 57 | + assert created_loop is fresh_event_loop_policy.get_event_loop() |
| 58 | + |
| 59 | + fresh_event_loop_policy.set_event_loop(None) |
| 60 | + created_loop.close() |
| 61 | + |
| 62 | + |
| 63 | +def test_run_sync_errors_when_loop_already_running(monkeypatch, fresh_event_loop_policy): |
| 64 | + runner = AgentRunner() |
| 65 | + |
| 66 | + async def fake_run(self, *_args, **_kwargs): |
| 67 | + return object() |
| 68 | + |
| 69 | + monkeypatch.setattr(AgentRunner, "run", fake_run, raising=False) |
| 70 | + |
| 71 | + async def invoke(): |
| 72 | + with pytest.raises(RuntimeError): |
| 73 | + runner.run_sync(Agent(name="test-agent"), "input") |
| 74 | + |
| 75 | + asyncio.run(invoke()) |
| 76 | + |
| 77 | + |
| 78 | +def test_run_sync_cancels_task_when_interrupted(monkeypatch, fresh_event_loop_policy): |
| 79 | + runner = AgentRunner() |
| 80 | + |
| 81 | + async def fake_run(self, *_args, **_kwargs): |
| 82 | + await asyncio.sleep(3600) |
| 83 | + |
| 84 | + monkeypatch.setattr(AgentRunner, "run", fake_run, raising=False) |
| 85 | + |
| 86 | + test_loop = asyncio.new_event_loop() |
| 87 | + fresh_event_loop_policy.set_event_loop(test_loop) |
| 88 | + |
| 89 | + created_tasks: list[asyncio.Task[Any]] = [] |
| 90 | + original_create_task = test_loop.create_task |
| 91 | + |
| 92 | + def capturing_create_task(coro): |
| 93 | + task = original_create_task(coro) |
| 94 | + created_tasks.append(task) |
| 95 | + return task |
| 96 | + |
| 97 | + original_run_until_complete = test_loop.run_until_complete |
| 98 | + call_count = {"value": 0} |
| 99 | + |
| 100 | + def interrupt_once(future): |
| 101 | + call_count["value"] += 1 |
| 102 | + if call_count["value"] == 1: |
| 103 | + raise KeyboardInterrupt() |
| 104 | + return original_run_until_complete(future) |
| 105 | + |
| 106 | + monkeypatch.setattr(test_loop, "create_task", capturing_create_task) |
| 107 | + monkeypatch.setattr(test_loop, "run_until_complete", interrupt_once) |
| 108 | + |
| 109 | + try: |
| 110 | + with pytest.raises(KeyboardInterrupt): |
| 111 | + runner.run_sync(Agent(name="test-agent"), "input") |
| 112 | + |
| 113 | + assert created_tasks, "Expected run_sync to schedule a task." |
| 114 | + assert created_tasks[0].done() |
| 115 | + assert created_tasks[0].cancelled() |
| 116 | + assert call_count["value"] >= 2 |
| 117 | + finally: |
| 118 | + monkeypatch.undo() |
| 119 | + fresh_event_loop_policy.set_event_loop(None) |
| 120 | + test_loop.close() |
| 121 | + |
| 122 | + |
| 123 | +def test_run_sync_finalizes_async_generators(monkeypatch, fresh_event_loop_policy): |
| 124 | + runner = AgentRunner() |
| 125 | + cleanup_markers: list[str] = [] |
| 126 | + |
| 127 | + async def fake_run(self, *_args, **_kwargs): |
| 128 | + async def agen(): |
| 129 | + try: |
| 130 | + yield None |
| 131 | + finally: |
| 132 | + cleanup_markers.append("done") |
| 133 | + |
| 134 | + gen = agen() |
| 135 | + await gen.__anext__() |
| 136 | + return "ok" |
| 137 | + |
| 138 | + monkeypatch.setattr(AgentRunner, "run", fake_run, raising=False) |
| 139 | + |
| 140 | + test_loop = asyncio.new_event_loop() |
| 141 | + fresh_event_loop_policy.set_event_loop(test_loop) |
| 142 | + |
| 143 | + try: |
| 144 | + runner.run_sync(Agent(name="test-agent"), "input") |
| 145 | + assert cleanup_markers == ["done"], ( |
| 146 | + "Async generators must be finalized after run_sync returns." |
| 147 | + ) |
| 148 | + finally: |
| 149 | + fresh_event_loop_policy.set_event_loop(None) |
| 150 | + test_loop.close() |
0 commit comments