Skip to content

Commit bf220d5

Browse files
committed
add assert that cancel scope triggered on server, add comments for readability
1 parent a0164f9 commit bf220d5

File tree

1 file changed

+18
-5
lines changed

1 file changed

+18
-5
lines changed

tests/shared/test_session.py

Lines changed: 18 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ async def test_request_cancellation():
4646
# The tool is already registered in the fixture
4747

4848
ev_tool_called = anyio.Event()
49+
ev_tool_cancelled = anyio.Event()
4950
ev_cancelled = anyio.Event()
5051
ev_cancel_notified = anyio.Event()
5152

@@ -56,11 +57,17 @@ def make_server() -> Server:
5657
# Register the tool handler
5758
@server.call_tool()
5859
async def handle_call_tool(name: str, arguments: dict | None) -> list:
59-
nonlocal ev_tool_called
60+
nonlocal ev_tool_called, ev_tool_cancelled
6061
if name == "slow_tool":
6162
ev_tool_called.set()
62-
await anyio.sleep(10) # Long enough to ensure we can cancel
63-
return []
63+
with anyio.CancelScope():
64+
try:
65+
await anyio.sleep(10) # Long enough to ensure we can cancel
66+
return []
67+
except anyio.get_cancelled_exc_class() as err:
68+
ev_tool_cancelled.set()
69+
raise err
70+
6471
raise ValueError(f"Unknown tool: {name}")
6572

6673
@server.cancel_notification()
@@ -111,11 +118,17 @@ async def make_request(client_session):
111118
with anyio.fail_after(1): # Timeout after 1 second
112119
await ev_tool_called.wait()
113120

121+
# cancel the task via task group
114122
tg.cancel_scope.cancel()
115123

124+
# Give cancellation time to process
125+
with anyio.fail_after(1):
126+
await ev_cancelled.wait()
127+
128+
# check server cancel notification received
116129
with anyio.fail_after(1):
117130
await ev_cancel_notified.wait()
118131

119-
# Give cancellation time to process
132+
# Give cancellation time to process on server
120133
with anyio.fail_after(1):
121-
await ev_cancelled.wait()
134+
await ev_tool_cancelled.wait()

0 commit comments

Comments
 (0)