@@ -87,8 +87,10 @@ class BaseTaskTests:
8787 Task = None
8888 Future = None
8989
90- def new_task (self , loop , coro , name = 'TestTask' , context = None ):
91- return self .__class__ .Task (coro , loop = loop , name = name , context = context )
90+ def new_task (self , loop , coro , name = 'TestTask' , context = None ,
91+ eager_start = None ):
92+ return self .__class__ .Task (coro , loop = loop , name = name , context = context ,
93+ eager_start = eager_start )
9294
9395 def new_future (self , loop ):
9496 return self .__class__ .Future (loop = loop )
@@ -2518,6 +2520,68 @@ async def main():
25182520 finally :
25192521 loop .close ()
25202522
2523+ def test_context_not_a_context (self ):
2524+ # gh-157301
2525+ async def coro ():
2526+ pass
2527+
2528+ loop = asyncio .new_event_loop ()
2529+ c = coro ()
2530+ try :
2531+ with self .assertRaises (TypeError ):
2532+ self .new_task (loop , c , context = 'not a context' )
2533+ finally :
2534+ c .close ()
2535+ loop .close ()
2536+
2537+ def test_context_not_a_context_leaves_loop_usable (self ):
2538+ # gh-157301
2539+ async def coro ():
2540+ pass
2541+
2542+ async def main ():
2543+ c = coro ()
2544+ try :
2545+ with self .assertRaises (TypeError ):
2546+ self .new_task (loop , c , context = 'not a context' ,
2547+ eager_start = True )
2548+ finally :
2549+ c .close ()
2550+ await asyncio .sleep (0 )
2551+
2552+ loop = asyncio .new_event_loop ()
2553+ loop .call_later (support .SHORT_TIMEOUT , loop .stop )
2554+ try :
2555+ loop .run_until_complete (self .new_task (loop , main ()))
2556+ finally :
2557+ loop .close ()
2558+
2559+ def test_context_already_entered_leaves_loop_usable (self ):
2560+ # gh-157301
2561+ async def coro ():
2562+ pass
2563+
2564+ async def main ():
2565+ ctx = contextvars .copy_context ()
2566+
2567+ def inside ():
2568+ c = coro ()
2569+ try :
2570+ with self .assertRaises (RuntimeError ):
2571+ self .new_task (loop , c , context = ctx , eager_start = True )
2572+ finally :
2573+ c .close ()
2574+
2575+ ctx .run (inside )
2576+ await asyncio .sleep (0 )
2577+
2578+ loop = asyncio .new_event_loop ()
2579+ loop .call_later (support .SHORT_TIMEOUT , loop .stop )
2580+ try :
2581+ loop .run_until_complete (self .new_task (loop , main ()))
2582+ finally :
2583+ loop .close ()
2584+
25212585 def test_context_2 (self ):
25222586 cvar = contextvars .ContextVar ('cvar' , default = 'nope' )
25232587
@@ -2690,7 +2754,7 @@ class Break:
26902754 def __str__ (self ):
26912755 raise RuntimeError ("break" )
26922756
2693- obj = object ()
2757+ obj = contextvars . copy_context ()
26942758 initial_refcount = sys .getrefcount (obj )
26952759
26962760 coro = coroutine_function ()
0 commit comments