From f194ad3185350cc16b1b3245fa394282a4c055b1 Mon Sep 17 00:00:00 2001 From: Serhiy Storchaka Date: Sat, 4 Sep 2021 20:55:20 +0300 Subject: [PATCH 1/2] bpo-45097: Add more tests for shutdown_asyncgens() (GH-28154) (cherry picked from commit c2970fdec52788b6d9ff419ab7e31f255d87433d) Co-authored-by: Serhiy Storchaka --- Lib/test/test_asyncgen.py | 79 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 79 insertions(+) diff --git a/Lib/test/test_asyncgen.py b/Lib/test/test_asyncgen.py index 77c15c02bc8914f..8defc19af4cd93c 100644 --- a/Lib/test/test_asyncgen.py +++ b/Lib/test/test_asyncgen.py @@ -1287,6 +1287,85 @@ async def wait(): self.assertEqual(finalized, 2) + def test_async_gen_asyncio_shutdown_02(self): + messages = [] + + def exception_handler(loop, context): + messages.append(context) + + async def async_iterate(): + yield 1 + yield 2 + + it = async_iterate() + async def main(): + loop = asyncio.get_running_loop() + loop.set_exception_handler(exception_handler) + + async for i in it: + break + + asyncio.run(main()) + + self.assertEqual(messages, []) + + def test_async_gen_asyncio_shutdown_exception_01(self): + messages = [] + + def exception_handler(loop, context): + messages.append(context) + + async def async_iterate(): + try: + yield 1 + yield 2 + finally: + 1/0 + + it = async_iterate() + async def main(): + loop = asyncio.get_running_loop() + loop.set_exception_handler(exception_handler) + + async for i in it: + break + + asyncio.run(main()) + + message, = messages + self.assertEqual(message['asyncgen'], it) + self.assertIsInstance(message['exception'], ZeroDivisionError) + self.assertIn('an error occurred during closing of asynchronous generator', + message['message']) + + def test_async_gen_asyncio_shutdown_exception_02(self): + messages = [] + + def exception_handler(loop, context): + messages.append(context) + + async def async_iterate(): + try: + yield 1 + yield 2 + finally: + 1/0 + + async def main(): + loop = asyncio.get_running_loop() + loop.set_exception_handler(exception_handler) + + async for i in async_iterate(): + break + gc_collect() + + asyncio.run(main()) + + message, = messages + self.assertIsInstance(message['exception'], ZeroDivisionError) + self.assertIn('unhandled exception during asyncio.run() shutdown', + message['message']) + def test_async_gen_expression_01(self): async def arange(n): for i in range(n): From 2c92f4db7e69f0e354792cd74efd7f15941396c2 Mon Sep 17 00:00:00 2001 From: Serhiy Storchaka Date: Sat, 4 Sep 2021 22:43:54 +0300 Subject: [PATCH 2/2] Update test_asyncgen.py --- Lib/test/test_asyncgen.py | 1 + 1 file changed, 1 insertion(+) diff --git a/Lib/test/test_asyncgen.py b/Lib/test/test_asyncgen.py index 8defc19af4cd93c..0814451d3175710 100644 --- a/Lib/test/test_asyncgen.py +++ b/Lib/test/test_asyncgen.py @@ -3,6 +3,7 @@ import unittest from test.support.import_helper import import_module +from test.support import gc_collect asyncio = import_module("asyncio")