Skip to content

Commit 0187b60

Browse files
GH-93896: AAlways set event loop in asyncio.run and IsolatedAsyncioTestCase (GH-94593)
(cherry picked from commit 14fea6b) Co-authored-by: Kumar Aditya <[email protected]>
1 parent b22f9d6 commit 0187b60

File tree

3 files changed

+19
-0
lines changed

3 files changed

+19
-0
lines changed

Lib/asyncio/runners.py

+6
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ def __init__(self, *, debug=None, loop_factory=None):
5353
self._loop = None
5454
self._context = None
5555
self._interrupt_count = 0
56+
self._set_event_loop = False
5657

5758
def __enter__(self):
5859
self._lazy_init()
@@ -71,6 +72,8 @@ def close(self):
7172
loop.run_until_complete(loop.shutdown_asyncgens())
7273
loop.run_until_complete(loop.shutdown_default_executor())
7374
finally:
75+
if self._set_event_loop:
76+
events.set_event_loop(None)
7477
loop.close()
7578
self._loop = None
7679
self._state = _State.CLOSED
@@ -112,6 +115,8 @@ def run(self, coro, *, context=None):
112115

113116
self._interrupt_count = 0
114117
try:
118+
if self._set_event_loop:
119+
events.set_event_loop(self._loop)
115120
return self._loop.run_until_complete(task)
116121
except exceptions.CancelledError:
117122
if self._interrupt_count > 0 and task.uncancel() == 0:
@@ -131,6 +136,7 @@ def _lazy_init(self):
131136
return
132137
if self._loop_factory is None:
133138
self._loop = events.new_event_loop()
139+
self._set_event_loop = True
134140
else:
135141
self._loop = self._loop_factory()
136142
if self._debug is not None:

Lib/test/test_asyncio/test_runners.py

+12
Original file line numberDiff line numberDiff line change
@@ -199,6 +199,18 @@ async def main():
199199
self.assertIsNone(spinner.ag_frame)
200200
self.assertFalse(spinner.ag_running)
201201

202+
def test_asyncio_run_set_event_loop(self):
203+
#See https://github.com/python/cpython/issues/93896
204+
205+
async def main():
206+
await asyncio.sleep(0)
207+
return 42
208+
209+
policy = asyncio.get_event_loop_policy()
210+
policy.set_event_loop = mock.Mock()
211+
asyncio.run(main())
212+
self.assertTrue(policy.set_event_loop.called)
213+
202214

203215
class RunnerTests(BaseTest):
204216

Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
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.

0 commit comments

Comments
 (0)