From: Kumar Aditya <59607654+kumaraditya303@users.noreply.github.com> Date: Tue, 16 Aug 2022 15:52:06 +0000 (+0530) Subject: GH-95736: fix IsolatedAsyncioTestCase to initialize Runner before calling setup funct... X-Git-Tag: v3.12.0a1~638 X-Git-Url: http://git.ipfire.org/gitweb.cgi?a=commitdiff_plain;h=9d515997f943b7b510268448f372dabcbf957858;p=thirdparty%2FPython%2Fcpython.git GH-95736: fix IsolatedAsyncioTestCase to initialize Runner before calling setup functions (#95898) --- diff --git a/Lib/test/test_unittest/test_async_case.py b/Lib/test/test_unittest/test_async_case.py index beadcac070b4..f59fc760d381 100644 --- a/Lib/test/test_unittest/test_async_case.py +++ b/Lib/test/test_unittest/test_async_case.py @@ -434,6 +434,21 @@ class TestAsyncCase(unittest.TestCase): test.doCleanups() self.assertEqual(events, ['asyncSetUp', 'test', 'cleanup']) + def test_setup_get_event_loop(self): + # See https://github.com/python/cpython/issues/95736 + # Make sure the default event loop is not used + asyncio.set_event_loop(None) + + class TestCase1(unittest.IsolatedAsyncioTestCase): + def setUp(self): + asyncio.get_event_loop_policy().get_event_loop() + + async def test_demo1(self): + pass + + test = TestCase1('test_demo1') + result = test.run() + self.assertTrue(result.wasSuccessful()) if __name__ == "__main__": unittest.main() diff --git a/Lib/unittest/async_case.py b/Lib/unittest/async_case.py index a90eed98f871..8b06fad06209 100644 --- a/Lib/unittest/async_case.py +++ b/Lib/unittest/async_case.py @@ -116,6 +116,10 @@ class IsolatedAsyncioTestCase(TestCase): assert self._asyncioRunner is None, 'asyncio runner is already initialized' runner = asyncio.Runner(debug=True) self._asyncioRunner = runner + # Force loop to be initialized and set as the current loop + # so that setUp functions can use get_event_loop() and get the + # correct loop instance. + runner.get_loop() def _tearDownAsyncioRunner(self): runner = self._asyncioRunner diff --git a/Misc/NEWS.d/next/Library/2022-08-11-18-22-29.gh-issue-95736.LzRZXe.rst b/Misc/NEWS.d/next/Library/2022-08-11-18-22-29.gh-issue-95736.LzRZXe.rst new file mode 100644 index 000000000000..abc270fe35ca --- /dev/null +++ b/Misc/NEWS.d/next/Library/2022-08-11-18-22-29.gh-issue-95736.LzRZXe.rst @@ -0,0 +1 @@ +Fix :class:`unittest.IsolatedAsyncioTestCase` to set event loop before calling setup functions. Patch by Kumar Aditya.