GH-93896: AAlways set event loop in asyncio.run and IsolatedAsyncioTestCase (GH-94593)

(cherry picked from commit 14fea6b4d2)

Co-authored-by: Kumar Aditya <59607654+kumaraditya303@users.noreply.github.com>
This commit is contained in:
Miss Islington (bot) 2022-07-06 08:48:37 -07:00 committed by GitHub
parent b22f9d6e8c
commit 0187b60106
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
3 changed files with 19 additions and 0 deletions

View file

@ -53,6 +53,7 @@ class Runner:
self._loop = None
self._context = None
self._interrupt_count = 0
self._set_event_loop = False
def __enter__(self):
self._lazy_init()
@ -71,6 +72,8 @@ class Runner:
loop.run_until_complete(loop.shutdown_asyncgens())
loop.run_until_complete(loop.shutdown_default_executor())
finally:
if self._set_event_loop:
events.set_event_loop(None)
loop.close()
self._loop = None
self._state = _State.CLOSED
@ -112,6 +115,8 @@ class Runner:
self._interrupt_count = 0
try:
if self._set_event_loop:
events.set_event_loop(self._loop)
return self._loop.run_until_complete(task)
except exceptions.CancelledError:
if self._interrupt_count > 0 and task.uncancel() == 0:
@ -131,6 +136,7 @@ class Runner:
return
if self._loop_factory is None:
self._loop = events.new_event_loop()
self._set_event_loop = True
else:
self._loop = self._loop_factory()
if self._debug is not None:

View file

@ -199,6 +199,18 @@ class RunTests(BaseTest):
self.assertIsNone(spinner.ag_frame)
self.assertFalse(spinner.ag_running)
def test_asyncio_run_set_event_loop(self):
#See https://github.com/python/cpython/issues/93896
async def main():
await asyncio.sleep(0)
return 42
policy = asyncio.get_event_loop_policy()
policy.set_event_loop = mock.Mock()
asyncio.run(main())
self.assertTrue(policy.set_event_loop.called)
class RunnerTests(BaseTest):

View file

@ -0,0 +1 @@
Fix :func:`asyncio.run` and :class:`unittest.IsolatedAsyncioTestCase` to always the set event loop as it was done in Python 3.10 and earlier. Patch by Kumar Aditya.