77import contextlib
88from asyncio import taskgroups
99import unittest
10+ import warnings
1011
1112from test .test_asyncio .utils import await_without_task
1213
@@ -738,10 +739,7 @@ async def coro2(g):
738739 await asyncio .sleep (1 )
739740 except asyncio .CancelledError :
740741 with self .assertRaises (RuntimeError ):
741- g .create_task (c1 := coro1 ())
742- # We still have to await c1 to avoid a warning
743- with self .assertRaises (ZeroDivisionError ):
744- await c1
742+ g .create_task (coro1 ())
745743
746744 with self .assertRaises (ExceptionGroup ) as cm :
747745 async with taskgroups .TaskGroup () as g :
@@ -797,22 +795,25 @@ async def test_taskgroup_double_enter(self):
797795 pass
798796
799797 async def test_taskgroup_finished (self ):
800- tg = taskgroups .TaskGroup ()
801- async with tg :
802- pass
803- coro = asyncio .sleep (0 )
804- with self .assertRaisesRegex (RuntimeError , "is finished" ):
805- tg .create_task (coro )
806- # We still have to await coro to avoid a warning
807- await coro
798+ async def create_task_after_tg_finish ():
799+ tg = taskgroups .TaskGroup ()
800+ async with tg :
801+ pass
802+ coro = asyncio .sleep (0 )
803+ with self .assertRaisesRegex (RuntimeError , "is finished" ):
804+ tg .create_task (coro )
805+
806+ # Make sure the coroutine was closed when submitted to the inactive tg
807+ # (if not closed, a RuntimeWarning should have been raised)
808+ with warnings .catch_warnings (record = True ) as w :
809+ await create_task_after_tg_finish ()
810+ self .assertEqual (len (w ), 0 )
808811
809812 async def test_taskgroup_not_entered (self ):
810813 tg = taskgroups .TaskGroup ()
811814 coro = asyncio .sleep (0 )
812815 with self .assertRaisesRegex (RuntimeError , "has not been entered" ):
813816 tg .create_task (coro )
814- # We still have to await coro to avoid a warning
815- await coro
816817
817818 async def test_taskgroup_without_parent_task (self ):
818819 tg = taskgroups .TaskGroup ()
@@ -821,8 +822,16 @@ async def test_taskgroup_without_parent_task(self):
821822 coro = asyncio .sleep (0 )
822823 with self .assertRaisesRegex (RuntimeError , "has not been entered" ):
823824 tg .create_task (coro )
824- # We still have to await coro to avoid a warning
825- await coro
825+
826+ def test_coro_closed_when_tg_closed (self ):
827+ async def run_coro_after_tg_closes ():
828+ async with taskgroups .TaskGroup () as tg :
829+ pass
830+ coro = asyncio .sleep (0 )
831+ with self .assertRaisesRegex (RuntimeError , "is finished" ):
832+ tg .create_task (coro )
833+ loop = asyncio .get_event_loop ()
834+ loop .run_until_complete (run_coro_after_tg_closes ())
826835
827836
828837if __name__ == "__main__" :
0 commit comments