Skip to content

Commit b68ea2a

Browse files
[3.11] GH-95736: fix IsolatedAsyncioTestCase to initialize Runner bef… (#96042)
Co-authored-by: Kumar Aditya <[email protected]> Co-authored-by: Serhiy Storchaka <[email protected]>
1 parent 1b9b485 commit b68ea2a

File tree

3 files changed

+20
-0
lines changed

3 files changed

+20
-0
lines changed

Lib/unittest/async_case.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -79,6 +79,10 @@ async def enterAsyncContext(self, cm):
7979
return result
8080

8181
def _callSetUp(self):
82+
# Force loop to be initialized and set as the current loop
83+
# so that setUp functions can use get_event_loop() and get the
84+
# correct loop instance.
85+
self._asyncioRunner.get_loop()
8286
self._asyncioTestContext.run(self.setUp)
8387
self._callAsync(self.asyncSetUp)
8488

Lib/unittest/test/test_async_case.py

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -434,6 +434,21 @@ async def cleanup(self, fut):
434434
test.doCleanups()
435435
self.assertEqual(events, ['asyncSetUp', 'test', 'cleanup'])
436436

437+
def test_setup_get_event_loop(self):
438+
# See https://github.com/python/cpython/issues/95736
439+
# Make sure the default event loop is not used
440+
asyncio.set_event_loop(None)
441+
442+
class TestCase1(unittest.IsolatedAsyncioTestCase):
443+
def setUp(self):
444+
asyncio.get_event_loop_policy().get_event_loop()
445+
446+
async def test_demo1(self):
447+
pass
448+
449+
test = TestCase1('test_demo1')
450+
result = test.run()
451+
self.assertTrue(result.wasSuccessful())
437452

438453
if __name__ == "__main__":
439454
unittest.main()
Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
Fix :class:`unittest.IsolatedAsyncioTestCase` to set event loop before calling setup functions. Patch by Kumar Aditya.

0 commit comments

Comments
 (0)