Debian Codegraph @

pypy/interpreter/test/apptest_coroutine.py

raw symbols SCIP
1 import pytest
2 from pytest import raises
3 import gc
4 import sys
5 import warnings # XXX: importing warnings is expensive untranslated
6
7
8 class suspend:
9 """
10 A simple awaitable that returns control to the "event loop" with `msg`
11 as value.
12 """
13 def __init__(self, msg=None):
14 self.msg = msg
15
16 def __await__(self):
17 yield self.msg
18
19
20 def test_cannot_iterate():
21 async def f(x):
22 pass
23
24 with warnings.catch_warnings():
25 warnings.simplefilter("ignore")
26 with raises(TypeError):
27 for i in f(5):
28 pass
29 raises(TypeError, iter, f(5))
30 raises(TypeError, next, f(5))
31 gc.collect()
32
33
34 def test_async_for():
35 class X:
36 def __aiter__(self):
37 return MyAIter()
38
39 class MyAIter:
40 async def __anext__(self):
41 return 42
42 async def f(x):
43 sum = 0
44 async for a in x:
45 sum += a
46 if sum > 100:
47 break
48 return sum
49 cr = f(X())
50 try:
51 cr.send(None)
52 except StopIteration as e:
53 assert e.value == 42 * 3
54 else:
55 assert False, "should have raised"
56
57
58 def test_StopAsyncIteration():
59 class X:
60 def __aiter__(self):
61 return MyAIter()
62 class MyAIter:
63 count = 0
64 async def __anext__(self):
65 if self.count == 3:
66 raise StopAsyncIteration
67 self.count += 1
68 return 42
69 async def f(x):
70 sum = 0
71 async for a in x:
72 sum += a
73 return sum
74 cr = f(X())
75 try:
76 cr.send(None)
77 except StopIteration as e:
78 assert e.value == 42 * 3
79 else:
80 assert False, "should have raised"
81
82 def test_for_error_cause():
83 class F:
84 def __aiter__(self):
85 return self
86 def __anext__(self):
87 return self
88 def __await__(self):
89 1 / 0
90
91 async def main():
92 async for _ in F():
93 pass
94
95 c = pytest.raises(TypeError, main().send, None)
96 assert 'an invalid object from __anext__' in c.value.args[0], c.value
97 assert isinstance(c.value.__cause__, ZeroDivisionError)
98
99 def test_async_with():
100 seen = []
101 class X:
102 async def __aenter__(self):
103 seen.append('aenter')
104 async def __aexit__(self, *args):
105 seen.append('aexit')
106 async def f(x):
107 async with x:
108 return 42
109 c = f(X())
110 try:
111 c.send(None)
112 except StopIteration as e:
113 assert e.value == 42
114 else:
115 assert False, "should have raised"
116 assert seen == ['aenter', 'aexit']
117
118 def test_async_with_exit_True():
119 seen = []
120 class X:
121 async def __aenter__(self):
122 seen.append('aenter')
123 async def __aexit__(self, *args):
124 seen.append('aexit')
125 return True
126 async def f(x):
127 async with x:
128 return 42
129 c = f(X())
130 try:
131 c.send(None)
132 except StopIteration as e:
133 assert e.value == 42
134 else:
135 assert False, "should have raised"
136 assert seen == ['aenter', 'aexit']
137
138 def test_await():
139 class X:
140 def __await__(self):
141 i1 = yield 40
142 assert i1 == 82
143 i2 = yield 41
144 assert i2 == 93
145 async def f():
146 await X()
147 await X()
148 c = f()
149 assert c.send(None) == 40
150 assert c.send(82) == 41
151 assert c.send(93) == 40
152 assert c.send(82) == 41
153 pytest.raises(StopIteration, c.send, 93)
154
155
156 def test_await_error():
157 async def f():
158 await [42]
159 c = f()
160 try:
161 c.send(None)
162 except TypeError as e:
163 assert str(e) == "object list can't be used in 'await' expression"
164 else:
165 assert False, "should have raised"
166
167
168 def test_async_with_exception_context():
169 class CM:
170 async def __aenter__(self):
171 pass
172 async def __aexit__(self, *e):
173 1/0
174 async def f():
175 async with CM():
176 raise ValueError
177 c = f()
178 try:
179 c.send(None)
180 except ZeroDivisionError as e:
181 assert e.__context__ is not None
182 assert isinstance(e.__context__, ValueError)
183 else:
184 assert False, "should have raised"
185
186
187 def test_runtime_warning():
188 async def foobaz():
189 pass
190 gc.collect() # emit warnings from unrelated older tests
191 with warnings.catch_warnings(record=True) as l:
192 foobaz()
193 gc.collect()
194 gc.collect()
195 gc.collect()
196
197 assert len(l) == 1, repr(l)
198 w = l[0].message
199 assert isinstance(w, RuntimeWarning)
200 assert str(w).startswith("coroutine ")
201 assert str(w).endswith("foobaz' was never awaited")
202
203
204 def test_async_for_with_tuple_subclass():
205 class Done(Exception): pass
206
207 class AIter(tuple):
208 i = 0
209 def __aiter__(self):
210 return self
211 async def __anext__(self):
212 if self.i >= len(self):
213 raise StopAsyncIteration
214 self.i += 1
215 return self[self.i - 1]
216
217 result = []
218 async def foo():
219 async for i in AIter([42]):
220 result.append(i)
221 raise Done
222
223 try:
224 foo().send(None)
225 except Done:
226 pass
227 assert result == [42]
228
229 def test_async_yield():
230 class Done(Exception): pass
231
232 async def mygen():
233 yield 5
234
235 result = []
236 async def foo():
237 async for i in mygen():
238 result.append(i)
239 raise Done
240
241 try:
242 foo().send(None)
243 except Done:
244 pass
245 assert result == [5]
246
247 def test_async_yield_already_finished():
248 class Done(Exception): pass
249
250 async def mygen():
251 yield 5
252
253 result = []
254 async def foo():
255 g = mygen()
256 async for i in g:
257 result.append(i)
258 async for i in g:
259 assert False # should not be reached
260 raise Done
261
262 try:
263 foo().send(None)
264 except Done:
265 pass
266 assert result == [5]
267
268 def test_async_yield_with_await():
269 class Done(Exception): pass
270
271 class X:
272 def __await__(self):
273 i1 = yield 40
274 assert i1 == 82
275 i2 = yield 41
276 assert i2 == 93
277
278 async def mygen():
279 yield 5
280 await X()
281 yield 6
282
283 result = []
284 async def foo():
285 async for i in mygen():
286 result.append(i)
287 raise Done
288
289 co = foo()
290 x = co.send(None)
291 assert x == 40
292 assert result == [5]
293 x = co.send(82)
294 assert x == 41
295 assert result == [5]
296 raises(Done, co.send, 93)
297 assert result == [5, 6]
298
299 def test_async_yield_with_explicit_send():
300 class X:
301 def __await__(self):
302 i1 = yield 40
303 assert i1 == 82
304 i2 = yield 41
305 assert i2 == 93
306
307 async def mygen():
308 x = yield 5
309 assert x == 2189
310 await X()
311 y = yield 6
312 assert y == 319
313
314 result = []
315 async def foo():
316 gen = mygen()
317 result.append(await gen.asend(None))
318 result.append(await gen.asend(2189))
319 try:
320 await gen.asend(319)
321 except StopAsyncIteration:
322 return 42
323 else:
324 raise AssertionError
325
326 co = foo()
327 x = co.send(None)
328 assert x == 40
329 assert result == [5]
330 x = co.send(82)
331 assert x == 41
332 assert result == [5]
333 e = raises(StopIteration, co.send, 93)
334 assert e.value.args == (42,)
335 assert result == [5, 6]
336
337 def test_async_yield_explicit_asend_and_next():
338 async def mygen(y):
339 assert y == 4983
340 x = yield 5
341 assert x == 2189
342 yield "ok"
343
344 g = mygen(4983)
345 raises(TypeError, g.asend(42).__next__)
346 e = raises(StopIteration, g.asend(None).__next__)
347 assert e.value.args == (5,)
348 e = raises(StopIteration, g.asend(2189).__next__)
349 assert e.value.args == ("ok",)
350
351 def test_async_yield_explicit_asend_and_send():
352 async def mygen(y):
353 assert y == 4983
354 x = yield 5
355 assert x == 2189
356 yield "ok"
357
358 g = mygen(4983)
359 e = raises(TypeError, g.asend(None).send, 42)
360 assert str(e.value) == ("can't send non-None value to a just-started "
361 "async generator")
362 e = raises(StopIteration, g.asend(None).send, None)
363 assert e.value.args == (5,)
364 e = raises(StopIteration, g.asend("IGNORED").send, 2189) # xxx
365 assert e.value.args == ("ok",)
366
367 def test_async_yield_explicit_asend_used_several_times():
368 class X:
369 def __await__(self):
370 r = yield -2
371 assert r == "cont1"
372 r = yield -3
373 assert r == "cont2"
374 return -4
375 async def mygen(y):
376 x = await X()
377 assert x == -4
378 r = yield -5
379 assert r == "foo"
380 r = yield -6
381 assert r == "bar"
382
383 g = mygen(4983)
384 gs = g.asend(None)
385 r = gs.send(None)
386 assert r == -2
387 r = gs.send("cont1")
388 assert r == -3
389 e = raises(StopIteration, gs.send, "cont2")
390 assert e.value.args == (-5,)
391 e = raises(RuntimeError, gs.send, None)
392 e = raises(RuntimeError, gs.send, None)
393 #
394 gs = g.asend("foo")
395 e = raises(StopIteration, gs.send, None)
396 assert e.value.args == (-6,)
397 e = raises(RuntimeError, gs.send, "bar")
398
399 def test_async_yield_asend_notnone_throw():
400 async def f():
401 yield 123
402
403 raises(ValueError, f().asend(42).throw, ValueError)
404
405 def test_async_yield_asend_none_throw():
406 async def f():
407 yield 123
408
409 raises(ValueError, f().asend(None).throw, ValueError)
410
411 def test_async_yield_athrow_send_none():
412 async def ag():
413 yield 42
414
415 raises(ValueError, ag().athrow(ValueError).send, None)
416
417 def test_async_yield_athrow_send_notnone():
418 async def ag():
419 yield 42
420
421 ex = raises(RuntimeError, ag().athrow(ValueError).send, 42)
422 expected = ("can't send non-None value to a just-started coroutine", )
423 assert ex.value.args == expected
424
425 def test_async_yield_athrow_send_after_exception():
426 async def ag():
427 yield 42
428
429 athrow_coro = ag().athrow(ValueError)
430 raises(ValueError, athrow_coro.send, None)
431 raises(RuntimeError, athrow_coro.send, None)
432
433 def test_async_yield_athrow_throw():
434 async def ag():
435 yield 42
436
437 with raises(LookupError):
438 ag().athrow(ValueError).throw(LookupError)
439 # CPython's message makes little sense; PyPy's message is different
440
441 def test_async_yield_athrow_while_running():
442 values = []
443 async def ag():
444 try:
445 received = yield 1
446 except ValueError:
447 values.append(42)
448 return
449 yield 2
450
451
452 async def run():
453 running = ag()
454 x = await running.asend(None)
455 assert x == 1
456 try:
457 await running.athrow(ValueError)
458 except StopAsyncIteration:
459 pass
460
461
462 try:
463 run().send(None)
464 except StopIteration:
465 assert values == [42]
466
467 def test_async_aclose():
468 raises_generator_exit = False
469 async def ag():
470 nonlocal raises_generator_exit
471 try:
472 yield
473 except GeneratorExit:
474 raises_generator_exit = True
475 raise
476
477 async def run():
478 a = ag()
479 async for i in a:
480 break
481 await a.aclose()
482 try:
483 run().send(None)
484 except StopIteration:
485 pass
486 assert raises_generator_exit
487
488 def test_async_aclose_ignore_generator_exit():
489 async def ag():
490 try:
491 yield
492 except GeneratorExit:
493 yield
494
495 async def run():
496 a = ag()
497 async for i in a:
498 break
499 await a.aclose()
500 raises(RuntimeError, run().send, None)
501
502 def test_async_aclose_await_in_finally():
503 state = 0
504 async def ag():
505 nonlocal state
506 try:
507 yield
508 finally:
509 state = 1
510 await suspend('coro')
511 state = 2
512
513 async def run():
514 a = ag()
515 async for i in a:
516 break
517 await a.aclose()
518 a = run()
519 assert state == 0
520 assert a.send(None) == 'coro'
521 assert state == 1
522 try:
523 a.send(None)
524 except StopIteration:
525 pass
526 assert state == 2
527
528 def test_async_aclose_await_in_finally_with_exception():
529 state = 0
530 async def ag():
531 nonlocal state
532 try:
533 yield
534 finally:
535 state = 1
536 try:
537 await suspend('coro')
538 except Exception as exc:
539 state = exc
540
541 async def run():
542 a = ag()
543 async for i in a:
544 break
545 await a.aclose()
546 a = run()
547 assert state == 0
548 assert a.send(None) == 'coro'
549 assert state == 1
550 exc = RuntimeError()
551 try:
552 a.throw(exc)
553 except StopIteration:
554 pass
555 assert state == exc
556
557 def test_agen_aclose_await_and_yield_in_finally():
558 async def foo():
559 try:
560 yield 1
561 1 / 0
562 finally:
563 await suspend(42)
564 yield 12
565
566 async def run():
567 gen = foo()
568 it = gen.__aiter__()
569 await it.__anext__()
570 await gen.aclose()
571
572 coro = run()
573 assert coro.send(None) == 42
574 with pytest.raises(RuntimeError):
575 coro.send(None)
576
577 def test_async_aclose_in_finalize_hook_await_in_finally():
578 state = 0
579 async def ag():
580 nonlocal state
581 try:
582 yield
583 finally:
584 state = 1
585 await suspend('coro')
586 state = 2
587
588 async def run():
589 a = ag()
590 async for i in a:
591 break
592 del a
593 gc.collect()
594 gc.collect()
595 gc.collect()
596 a = run()
597
598 a2 = None
599 assert sys.get_asyncgen_hooks() == (None, None)
600 def _finalize(g):
601 nonlocal a2
602 a2 = g.aclose()
603 sys.set_asyncgen_hooks(finalizer=_finalize)
604 assert state == 0
605 with pytest.raises(StopIteration):
606 a.send(None)
607 assert a2.send(None) == 'coro'
608 assert state == 1
609 with pytest.raises(StopIteration):
610 a2.send(None)
611 assert state == 2
612 sys.set_asyncgen_hooks(None, None)
613
614 def test_async_anext_close():
615 async def ag():
616 yield 42
617
618 an = ag().__anext__()
619 an.close()
620 try:
621 next(an)
622 except RuntimeError:
623 pass
624 else:
625 assert False, "didn't raise"
626
627 def run_async(coro):
628 buffer = []
629 result = None
630 while True:
631 try:
632 buffer.append(coro.send(None))
633 except StopIteration as ex:
634 result = ex.args[0] if ex.args else None
635 break
636 return buffer, result
637
638 def test_async_generator():
639 async def f(i):
640 return i
641
642 async def run_list():
643 return [await c for c in [f(1), f(41)]]
644
645 assert run_async(run_list()) == ([], [1, 41])
646
647 def test_async_genexpr():
648 async def f(it):
649 for i in it:
650 yield i
651
652 async def run_gen():
653 gen = (i + 1 async for i in f([10, 20]))
654 return [g + 100 async for g in gen]
655
656 assert run_async(run_gen()) == ([], [111, 121])
657
658 def test_anext_tuple():
659 async def foo():
660 try:
661 yield (1,)
662 except ZeroDivisionError:
663 yield (2,)
664
665 async def run():
666 it = foo().__aiter__()
667 return await it.__anext__()
668
669 assert run_async(run()) == ([], (1,))
670
671 def test_async_genexpr_in_regular_function():
672 async def arange(n):
673 for i in range(n):
674 yield i
675
676 def make_arange(n):
677 # This syntax is legal starting with Python 3.7
678 return (i * 2 async for i in arange(n))
679
680 async def run():
681 return [i async for i in make_arange(10)]
682 res = run_async(run())
683 assert res[1] == [i * 2 for i in range(10)]
684
685 # Helpers for test_async_gen_exception_11() below
686 def sync_iterate(g):
687 res = []
688 while True:
689 try:
690 res.append(g.__next__())
691 except StopIteration:
692 res.append('STOP')
693 break
694 except Exception as ex:
695 res.append(str(type(ex)))
696 return res
697
698 def async_iterate(g):
699 res = []
700 while True:
701 try:
702 g.__anext__().__next__()
703 except StopAsyncIteration:
704 res.append('STOP')
705 break
706 except StopIteration as ex:
707 if ex.args:
708 res.append(ex.args[0])
709 else:
710 res.append('EMPTY StopIteration')
711 break
712 except Exception as ex:
713 res.append(str(type(ex)))
714 return res
715
716
717 def test_async_gen_exception_11():
718 # bpo-33786
719 def sync_gen():
720 yield 10
721 yield 20
722
723 def sync_gen_wrapper():
724 yield 1
725 sg = sync_gen()
726 sg.send(None)
727 try:
728 sg.throw(GeneratorExit())
729 except GeneratorExit:
730 yield 2
731 yield 3
732
733 async def async_gen():
734 yield 10
735 yield 20
736
737 async def async_gen_wrapper():
738 yield 1
739 asg = async_gen()
740 await asg.asend(None)
741 try:
742 await asg.athrow(GeneratorExit())
743 except GeneratorExit:
744 yield 2
745 yield 3
746
747 sync_gen_result = sync_iterate(sync_gen_wrapper())
748 async_gen_result = async_iterate(async_gen_wrapper())
749 assert sync_gen_result == async_gen_result
750
751 def test_asyncgen_yield_stopiteration():
752 async def foo():
753 yield 1
754 yield StopIteration(2)
755
756 async def run():
757 it = foo().__aiter__()
758 val1 = await it.__anext__()
759 assert val1 == 1
760 val2 = await it.__anext__()
761 assert isinstance(val2, StopIteration)
762 assert val2.value == 2
763
764 run_async(run())
765
766 def test_asyncgen_hooks_shutdown():
767 finalized = 0
768 asyncgens = []
769
770 def register_agen(agen):
771 asyncgens.append(agen)
772
773 async def waiter(timeout):
774 nonlocal finalized
775 try:
776 await suspend('running waiter')
777 yield 1
778 finally:
779 await suspend('closing waiter')
780 finalized += 1
781
782 async def wait():
783 async for _ in waiter(1):
784 pass
785
786 task1 = wait()
787 task2 = wait()
788 old_hooks = sys.get_asyncgen_hooks()
789 try:
790 sys.set_asyncgen_hooks(firstiter=register_agen)
791 assert task1.send(None) == 'running waiter'
792 assert task2.send(None) == 'running waiter'
793 assert len(asyncgens) == 2
794
795 assert run_async(asyncgens[0].aclose()) == (['closing waiter'], None)
796 assert run_async(asyncgens[1].aclose()) == (['closing waiter'], None)
797 assert finalized == 2
798 finally:
799 sys.set_asyncgen_hooks(*old_hooks)
800
801 def test_coroutine_capture_origin():
802 import contextlib
803
804 def here():
805 f = sys._getframe().f_back
806 return (f.f_code.co_filename, f.f_lineno)
807
808 try:
809 async def corofn():
810 pass
811
812 with contextlib.closing(corofn()) as coro:
813 assert coro.cr_origin is None
814
815 sys.set_coroutine_origin_tracking_depth(1)
816
817 fname, lineno = here()
818 with contextlib.closing(corofn()) as coro:
819 print(coro.cr_origin)
820 assert coro.cr_origin == (
821 (fname, lineno + 1, "test_coroutine_capture_origin"),)
822
823
824 sys.set_coroutine_origin_tracking_depth(2)
825
826 def nested():
827 return (here(), corofn())
828 fname, lineno = here()
829 ((nested_fname, nested_lineno), coro) = nested()
830 with contextlib.closing(coro):
831 print(coro.cr_origin)
832 assert coro.cr_origin == (
833 (nested_fname, nested_lineno, "nested"),
834 (fname, lineno + 1, "test_coroutine_capture_origin"))
835
836 # Check we handle running out of frames correctly
837 sys.set_coroutine_origin_tracking_depth(1000)
838 with contextlib.closing(corofn()) as coro:
839 print(coro.cr_origin)
840 assert 1 <= len(coro.cr_origin) < 1000
841 finally:
842 sys.set_coroutine_origin_tracking_depth(0)
843
844 def test_runtime_warning_origin_tracking():
845 async def foobaz():
846 pass
847 gc.collect() # emit warnings from unrelated older tests
848 with warnings.catch_warnings(record=True) as l:
849 foobaz()
850 gc.collect()
851 gc.collect()
852 gc.collect()
853
854 assert len(l) == 1, repr(l)
855 w = l[0].message
856 assert isinstance(w, RuntimeWarning)
857 assert str(w).startswith("coroutine ")
858 assert str(w).endswith("foobaz' was never awaited")
859 assert "test_runtime_warning_origin_tracking" in str(w)
860
861 def test_cr_frame_access_before_await_no_spurious_warning():
862 # issue 5454: accessing cr_frame before awaiting must not emit a warning
863 import warnings
864 async def other_async_thing():
865 pass
866 gc.collect()
867 with warnings.catch_warnings(record=True) as l:
868 warnings.simplefilter("always")
869 coro = other_async_thing()
870 _ = coro.cr_frame # inspect frame before awaiting
871 try:
872 coro.send(None) # drive to completion
873 except StopIteration:
874 pass
875 gc.collect()
876 gc.collect()
877 runtime_warnings = [w for w in l if issubclass(w.category, RuntimeWarning)]
878 assert runtime_warnings == [], repr(runtime_warnings)
879
880 def test_await_multiple_times_same_gen():
881 async def async_iterate():
882 yield 1
883 yield 2
884
885 async def run():
886 it = async_iterate()
887 nxt = it.__anext__()
888 await nxt
889 with pytest.raises(RuntimeError):
890 await nxt
891
892 coro = it.aclose()
893 await coro
894 with pytest.raises(RuntimeError):
895 await coro
896
897 run_async(run())
898
899 def test_async_generator_wrapped_value_is_real_type():
900 def tracer(frame, evt, *args):
901 str(args) # used to crash when seeing the AsyncGenValueWrapper
902 return tracer
903
904 async def async_gen():
905 yield -2
906
907 async def async_test():
908 a = 2
909 async for i in async_gen():
910 a = 4
911 else:
912 a = 6
913
914 def run():
915 x = async_test()
916 try:
917 sys.settrace(tracer)
918 x.send(None)
919 finally:
920 sys.settrace(None)
921 raises(StopIteration, run)
922
923 def test_async_listcomp_bug():
924 async def f(it):
925 for i in it:
926 yield i
927
928 async def run_list():
929 return [i + 1 async for seq in f([(10, 20), (30,)])
930 for i in seq]
931
932 assert run_async(run_list()) == ([], [11, 21, 31])
933
934 # this one includes the name binding hack
935 async def run_list():
936 return [j async for seq in f([(10, 20), (30,)])
937 for i in seq for j in [i + 1]]
938
939 assert run_async(run_list()) == ([], [11, 21, 31])
940
941 def test_ag_running_asend_send():
942 async def agen():
943 await suspend('coro')
944 yield 0
945
946 a = agen()
947 assert a.ag_running is False
948 coro = a.asend(None)
949 res = coro.send(None)
950 assert res == 'coro'
951 assert a.ag_running is True
952 with raises(RuntimeError):
953 a.asend(None).send(None)
954 with raises(StopIteration) as info:
955 res = coro.send(None)
956 assert info.value.value == 0
957 assert a.ag_running is False
958
959 async def asynciter(iterable):
960 """Convert an iterable to an asynchronous iterator."""
961 for x in iterable:
962 yield x
963
964 def test_nested_comprehension():
965 async def run_list_inside_list():
966 return [[i + j async for i in asynciter([1, 2])] for j in [10, 20]]
967 res = run_async(run_list_inside_list())
968 assert res == ([], [[11, 12], [21, 22]])
969
970 def test_nested_comprehension_syntax_error_regression():
971 s = '''if 1:
972 def bar():
973 [i async for i in els]
974 '''
975 with raises(SyntaxError) as info:
976 exec(s)
977
978 def test_ag_suspended():
979 import types
980 @types.coroutine
981 def a():
982 yield
983
984 async def c():
985 await a()
986
987 async def b():
988 assert coro_b.cr_running
989 assert not coro_b.cr_suspended
990 await c()
991
992 coro_b = b()
993 assert not coro_b.cr_running
994 assert not coro_b.cr_suspended
995 coro_b.send(None)
996 assert not coro_b.cr_running
997 assert coro_b.cr_suspended
998 with raises(StopIteration):
999 coro_b.send(None)
1000 assert not coro_b.cr_suspended
1001
1002
1003 def _run_async(coro):
1004 import types
1005 assert type(coro) in {types.GeneratorType, types.CoroutineType}
1006 result = None
1007 while True:
1008 try:
1009 coro.send(None)
1010 except StopIteration as ex:
1011 result = ex.args[0] if ex.args else None
1012 break
1013 return result
1014
1015 def test_async_with_break_non_awaitable_aexit():
1016 # async with whose __aexit__ returns a non-awaitable, body exits via break.
1017 # Should raise TypeError (not segfault).
1018 class CM:
1019 async def __aenter__(self):
1020 return self
1021 def __aexit__(self, *e):
1022 return 456 # not awaitable
1023
1024 async def foo():
1025 for i in range(2):
1026 async with CM():
1027 break
1028
1029 with raises(TypeError, match="'async with' received an object from __aexit__"):
1030 _run_async(foo())
1031
1032 def test_async_with_continue_non_awaitable_aexit():
1033 # async with whose __aexit__ returns a non-awaitable, body exits via continue.
1034 # Same cleanup path as break; should raise TypeError.
1035 class CM:
1036 async def __aenter__(self):
1037 return self
1038 def __aexit__(self, *e):
1039 return 456 # not awaitable
1040
1041 async def foo():
1042 for i in range(1):
1043 async with CM():
1044 continue
1045
1046 with raises(TypeError, match="'async with' received an object from __aexit__"):
1047 _run_async(foo())
1048
1049 def test_async_with_return_non_awaitable_aexit():
1050 # async with whose __aexit__ returns a non-awaitable, body exits via return.
1051 # Exercises the preserve_tos cleanup path; should raise TypeError.
1052 class CM:
1053 async def __aenter__(self):
1054 return self
1055 def __aexit__(self, *e):
1056 return 456 # not awaitable
1057
1058 async def foo():
1059 async with CM():
1060 return 42
1061
1062 with raises(TypeError, match="'async with' received an object from __aexit__"):
1063 _run_async(foo())
1064
1065 def test_nested_async_with_break_non_awaitable_aexit():
1066 # nested async with; inner __aexit__ returns non-awaitable, body exits via break.
1067 # Verifies outer exception table entry is not accidentally triggered.
1068 class GoodCM:
1069 async def __aenter__(self):
1070 return self
1071 async def __aexit__(self, *e):
1072 return False
1073
1074 class BadCM:
1075 async def __aenter__(self):
1076 return self
1077 def __aexit__(self, *e):
1078 return 456 # not awaitable
1079
1080 async def foo():
1081 for i in range(1):
1082 async with GoodCM():
1083 async with BadCM():
1084 break
1085
1086 with raises(TypeError, match="'async with' received an object from __aexit__"):
1087 _run_async(foo())