Skip to content

Commit d531c75

Browse files
add test case
1 parent d475316 commit d531c75

File tree

1 file changed

+26
-0
lines changed

1 file changed

+26
-0
lines changed

tornado/test/asyncio_test.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@
1111
# under the License.
1212

1313
import asyncio
14+
import contextvars
1415
import threading
1516
import time
1617
import unittest
@@ -261,3 +262,28 @@ def test_tornado_accessor(self):
261262
asyncio.set_event_loop_policy(self.AnyThreadEventLoopPolicy())
262263
self.assertIsInstance(self.executor.submit(IOLoop.current).result(), IOLoop)
263264
self.executor.submit(lambda: asyncio.get_event_loop().close()).result() # type: ignore
265+
266+
267+
class SelectorThreadContextvarsTest(AsyncHTTPTestCase):
268+
ctx_value = 'foo'
269+
test_endpoint = '/'
270+
tornado_test_ctx = contextvars.ContextVar('tornado_test_ctx', default='default')
271+
tornado_test_ctx.set(ctx_value)
272+
273+
def get_app(self) -> Application:
274+
tornado_test_ctx = self.tornado_test_ctx
275+
276+
class Handler(RequestHandler):
277+
async def get(self):
278+
# On the Windows platform,
279+
# when a asyncio.events.Handle is created in the SelectorThread without providing a context,
280+
# it will copy the current thread's context,
281+
# which can lead to the loss of the main thread's context when executing the handle.
282+
# Therefore, it is necessary to
283+
# save a copy of the main thread's context in the SelectorThread for creating the handle.
284+
self.write(tornado_test_ctx.get())
285+
286+
return Application([(self.test_endpoint, Handler)])
287+
288+
def test_context_vars(self):
289+
self.assertEqual(self.ctx_value, self.fetch(self.test_endpoint).body.decode())

0 commit comments

Comments
 (0)