asyncio_test.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298
  1. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  2. # not use this file except in compliance with the License. You may obtain
  3. # a copy of the License at
  4. #
  5. # http://www.apache.org/licenses/LICENSE-2.0
  6. #
  7. # Unless required by applicable law or agreed to in writing, software
  8. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  9. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  10. # License for the specific language governing permissions and limitations
  11. # under the License.
  12. import asyncio
  13. import contextvars
  14. import threading
  15. import time
  16. import unittest
  17. import warnings
  18. from concurrent.futures import ThreadPoolExecutor
  19. import tornado.platform.asyncio
  20. from tornado import gen
  21. from tornado.ioloop import IOLoop
  22. from tornado.platform.asyncio import (
  23. AsyncIOLoop,
  24. to_asyncio_future,
  25. AddThreadSelectorEventLoop,
  26. )
  27. from tornado.testing import (
  28. AsyncTestCase,
  29. gen_test,
  30. setup_with_context_manager,
  31. AsyncHTTPTestCase,
  32. )
  33. from tornado.test.util import ignore_deprecation
  34. from tornado.web import Application, RequestHandler
  35. class AsyncIOLoopTest(AsyncTestCase):
  36. @property
  37. def asyncio_loop(self):
  38. return self.io_loop.asyncio_loop # type: ignore
  39. def test_asyncio_callback(self):
  40. # Basic test that the asyncio loop is set up correctly.
  41. async def add_callback():
  42. asyncio.get_event_loop().call_soon(self.stop)
  43. self.asyncio_loop.run_until_complete(add_callback())
  44. self.wait()
  45. @gen_test
  46. def test_asyncio_future(self):
  47. # Test that we can yield an asyncio future from a tornado coroutine.
  48. # Without 'yield from', we must wrap coroutines in ensure_future.
  49. x = yield asyncio.ensure_future(
  50. asyncio.get_event_loop().run_in_executor(None, lambda: 42)
  51. )
  52. self.assertEqual(x, 42)
  53. @gen_test
  54. def test_asyncio_yield_from(self):
  55. @gen.coroutine
  56. def f():
  57. event_loop = asyncio.get_event_loop()
  58. x = yield from event_loop.run_in_executor(None, lambda: 42)
  59. return x
  60. result = yield f()
  61. self.assertEqual(result, 42)
  62. def test_asyncio_adapter(self):
  63. # This test demonstrates that when using the asyncio coroutine
  64. # runner (i.e. run_until_complete), the to_asyncio_future
  65. # adapter is needed. No adapter is needed in the other direction,
  66. # as demonstrated by other tests in the package.
  67. @gen.coroutine
  68. def tornado_coroutine():
  69. yield gen.moment
  70. raise gen.Return(42)
  71. async def native_coroutine_without_adapter():
  72. return await tornado_coroutine()
  73. async def native_coroutine_with_adapter():
  74. return await to_asyncio_future(tornado_coroutine())
  75. # Use the adapter, but two degrees from the tornado coroutine.
  76. async def native_coroutine_with_adapter2():
  77. return await to_asyncio_future(native_coroutine_without_adapter())
  78. # Tornado supports native coroutines both with and without adapters
  79. self.assertEqual(self.io_loop.run_sync(native_coroutine_without_adapter), 42)
  80. self.assertEqual(self.io_loop.run_sync(native_coroutine_with_adapter), 42)
  81. self.assertEqual(self.io_loop.run_sync(native_coroutine_with_adapter2), 42)
  82. # Asyncio only supports coroutines that yield asyncio-compatible
  83. # Futures (which our Future is since 5.0).
  84. self.assertEqual(
  85. self.asyncio_loop.run_until_complete(native_coroutine_without_adapter()),
  86. 42,
  87. )
  88. self.assertEqual(
  89. self.asyncio_loop.run_until_complete(native_coroutine_with_adapter()),
  90. 42,
  91. )
  92. self.assertEqual(
  93. self.asyncio_loop.run_until_complete(native_coroutine_with_adapter2()),
  94. 42,
  95. )
  96. def test_add_thread_close_idempotent(self):
  97. loop = AddThreadSelectorEventLoop(asyncio.get_event_loop()) # type: ignore
  98. loop.close()
  99. loop.close()
  100. class LeakTest(unittest.TestCase):
  101. def setUp(self):
  102. # Trigger a cleanup of the mapping so we start with a clean slate.
  103. AsyncIOLoop(make_current=False).close()
  104. def tearDown(self):
  105. try:
  106. loop = asyncio.get_event_loop_policy().get_event_loop()
  107. except Exception:
  108. # We may not have a current event loop at this point.
  109. pass
  110. else:
  111. loop.close()
  112. def test_ioloop_close_leak(self):
  113. orig_count = len(IOLoop._ioloop_for_asyncio)
  114. for i in range(10):
  115. # Create and close an AsyncIOLoop using Tornado interfaces.
  116. with warnings.catch_warnings():
  117. warnings.simplefilter("ignore", DeprecationWarning)
  118. loop = AsyncIOLoop()
  119. loop.close()
  120. new_count = len(IOLoop._ioloop_for_asyncio) - orig_count
  121. self.assertEqual(new_count, 0)
  122. def test_asyncio_close_leak(self):
  123. orig_count = len(IOLoop._ioloop_for_asyncio)
  124. for i in range(10):
  125. # Create and close an AsyncIOMainLoop using asyncio interfaces.
  126. loop = asyncio.new_event_loop()
  127. loop.call_soon(IOLoop.current)
  128. loop.call_soon(loop.stop)
  129. loop.run_forever()
  130. loop.close()
  131. new_count = len(IOLoop._ioloop_for_asyncio) - orig_count
  132. # Because the cleanup is run on new loop creation, we have one
  133. # dangling entry in the map (but only one).
  134. self.assertEqual(new_count, 1)
  135. class SelectorThreadLeakTest(unittest.TestCase):
  136. # These tests are only relevant on windows, but they should pass anywhere.
  137. def setUp(self):
  138. # As a precaution, ensure that we've run an event loop at least once
  139. # so if it spins up any singleton threads they're already there.
  140. asyncio.run(self.dummy_tornado_coroutine())
  141. self.orig_thread_count = threading.active_count()
  142. def assert_no_thread_leak(self):
  143. # For some reason we see transient failures here, but I haven't been able
  144. # to catch it to identify which thread is causing it. Whatever thread it
  145. # is, it appears to quickly clean up on its own, so just retry a few times.
  146. # At least some of the time the errant thread was running at the time we
  147. # captured self.orig_thread_count, so use inequalities.
  148. deadline = time.time() + 1
  149. while time.time() < deadline:
  150. threads = list(threading.enumerate())
  151. if len(threads) <= self.orig_thread_count:
  152. break
  153. time.sleep(0.1)
  154. self.assertLessEqual(len(threads), self.orig_thread_count, threads)
  155. async def dummy_tornado_coroutine(self):
  156. # Just access the IOLoop to initialize the selector thread.
  157. IOLoop.current()
  158. def test_asyncio_run(self):
  159. for i in range(10):
  160. # asyncio.run calls shutdown_asyncgens for us.
  161. asyncio.run(self.dummy_tornado_coroutine())
  162. self.assert_no_thread_leak()
  163. def test_asyncio_manual(self):
  164. for i in range(10):
  165. loop = asyncio.new_event_loop()
  166. loop.run_until_complete(self.dummy_tornado_coroutine())
  167. # Without this step, we'd leak the thread.
  168. loop.run_until_complete(loop.shutdown_asyncgens())
  169. loop.close()
  170. self.assert_no_thread_leak()
  171. def test_tornado(self):
  172. for i in range(10):
  173. # The IOLoop interfaces are aware of the selector thread and
  174. # (synchronously) shut it down.
  175. loop = IOLoop(make_current=False)
  176. loop.run_sync(self.dummy_tornado_coroutine)
  177. loop.close()
  178. self.assert_no_thread_leak()
  179. class AnyThreadEventLoopPolicyTest(unittest.TestCase):
  180. def setUp(self):
  181. setup_with_context_manager(self, ignore_deprecation())
  182. # Referencing the event loop policy attributes raises deprecation warnings,
  183. # so instead of importing this at the top of the file we capture it here.
  184. self.AnyThreadEventLoopPolicy = (
  185. tornado.platform.asyncio.AnyThreadEventLoopPolicy
  186. )
  187. self.orig_policy = asyncio.get_event_loop_policy()
  188. self.executor = ThreadPoolExecutor(1)
  189. def tearDown(self):
  190. asyncio.set_event_loop_policy(self.orig_policy)
  191. self.executor.shutdown()
  192. def get_event_loop_on_thread(self):
  193. def get_and_close_event_loop():
  194. """Get the event loop. Close it if one is returned.
  195. Returns the (closed) event loop. This is a silly thing
  196. to do and leaves the thread in a broken state, but it's
  197. enough for this test. Closing the loop avoids resource
  198. leak warnings.
  199. """
  200. loop = asyncio.get_event_loop()
  201. loop.close()
  202. return loop
  203. future = self.executor.submit(get_and_close_event_loop)
  204. return future.result()
  205. def test_asyncio_accessor(self):
  206. with warnings.catch_warnings():
  207. warnings.simplefilter("ignore", DeprecationWarning)
  208. # With the default policy, non-main threads don't get an event
  209. # loop.
  210. self.assertRaises(
  211. RuntimeError, self.executor.submit(asyncio.get_event_loop).result
  212. )
  213. # Set the policy and we can get a loop.
  214. asyncio.set_event_loop_policy(self.AnyThreadEventLoopPolicy())
  215. self.assertIsInstance(
  216. self.executor.submit(asyncio.get_event_loop).result(),
  217. asyncio.AbstractEventLoop,
  218. )
  219. # Clean up to silence leak warnings. Always use asyncio since
  220. # IOLoop doesn't (currently) close the underlying loop.
  221. self.executor.submit(lambda: asyncio.get_event_loop().close()).result() # type: ignore
  222. def test_tornado_accessor(self):
  223. # Tornado's IOLoop.current() API can create a loop for any thread,
  224. # regardless of this event loop policy.
  225. with warnings.catch_warnings():
  226. warnings.simplefilter("ignore", DeprecationWarning)
  227. self.assertIsInstance(self.executor.submit(IOLoop.current).result(), IOLoop)
  228. # Clean up to silence leak warnings. Always use asyncio since
  229. # IOLoop doesn't (currently) close the underlying loop.
  230. self.executor.submit(lambda: asyncio.get_event_loop().close()).result() # type: ignore
  231. asyncio.set_event_loop_policy(self.AnyThreadEventLoopPolicy())
  232. self.assertIsInstance(self.executor.submit(IOLoop.current).result(), IOLoop)
  233. self.executor.submit(lambda: asyncio.get_event_loop().close()).result() # type: ignore
  234. class SelectorThreadContextvarsTest(AsyncHTTPTestCase):
  235. ctx_value = "foo"
  236. test_endpoint = "/"
  237. tornado_test_ctx = contextvars.ContextVar("tornado_test_ctx", default="default")
  238. tornado_test_ctx.set(ctx_value)
  239. def get_app(self) -> Application:
  240. tornado_test_ctx = self.tornado_test_ctx
  241. class Handler(RequestHandler):
  242. async def get(self):
  243. # On the Windows platform,
  244. # when a asyncio.events.Handle is created
  245. # in the SelectorThread without providing a context,
  246. # it will copy the current thread's context,
  247. # which can lead to the loss of the main thread's context
  248. # when executing the handle.
  249. # Therefore, it is necessary to
  250. # save a copy of the main thread's context in the SelectorThread
  251. # for creating the handle.
  252. self.write(tornado_test_ctx.get())
  253. return Application([(self.test_endpoint, Handler)])
  254. def test_context_vars(self):
  255. self.assertEqual(self.ctx_value, self.fetch(self.test_endpoint).body.decode())