@@ -520,3 +520,39 @@ def charts(year: str) -> list[_Chart]:
520520
521521 template = ResourceTemplate .from_function (charts , uri_template = "charts://{year}" )
522522 assert template .uri_template == "charts://{year}"
523+
524+
525+ @pytest .mark .anyio
526+ async def test_template_read_avoids_extra_worker_thread_hop (monkeypatch : pytest .MonkeyPatch ) -> None :
527+ """Reading a resource created from a template should not hop to a worker thread just to return the value."""
528+ import anyio .to_thread
529+
530+ hops = 0
531+ real_run_sync = anyio .to_thread .run_sync
532+
533+ async def counting_run_sync (func : Any , * args : Any , ** kwargs : Any ) -> Any :
534+ nonlocal hops
535+ hops += 1
536+ return await real_run_sync (func , * args , ** kwargs )
537+
538+ monkeypatch .setattr (anyio .to_thread , "run_sync" , counting_run_sync )
539+
540+ def sync_user (user_id : str ) -> str :
541+ return f"user { user_id } "
542+
543+ async def async_order (order_id : str ) -> str :
544+ return f"order { order_id } "
545+
546+ sync_template = ResourceTemplate .from_function (fn = sync_user , uri_template = "users://{user_id}" )
547+ async_template = ResourceTemplate .from_function (fn = async_order , uri_template = "orders://{order_id}" )
548+
549+ sync_resource = await sync_template .create_resource ("users://1" , {"user_id" : "1" }, Context ())
550+ assert isinstance (sync_resource , FunctionResource )
551+ assert await sync_resource .read () == "user 1"
552+ assert hops == 1
553+
554+ hops = 0
555+ async_resource = await async_template .create_resource ("orders://1" , {"order_id" : "1" }, Context ())
556+ assert isinstance (async_resource , FunctionResource )
557+ assert await async_resource .read () == "order 1"
558+ assert hops == 0
0 commit comments