Debian Codegraph @

lib-python/3/test/test_coroutines.py

raw symbols SCIP
1 import contextlib
2 import copy
3 import inspect
4 import pickle
5 import sys
6 import types
7 import traceback
8 import unittest
9 import warnings
10 from test import support
11 from test.support import import_helper
12 from test.support import warnings_helper
13 from test.support.script_helper import assert_python_ok
14
15 def _getrefcount(obj):
16 if hasattr(sys, 'getrefcount'):
17 return sys.getrefcount(obj)
18 return '<no reference counts on this implementation>'
19
20
21 class AsyncYieldFrom:
22 def __init__(self, obj):
23 self.obj = obj
24
25 def __await__(self):
26 yield from self.obj
27
28
29 class AsyncYield:
30 def __init__(self, value):
31 self.value = value
32
33 def __await__(self):
34 yield self.value
35
36
37 async def asynciter(iterable):
38 """Convert an iterable to an asynchronous iterator."""
39 for x in iterable:
40 yield x
41
42
43 def run_async(coro):
44 assert coro.__class__ in {types.GeneratorType, types.CoroutineType}
45
46 buffer = []
47 result = None
48 while True:
49 try:
50 buffer.append(coro.send(None))
51 except StopIteration as ex:
52 result = ex.args[0] if ex.args else None
53 break
54 return buffer, result
55
56
57 def run_async__await__(coro):
58 assert coro.__class__ is types.CoroutineType
59 aw = coro.__await__()
60 buffer = []
61 result = None
62 i = 0
63 while True:
64 try:
65 if i % 2:
66 buffer.append(next(aw))
67 else:
68 buffer.append(aw.send(None))
69 i += 1
70 except StopIteration as ex:
71 result = ex.args[0] if ex.args else None
72 break
73 return buffer, result
74
75
76 @contextlib.contextmanager
77 def silence_coro_gc():
78 with warnings.catch_warnings():
79 warnings.simplefilter("ignore")
80 yield
81 support.gc_collect()
82
83
84 class AsyncBadSyntaxTest(unittest.TestCase):
85
86 def test_badsyntax_1(self):
87 samples = [
88 """def foo():
89 await something()
90 """,
91
92 """await something()""",
93
94 """async def foo():
95 yield from []
96 """,
97
98 """async def foo():
99 await await fut
100 """,
101
102 """async def foo(a=await something()):
103 pass
104 """,
105
106 """async def foo(a:await something()):
107 pass
108 """,
109
110 """async def foo():
111 def bar():
112 [i async for i in els]
113 """,
114
115 """async def foo():
116 def bar():
117 [await i for i in els]
118 """,
119
120 """async def foo():
121 def bar():
122 [i for i in els
123 async for b in els]
124 """,
125
126 """async def foo():
127 def bar():
128 [i for i in els
129 for c in b
130 async for b in els]
131 """,
132
133 """async def foo():
134 def bar():
135 [i for i in els
136 async for b in els
137 for c in b]
138 """,
139
140 """async def foo():
141 def bar():
142 [[async for i in b] for b in els]
143 """,
144
145 """async def foo():
146 def bar():
147 [i for i in els
148 for b in await els]
149 """,
150
151 """async def foo():
152 def bar():
153 [i for i in els
154 for b in els
155 if await b]
156 """,
157
158 """async def foo():
159 def bar():
160 [i for i in await els]
161 """,
162
163 """async def foo():
164 def bar():
165 [i for i in els if await i]
166 """,
167
168 """def bar():
169 [i async for i in els]
170 """,
171
172 """def bar():
173 {i: i async for i in els}
174 """,
175
176 """def bar():
177 {i async for i in els}
178 """,
179
180 """def bar():
181 [await i for i in els]
182 """,
183
184 """def bar():
185 [i for i in els
186 async for b in els]
187 """,
188
189 """def bar():
190 [i for i in els
191 for c in b
192 async for b in els]
193 """,
194
195 """def bar():
196 [i for i in els
197 async for b in els
198 for c in b]
199 """,
200
201 """def bar():
202 [i for i in els
203 for b in await els]
204 """,
205
206 """def bar():
207 [i for i in els
208 for b in els
209 if await b]
210 """,
211
212 """def bar():
213 [i for i in await els]
214 """,
215
216 """def bar():
217 [i for i in els if await i]
218 """,
219
220 """def bar():
221 [[i async for i in a] for a in elts]
222 """,
223
224 """[[i async for i in a] for a in elts]
225 """,
226
227 """async def foo():
228 await
229 """,
230
231 """async def foo():
232 def bar(): pass
233 await = 1
234 """,
235
236 """async def foo():
237
238 def bar(): pass
239 await = 1
240 """,
241
242 """async def foo():
243 def bar(): pass
244 if 1:
245 await = 1
246 """,
247
248 """def foo():
249 async def bar(): pass
250 if 1:
251 await a
252 """,
253
254 """def foo():
255 async def bar(): pass
256 await a
257 """,
258
259 """def foo():
260 def baz(): pass
261 async def bar(): pass
262 await a
263 """,
264
265 """def foo():
266 def baz(): pass
267 # 456
268 async def bar(): pass
269 # 123
270 await a
271 """,
272
273 """async def foo():
274 def baz(): pass
275 # 456
276 async def bar(): pass
277 # 123
278 await = 2
279 """,
280
281 """def foo():
282
283 def baz(): pass
284
285 async def bar(): pass
286
287 await a
288 """,
289
290 """async def foo():
291
292 def baz(): pass
293
294 async def bar(): pass
295
296 await = 2
297 """,
298
299 """async def foo():
300 def async(): pass
301 """,
302
303 """async def foo():
304 def await(): pass
305 """,
306
307 """async def foo():
308 def bar():
309 await
310 """,
311
312 """async def foo():
313 return lambda async: await
314 """,
315
316 """async def foo():
317 return lambda a: await
318 """,
319
320 """await a()""",
321
322 """async def foo(a=await b):
323 pass
324 """,
325
326 """async def foo(a:await b):
327 pass
328 """,
329
330 """def baz():
331 async def foo(a=await b):
332 pass
333 """,
334
335 """async def foo(async):
336 pass
337 """,
338
339 """async def foo():
340 def bar():
341 def baz():
342 async = 1
343 """,
344
345 """async def foo():
346 def bar():
347 def baz():
348 pass
349 async = 1
350 """,
351
352 """def foo():
353 async def bar():
354
355 async def baz():
356 pass
357
358 def baz():
359 42
360
361 async = 1
362 """,
363
364 """async def foo():
365 def bar():
366 def baz():
367 pass\nawait foo()
368 """,
369
370 """def foo():
371 def bar():
372 async def baz():
373 pass\nawait foo()
374 """,
375
376 """async def foo(await):
377 pass
378 """,
379
380 """def foo():
381
382 async def bar(): pass
383
384 await a
385 """,
386
387 """def foo():
388 async def bar():
389 pass\nawait a
390 """,
391 """def foo():
392 async for i in arange(2):
393 pass
394 """,
395 """def foo():
396 async with resource:
397 pass
398 """,
399 """async with resource:
400 pass
401 """,
402 """async for i in arange(2):
403 pass
404 """,
405 ]
406
407 for code in samples:
408 with self.subTest(code=code), self.assertRaises(SyntaxError):
409 compile(code, "<test>", "exec")
410
411 def test_badsyntax_2(self):
412 samples = [
413 """def foo():
414 await = 1
415 """,
416
417 """class Bar:
418 def async(): pass
419 """,
420
421 """class Bar:
422 async = 1
423 """,
424
425 """class async:
426 pass
427 """,
428
429 """class await:
430 pass
431 """,
432
433 """import math as await""",
434
435 """def async():
436 pass""",
437
438 """def foo(*, await=1):
439 pass"""
440
441 """async = 1""",
442
443 """print(await=1)"""
444 ]
445
446 for code in samples:
447 with self.subTest(code=code), self.assertRaises(SyntaxError):
448 compile(code, "<test>", "exec")
449
450 def test_badsyntax_3(self):
451 with self.assertRaises(SyntaxError):
452 compile("async = 1", "<test>", "exec")
453
454 def test_badsyntax_4(self):
455 samples = [
456 '''def foo(await):
457 async def foo(): pass
458 async def foo():
459 pass
460 return await + 1
461 ''',
462
463 '''def foo(await):
464 async def foo(): pass
465 async def foo(): pass
466 return await + 1
467 ''',
468
469 '''def foo(await):
470
471 async def foo(): pass
472
473 async def foo(): pass
474
475 return await + 1
476 ''',
477
478 '''def foo(await):
479 """spam"""
480 async def foo(): \
481 pass
482 # 123
483 async def foo(): pass
484 # 456
485 return await + 1
486 ''',
487
488 '''def foo(await):
489 def foo(): pass
490 def foo(): pass
491 async def bar(): return await_
492 await_ = await
493 try:
494 bar().send(None)
495 except StopIteration as ex:
496 return ex.args[0] + 1
497 '''
498 ]
499
500 for code in samples:
501 with self.subTest(code=code), self.assertRaises(SyntaxError):
502 compile(code, "<test>", "exec")
503
504
505 class TokenizerRegrTest(unittest.TestCase):
506
507 def test_oneline_defs(self):
508 buf = []
509 for i in range(500):
510 buf.append('def i{i}(): return {i}'.format(i=i))
511 buf = '\n'.join(buf)
512
513 # Test that 500 consequent, one-line defs is OK
514 ns = {}
515 exec(buf, ns, ns)
516 self.assertEqual(ns['i499'](), 499)
517
518 # Test that 500 consequent, one-line defs *and*
519 # one 'async def' following them is OK
520 buf += '\nasync def foo():\n return'
521 ns = {}
522 exec(buf, ns, ns)
523 self.assertEqual(ns['i499'](), 499)
524 self.assertTrue(inspect.iscoroutinefunction(ns['foo']))
525
526
527 class CoroutineTest(unittest.TestCase):
528
529 def test_gen_1(self):
530 def gen(): yield
531 self.assertFalse(hasattr(gen, '__await__'))
532
533 def test_func_1(self):
534 async def foo():
535 return 10
536
537 f = foo()
538 self.assertIsInstance(f, types.CoroutineType)
539 self.assertTrue(bool(foo.__code__.co_flags & inspect.CO_COROUTINE))
540 self.assertFalse(bool(foo.__code__.co_flags & inspect.CO_GENERATOR))
541 self.assertTrue(bool(f.cr_code.co_flags & inspect.CO_COROUTINE))
542 self.assertFalse(bool(f.cr_code.co_flags & inspect.CO_GENERATOR))
543 self.assertEqual(run_async(f), ([], 10))
544
545 self.assertEqual(run_async__await__(foo()), ([], 10))
546
547 def bar(): pass
548 self.assertFalse(bool(bar.__code__.co_flags & inspect.CO_COROUTINE))
549
550 def test_func_2(self):
551 async def foo():
552 raise StopIteration
553
554 with self.assertRaisesRegex(
555 RuntimeError, "coroutine raised StopIteration"):
556
557 run_async(foo())
558
559 def test_func_3(self):
560 async def foo():
561 raise StopIteration
562
563 coro = foo()
564 self.assertRegex(repr(coro), '^<coroutine object.* at 0x.*>$')
565 coro.close()
566
567 def test_func_4(self):
568 async def foo():
569 raise StopIteration
570 coro = foo()
571
572 check = lambda: self.assertRaisesRegex(
573 TypeError, "'coroutine' object is not iterable")
574
575 with check():
576 list(coro)
577
578 with check():
579 tuple(coro)
580
581 with check():
582 sum(coro)
583
584 with check():
585 iter(coro)
586
587 with check():
588 for i in coro:
589 pass
590
591 with check():
592 [i for i in coro]
593
594 coro.close()
595
596 def test_func_5(self):
597 @types.coroutine
598 def bar():
599 yield 1
600
601 async def foo():
602 await bar()
603
604 check = lambda: self.assertRaisesRegex(
605 TypeError, "'coroutine' object is not iterable")
606
607 coro = foo()
608 with check():
609 for el in coro:
610 pass
611 coro.close()
612
613 # the following should pass without an error
614 for el in bar():
615 self.assertEqual(el, 1)
616 self.assertEqual([el for el in bar()], [1])
617 self.assertEqual(tuple(bar()), (1,))
618 self.assertEqual(next(iter(bar())), 1)
619
620 def test_func_6(self):
621 @types.coroutine
622 def bar():
623 yield 1
624 yield 2
625
626 async def foo():
627 await bar()
628
629 f = foo()
630 self.assertEqual(f.send(None), 1)
631 self.assertEqual(f.send(None), 2)
632 with self.assertRaises(StopIteration):
633 f.send(None)
634
635 def test_func_7(self):
636 async def bar():
637 return 10
638 coro = bar()
639
640 def foo():
641 yield from coro
642
643 with self.assertRaisesRegex(
644 TypeError,
645 "cannot 'yield from' a coroutine object in "
646 "a non-coroutine generator"):
647 list(foo())
648
649 coro.close()
650
651 def test_func_8(self):
652 @types.coroutine
653 def bar():
654 return (yield from coro)
655
656 async def foo():
657 return 'spam'
658
659 coro = foo()
660 self.assertEqual(run_async(bar()), ([], 'spam'))
661 coro.close()
662
663 def test_func_9(self):
664 async def foo():
665 pass
666
667 with self.assertWarnsRegex(
668 RuntimeWarning,
669 r"coroutine '.*test_func_9.*foo' was never awaited"):
670
671 foo()
672 support.gc_collect()
673
674 with self.assertWarnsRegex(
675 RuntimeWarning,
676 r"coroutine '.*test_func_9.*foo' was never awaited"):
677
678 with self.assertRaises(TypeError):
679 # See bpo-32703.
680 for _ in foo():
681 pass
682
683 support.gc_collect()
684
685 def test_func_10(self):
686 N = 0
687
688 @types.coroutine
689 def gen():
690 nonlocal N
691 try:
692 a = yield
693 yield (a ** 2)
694 except ZeroDivisionError:
695 N += 100
696 raise
697 finally:
698 N += 1
699
700 async def foo():
701 await gen()
702
703 coro = foo()
704 aw = coro.__await__()
705 self.assertIs(aw, iter(aw))
706 next(aw)
707 self.assertEqual(aw.send(10), 100)
708
709 self.assertEqual(N, 0)
710 aw.close()
711 self.assertEqual(N, 1)
712
713 coro = foo()
714 aw = coro.__await__()
715 next(aw)
716 with self.assertRaises(ZeroDivisionError):
717 aw.throw(ZeroDivisionError, None, None)
718 self.assertEqual(N, 102)
719
720 def test_func_11(self):
721 async def func(): pass
722 coro = func()
723 # Test that PyCoro_Type and _PyCoroWrapper_Type types were properly
724 # initialized
725 self.assertIn('__await__', dir(coro))
726 self.assertIn('__iter__', dir(coro.__await__()))
727 self.assertIn('coroutine_wrapper', repr(coro.__await__()))
728 coro.close() # avoid RuntimeWarning
729
730 def test_func_12(self):
731 async def g():
732 i = me.send(None)
733 await foo
734 me = g()
735 with self.assertRaisesRegex(ValueError,
736 "coroutine already executing"):
737 me.send(None)
738
739 def test_func_13(self):
740 async def g():
741 pass
742
743 coro = g()
744 with self.assertRaisesRegex(
745 TypeError,
746 "can't send non-None value to a just-started coroutine"):
747 coro.send('spam')
748
749 coro.close()
750
751 def test_func_14(self):
752 @types.coroutine
753 def gen():
754 yield
755 async def coro():
756 try:
757 await gen()
758 except GeneratorExit:
759 await gen()
760 c = coro()
761 c.send(None)
762 with self.assertRaisesRegex(RuntimeError,
763 "coroutine ignored GeneratorExit"):
764 c.close()
765
766 def test_func_15(self):
767 # See http://bugs.python.org/issue25887 for details
768
769 async def spammer():
770 return 'spam'
771 async def reader(coro):
772 return await coro
773
774 spammer_coro = spammer()
775
776 with self.assertRaisesRegex(StopIteration, 'spam'):
777 reader(spammer_coro).send(None)
778
779 with self.assertRaisesRegex(RuntimeError,
780 'cannot reuse already awaited coroutine'):
781 reader(spammer_coro).send(None)
782
783 def test_func_16(self):
784 # See http://bugs.python.org/issue25887 for details
785
786 @types.coroutine
787 def nop():
788 yield
789 async def send():
790 await nop()
791 return 'spam'
792 async def read(coro):
793 await nop()
794 return await coro
795
796 spammer = send()
797
798 reader = read(spammer)
799 reader.send(None)
800 reader.send(None)
801 with self.assertRaisesRegex(Exception, 'ham'):
802 reader.throw(Exception('ham'))
803
804 reader = read(spammer)
805 reader.send(None)
806 with self.assertRaisesRegex(RuntimeError,
807 'cannot reuse already awaited coroutine'):
808 reader.send(None)
809
810 with self.assertRaisesRegex(RuntimeError,
811 'cannot reuse already awaited coroutine'):
812 reader.throw(Exception('wat'))
813
814 def test_func_17(self):
815 # See http://bugs.python.org/issue25887 for details
816
817 async def coroutine():
818 return 'spam'
819
820 coro = coroutine()
821 with self.assertRaisesRegex(StopIteration, 'spam'):
822 coro.send(None)
823
824 with self.assertRaisesRegex(RuntimeError,
825 'cannot reuse already awaited coroutine'):
826 coro.send(None)
827
828 with self.assertRaisesRegex(RuntimeError,
829 'cannot reuse already awaited coroutine'):
830 coro.throw(Exception('wat'))
831
832 # Closing a coroutine shouldn't raise any exception even if it's
833 # already closed/exhausted (similar to generators)
834 coro.close()
835 coro.close()
836
837 def test_func_18(self):
838 # See http://bugs.python.org/issue25887 for details
839
840 async def coroutine():
841 return 'spam'
842
843 coro = coroutine()
844 await_iter = coro.__await__()
845 it = iter(await_iter)
846
847 with self.assertRaisesRegex(StopIteration, 'spam'):
848 it.send(None)
849
850 with self.assertRaisesRegex(RuntimeError,
851 'cannot reuse already awaited coroutine'):
852 it.send(None)
853
854 with self.assertRaisesRegex(RuntimeError,
855 'cannot reuse already awaited coroutine'):
856 # Although the iterator protocol requires iterators to
857 # raise another StopIteration here, we don't want to do
858 # that. In this particular case, the iterator will raise
859 # a RuntimeError, so that 'yield from' and 'await'
860 # expressions will trigger the error, instead of silently
861 # ignoring the call.
862 next(it)
863
864 with self.assertRaisesRegex(RuntimeError,
865 'cannot reuse already awaited coroutine'):
866 it.throw(Exception('wat'))
867
868 with self.assertRaisesRegex(RuntimeError,
869 'cannot reuse already awaited coroutine'):
870 it.throw(Exception('wat'))
871
872 # Closing a coroutine shouldn't raise any exception even if it's
873 # already closed/exhausted (similar to generators)
874 it.close()
875 it.close()
876
877 def test_func_19(self):
878 CHK = 0
879
880 @types.coroutine
881 def foo():
882 nonlocal CHK
883 yield
884 try:
885 yield
886 except GeneratorExit:
887 CHK += 1
888
889 async def coroutine():
890 await foo()
891
892 coro = coroutine()
893
894 coro.send(None)
895 coro.send(None)
896
897 self.assertEqual(CHK, 0)
898 coro.close()
899 self.assertEqual(CHK, 1)
900
901 for _ in range(3):
902 # Closing a coroutine shouldn't raise any exception even if it's
903 # already closed/exhausted (similar to generators)
904 coro.close()
905 self.assertEqual(CHK, 1)
906
907 def test_coro_wrapper_send_tuple(self):
908 async def foo():
909 return (10,)
910
911 result = run_async__await__(foo())
912 self.assertEqual(result, ([], (10,)))
913
914 def test_coro_wrapper_send_stop_iterator(self):
915 async def foo():
916 return StopIteration(10)
917
918 result = run_async__await__(foo())
919 self.assertIsInstance(result[1], StopIteration)
920 self.assertEqual(result[1].value, 10)
921
922 def test_cr_await(self):
923 @types.coroutine
924 def a():
925 self.assertEqual(inspect.getcoroutinestate(coro_b), inspect.CORO_RUNNING)
926 self.assertIsNone(coro_b.cr_await)
927 yield
928 self.assertEqual(inspect.getcoroutinestate(coro_b), inspect.CORO_RUNNING)
929 self.assertIsNone(coro_b.cr_await)
930
931 async def c():
932 await a()
933
934 async def b():
935 self.assertIsNone(coro_b.cr_await)
936 await c()
937 self.assertIsNone(coro_b.cr_await)
938
939 coro_b = b()
940 self.assertEqual(inspect.getcoroutinestate(coro_b), inspect.CORO_CREATED)
941 self.assertIsNone(coro_b.cr_await)
942
943 coro_b.send(None)
944 self.assertEqual(inspect.getcoroutinestate(coro_b), inspect.CORO_SUSPENDED)
945 self.assertEqual(coro_b.cr_await.cr_await.gi_code.co_name, 'a')
946
947 with self.assertRaises(StopIteration):
948 coro_b.send(None) # complete coroutine
949 self.assertEqual(inspect.getcoroutinestate(coro_b), inspect.CORO_CLOSED)
950 self.assertIsNone(coro_b.cr_await)
951
952 def test_corotype_1(self):
953 ct = types.CoroutineType
954 if not support.MISSING_C_DOCSTRINGS:
955 import sys
956 if sys.implementation.name == 'pypy':
957 send_msg = 'generator/coroutine'
958 close_msg = 'generator/coroutine'
959 throw_msg = 'generator/coroutine'
960 name_msg = 'of the coroutine'
961 else:
962 send_msg = 'into coroutine'
963 close_msg = 'inside coroutine'
964 throw_msg = 'in coroutine'
965 name_msg = 'of the coroutine'
966 self.assertIn(send_msg, ct.send.__doc__)
967 self.assertIn(close_msg, ct.close.__doc__)
968 self.assertIn(throw_msg, ct.throw.__doc__)
969 self.assertIn(name_msg, ct.__dict__['__name__'].__doc__)
970 self.assertIn(name_msg, ct.__dict__['__qualname__'].__doc__)
971 self.assertEqual(ct.__name__, 'coroutine')
972
973 async def f(): pass
974 c = f()
975 self.assertIn('coroutine object', repr(c))
976 c.close()
977
978 def test_await_1(self):
979
980 async def foo():
981 await 1
982 with self.assertRaisesRegex(TypeError, "object int can.t.*await"):
983 run_async(foo())
984
985 def test_await_2(self):
986 async def foo():
987 await []
988 with self.assertRaisesRegex(TypeError, "object list can.t.*await"):
989 run_async(foo())
990
991 def test_await_3(self):
992 async def foo():
993 await AsyncYieldFrom([1, 2, 3])
994
995 self.assertEqual(run_async(foo()), ([1, 2, 3], None))
996 self.assertEqual(run_async__await__(foo()), ([1, 2, 3], None))
997
998 def test_await_4(self):
999 async def bar():
1000 return 42
1001
1002 async def foo():
1003 return await bar()
1004
1005 self.assertEqual(run_async(foo()), ([], 42))
1006
1007 def test_await_5(self):
1008 class Awaitable:
1009 def __await__(self):
1010 return
1011
1012 async def foo():
1013 return (await Awaitable())
1014
1015 with self.assertRaisesRegex(
1016 TypeError, "__await__.*returned non-iterator of type"):
1017
1018 run_async(foo())
1019
1020 def test_await_6(self):
1021 class Awaitable:
1022 def __await__(self):
1023 return iter([52])
1024
1025 async def foo():
1026 return (await Awaitable())
1027
1028 self.assertEqual(run_async(foo()), ([52], None))
1029
1030 def test_await_7(self):
1031 class Awaitable:
1032 def __await__(self):
1033 yield 42
1034 return 100
1035
1036 async def foo():
1037 return (await Awaitable())
1038
1039 self.assertEqual(run_async(foo()), ([42], 100))
1040
1041 def test_await_8(self):
1042 class Awaitable:
1043 pass
1044
1045 async def foo(): return await Awaitable()
1046
1047 with self.assertRaisesRegex(
1048 TypeError, "object Awaitable can't be used in 'await' expression"):
1049
1050 run_async(foo())
1051
1052 def test_await_9(self):
1053 def wrap():
1054 return bar
1055
1056 async def bar():
1057 return 42
1058
1059 async def foo():
1060 db = {'b': lambda: wrap}
1061
1062 class DB:
1063 b = wrap
1064
1065 return (await bar() + await wrap()() + await db['b']()()() +
1066 await bar() * 1000 + await DB.b()())
1067
1068 async def foo2():
1069 return -await bar()
1070
1071 self.assertEqual(run_async(foo()), ([], 42168))
1072 self.assertEqual(run_async(foo2()), ([], -42))
1073
1074 def test_await_10(self):
1075 async def baz():
1076 return 42
1077
1078 async def bar():
1079 return baz()
1080
1081 async def foo():
1082 return await (await bar())
1083
1084 self.assertEqual(run_async(foo()), ([], 42))
1085
1086 def test_await_11(self):
1087 def ident(val):
1088 return val
1089
1090 async def bar():
1091 return 'spam'
1092
1093 async def foo():
1094 return ident(val=await bar())
1095
1096 async def foo2():
1097 return await bar(), 'ham'
1098
1099 self.assertEqual(run_async(foo2()), ([], ('spam', 'ham')))
1100
1101 def test_await_12(self):
1102 async def coro():
1103 return 'spam'
1104 c = coro()
1105
1106 class Awaitable:
1107 def __await__(self):
1108 return c
1109
1110 async def foo():
1111 return await Awaitable()
1112
1113 with self.assertRaisesRegex(
1114 TypeError, r"__await__\(\) returned a coroutine"):
1115 run_async(foo())
1116
1117 c.close()
1118
1119 def test_await_13(self):
1120 class Awaitable:
1121 def __await__(self):
1122 return self
1123
1124 async def foo():
1125 return await Awaitable()
1126
1127 with self.assertRaisesRegex(
1128 TypeError, "__await__.*returned non-iterator of type"):
1129
1130 run_async(foo())
1131
1132 def test_await_14(self):
1133 class Wrapper:
1134 # Forces the interpreter to use CoroutineType.__await__
1135 def __init__(self, coro):
1136 assert coro.__class__ is types.CoroutineType
1137 self.coro = coro
1138 def __await__(self):
1139 return self.coro.__await__()
1140
1141 class FutureLike:
1142 def __await__(self):
1143 return (yield)
1144
1145 class Marker(Exception):
1146 pass
1147
1148 async def coro1():
1149 try:
1150 return await FutureLike()
1151 except ZeroDivisionError:
1152 raise Marker
1153 async def coro2():
1154 return await Wrapper(coro1())
1155
1156 c = coro2()
1157 c.send(None)
1158 with self.assertRaisesRegex(StopIteration, 'spam'):
1159 c.send('spam')
1160
1161 c = coro2()
1162 c.send(None)
1163 with self.assertRaises(Marker):
1164 c.throw(ZeroDivisionError)
1165
1166 def test_await_15(self):
1167 @types.coroutine
1168 def nop():
1169 yield
1170
1171 async def coroutine():
1172 await nop()
1173
1174 async def waiter(coro):
1175 await coro
1176
1177 coro = coroutine()
1178 coro.send(None)
1179
1180 with self.assertRaisesRegex(RuntimeError,
1181 "coroutine is being awaited already"):
1182 waiter(coro).send(None)
1183
1184 def test_await_16(self):
1185 # See https://bugs.python.org/issue29600 for details.
1186
1187 async def f():
1188 return ValueError()
1189
1190 async def g():
1191 try:
1192 raise KeyError
1193 except:
1194 return await f()
1195
1196 _, result = run_async(g())
1197 self.assertIsNone(result.__context__)
1198
1199 def test_with_1(self):
1200 class Manager:
1201 def __init__(self, name):
1202 self.name = name
1203
1204 async def __aenter__(self):
1205 await AsyncYieldFrom(['enter-1-' + self.name,
1206 'enter-2-' + self.name])
1207 return self
1208
1209 async def __aexit__(self, *args):
1210 await AsyncYieldFrom(['exit-1-' + self.name,
1211 'exit-2-' + self.name])
1212
1213 if self.name == 'B':
1214 return True
1215
1216
1217 async def foo():
1218 async with Manager("A") as a, Manager("B") as b:
1219 await AsyncYieldFrom([('managers', a.name, b.name)])
1220 1/0
1221
1222 f = foo()
1223 result, _ = run_async(f)
1224
1225 self.assertEqual(
1226 result, ['enter-1-A', 'enter-2-A', 'enter-1-B', 'enter-2-B',
1227 ('managers', 'A', 'B'),
1228 'exit-1-B', 'exit-2-B', 'exit-1-A', 'exit-2-A']
1229 )
1230
1231 async def foo():
1232 async with Manager("A") as a, Manager("C") as c:
1233 await AsyncYieldFrom([('managers', a.name, c.name)])
1234 1/0
1235
1236 with self.assertRaises(ZeroDivisionError):
1237 run_async(foo())
1238
1239 def test_with_2(self):
1240 class CM:
1241 def __aenter__(self):
1242 pass
1243
1244 body_executed = None
1245 async def foo():
1246 nonlocal body_executed
1247 body_executed = False
1248 async with CM():
1249 body_executed = True
1250
1251 with self.assertRaisesRegex(TypeError, 'asynchronous context manager.*__aexit__'):
1252 run_async(foo())
1253 self.assertIs(body_executed, False)
1254
1255 def test_with_3(self):
1256 class CM:
1257 def __aexit__(self):
1258 pass
1259
1260 body_executed = None
1261 async def foo():
1262 nonlocal body_executed
1263 body_executed = False
1264 async with CM():
1265 body_executed = True
1266
1267 with self.assertRaisesRegex(TypeError, 'asynchronous context manager'):
1268 run_async(foo())
1269 self.assertIs(body_executed, False)
1270
1271 def test_with_4(self):
1272 class CM:
1273 pass
1274
1275 body_executed = None
1276 async def foo():
1277 nonlocal body_executed
1278 body_executed = False
1279 async with CM():
1280 body_executed = True
1281
1282 with self.assertRaisesRegex(TypeError, 'asynchronous context manager'):
1283 run_async(foo())
1284 self.assertIs(body_executed, False)
1285
1286 def test_with_5(self):
1287 # While this test doesn't make a lot of sense,
1288 # it's a regression test for an early bug with opcodes
1289 # generation
1290
1291 class CM:
1292 async def __aenter__(self):
1293 return self
1294
1295 async def __aexit__(self, *exc):
1296 pass
1297
1298 async def func():
1299 async with CM():
1300 self.assertEqual((1, ), 1)
1301
1302 with self.assertRaises(AssertionError):
1303 run_async(func())
1304
1305 def test_with_6(self):
1306 class CM:
1307 def __aenter__(self):
1308 return 123
1309
1310 def __aexit__(self, *e):
1311 return 456
1312
1313 async def foo():
1314 async with CM():
1315 pass
1316
1317 with self.assertRaisesRegex(
1318 TypeError,
1319 "'async with' received an object from __aenter__ "
1320 "that does not implement __await__: int"):
1321 # it's important that __aexit__ wasn't called
1322 run_async(foo())
1323
1324 def test_with_7(self):
1325 class CM:
1326 async def __aenter__(self):
1327 return self
1328
1329 def __aexit__(self, *e):
1330 return 444
1331
1332 # Exit with exception
1333 async def foo():
1334 async with CM():
1335 1/0
1336
1337 try:
1338 run_async(foo())
1339 except TypeError as exc:
1340 self.assertRegex(
1341 exc.args[0],
1342 "'async with' received an object from __aexit__ "
1343 "that does not implement __await__: int")
1344 self.assertTrue(exc.__context__ is not None)
1345 self.assertTrue(isinstance(exc.__context__, ZeroDivisionError))
1346 else:
1347 self.fail('invalid asynchronous context manager did not fail')
1348
1349
1350 def test_with_8(self):
1351 CNT = 0
1352
1353 class CM:
1354 async def __aenter__(self):
1355 return self
1356
1357 def __aexit__(self, *e):
1358 return 456
1359
1360 # Normal exit
1361 async def foo():
1362 nonlocal CNT
1363 async with CM():
1364 CNT += 1
1365 with self.assertRaisesRegex(
1366 TypeError,
1367 "'async with' received an object from __aexit__ "
1368 "that does not implement __await__: int"):
1369 run_async(foo())
1370 self.assertEqual(CNT, 1)
1371
1372 # Exit with 'break'
1373 async def foo():
1374 nonlocal CNT
1375 for i in range(2):
1376 async with CM():
1377 CNT += 1
1378 break
1379 with self.assertRaisesRegex(
1380 TypeError,
1381 "'async with' received an object from __aexit__ "
1382 "that does not implement __await__: int"):
1383 run_async(foo())
1384 self.assertEqual(CNT, 2)
1385
1386 # Exit with 'continue'
1387 async def foo():
1388 nonlocal CNT
1389 for i in range(2):
1390 async with CM():
1391 CNT += 1
1392 continue
1393 with self.assertRaisesRegex(
1394 TypeError,
1395 "'async with' received an object from __aexit__ "
1396 "that does not implement __await__: int"):
1397 run_async(foo())
1398 self.assertEqual(CNT, 3)
1399
1400 # Exit with 'return'
1401 async def foo():
1402 nonlocal CNT
1403 async with CM():
1404 CNT += 1
1405 return
1406 with self.assertRaisesRegex(
1407 TypeError,
1408 "'async with' received an object from __aexit__ "
1409 "that does not implement __await__: int"):
1410 run_async(foo())
1411 self.assertEqual(CNT, 4)
1412
1413
1414 def test_with_9(self):
1415 CNT = 0
1416
1417 class CM:
1418 async def __aenter__(self):
1419 return self
1420
1421 async def __aexit__(self, *e):
1422 1/0
1423
1424 async def foo():
1425 nonlocal CNT
1426 async with CM():
1427 CNT += 1
1428
1429 with self.assertRaises(ZeroDivisionError):
1430 run_async(foo())
1431
1432 self.assertEqual(CNT, 1)
1433
1434 def test_with_10(self):
1435 CNT = 0
1436
1437 class CM:
1438 async def __aenter__(self):
1439 return self
1440
1441 async def __aexit__(self, *e):
1442 1/0
1443
1444 async def foo():
1445 nonlocal CNT
1446 async with CM():
1447 async with CM():
1448 raise RuntimeError
1449
1450 try:
1451 run_async(foo())
1452 except ZeroDivisionError as exc:
1453 self.assertTrue(exc.__context__ is not None)
1454 self.assertTrue(isinstance(exc.__context__, ZeroDivisionError))
1455 self.assertTrue(isinstance(exc.__context__.__context__,
1456 RuntimeError))
1457 else:
1458 self.fail('exception from __aexit__ did not propagate')
1459
1460 def test_with_11(self):
1461 CNT = 0
1462
1463 class CM:
1464 async def __aenter__(self):
1465 raise NotImplementedError
1466
1467 async def __aexit__(self, *e):
1468 1/0
1469
1470 async def foo():
1471 nonlocal CNT
1472 async with CM():
1473 raise RuntimeError
1474
1475 try:
1476 run_async(foo())
1477 except NotImplementedError as exc:
1478 self.assertTrue(exc.__context__ is None)
1479 else:
1480 self.fail('exception from __aenter__ did not propagate')
1481
1482 def test_with_12(self):
1483 CNT = 0
1484
1485 class CM:
1486 async def __aenter__(self):
1487 return self
1488
1489 async def __aexit__(self, *e):
1490 return True
1491
1492 async def foo():
1493 nonlocal CNT
1494 async with CM() as cm:
1495 self.assertIs(cm.__class__, CM)
1496 raise RuntimeError
1497
1498 run_async(foo())
1499
1500 def test_with_13(self):
1501 CNT = 0
1502
1503 class CM:
1504 async def __aenter__(self):
1505 1/0
1506
1507 async def __aexit__(self, *e):
1508 return True
1509
1510 async def foo():
1511 nonlocal CNT
1512 CNT += 1
1513 async with CM():
1514 CNT += 1000
1515 CNT += 10000
1516
1517 with self.assertRaises(ZeroDivisionError):
1518 run_async(foo())
1519 self.assertEqual(CNT, 1)
1520
1521 def test_for_1(self):
1522 aiter_calls = 0
1523
1524 class AsyncIter:
1525 def __init__(self):
1526 self.i = 0
1527
1528 def __aiter__(self):
1529 nonlocal aiter_calls
1530 aiter_calls += 1
1531 return self
1532
1533 async def __anext__(self):
1534 self.i += 1
1535
1536 if not (self.i % 10):
1537 await AsyncYield(self.i * 10)
1538
1539 if self.i > 100:
1540 raise StopAsyncIteration
1541
1542 return self.i, self.i
1543
1544
1545 buffer = []
1546 async def test1():
1547 async for i1, i2 in AsyncIter():
1548 buffer.append(i1 + i2)
1549
1550 yielded, _ = run_async(test1())
1551 # Make sure that __aiter__ was called only once
1552 self.assertEqual(aiter_calls, 1)
1553 self.assertEqual(yielded, [i * 100 for i in range(1, 11)])
1554 self.assertEqual(buffer, [i*2 for i in range(1, 101)])
1555
1556
1557 buffer = []
1558 async def test2():
1559 nonlocal buffer
1560 async for i in AsyncIter():
1561 buffer.append(i[0])
1562 if i[0] == 20:
1563 break
1564 else:
1565 buffer.append('what?')
1566 buffer.append('end')
1567
1568 yielded, _ = run_async(test2())
1569 # Make sure that __aiter__ was called only once
1570 self.assertEqual(aiter_calls, 2)
1571 self.assertEqual(yielded, [100, 200])
1572 self.assertEqual(buffer, [i for i in range(1, 21)] + ['end'])
1573
1574
1575 buffer = []
1576 async def test3():
1577 nonlocal buffer
1578 async for i in AsyncIter():
1579 if i[0] > 20:
1580 continue
1581 buffer.append(i[0])
1582 else:
1583 buffer.append('what?')
1584 buffer.append('end')
1585
1586 yielded, _ = run_async(test3())
1587 # Make sure that __aiter__ was called only once
1588 self.assertEqual(aiter_calls, 3)
1589 self.assertEqual(yielded, [i * 100 for i in range(1, 11)])
1590 self.assertEqual(buffer, [i for i in range(1, 21)] +
1591 ['what?', 'end'])
1592
1593 def test_for_2(self):
1594 tup = (1, 2, 3)
1595 refs_before = _getrefcount(tup)
1596
1597 async def foo():
1598 async for i in tup:
1599 print('never going to happen')
1600
1601 with self.assertRaisesRegex(
1602 TypeError, "async for' requires an object.*__aiter__.*tuple"):
1603
1604 run_async(foo())
1605
1606 self.assertEqual(_getrefcount(tup), refs_before)
1607
1608 def test_for_3(self):
1609 class I:
1610 def __aiter__(self):
1611 return self
1612
1613 aiter = I()
1614 refs_before = _getrefcount(aiter)
1615
1616 async def foo():
1617 async for i in aiter:
1618 print('never going to happen')
1619
1620 with self.assertRaisesRegex(
1621 TypeError,
1622 r"that does not implement __anext__"):
1623
1624 run_async(foo())
1625
1626 self.assertEqual(_getrefcount(aiter), refs_before)
1627
1628 def test_for_4(self):
1629 class I:
1630 def __aiter__(self):
1631 return self
1632
1633 def __anext__(self):
1634 return ()
1635
1636 aiter = I()
1637 refs_before = _getrefcount(aiter)
1638
1639 async def foo():
1640 async for i in aiter:
1641 print('never going to happen')
1642
1643 with self.assertRaisesRegex(
1644 TypeError,
1645 "async for' received an invalid object.*__anext__.*tuple"):
1646
1647 run_async(foo())
1648
1649 self.assertEqual(_getrefcount(aiter), refs_before)
1650
1651 def test_for_6(self):
1652 I = 0
1653
1654 class Manager:
1655 async def __aenter__(self):
1656 nonlocal I
1657 I += 10000
1658
1659 async def __aexit__(self, *args):
1660 nonlocal I
1661 I += 100000
1662
1663 class Iterable:
1664 def __init__(self):
1665 self.i = 0
1666
1667 def __aiter__(self):
1668 return self
1669
1670 async def __anext__(self):
1671 if self.i > 10:
1672 raise StopAsyncIteration
1673 self.i += 1
1674 return self.i
1675
1676 ##############
1677
1678 manager = Manager()
1679 iterable = Iterable()
1680 mrefs_before = _getrefcount(manager)
1681 irefs_before = _getrefcount(iterable)
1682
1683 async def main():
1684 nonlocal I
1685
1686 async with manager:
1687 async for i in iterable:
1688 I += 1
1689 I += 1000
1690
1691 with warnings.catch_warnings():
1692 warnings.simplefilter("error")
1693 # Test that __aiter__ that returns an asynchronous iterator
1694 # directly does not throw any warnings.
1695 run_async(main())
1696 self.assertEqual(I, 111011)
1697
1698 self.assertEqual(_getrefcount(manager), mrefs_before)
1699 self.assertEqual(_getrefcount(iterable), irefs_before)
1700
1701 ##############
1702
1703 async def main():
1704 nonlocal I
1705
1706 async with Manager():
1707 async for i in Iterable():
1708 I += 1
1709 I += 1000
1710
1711 async with Manager():
1712 async for i in Iterable():
1713 I += 1
1714 I += 1000
1715
1716 run_async(main())
1717 self.assertEqual(I, 333033)
1718
1719 ##############
1720
1721 async def main():
1722 nonlocal I
1723
1724 async with Manager():
1725 I += 100
1726 async for i in Iterable():
1727 I += 1
1728 else:
1729 I += 10000000
1730 I += 1000
1731
1732 async with Manager():
1733 I += 100
1734 async for i in Iterable():
1735 I += 1
1736 else:
1737 I += 10000000
1738 I += 1000
1739
1740 run_async(main())
1741 self.assertEqual(I, 20555255)
1742
1743 def test_for_7(self):
1744 CNT = 0
1745 class AI:
1746 def __aiter__(self):
1747 1/0
1748 async def foo():
1749 nonlocal CNT
1750 async for i in AI():
1751 CNT += 1
1752 CNT += 10
1753 with self.assertRaises(ZeroDivisionError):
1754 run_async(foo())
1755 self.assertEqual(CNT, 0)
1756
1757 def test_for_8(self):
1758 CNT = 0
1759 class AI:
1760 def __aiter__(self):
1761 1/0
1762 async def foo():
1763 nonlocal CNT
1764 async for i in AI():
1765 CNT += 1
1766 CNT += 10
1767 with self.assertRaises(ZeroDivisionError):
1768 with warnings.catch_warnings():
1769 warnings.simplefilter("error")
1770 # Test that if __aiter__ raises an exception it propagates
1771 # without any kind of warning.
1772 run_async(foo())
1773 self.assertEqual(CNT, 0)
1774
1775 def test_for_11(self):
1776 class F:
1777 def __aiter__(self):
1778 return self
1779 def __anext__(self):
1780 return self
1781 def __await__(self):
1782 1 / 0
1783
1784 async def main():
1785 async for _ in F():
1786 pass
1787
1788 with self.assertRaisesRegex(TypeError,
1789 'an invalid object from __anext__') as c:
1790 main().send(None)
1791
1792 err = c.exception
1793 self.assertIsInstance(err.__cause__, ZeroDivisionError)
1794
1795 def test_for_tuple(self):
1796 class Done(Exception): pass
1797
1798 class AIter(tuple):
1799 i = 0
1800 def __aiter__(self):
1801 return self
1802 async def __anext__(self):
1803 if self.i >= len(self):
1804 raise StopAsyncIteration
1805 self.i += 1
1806 return self[self.i - 1]
1807
1808 result = []
1809 async def foo():
1810 async for i in AIter([42]):
1811 result.append(i)
1812 raise Done
1813
1814 with self.assertRaises(Done):
1815 foo().send(None)
1816 self.assertEqual(result, [42])
1817
1818 def test_for_stop_iteration(self):
1819 class Done(Exception): pass
1820
1821 class AIter(StopIteration):
1822 i = 0
1823 def __aiter__(self):
1824 return self
1825 async def __anext__(self):
1826 if self.i:
1827 raise StopAsyncIteration
1828 self.i += 1
1829 return self.value
1830
1831 result = []
1832 async def foo():
1833 async for i in AIter(42):
1834 result.append(i)
1835 raise Done
1836
1837 with self.assertRaises(Done):
1838 foo().send(None)
1839 self.assertEqual(result, [42])
1840
1841 def test_comp_1(self):
1842 async def f(i):
1843 return i
1844
1845 async def run_list():
1846 return [await c for c in [f(1), f(41)]]
1847
1848 async def run_set():
1849 return {await c for c in [f(1), f(41)]}
1850
1851 async def run_dict1():
1852 return {await c: 'a' for c in [f(1), f(41)]}
1853
1854 async def run_dict2():
1855 return {i: await c for i, c in enumerate([f(1), f(41)])}
1856
1857 self.assertEqual(run_async(run_list()), ([], [1, 41]))
1858 self.assertEqual(run_async(run_set()), ([], {1, 41}))
1859 self.assertEqual(run_async(run_dict1()), ([], {1: 'a', 41: 'a'}))
1860 self.assertEqual(run_async(run_dict2()), ([], {0: 1, 1: 41}))
1861
1862 def test_comp_2(self):
1863 async def f(i):
1864 return i
1865
1866 async def run_list():
1867 return [s for c in [f(''), f('abc'), f(''), f(['de', 'fg'])]
1868 for s in await c]
1869
1870 self.assertEqual(
1871 run_async(run_list()),
1872 ([], ['a', 'b', 'c', 'de', 'fg']))
1873
1874 async def run_set():
1875 return {d
1876 for c in [f([f([10, 30]),
1877 f([20])])]
1878 for s in await c
1879 for d in await s}
1880
1881 self.assertEqual(
1882 run_async(run_set()),
1883 ([], {10, 20, 30}))
1884
1885 async def run_set2():
1886 return {await s
1887 for c in [f([f(10), f(20)])]
1888 for s in await c}
1889
1890 self.assertEqual(
1891 run_async(run_set2()),
1892 ([], {10, 20}))
1893
1894 def test_comp_3(self):
1895 async def f(it):
1896 for i in it:
1897 yield i
1898
1899 async def run_list():
1900 return [i + 1 async for i in f([10, 20])]
1901 self.assertEqual(
1902 run_async(run_list()),
1903 ([], [11, 21]))
1904
1905 async def run_set():
1906 return {i + 1 async for i in f([10, 20])}
1907 self.assertEqual(
1908 run_async(run_set()),
1909 ([], {11, 21}))
1910
1911 async def run_dict():
1912 return {i + 1: i + 2 async for i in f([10, 20])}
1913 self.assertEqual(
1914 run_async(run_dict()),
1915 ([], {11: 12, 21: 22}))
1916
1917 async def run_gen():
1918 gen = (i + 1 async for i in f([10, 20]))
1919 return [g + 100 async for g in gen]
1920 self.assertEqual(
1921 run_async(run_gen()),
1922 ([], [111, 121]))
1923
1924 def test_comp_4(self):
1925 async def f(it):
1926 for i in it:
1927 yield i
1928
1929 async def run_list():
1930 return [i + 1 async for i in f([10, 20]) if i > 10]
1931 self.assertEqual(
1932 run_async(run_list()),
1933 ([], [21]))
1934
1935 async def run_set():
1936 return {i + 1 async for i in f([10, 20]) if i > 10}
1937 self.assertEqual(
1938 run_async(run_set()),
1939 ([], {21}))
1940
1941 async def run_dict():
1942 return {i + 1: i + 2 async for i in f([10, 20]) if i > 10}
1943 self.assertEqual(
1944 run_async(run_dict()),
1945 ([], {21: 22}))
1946
1947 async def run_gen():
1948 gen = (i + 1 async for i in f([10, 20]) if i > 10)
1949 return [g + 100 async for g in gen]
1950 self.assertEqual(
1951 run_async(run_gen()),
1952 ([], [121]))
1953
1954 def test_comp_4_2(self):
1955 async def f(it):
1956 for i in it:
1957 yield i
1958
1959 async def run_list():
1960 return [i + 10 async for i in f(range(5)) if 0 < i < 4]
1961 self.assertEqual(
1962 run_async(run_list()),
1963 ([], [11, 12, 13]))
1964
1965 async def run_set():
1966 return {i + 10 async for i in f(range(5)) if 0 < i < 4}
1967 self.assertEqual(
1968 run_async(run_set()),
1969 ([], {11, 12, 13}))
1970
1971 async def run_dict():
1972 return {i + 10: i + 100 async for i in f(range(5)) if 0 < i < 4}
1973 self.assertEqual(
1974 run_async(run_dict()),
1975 ([], {11: 101, 12: 102, 13: 103}))
1976
1977 async def run_gen():
1978 gen = (i + 10 async for i in f(range(5)) if 0 < i < 4)
1979 return [g + 100 async for g in gen]
1980 self.assertEqual(
1981 run_async(run_gen()),
1982 ([], [111, 112, 113]))
1983
1984 def test_comp_5(self):
1985 async def f(it):
1986 for i in it:
1987 yield i
1988
1989 async def run_list():
1990 return [i + 1 for pair in ([10, 20], [30, 40]) if pair[0] > 10
1991 async for i in f(pair) if i > 30]
1992 self.assertEqual(
1993 run_async(run_list()),
1994 ([], [41]))
1995
1996 def test_comp_6(self):
1997 async def f(it):
1998 for i in it:
1999 yield i
2000
2001 async def run_list():
2002 return [i + 1 async for seq in f([(10, 20), (30,)])
2003 for i in seq]
2004
2005 self.assertEqual(
2006 run_async(run_list()),
2007 ([], [11, 21, 31]))
2008
2009 def test_comp_7(self):
2010 async def f():
2011 yield 1
2012 yield 2
2013 raise Exception('aaa')
2014
2015 async def run_list():
2016 return [i async for i in f()]
2017
2018 with self.assertRaisesRegex(Exception, 'aaa'):
2019 run_async(run_list())
2020
2021 def test_comp_8(self):
2022 async def f():
2023 return [i for i in [1, 2, 3]]
2024
2025 self.assertEqual(
2026 run_async(f()),
2027 ([], [1, 2, 3]))
2028
2029 def test_comp_9(self):
2030 async def gen():
2031 yield 1
2032 yield 2
2033 async def f():
2034 l = [i async for i in gen()]
2035 return [i for i in l]
2036
2037 self.assertEqual(
2038 run_async(f()),
2039 ([], [1, 2]))
2040
2041 def test_comp_10(self):
2042 async def f():
2043 xx = {i for i in [1, 2, 3]}
2044 return {x: x for x in xx}
2045
2046 self.assertEqual(
2047 run_async(f()),
2048 ([], {1: 1, 2: 2, 3: 3}))
2049
2050 def test_nested_comp(self):
2051 async def run_list_inside_list():
2052 return [[i + j async for i in asynciter([1, 2])] for j in [10, 20]]
2053 self.assertEqual(
2054 run_async(run_list_inside_list()),
2055 ([], [[11, 12], [21, 22]]))
2056
2057 async def run_set_inside_list():
2058 return [{i + j async for i in asynciter([1, 2])} for j in [10, 20]]
2059 self.assertEqual(
2060 run_async(run_set_inside_list()),
2061 ([], [{11, 12}, {21, 22}]))
2062
2063 async def run_list_inside_set():
2064 return {sum([i async for i in asynciter(range(j))]) for j in [3, 5]}
2065 self.assertEqual(
2066 run_async(run_list_inside_set()),
2067 ([], {3, 10}))
2068
2069 async def run_dict_inside_dict():
2070 return {j: {i: i + j async for i in asynciter([1, 2])} for j in [10, 20]}
2071 self.assertEqual(
2072 run_async(run_dict_inside_dict()),
2073 ([], {10: {1: 11, 2: 12}, 20: {1: 21, 2: 22}}))
2074
2075 async def run_list_inside_gen():
2076 gen = ([i + j async for i in asynciter([1, 2])] for j in [10, 20])
2077 return [x async for x in gen]
2078 self.assertEqual(
2079 run_async(run_list_inside_gen()),
2080 ([], [[11, 12], [21, 22]]))
2081
2082 async def run_gen_inside_list():
2083 gens = [(i async for i in asynciter(range(j))) for j in [3, 5]]
2084 return [x for g in gens async for x in g]
2085 self.assertEqual(
2086 run_async(run_gen_inside_list()),
2087 ([], [0, 1, 2, 0, 1, 2, 3, 4]))
2088
2089 async def run_gen_inside_gen():
2090 gens = ((i async for i in asynciter(range(j))) for j in [3, 5])
2091 return [x for g in gens async for x in g]
2092 self.assertEqual(
2093 run_async(run_gen_inside_gen()),
2094 ([], [0, 1, 2, 0, 1, 2, 3, 4]))
2095
2096 async def run_list_inside_list_inside_list():
2097 return [[[i + j + k async for i in asynciter([1, 2])]
2098 for j in [10, 20]]
2099 for k in [100, 200]]
2100 self.assertEqual(
2101 run_async(run_list_inside_list_inside_list()),
2102 ([], [[[111, 112], [121, 122]], [[211, 212], [221, 222]]]))
2103
2104 def test_copy(self):
2105 async def func(): pass
2106 coro = func()
2107 with self.assertRaises(TypeError):
2108 copy.copy(coro)
2109
2110 aw = coro.__await__()
2111 try:
2112 with self.assertRaises(TypeError):
2113 copy.copy(aw)
2114 finally:
2115 aw.close()
2116
2117 def test_pickle(self):
2118 async def func(): pass
2119 coro = func()
2120 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
2121 with self.assertRaises((TypeError, pickle.PicklingError)):
2122 pickle.dumps(coro, proto)
2123
2124 aw = coro.__await__()
2125 try:
2126 for proto in range(pickle.HIGHEST_PROTOCOL + 1):
2127 with self.assertRaises((TypeError, pickle.PicklingError)):
2128 pickle.dumps(aw, proto)
2129 finally:
2130 aw.close()
2131
2132 def test_fatal_coro_warning(self):
2133 # Issue 27811
2134 async def func(): pass
2135 with warnings.catch_warnings(), \
2136 support.catch_unraisable_exception() as cm:
2137 warnings.filterwarnings("error")
2138 coro = func()
2139 # only store repr() to avoid keeping the coroutine alive
2140 coro_repr = repr(coro)
2141 coro = None
2142 support.gc_collect()
2143
2144 self.assertIn("was never awaited", str(cm.unraisable.exc_value))
2145 self.assertEqual(repr(cm.unraisable.object), coro_repr)
2146
2147 def test_for_assign_raising_stop_async_iteration(self):
2148 class BadTarget:
2149 def __setitem__(self, key, value):
2150 raise StopAsyncIteration(42)
2151 tgt = BadTarget()
2152 async def source():
2153 yield 10
2154
2155 async def run_for():
2156 with self.assertRaises(StopAsyncIteration) as cm:
2157 async for tgt[0] in source():
2158 pass
2159 self.assertEqual(cm.exception.args, (42,))
2160 return 'end'
2161 self.assertEqual(run_async(run_for()), ([], 'end'))
2162
2163 async def run_list():
2164 with self.assertRaises(StopAsyncIteration) as cm:
2165 return [0 async for tgt[0] in source()]
2166 self.assertEqual(cm.exception.args, (42,))
2167 return 'end'
2168 self.assertEqual(run_async(run_list()), ([], 'end'))
2169
2170 async def run_gen():
2171 gen = (0 async for tgt[0] in source())
2172 a = gen.asend(None)
2173 with self.assertRaises(RuntimeError) as cm:
2174 await a
2175 self.assertIsInstance(cm.exception.__cause__, StopAsyncIteration)
2176 self.assertEqual(cm.exception.__cause__.args, (42,))
2177 return 'end'
2178 self.assertEqual(run_async(run_gen()), ([], 'end'))
2179
2180 def test_for_assign_raising_stop_async_iteration_2(self):
2181 class BadIterable:
2182 def __iter__(self):
2183 raise StopAsyncIteration(42)
2184 async def badpairs():
2185 yield BadIterable()
2186
2187 async def run_for():
2188 with self.assertRaises(StopAsyncIteration) as cm:
2189 async for i, j in badpairs():
2190 pass
2191 self.assertEqual(cm.exception.args, (42,))
2192 return 'end'
2193 self.assertEqual(run_async(run_for()), ([], 'end'))
2194
2195 async def run_list():
2196 with self.assertRaises(StopAsyncIteration) as cm:
2197 return [0 async for i, j in badpairs()]
2198 self.assertEqual(cm.exception.args, (42,))
2199 return 'end'
2200 self.assertEqual(run_async(run_list()), ([], 'end'))
2201
2202 async def run_gen():
2203 gen = (0 async for i, j in badpairs())
2204 a = gen.asend(None)
2205 with self.assertRaises(RuntimeError) as cm:
2206 await a
2207 self.assertIsInstance(cm.exception.__cause__, StopAsyncIteration)
2208 self.assertEqual(cm.exception.__cause__.args, (42,))
2209 return 'end'
2210 self.assertEqual(run_async(run_gen()), ([], 'end'))
2211
2212 def test_bpo_45813_1(self):
2213 'This would crash the interpreter in 3.11a2'
2214 async def f():
2215 pass
2216 with self.assertWarns(RuntimeWarning):
2217 frame = f().cr_frame
2218 support.gc_collect() # PyPy: GC triggers _finalize_ which emits the warning
2219 frame.clear()
2220
2221 def test_bpo_45813_2(self):
2222 'This would crash the interpreter in 3.11a2'
2223 async def f():
2224 pass
2225 gen = f()
2226 with self.assertWarns(RuntimeWarning):
2227 gen.cr_frame.clear()
2228 gen.close()
2229
2230 def test_stack_in_coroutine_throw(self):
2231 # Regression test for https://github.com/python/cpython/issues/93592
2232 async def a():
2233 return await b()
2234
2235 async def b():
2236 return await c()
2237
2238 @types.coroutine
2239 def c():
2240 try:
2241 # traceback.print_stack()
2242 yield len(traceback.extract_stack())
2243 except ZeroDivisionError:
2244 # traceback.print_stack()
2245 yield len(traceback.extract_stack())
2246
2247 coro = a()
2248 len_send = coro.send(None)
2249 len_throw = coro.throw(ZeroDivisionError)
2250 # before fixing, visible stack from throw would be shorter than from send.
2251 self.assertEqual(len_send, len_throw)
2252
2253
2254 @unittest.skipIf(
2255 support.is_emscripten or support.is_wasi,
2256 "asyncio does not work under Emscripten/WASI yet."
2257 )
2258 class CoroAsyncIOCompatTest(unittest.TestCase):
2259
2260 def test_asyncio_1(self):
2261 # asyncio cannot be imported when Python is compiled without thread
2262 # support
2263 asyncio = import_helper.import_module('asyncio')
2264
2265 class MyException(Exception):
2266 pass
2267
2268 buffer = []
2269
2270 class CM:
2271 async def __aenter__(self):
2272 buffer.append(1)
2273 await asyncio.sleep(0.01)
2274 buffer.append(2)
2275 return self
2276
2277 async def __aexit__(self, exc_type, exc_val, exc_tb):
2278 await asyncio.sleep(0.01)
2279 buffer.append(exc_type.__name__)
2280
2281 async def f():
2282 async with CM() as c:
2283 await asyncio.sleep(0.01)
2284 raise MyException
2285 buffer.append('unreachable')
2286
2287 loop = asyncio.new_event_loop()
2288 asyncio.set_event_loop(loop)
2289 try:
2290 loop.run_until_complete(f())
2291 except MyException:
2292 pass
2293 finally:
2294 loop.close()
2295 asyncio.set_event_loop_policy(None)
2296
2297 self.assertEqual(buffer, [1, 2, 'MyException'])
2298
2299
2300 class OriginTrackingTest(unittest.TestCase):
2301 def here(self):
2302 info = inspect.getframeinfo(inspect.currentframe().f_back)
2303 return (info.filename, info.lineno)
2304
2305 def test_origin_tracking(self):
2306 orig_depth = sys.get_coroutine_origin_tracking_depth()
2307 try:
2308 async def corofn():
2309 pass
2310
2311 sys.set_coroutine_origin_tracking_depth(0)
2312 self.assertEqual(sys.get_coroutine_origin_tracking_depth(), 0)
2313
2314 with contextlib.closing(corofn()) as coro:
2315 self.assertIsNone(coro.cr_origin)
2316
2317 sys.set_coroutine_origin_tracking_depth(1)
2318 self.assertEqual(sys.get_coroutine_origin_tracking_depth(), 1)
2319
2320 fname, lineno = self.here()
2321 with contextlib.closing(corofn()) as coro:
2322 self.assertEqual(coro.cr_origin,
2323 ((fname, lineno + 1, "test_origin_tracking"),))
2324
2325 sys.set_coroutine_origin_tracking_depth(2)
2326 self.assertEqual(sys.get_coroutine_origin_tracking_depth(), 2)
2327
2328 def nested():
2329 return (self.here(), corofn())
2330 fname, lineno = self.here()
2331 ((nested_fname, nested_lineno), coro) = nested()
2332 with contextlib.closing(coro):
2333 self.assertEqual(coro.cr_origin,
2334 ((nested_fname, nested_lineno, "nested"),
2335 (fname, lineno + 1, "test_origin_tracking")))
2336
2337 # Check we handle running out of frames correctly
2338 sys.set_coroutine_origin_tracking_depth(1000)
2339 with contextlib.closing(corofn()) as coro:
2340 self.assertTrue(2 < len(coro.cr_origin) < 1000)
2341
2342 # We can't set depth negative
2343 with self.assertRaises(ValueError):
2344 sys.set_coroutine_origin_tracking_depth(-1)
2345 # And trying leaves it unchanged
2346 self.assertEqual(sys.get_coroutine_origin_tracking_depth(), 1000)
2347
2348 finally:
2349 sys.set_coroutine_origin_tracking_depth(orig_depth)
2350
2351 def test_origin_tracking_warning(self):
2352 async def corofn():
2353 pass
2354
2355 a1_filename, a1_lineno = self.here()
2356 def a1():
2357 return corofn() # comment in a1
2358 a1_lineno += 2
2359
2360 a2_filename, a2_lineno = self.here()
2361 def a2():
2362 return a1() # comment in a2
2363 a2_lineno += 2
2364
2365 def check(depth, msg):
2366 sys.set_coroutine_origin_tracking_depth(depth)
2367 with self.assertWarns(RuntimeWarning) as cm:
2368 a2()
2369 support.gc_collect()
2370 self.assertEqual(msg, str(cm.warning))
2371
2372 orig_depth = sys.get_coroutine_origin_tracking_depth()
2373 try:
2374 msg = check(0, f"coroutine '{corofn.__qualname__}' was never awaited")
2375 check(1, "".join([
2376 f"coroutine '{corofn.__qualname__}' was never awaited\n",
2377 "Coroutine created at (most recent call last)\n",
2378 f' File "{a1_filename}", line {a1_lineno}, in a1\n',
2379 f' return corofn() # comment in a1',
2380 ]))
2381 check(2, "".join([
2382 f"coroutine '{corofn.__qualname__}' was never awaited\n",
2383 "Coroutine created at (most recent call last)\n",
2384 f' File "{a2_filename}", line {a2_lineno}, in a2\n',
2385 f' return a1() # comment in a2\n',
2386 f' File "{a1_filename}", line {a1_lineno}, in a1\n',
2387 f' return corofn() # comment in a1',
2388 ]))
2389
2390 finally:
2391 sys.set_coroutine_origin_tracking_depth(orig_depth)
2392
2393 @support.cpython_only # pypy has this function in _warnings
2394 def test_unawaited_warning_when_module_broken(self):
2395 # Make sure we don't blow up too bad if
2396 # warnings._warn_unawaited_coroutine is broken somehow (e.g. because
2397 # of shutdown problems)
2398 async def corofn():
2399 pass
2400
2401 orig_wuc = warnings._warn_unawaited_coroutine
2402 try:
2403 warnings._warn_unawaited_coroutine = lambda coro: 1/0
2404 with support.catch_unraisable_exception() as cm, \
2405 warnings_helper.check_warnings(
2406 (r'coroutine .* was never awaited',
2407 RuntimeWarning)):
2408 # only store repr() to avoid keeping the coroutine alive
2409 coro = corofn()
2410 coro_repr = repr(coro)
2411
2412 # clear reference to the coroutine without awaiting for it
2413 del coro
2414 support.gc_collect()
2415
2416 self.assertEqual(repr(cm.unraisable.object), coro_repr)
2417 self.assertEqual(cm.unraisable.exc_type, ZeroDivisionError)
2418
2419 del warnings._warn_unawaited_coroutine
2420 with warnings_helper.check_warnings(
2421 (r'coroutine .* was never awaited', RuntimeWarning)):
2422 corofn()
2423 support.gc_collect()
2424
2425 finally:
2426 warnings._warn_unawaited_coroutine = orig_wuc
2427
2428
2429 class UnawaitedWarningDuringShutdownTest(unittest.TestCase):
2430 # https://bugs.python.org/issue32591#msg310726
2431 def test_unawaited_warning_during_shutdown(self):
2432 code = ("import asyncio\n"
2433 "async def f(): pass\n"
2434 "async def t(): asyncio.gather(f())\n"
2435 "asyncio.run(t())\n")
2436 assert_python_ok("-c", code)
2437
2438 code = ("import sys\n"
2439 "async def f(): pass\n"
2440 "sys.coro = f()\n")
2441 assert_python_ok("-c", code)
2442
2443 code = ("import sys\n"
2444 "async def f(): pass\n"
2445 "sys.corocycle = [f()]\n"
2446 "sys.corocycle.append(sys.corocycle)\n")
2447 assert_python_ok("-c", code)
2448
2449
2450 @support.cpython_only
2451 class CAPITest(unittest.TestCase):
2452
2453 def test_tp_await_1(self):
2454 from _testcapi import awaitType as at
2455
2456 async def foo():
2457 future = at(iter([1]))
2458 return (await future)
2459
2460 self.assertEqual(foo().send(None), 1)
2461
2462 def test_tp_await_2(self):
2463 # Test tp_await to __await__ mapping
2464 from _testcapi import awaitType as at
2465 future = at(iter([1]))
2466 self.assertEqual(next(future.__await__()), 1)
2467
2468 def test_tp_await_3(self):
2469 from _testcapi import awaitType as at
2470
2471 async def foo():
2472 future = at(1)
2473 return (await future)
2474
2475 with self.assertRaisesRegex(
2476 TypeError, "__await__.*returned non-iterator of type 'int'"):
2477 self.assertEqual(foo().send(None), 1)
2478
2479
2480 if __name__=="__main__":
2481 unittest.main()