|
1 | 1 | import asyncio |
2 | 2 | from collections.abc import Generator |
| 3 | +from typing import Any |
3 | 4 |
|
4 | 5 | import pytest |
5 | 6 |
|
@@ -72,3 +73,48 @@ async def invoke(): |
72 | 73 | runner.run_sync(Agent(name="test-agent"), "input") |
73 | 74 |
|
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() |
0 commit comments