@@ -59,45 +59,40 @@ def sync_function():
5959@pytest .mark .asyncio
6060async def test_sync_to_async_contextvars_with_custom_context ():
6161 """
62- Test that passing a custom context to `sync_to_async` ensures that changes to
63- context variables within the synchronous function are isolated to the
64- provided context and do not affect the caller's context. Specifically,
65- verifies that modifications to a context variable inside the
66- sync function are reflected only in the custom context and not in the
67- outer context.
62+ Passing a custom context to `sync_to_async` ensures that changes to context
63+ variables within the synchronous function are isolated to the provided
64+ context and do not affect the caller's context. Specifically, verifies that
65+ modifications to a context variable inside the sync function are reflected
66+ only in the custom context and not in the outer context.
6867 """
69- # Define sync function
68+
7069 def sync_function ():
7170 time .sleep (1 )
7271 assert foo .get () == "bar"
7372 foo .set ("baz" )
7473 return 42
7574
76- # Ensure outermost detection works
77- # Wrap it
7875 foo .set ("bar" )
7976 context = contextvars .copy_context ()
77+
8078 async_function = sync_to_async (sync_function , context = context )
8179 assert await async_function () == 42
8280
83- # verify that the current context remains unchanged
81+ # Current context remains unchanged.
8482 assert foo .get () == "bar"
8583
86- # verify that the custom context reflects the changes made within the
87- # sync function
84+ # Custom context reflects the changes made within the sync function.
8885 assert context .get (foo ) == "baz"
8986
9087
9188@pytest .mark .asyncio
9289@pytest .mark .skipif (sys .version_info < (3 , 11 ), reason = "requires python3.11" )
9390async def test_sync_to_async_contextvars_with_custom_context_and_parallel_tasks ():
9491 """
95- Test that using a custom context with `sync_to_async` and asyncio tasks
96- isolates contextvars changes, leaving the original context unchanged and
97- reflecting all modifications in the custom context.
92+ Using a custom context with `sync_to_async` and asyncio tasks isolates
93+ contextvars changes, leaving the original context unchanged and reflecting
94+ all modifications in the custom context.
9895 """
99- # Ensure outermost detection works
100- # Wrap it
10196 foo .set ("" )
10297
10398 def sync_function ():
@@ -117,11 +112,10 @@ async def async_function():
117112 asyncio .create_task (async_function (), context = context ),
118113 )
119114
120- # verify that the current context remains unchanged
115+ # Current context remains unchanged
121116 assert foo .get () == ""
122117
123- # verify that the custom context reflects the changes made within the
124- # sync function
118+ # Custom context reflects the changes made within all the gathered tasks.
125119 assert context .get (foo ) == "1111"
126120
127121
0 commit comments