@@ -271,6 +271,68 @@ async def main(t1, t2):
271271 ]
272272 ])
273273
274+ async def test_stack_as_completed (self ):
275+ # gh-156523: as_completed() must record the awaiting task
276+ stack_for_inner = None
277+
278+ async def inner ():
279+ await asyncio .sleep (0 )
280+ nonlocal stack_for_inner
281+ stack_for_inner = capture_test_stack ()
282+
283+ async def main (t ):
284+ for f in asyncio .as_completed ([t ]):
285+ await f
286+
287+ t = asyncio .create_task (inner (), name = 'inner' )
288+ await main (t )
289+ self .assertFalse (t ._asyncio_awaited_by )
290+
291+ self .assertEqual (stack_for_inner [0 ], [
292+ 'T<inner>' ,
293+ ['s capture_test_stack' , 'a inner' ],
294+ [
295+ ['T<anon>' ,
296+ ['a get' , 'a _wait_for_one' , 'a main' ,
297+ 'a test_stack_as_completed' ],
298+ []
299+ ]
300+ ]
301+ ])
302+
303+ async def test_stack_as_completed_timeout (self ):
304+ # gh-156523: the awaiting task must be dropped when as_completed() times out
305+ stack_for_inner = None
306+
307+ async def inner ():
308+ nonlocal stack_for_inner
309+ stack_for_inner = capture_test_stack ()
310+ await asyncio .sleep (3600 )
311+
312+ async def main (t ):
313+ with self .assertRaises (TimeoutError ):
314+ for f in asyncio .as_completed ([t ], timeout = 0.01 ):
315+ await f
316+
317+ t = asyncio .create_task (inner (), name = 'inner' )
318+ await main (t )
319+ self .assertFalse (t ._asyncio_awaited_by )
320+ t .cancel ()
321+ with self .assertRaises (asyncio .CancelledError ):
322+ await t
323+
324+ self .assertEqual (stack_for_inner [0 ], [
325+ 'T<inner>' ,
326+ ['s capture_test_stack' , 'a inner' ],
327+ [
328+ ['T<anon>' ,
329+ ['a get' , 'a _wait_for_one' , 'a main' ,
330+ 'a test_stack_as_completed_timeout' ],
331+ []
332+ ]
333+ ]
334+ ])
335+
274336 async def test_stack_task (self ):
275337
276338 stack_for_inner = None
0 commit comments