]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
GH-93896: AAlways set event loop in asyncio.run and IsolatedAsyncioTestCase (#94593)
authorKumar Aditya <59607654+kumaraditya303@users.noreply.github.com>
Wed, 6 Jul 2022 15:18:21 +0000 (20:48 +0530)
committerGitHub <noreply@github.com>
Wed, 6 Jul 2022 15:18:21 +0000 (16:18 +0100)
Lib/asyncio/runners.py
Lib/test/test_asyncio/test_runners.py
Misc/NEWS.d/next/Library/2022-07-06-06-02-02.gh-issue-93896.vIgWGr.rst [new file with mode: 0644]

index f524c3b8e424f562f139d660e8a1022e46b8c9fe..7489a50f8e48da8023685da8811d15a526fc606c 100644 (file)
@@ -52,6 +52,7 @@ class Runner:
         self._loop = None
         self._context = None
         self._interrupt_count = 0
+        self._set_event_loop = False
 
     def __enter__(self):
         self._lazy_init()
@@ -70,6 +71,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
@@ -111,6 +114,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:
@@ -130,6 +135,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:
index 7780a5f15e1b4477fb2e176ff5db3611f186f1da..1f6a4983690cdc6e00f4051caf702f69e23759fd 100644 (file)
@@ -198,6 +198,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):
 
diff --git a/Misc/NEWS.d/next/Library/2022-07-06-06-02-02.gh-issue-93896.vIgWGr.rst b/Misc/NEWS.d/next/Library/2022-07-06-06-02-02.gh-issue-93896.vIgWGr.rst
new file mode 100644 (file)
index 0000000..2283e14
--- /dev/null
@@ -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.