@@ -619,6 +619,33 @@ async def agenfn():
619619 with self .assertRaisesRegex (RuntimeError , "coroutine ignored GeneratorExit" ):
620620 gen .close ()
621621
622+ def test_async_gen_athrow_send_non_none (self ):
623+ # gh-120321: sending a non-None value to a just-started athrow()
624+ # awaitable must not claim the generator, so the generator stays
625+ # usable and the awaitable can still be awaited afterwards.
626+ class MyExc (Exception ):
627+ pass
628+
629+ async def agenfn ():
630+ try :
631+ yield 1
632+ except MyExc :
633+ yield 2
634+
635+ agen = agenfn ()
636+ with self .assertRaises (StopIteration ):
637+ agen .asend (None ).send (None )
638+
639+ gen = agen .athrow (MyExc )
640+ with self .assertRaisesRegex (RuntimeError , "non-None value" ):
641+ gen .send (42 )
642+ self .assertFalse (agen .ag_running )
643+
644+ # The awaitable is still in its initial state and works normally.
645+ with self .assertRaises (StopIteration ) as cm :
646+ gen .send (None )
647+ self .assertEqual (cm .exception .value , 2 )
648+
622649
623650class AsyncGenAsyncioTest (unittest .TestCase ):
624651
@@ -1950,6 +1977,41 @@ class MyException(Exception):
19501977 ):
19511978 nxt .throw (MyException )
19521979
1980+ def test_async_gen_send_same_athrow_coro_after_completion (self ):
1981+ # gh-120321: an athrow() awaitable that needs more than one send()
1982+ # to complete must be closed on completion; sending to it again
1983+ # must raise instead of resuming the generator.
1984+ class YieldOnce :
1985+ def __await__ (self ):
1986+ yield
1987+
1988+ async def async_iterate ():
1989+ try :
1990+ yield 1
1991+ except ValueError :
1992+ await YieldOnce ()
1993+ yield 2
1994+
1995+ it = async_iterate ()
1996+ with self .assertRaises (StopIteration ):
1997+ it .__anext__ ().send (None )
1998+
1999+ nxt = it .athrow (ValueError )
2000+ # The exception handler suspends before the operation completes.
2001+ nxt .send (None )
2002+ with self .assertRaises (StopIteration ) as cm :
2003+ nxt .send (None )
2004+ self .assertEqual (cm .exception .value , 2 )
2005+
2006+ with self .assertRaisesRegex (
2007+ RuntimeError ,
2008+ r"cannot reuse already awaited aclose\(\)/athrow\(\)"
2009+ ):
2010+ nxt .send (None )
2011+
2012+ with self .assertRaises (StopIteration ):
2013+ it .aclose ().send (None )
2014+
19532015 def test_async_gen_aclose_twice_with_different_coros (self ):
19542016 # Regression test for https://bugs.python.org/issue39606
19552017 async def async_iterate ():
0 commit comments