|
| 1 | +import threading |
| 2 | + |
| 3 | +import anyio |
| 4 | +import anyio.from_thread |
1 | 5 | import pytest |
2 | 6 | from pydantic import BaseModel |
3 | 7 |
|
@@ -190,3 +194,51 @@ def get_data() -> str: # pragma: no cover |
190 | 194 | ) |
191 | 195 |
|
192 | 196 | assert resource.meta is None |
| 197 | + |
| 198 | + |
| 199 | +@pytest.mark.anyio |
| 200 | +async def test_sync_fn_runs_in_worker_thread(): |
| 201 | + """Sync resource functions must run in a worker thread, not the event loop.""" |
| 202 | + |
| 203 | + main_thread = threading.get_ident() |
| 204 | + fn_thread: list[int] = [] |
| 205 | + |
| 206 | + def blocking_fn() -> str: |
| 207 | + fn_thread.append(threading.get_ident()) |
| 208 | + return "data" |
| 209 | + |
| 210 | + resource = FunctionResource(uri="resource://test", name="test", fn=blocking_fn) |
| 211 | + result = await resource.read() |
| 212 | + |
| 213 | + assert result == "data" |
| 214 | + assert fn_thread[0] != main_thread |
| 215 | + |
| 216 | + |
| 217 | +@pytest.mark.anyio |
| 218 | +async def test_sync_fn_does_not_block_event_loop(): |
| 219 | + """A blocking sync resource function must not stall the event loop. |
| 220 | +
|
| 221 | + On regression (sync runs inline), anyio.from_thread.run_sync raises |
| 222 | + RuntimeError because there is no worker-thread context, failing fast. |
| 223 | + """ |
| 224 | + handler_entered = anyio.Event() |
| 225 | + release = threading.Event() |
| 226 | + |
| 227 | + def blocking_fn() -> str: |
| 228 | + anyio.from_thread.run_sync(handler_entered.set) |
| 229 | + release.wait() |
| 230 | + return "done" |
| 231 | + |
| 232 | + resource = FunctionResource(uri="resource://test", name="test", fn=blocking_fn) |
| 233 | + result: list[str | bytes] = [] |
| 234 | + |
| 235 | + async def run() -> None: |
| 236 | + result.append(await resource.read()) |
| 237 | + |
| 238 | + with anyio.fail_after(5): |
| 239 | + async with anyio.create_task_group() as tg: |
| 240 | + tg.start_soon(run) |
| 241 | + await handler_entered.wait() |
| 242 | + release.set() |
| 243 | + |
| 244 | + assert result == ["done"] |
0 commit comments