Debian Codegraph @

mypyc/test-data/run-async.test

raw
1 # async test cases (compile and run)
2
3 [case testRunAsyncBasics]
4 import asyncio
5 from typing import Callable, Awaitable
6
7 from testutil import assertRaises
8
9 async def h() -> int:
10 return 1
11
12 async def g() -> int:
13 await asyncio.sleep(0)
14 return await h()
15
16 async def f() -> int:
17 return await g() + 2
18
19 async def f2() -> int:
20 x = 0
21 for i in range(2):
22 x += i + await f() + await g()
23 return x
24
25 async def test_simple_call() -> None:
26 result = await f()
27 assert result == 3
28
29 async def test_multiple_awaits_in_expression() -> None:
30 result = await f2()
31 assert result == 9
32
33 class MyError(Exception):
34 pass
35
36 async def exc1() -> None:
37 await asyncio.sleep(0)
38 raise MyError()
39
40 async def exc2() -> None:
41 await asyncio.sleep(0)
42 raise MyError()
43
44 async def exc3() -> None:
45 await exc1()
46
47 async def exc4() -> None:
48 await exc2()
49
50 async def exc5() -> int:
51 try:
52 await exc1()
53 except MyError:
54 return 3
55 return 4
56
57 async def exc6() -> int:
58 try:
59 await exc4()
60 except MyError:
61 return 3
62 return 4
63
64 async def test_exception() -> None:
65 with assertRaises(MyError):
66 await exc1()
67 with assertRaises(MyError):
68 await exc2()
69 with assertRaises(MyError):
70 await exc3()
71 with assertRaises(MyError):
72 await exc4()
73 assert await exc5() == 3
74 assert await exc6() == 3
75
76 async def indirect_call(x: int, c: Callable[[int], Awaitable[int]]) -> int:
77 return await c(x)
78
79 async def indirect_call_2(a: Awaitable[None]) -> None:
80 await a
81
82 async def indirect_call_3(a: Awaitable[float]) -> float:
83 return (await a) + 1.0
84
85 async def inc(x: int) -> int:
86 await asyncio.sleep(0)
87 return x + 1
88
89 async def ident(x: float, err: bool = False) -> float:
90 await asyncio.sleep(0.0)
91 if err:
92 raise MyError()
93 return x + float("0.0")
94
95 async def test_indirect_call() -> None:
96 assert await indirect_call(3, inc) == 4
97
98 with assertRaises(MyError):
99 await indirect_call_2(exc1())
100
101 assert await indirect_call_3(ident(2.0)) == 3.0
102 assert await indirect_call_3(ident(-113.0)) == -112.0
103 assert await indirect_call_3(ident(-114.0)) == -113.0
104
105 with assertRaises(MyError):
106 await indirect_call_3(ident(1.0, True))
107 with assertRaises(MyError):
108 await indirect_call_3(ident(-113.0, True))
109
110 class C:
111 def __init__(self, n: int) -> None:
112 self.n = n
113
114 async def add(self, x: int, err: bool = False) -> int:
115 await asyncio.sleep(0)
116 if err:
117 raise MyError()
118 return x + self.n
119
120 async def method_call(x: int) -> int:
121 c = C(5)
122 return await c.add(x)
123
124 async def method_call_exception() -> int:
125 c = C(5)
126 return await c.add(3, err=True)
127
128 async def test_async_method_call() -> None:
129 assert await method_call(3) == 8
130 with assertRaises(MyError):
131 await method_call_exception()
132
133 [file asyncio/__init__.pyi]
134 async def sleep(t: float) -> None: ...
135
136 [typing fixtures/typing-full.pyi]
137
138 [case testRunAsyncAwaitInVariousPositions]
139 from typing import cast, Any
140
141 import asyncio
142
143 async def one() -> int:
144 await asyncio.sleep(0.0)
145 return int() + 1
146
147 async def true() -> bool:
148 return bool(int() + await one())
149
150 async def branch_await() -> int:
151 if bool(int() + 1) == await true():
152 return 3
153 return 2
154
155 async def branch_await_not() -> int:
156 if bool(int() + 1) == (not await true()):
157 return 3
158 return 2
159
160 async def test_branch() -> None:
161 assert await branch_await() == 3
162 assert await branch_await_not() == 2
163
164 async def assign_multi() -> int:
165 _, x = int(), await one()
166 return x + 1
167
168 async def test_assign_multi() -> None:
169 assert await assign_multi() == 2
170
171 class C:
172 def __init__(self, s: str) -> None:
173 self.s = s
174
175 def concat(self, s: str) -> str:
176 return self.s + s
177
178 async def make_c(s: str) -> C:
179 await one()
180 return C(s)
181
182 async def concat(s: str, t: str) -> str:
183 await one()
184 return s + t
185
186 async def set_attr(s: str) -> None:
187 (await make_c("xyz")).s = await concat(s, "!")
188
189 async def test_set_attr() -> None:
190 await set_attr("foo") # Just check that it compiles and runs
191
192 def concat2(x: str, y: str) -> str:
193 return x + y
194
195 async def call1(s: str) -> str:
196 return concat2(str(int()), await concat(s, "a"))
197
198 async def call2(s: str) -> str:
199 return await concat(str(int()), await concat(s, "b"))
200
201 async def test_call() -> None:
202 assert await call1("foo") == "0fooa"
203 assert await call2("foo") == "0foob"
204
205 async def method_call(s: str) -> str:
206 return C("<").concat(await concat(s, ">"))
207
208 async def test_method_call() -> None:
209 assert await method_call("foo") == "<foo>"
210
211 class D:
212 def __init__(self, a: str, b: str) -> None:
213 self.a = a
214 self.b = b
215
216 async def construct(s: str) -> str:
217 c = D(await concat(s, "!"), await concat(s, "?"))
218 return c.a + c.b
219
220 async def test_construct() -> None:
221 assert await construct("foo") == "foo!foo?"
222
223 [file asyncio/__init__.pyi]
224 async def sleep(t: float) -> None: ...
225
226 [typing fixtures/typing-full.pyi]
227
228
229 [case testAsyncWith]
230 from testutil import async_val
231 from typing import Any
232
233 class async_ctx:
234 async def __aenter__(self) -> str:
235 await async_val("enter")
236 return "test"
237
238 async def __aexit__(self, x, y, z) -> None:
239 await async_val("exit")
240
241
242 async def async_with() -> str:
243 async with async_ctx() as x:
244 return await async_val("body")
245
246 async def async_with_vectorcall() -> str:
247 ctx: Any = async_ctx()
248 async with ctx:
249 return await async_val("vc")
250
251 [file driver.py]
252 from native import async_with, async_with_vectorcall
253 from testutil import run_generator
254
255 yields, val = run_generator(async_with(), [None, 'x', None])
256 assert yields == ('enter', 'body', 'exit'), yields
257 assert val == 'x', val
258
259 yields, val = run_generator(async_with_vectorcall(), [None, 'x', None])
260 assert yields == ('enter', 'vc', 'exit'), yields
261 assert val == 'x', val
262
263 [case testAsyncReturn]
264 from testutil import async_val
265
266 async def async_return() -> str:
267 try:
268 return 'test'
269 finally:
270 await async_val('foo')
271
272 [file driver.py]
273 from native import async_return
274 from testutil import run_generator
275
276 yields, val = run_generator(async_return())
277 assert yields == ('foo',)
278 assert val == 'test', val
279
280 [case testAsyncFor]
281 from typing import AsyncIterable, List, Set, Dict
282
283 async def async_iter(xs: AsyncIterable[int]) -> List[int]:
284 ys = []
285 async for x in xs:
286 ys.append(x)
287 return ys
288
289 async def async_comp(xs: AsyncIterable[int]) -> List[int]:
290 ys = [x async for x in xs]
291 return ys
292
293 async def async_comp_set(xs: AsyncIterable[int]) -> Set[int]:
294 return {x async for x in xs}
295
296 async def async_comp_dict(xs: AsyncIterable[int]) -> Dict[int, str]:
297 return {x: str(x) async for x in xs}
298
299 [typing fixtures/typing-full.pyi]
300
301 [file driver.py]
302 from native import async_iter, async_comp, async_comp_set, async_comp_dict
303 from testutil import run_generator, async_val
304 from typing import AsyncIterable, List
305
306 # defined here since we couldn't do it inside the test yet...
307 async def foo() -> AsyncIterable[int]:
308 for x in range(3):
309 await async_val(x)
310 yield x
311
312 yields, val = run_generator(async_iter(foo()))
313 assert val == [0,1,2], val
314 assert yields == (0,1,2), yields
315
316 yields, val = run_generator(async_comp(foo()))
317 assert val == [0,1,2], val
318 assert yields == (0,1,2), yields
319
320 yields, val = run_generator(async_comp_set(foo()))
321 assert val == {0,1,2}, val
322 assert yields == (0,1,2), yields
323
324 yields, val = run_generator(async_comp_dict(foo()))
325 assert val == {0: '0',1: '1', 2: '2'}, val
326 assert yields == (0,1,2), yields
327
328 [case testAsyncFor2]
329 from typing import AsyncIterable, List
330
331 async def async_iter(xs: AsyncIterable[int]) -> List[int]:
332 ys = []
333 async for x in xs:
334 ys.append(x)
335 return ys
336
337 [typing fixtures/typing-full.pyi]
338
339 [file driver.py]
340 from native import async_iter
341 from testutil import run_generator, async_val
342 from typing import AsyncIterable, List
343
344 # defined here since we couldn't do it inside the test yet...
345 async def foo() -> AsyncIterable[int]:
346 for x in range(3):
347 await async_val(x)
348 yield x
349 raise Exception('lol no')
350
351 yields, val = run_generator(async_iter(foo()))
352 assert yields == (0,1,2), yields
353 assert val == 'lol no', val
354
355 [case testAsyncWithVarReuse]
356 class ConMan:
357 async def __aenter__(self) -> int:
358 return 1
359 async def __aexit__(self, *exc: object):
360 pass
361
362 class ConManB:
363 async def __aenter__(self) -> int:
364 return 2
365 async def __aexit__(self, *exc: object):
366 pass
367
368 async def test_x() -> None:
369 value = 2
370 async with ConMan() as f:
371 value += f
372 assert value == 3, value
373 async with ConManB() as f:
374 value += f
375 assert value == 5, value
376
377 [case testRunAsyncSpecialCases]
378 import asyncio
379
380 async def t() -> tuple[int, str, str]:
381 return (1, "x", "y")
382
383 async def f() -> tuple[int, str, str]:
384 return await t()
385
386 async def test_tuple_return() -> None:
387 result = await f()
388 assert result == (1, "x", "y")
389
390 async def e() -> ValueError:
391 return ValueError("foo")
392
393 async def g() -> ValueError:
394 return await e()
395
396 async def test_exception_return() -> None:
397 result = await g()
398 assert isinstance(result, ValueError)
399
400 [file asyncio/__init__.pyi]
401 async def sleep(t: float) -> None: ...
402
403 [typing fixtures/typing-full.pyi]
404
405 [case testRunAsyncRefCounting]
406 import asyncio
407 import gc
408 import platform
409
410 from testutil import is_gil_disabled
411
412 def immediate_deallocation_checks_are_reliable() -> bool:
413 # Free-threaded builds can defer deallocation, so weakref liveness is not deterministic.
414 return not is_gil_disabled()
415
416 async def sleep() -> None:
417 # Non-zero value hangs on Windows.
418 time = 0 if platform.system() == "Windows" else 0.0001
419 await asyncio.sleep(time)
420
421 async def assert_no_leaks(fn, max_new):
422 # Warm-up, in case asyncio allocates something on first use
423 await fn()
424
425 gc.collect()
426 old_objs = gc.get_objects()
427
428 for i in range(10):
429 await fn()
430
431 gc.collect()
432 new_objs = gc.get_objects()
433
434 delta = len(new_objs) - len(old_objs)
435 # Often a few persistent objects get allocated, which may be unavoidable.
436 # The main thing we care about is that each iteration does not leak an
437 # additional object.
438 assert delta <= max_new, delta
439
440 async def concat_one(x: str) -> str:
441 return x + "1"
442
443 async def foo(n: int) -> str:
444 s = ""
445 while len(s) < n:
446 s = await concat_one(s)
447 return s
448
449 async def test_trivial() -> None:
450 await assert_no_leaks(lambda: foo(1000), 5)
451
452 async def make_list(a: list[int]) -> list[int]:
453 await concat_one("foobar")
454 return [a[0]]
455
456 async def spill() -> list[int]:
457 a: list[int] = []
458 for i in range(5):
459 await sleep()
460 a = (await make_list(a + [1])) + a + (await make_list(a + [2]))
461 return a
462
463 async def bar(n: int) -> None:
464 for i in range(n):
465 await spill()
466
467 async def test_spilled() -> None:
468 await assert_no_leaks(lambda: bar(80), 13)
469
470 async def raise_deep(n: int) -> str:
471 if n == 0:
472 await sleep()
473 raise TypeError(str(n))
474 else:
475 if n == 2:
476 await sleep()
477 return await raise_deep(n - 1)
478
479 async def maybe_raise(n: int) -> str:
480 if n % 3 == 0:
481 await raise_deep(5)
482 elif n % 29 == 0:
483 await sleep()
484 return str(n)
485
486 async def exc(n: int) -> list[str]:
487 a = []
488 for i in range(n):
489 try:
490 a.append(str(int()) + await maybe_raise(n))
491 except TypeError:
492 a.append(str(int() + 5))
493 return a
494
495 async def test_exception() -> None:
496 await assert_no_leaks(lambda: exc(50), 2)
497
498 class C:
499 def __init__(self, s: str) -> None:
500 self.s = s
501
502 async def id(c: C) -> C:
503 return c
504
505 async def stolen_helper(c: C, s: str) -> str:
506 await sleep()
507 (await id(c)).s = await concat_one(s)
508 await sleep()
509 return c.s
510
511 async def stolen(n: int) -> int:
512 for i in range(n):
513 c = C(str(i))
514 s = await stolen_helper(c, str(i + 2))
515 assert s == str(i + 2) + "1"
516 return n
517
518 async def test_stolen() -> None:
519 await assert_no_leaks(lambda: stolen(200), 16)
520
521 async def retain_arg(c: set[int]) -> None:
522 async def nested() -> int:
523 await sleep()
524 return len(c)
525
526 await nested()
527
528 async def test_completed_coroutine_releases_environment() -> None:
529 if not immediate_deallocation_checks_are_reliable():
530 return
531
532 import weakref
533
534 c = {1}
535 ref = weakref.ref(c)
536 coro = retain_arg(c)
537 c = {2}
538 await coro
539 assert ref() is None
540
541 async def retain_arg_then_raise(c: set[int]) -> None:
542 async def nested() -> int:
543 await sleep()
544 return len(c)
545
546 await nested()
547 raise ValueError
548
549 async def test_failed_coroutine_releases_environment() -> None:
550 if not immediate_deallocation_checks_are_reliable():
551 return
552
553 import weakref
554
555 c = {1}
556 ref = weakref.ref(c)
557 coro = retain_arg_then_raise(c)
558 c = {2}
559 try:
560 await coro
561 except ValueError:
562 pass
563 assert ref() is None
564
565 async def close_retain_arg(c: set[int]) -> None:
566 await sleep()
567 len(c)
568
569 async def test_closed_coroutine_releases_environment() -> None:
570 if not immediate_deallocation_checks_are_reliable():
571 return
572
573 import weakref
574 from typing import Any, cast
575
576 c = {1}
577 ref = weakref.ref(c)
578 coro = cast(Any, close_retain_arg(c))
579 coro.send(None)
580 c = {2}
581 coro.close()
582 assert ref() is None
583
584 async def interpreted_leaf(c: set[int]) -> int:
585 await sleep()
586 return len(c)
587
588 async def compiled_leaf(c: set[int]) -> int:
589 await sleep()
590 return len(c)
591
592 async def compiled_awaits_interpreted(c: set[int]) -> int:
593 import interpreted
594
595 return await interpreted.interpreted_leaf(c)
596
597 async def interpreted_awaits_compiled(fn, c: set[int]) -> int:
598 return await fn(c)
599
600 async def test_completed_mixed_coroutine_releases_environment() -> None:
601 if not immediate_deallocation_checks_are_reliable():
602 return
603
604 import interpreted
605 import weakref
606
607 c = {1}
608 ref = weakref.ref(c)
609 coro = compiled_awaits_interpreted(c)
610 c = {2}
611 assert await coro == 1
612 assert ref() is None
613
614 c = {3}
615 ref = weakref.ref(c)
616 coro = interpreted.interpreted_awaits_compiled(compiled_leaf, c)
617 c = {4}
618 assert await coro == 1
619 assert ref() is None
620
621 [file asyncio/__init__.pyi]
622 async def sleep(t: float) -> None: ...
623
624 [case testRunAsyncMiscTypesInEnvironment]
625 # Here we test that values of various kinds of types can be spilled to the
626 # environment. In particular, types with "overlapping error values" such as
627 # i64 can be tricky, since they require extra work to support undefined
628 # attribute values (which raise AttributeError when accessed). For these,
629 # the object struct has a bitfield which keeps track of whether certain
630 # attributes have an assigned value.
631 #
632 # In practice we mark these attributes as "always defined", which causes these
633 # checks to be skipped on attribute access, and thus we don't require the
634 # bitfield to exist.
635 #
636 # See the comment of RType.error_overlap for more information.
637
638 import asyncio
639
640 from mypy_extensions import i64, i32, i16, u8
641
642 async def inc_float(x: float) -> float:
643 return x + 1.0
644
645 async def inc_i64(x: i64) -> i64:
646 return x + 1
647
648 async def inc_i32(x: i32) -> i32:
649 return x + 1
650
651 async def inc_i16(x: i16) -> i16:
652 return x + 1
653
654 async def inc_u8(x: u8) -> u8:
655 return x + 1
656
657 async def inc_tuple(x: tuple[i64, float]) -> tuple[i64, float]:
658 return x[0] + 1, x[1] + 1.5
659
660 async def neg_bool(b: bool) -> bool:
661 return not b
662
663 async def float_ops(x: float) -> float:
664 n = x
665 n = await inc_float(n)
666 n = float("0.5") + await inc_float(n)
667 return n
668
669 async def test_float() -> None:
670 assert await float_ops(2.5) == 5.0
671
672 async def i64_ops(x: i64) -> i64:
673 n = x
674 n = await inc_i64(n)
675 n = i64("1") + await inc_i64(n)
676 return n
677
678 async def test_i64() -> None:
679 assert await i64_ops(2) == 5
680
681 async def i32_ops(x: i32) -> i32:
682 n = x
683 n = await inc_i32(n)
684 n = i32("1") + await inc_i32(n)
685 return n
686
687 async def test_i32() -> None:
688 assert await i32_ops(3) == 6
689
690 async def i16_ops(x: i16) -> i16:
691 n = x
692 n = await inc_i16(n)
693 n = i16("1") + await inc_i16(n)
694 return n
695
696 async def test_i16() -> None:
697 assert await i16_ops(4) == 7
698
699 async def u8_ops(x: u8) -> u8:
700 n = x
701 n = await inc_u8(n)
702 n = u8("1") + await inc_u8(n)
703 return n
704
705 async def test_u8() -> None:
706 assert await u8_ops(5) == 8
707
708 async def tuple_ops(x: tuple[i64, float]) -> tuple[i64, float]:
709 n = x
710 n = await inc_tuple(n)
711 m = ((i64("1"), float("0.5")), await inc_tuple(n))
712 return m[1]
713
714 async def test_tuple() -> None:
715 assert await tuple_ops((1, 2.5)) == (3, 5.5)
716
717 async def bool_ops(x: bool) -> bool:
718 n = x
719 n = await neg_bool(n)
720 m = (bool("1"), await neg_bool(n))
721 return m[0] and m[1]
722
723 async def test_bool() -> None:
724 assert await bool_ops(True) is True
725 assert await bool_ops(False) is False
726
727 [file asyncio/__init__.pyi]
728 def run(x: object) -> object: ...
729
730 [case testRunAsyncNestedFunctions]
731 from __future__ import annotations
732
733 import asyncio
734 from typing import cast, Iterator, overload, Awaitable, Any, TypeVar
735
736 from testutil import assertRaises
737
738 def normal_contains_async_def(x: int) -> int:
739 async def f(y: int) -> int:
740 return x + y
741
742 return 5 + cast(int, asyncio.run(f(6)))
743
744 def test_def_contains_async_def() -> None:
745 assert normal_contains_async_def(3) == 14
746
747 async def inc(x: int) -> int:
748 return x + 1
749
750 async def async_def_contains_normal(x: int) -> int:
751 def nested(y: int, z: int) -> int:
752 return x + y + z
753
754 a = x
755 a += nested((await inc(3)), (await inc(4)))
756 return a
757
758 async def test_async_def_contains_normal() -> None:
759 assert await async_def_contains_normal(2) == (2 + 2 + 4 + 5)
760
761 async def async_def_contains_async_def(x: int) -> int:
762 async def f(y: int) -> int:
763 return (await inc(x)) + (await inc(y))
764
765 return (await f(1)) + (await f(2))
766
767 async def test_async_def_contains_async_def() -> None:
768 assert await async_def_contains_async_def(3) == (3 + 1 + 1 + 1) + (3 + 1 + 2 + 1)
769
770 async def async_def_contains_generator(x: int) -> tuple[int, int, int]:
771 def gen(y: int) -> Iterator[int]:
772 yield x + 1
773 yield x + y
774
775 it = gen(4)
776 res = x + 10, next(it), next(it)
777
778 with assertRaises(StopIteration):
779 next(it)
780
781 return res
782
783 async def test_async_def_contains_generator() -> None:
784 assert await async_def_contains_generator(3) == (13, 4, 7)
785
786 def generator_contains_async_def(x: int) -> Iterator[int]:
787 async def f(y: int) -> int:
788 return (await inc(x)) + (await inc(y))
789
790 yield cast(int, asyncio.run(f(2)))
791 yield cast(int, asyncio.run(f(3)))
792 yield x + 10
793
794 def test_generator_contains_async_def() -> None:
795 assert list(generator_contains_async_def(5)) == [6 + 3, 6 + 4, 15]
796
797 async def async_def_contains_two_nested_functions(x: int, y: int) -> tuple[int, int]:
798 def f(a: int) -> int:
799 return x + a
800
801 def g(b: int, c: int) -> int:
802 return y + b + c
803
804 return (await inc(f(3))), (await inc(g(4, 10)))
805
806 async def test_async_def_contains_two_nested_functions() -> None:
807 assert await async_def_contains_two_nested_functions(5, 7) == (
808 (5 + 3 + 1), (7 + 4 + 10 + 1)
809 )
810
811 async def async_def_contains_overloaded_async_def(n: int) -> int:
812 @overload
813 async def f(x: int) -> int: ...
814
815 @overload
816 async def f(x: str) -> str: ...
817
818 async def f(x: int | str) -> Any:
819 return x
820
821 return (await f(n)) + 1
822
823
824 async def test_async_def_contains_overloaded_async_def() -> None:
825 assert await async_def_contains_overloaded_async_def(5) == 6
826
827 T = TypeVar("T")
828
829 def deco(f: T) -> T:
830 return f
831
832 async def async_def_contains_decorated_async_def(n: int) -> int:
833 @deco
834 async def f(x: int) -> int:
835 return x + 2
836
837 return (await f(n)) + 1
838
839
840 async def test_async_def_contains_decorated_async_def() -> None:
841 assert await async_def_contains_decorated_async_def(7) == 10
842
843 [file asyncio/__init__.pyi]
844 def run(x: object) -> object: ...
845
846 [case testAsyncTryFinallyMixedReturn]
847 # This used to raise an AttributeError, when:
848 # - the try block contains multiple paths
849 # - at least one of those explicitly returns
850 # - at least one of those does not explicitly return
851 # - the non-returning path is taken at runtime
852
853 async def mixed_return(b: bool) -> bool:
854 try:
855 if b:
856 return b
857 finally:
858 pass
859 return b
860
861
862 async def test_async_try_finally_mixed_return() -> None:
863 # Test return path
864 result1 = await mixed_return(True)
865 assert result1 == True
866
867 # Test non-return path
868 result2 = await mixed_return(False)
869 assert result2 == False
870
871 [case testAsyncWithMixedReturn]
872 # This used to raise an AttributeError, related to
873 # testAsyncTryFinallyMixedReturn, this is essentially
874 # a far more extensive version of that test surfacing
875 # more edge cases
876
877 from typing import Optional, Type, Literal
878
879
880 class AsyncContextManager:
881 async def __aenter__(self) -> "AsyncContextManager":
882 return self
883
884 async def __aexit__(
885 self,
886 t: Optional[Type[BaseException]],
887 v: Optional[BaseException],
888 tb: object,
889 ) -> Literal[False]:
890 return False
891
892
893 # Simple async functions (generator class)
894 async def gen_1(b: bool) -> bool:
895 async with AsyncContextManager():
896 if b:
897 return b
898 return b
899
900
901 async def gen_2(b: bool) -> bool:
902 async with AsyncContextManager():
903 if b:
904 return b
905 else:
906 return b
907
908
909 async def gen_3(b: bool) -> bool:
910 async with AsyncContextManager():
911 if b:
912 return b
913 else:
914 pass
915 return b
916
917
918 async def gen_4(b: bool) -> bool:
919 ret: bool
920 async with AsyncContextManager():
921 if b:
922 ret = b
923 else:
924 ret = b
925 return ret
926
927
928 async def gen_5(i: int) -> int:
929 async with AsyncContextManager():
930 if i == 1:
931 return i
932 elif i == 2:
933 pass
934 elif i == 3:
935 return i
936 return i
937
938
939 async def gen_6(i: int) -> int:
940 async with AsyncContextManager():
941 if i == 1:
942 return i
943 elif i == 2:
944 return i
945 elif i == 3:
946 return i
947 return i
948
949
950 async def gen_7(i: int) -> int:
951 async with AsyncContextManager():
952 if i == 1:
953 return i
954 elif i == 2:
955 return i
956 elif i == 3:
957 return i
958 else:
959 return i
960
961
962 # Async functions with nested functions (environment class)
963 async def env_1(b: bool) -> bool:
964 def helper() -> bool:
965 return True
966
967 async with AsyncContextManager():
968 if b:
969 return helper()
970 return b
971
972
973 async def env_2(b: bool) -> bool:
974 def helper() -> bool:
975 return True
976
977 async with AsyncContextManager():
978 if b:
979 return helper()
980 else:
981 return b
982
983
984 async def env_3(b: bool) -> bool:
985 def helper() -> bool:
986 return True
987
988 async with AsyncContextManager():
989 if b:
990 return helper()
991 else:
992 pass
993 return b
994
995
996 async def env_4(b: bool) -> bool:
997 def helper() -> bool:
998 return True
999
1000 ret: bool
1001 async with AsyncContextManager():
1002 if b:
1003 ret = helper()
1004 else:
1005 ret = b
1006 return ret
1007
1008
1009 async def env_5(i: int) -> int:
1010 def helper() -> int:
1011 return 1
1012
1013 async with AsyncContextManager():
1014 if i == 1:
1015 return helper()
1016 elif i == 2:
1017 pass
1018 elif i == 3:
1019 return i
1020 return i
1021
1022
1023 async def env_6(i: int) -> int:
1024 def helper() -> int:
1025 return 1
1026
1027 async with AsyncContextManager():
1028 if i == 1:
1029 return helper()
1030 elif i == 2:
1031 return i
1032 elif i == 3:
1033 return i
1034 return i
1035
1036
1037 async def env_7(i: int) -> int:
1038 def helper() -> int:
1039 return 1
1040
1041 async with AsyncContextManager():
1042 if i == 1:
1043 return helper()
1044 elif i == 2:
1045 return i
1046 elif i == 3:
1047 return i
1048 else:
1049 return i
1050
1051
1052 async def test_async_with_mixed_return() -> None:
1053 # Test simple async functions (generator class)
1054 # env_1: mixed return/no-return
1055 assert await gen_1(True) is True
1056 assert await gen_1(False) is False
1057
1058 # gen_2: all branches return
1059 assert await gen_2(True) is True
1060 assert await gen_2(False) is False
1061
1062 # gen_3: mixed return/pass
1063 assert await gen_3(True) is True
1064 assert await gen_3(False) is False
1065
1066 # gen_4: no returns in async with
1067 assert await gen_4(True) is True
1068 assert await gen_4(False) is False
1069
1070 # gen_5: multiple branches, some return
1071 assert await gen_5(0) == 0
1072 assert await gen_5(1) == 1
1073 assert await gen_5(2) == 2
1074 assert await gen_5(3) == 3
1075
1076 # gen_6: all explicit branches return, implicit fallthrough
1077 assert await gen_6(0) == 0
1078 assert await gen_6(1) == 1
1079 assert await gen_6(2) == 2
1080 assert await gen_6(3) == 3
1081
1082 # gen_7: all branches return including else
1083 assert await gen_7(0) == 0
1084 assert await gen_7(1) == 1
1085 assert await gen_7(2) == 2
1086 assert await gen_7(3) == 3
1087
1088 # Test async functions with nested functions (environment class)
1089 # env_1: mixed return/no-return
1090 assert await env_1(True) is True
1091 assert await env_1(False) is False
1092
1093 # env_2: all branches return
1094 assert await env_2(True) is True
1095 assert await env_2(False) is False
1096
1097 # env_3: mixed return/pass
1098 assert await env_3(True) is True
1099 assert await env_3(False) is False
1100
1101 # env_4: no returns in async with
1102 assert await env_4(True) is True
1103 assert await env_4(False) is False
1104
1105 # env_5: multiple branches, some return
1106 assert await env_5(0) == 0
1107 assert await env_5(1) == 1
1108 assert await env_5(2) == 2
1109 assert await env_5(3) == 3
1110
1111 # env_6: all explicit branches return, implicit fallthrough
1112 assert await env_6(0) == 0
1113 assert await env_6(1) == 1
1114 assert await env_6(2) == 2
1115 assert await env_6(3) == 3
1116
1117 # env_7: all branches return including else
1118 assert await env_7(0) == 0
1119 assert await env_7(1) == 1
1120 assert await env_7(2) == 2
1121 assert await env_7(3) == 3
1122
1123 [case testAsyncTryExceptFinallyAwait]
1124 import asyncio
1125 from testutil import assertRaises
1126
1127 class TestError(Exception):
1128 pass
1129
1130 # Test 0: Simplest case - just try/finally with raise and await
1131 async def simple_try_finally_await() -> None:
1132 try:
1133 raise ValueError("simple error")
1134 finally:
1135 await asyncio.sleep(0)
1136
1137 # Test 1: Raise inside try, catch in except, don't re-raise
1138 async def async_try_except_no_reraise() -> int:
1139 try:
1140 raise ValueError("test error")
1141 return 1 # Never reached
1142 except ValueError:
1143 return 2 # Should return this
1144 finally:
1145 await asyncio.sleep(0)
1146 return 3 # Should not reach this
1147
1148 # Test 2: Raise inside try, catch in except, re-raise
1149 async def async_try_except_reraise() -> int:
1150 try:
1151 raise ValueError("test error")
1152 return 1 # Never reached
1153 except ValueError:
1154 raise # Re-raise the exception
1155 finally:
1156 await asyncio.sleep(0)
1157 return 2 # Should not reach this
1158
1159 # Test 3: Raise inside try, catch in except, raise different error
1160 async def async_try_except_raise_different() -> int:
1161 try:
1162 raise ValueError("original error")
1163 return 1 # Never reached
1164 except ValueError:
1165 raise RuntimeError("different error")
1166 finally:
1167 await asyncio.sleep(0)
1168 return 2 # Should not reach this
1169
1170 # Test 4: Another try/except block inside finally
1171 async def async_try_except_inside_finally() -> int:
1172 try:
1173 raise ValueError("outer error")
1174 return 1 # Never reached
1175 finally:
1176 await asyncio.sleep(0)
1177 try:
1178 raise RuntimeError("inner error")
1179 except RuntimeError:
1180 pass # Catch inner error
1181 return 2 # What happens after finally with inner exception handled?
1182
1183 # Test 5: Another try/finally block inside finally
1184 async def async_try_finally_inside_finally() -> int:
1185 try:
1186 raise ValueError("outer error")
1187 return 1 # Never reached
1188 finally:
1189 await asyncio.sleep(0)
1190 try:
1191 raise RuntimeError("inner error")
1192 finally:
1193 await asyncio.sleep(0)
1194 return 2 # Should not reach this
1195
1196 # Control case: No await in finally - should work correctly
1197 async def async_exception_no_await_in_finally() -> None:
1198 """Control case: This works correctly - exception propagates"""
1199 try:
1200 raise TestError("This exception will propagate!")
1201 finally:
1202 pass # No await here
1203
1204 # Test function with no exception to check normal flow
1205 async def async_no_exception_with_await_in_finally() -> int:
1206 try:
1207 return 1 # Normal return
1208 finally:
1209 await asyncio.sleep(0)
1210 return 2 # Should not reach this
1211
1212 async def test_async_try_except_finally_await() -> None:
1213 # Test 0: Simplest case - just try/finally with exception
1214 # Expected: ValueError propagates
1215 with assertRaises(ValueError):
1216 await simple_try_finally_await()
1217
1218 # Test 1: Exception caught, not re-raised
1219 # Expected: return 2 (from except block)
1220 result = await async_try_except_no_reraise()
1221 assert result == 2, f"Expected 2, got {result}"
1222
1223 # Test 2: Exception caught and re-raised
1224 # Expected: ValueError propagates
1225 with assertRaises(ValueError):
1226 await async_try_except_reraise()
1227
1228 # Test 3: Exception caught, different exception raised
1229 # Expected: RuntimeError propagates
1230 with assertRaises(RuntimeError):
1231 await async_try_except_raise_different()
1232
1233 # Test 4: Try/except inside finally
1234 # Expected: ValueError propagates (outer exception)
1235 with assertRaises(ValueError):
1236 await async_try_except_inside_finally()
1237
1238 # Test 5: Try/finally inside finally
1239 # Expected: RuntimeError propagates (inner error)
1240 with assertRaises(RuntimeError):
1241 await async_try_finally_inside_finally()
1242
1243 # Control case: No await in finally (should work correctly)
1244 with assertRaises(TestError):
1245 await async_exception_no_await_in_finally()
1246
1247 # Test normal flow (no exception)
1248 # Expected: return 1
1249 result = await async_no_exception_with_await_in_finally()
1250 assert result == 1, f"Expected 1, got {result}"
1251
1252 [file asyncio/__init__.pyi]
1253 async def sleep(t: float) -> None: ...
1254
1255 [case testAsyncContextManagerExceptionHandling]
1256 import asyncio
1257 from typing import Optional, Type
1258 from testutil import assertRaises
1259
1260 # Test 1: Basic async context manager that doesn't suppress exceptions
1261 class AsyncContextManager:
1262 async def __aenter__(self) -> 'AsyncContextManager':
1263 return self
1264
1265 async def __aexit__(self, exc_type: Optional[Type[BaseException]],
1266 exc_val: Optional[BaseException],
1267 exc_tb: object) -> None:
1268 # This await in __aexit__ is like await in finally
1269 await asyncio.sleep(0)
1270 # Don't suppress the exception (return None/False)
1271
1272 async def func_with_async_context_manager() -> str:
1273 async with AsyncContextManager():
1274 raise ValueError("Exception inside async with")
1275 return "should not reach" # Never reached
1276 return "should not reach either" # Never reached
1277
1278 async def test_basic_exception() -> str:
1279 try:
1280 await func_with_async_context_manager()
1281 return "func_a returned normally - bug!"
1282 except ValueError:
1283 return "caught ValueError - correct!"
1284 except Exception as e:
1285 return f"caught different exception: {type(e).__name__}"
1286
1287 # Test 2: Async context manager that raises a different exception in __aexit__
1288 class AsyncContextManagerRaisesInExit:
1289 async def __aenter__(self) -> 'AsyncContextManagerRaisesInExit':
1290 return self
1291
1292 async def __aexit__(self, exc_type: Optional[Type[BaseException]],
1293 exc_val: Optional[BaseException],
1294 exc_tb: object) -> None:
1295 # This await in __aexit__ is like await in finally
1296 await asyncio.sleep(0)
1297 # Raise a different exception - this should replace the original exception
1298 raise RuntimeError("Exception in __aexit__")
1299
1300 async def func_with_raising_context_manager() -> str:
1301 async with AsyncContextManagerRaisesInExit():
1302 raise ValueError("Original exception")
1303 return "should not reach" # Never reached
1304 return "should not reach either" # Never reached
1305
1306 async def test_exception_in_aexit() -> str:
1307 try:
1308 await func_with_raising_context_manager()
1309 return "func returned normally - unexpected!"
1310 except RuntimeError:
1311 return "caught RuntimeError - correct!"
1312 except ValueError:
1313 return "caught ValueError - original exception not replaced!"
1314 except Exception as e:
1315 return f"caught different exception: {type(e).__name__}"
1316
1317 async def test_async_context_manager_exception_handling() -> None:
1318 # Test 1: Basic exception propagation
1319 result = await test_basic_exception()
1320 # Expected: "caught ValueError - correct!"
1321 assert result == "caught ValueError - correct!", f"Expected exception to propagate, got: {result}"
1322
1323 # Test 2: Exception raised in __aexit__ replaces original exception
1324 result = await test_exception_in_aexit()
1325 # Expected: "caught RuntimeError - correct!"
1326 # (The RuntimeError from __aexit__ should replace the ValueError)
1327 assert result == "caught RuntimeError - correct!", f"Expected RuntimeError from __aexit__, got: {result}"
1328
1329 [file asyncio/__init__.pyi]
1330 async def sleep(t: float) -> None: ...
1331
1332 [case testCallableArgWithSameNameAsHelperMethod]
1333 import asyncio
1334 from typing import Awaitable, Callable
1335
1336
1337 MyCallable = Callable[[int, int], Awaitable[int]]
1338
1339 async def add(a: int, b: int) -> int:
1340 return a + b
1341
1342 async def await_send(send: MyCallable) -> int:
1343 return await send(1, 2)
1344
1345 async def await_throw(throw: MyCallable) -> int:
1346 return await throw(3, 4)
1347
1348 async def tests() -> None:
1349 assert await await_send(add) == 3
1350 assert await await_throw(add) == 7
1351
1352 def test_callable_arg_same_name_as_helper() -> None:
1353 asyncio.run(tests())
1354
1355 [file asyncio/__init__.pyi]
1356 def run(x: object) -> object: ...
1357
1358 [case testRunAsyncCancelFinallySpecialCase]
1359 import asyncio
1360
1361 from testutil import assertRaises
1362
1363 # Greatly simplified from asyncio.Condition
1364 class Condition:
1365 async def acquire(self) -> None: pass
1366
1367 async def wait(self) -> bool:
1368 l = asyncio.get_running_loop()
1369 fut = l.create_future()
1370 a = []
1371 try:
1372 try:
1373 a.append(fut)
1374 try:
1375 await fut
1376 return True
1377 finally:
1378 a.pop()
1379 finally:
1380 err = None
1381 while True:
1382 try:
1383 await self.acquire()
1384 break
1385 except asyncio.CancelledError as e:
1386 err = e
1387
1388 if err is not None:
1389 try:
1390 raise err
1391 finally:
1392 err = None
1393 except BaseException:
1394 raise
1395
1396 async def do_cancel() -> None:
1397 cond = Condition()
1398 wait = asyncio.create_task(cond.wait())
1399 asyncio.get_running_loop().call_soon(wait.cancel)
1400 with assertRaises(asyncio.CancelledError):
1401 await wait
1402
1403 def test_cancel_special_case() -> None:
1404 asyncio.run(do_cancel())
1405
1406 [file asyncio/__init__.pyi]
1407 from typing import Any
1408
1409 class CancelledError(Exception): ...
1410
1411 def run(x: object) -> object: ...
1412 def get_running_loop() -> Any: ...
1413 def create_task(x: object) -> Any: ...
1414
1415 [case testAsyncInheritance1]
1416 from typing import final, Coroutine, Any, TypeVar
1417
1418 import asyncio
1419
1420 from mypy_extensions import trait
1421
1422 class Base1:
1423 async def foo(self) -> int:
1424 return 1
1425
1426 class Derived1(Base1):
1427 async def foo(self) -> int:
1428 return await super().foo() + 1
1429
1430 async def base1_foo(b: Base1) -> int:
1431 return await b.foo()
1432
1433 async def derived1_foo(b: Derived1) -> int:
1434 return await b.foo()
1435
1436 def test_async_inheritance() -> None:
1437 assert asyncio.run(base1_foo(Base1())) == 1
1438 assert asyncio.run(base1_foo(Derived1())) == 2
1439 assert asyncio.run(derived1_foo(Derived1())) == 2
1440
1441 @final
1442 class FinalClass:
1443 async def foo(self) -> int:
1444 return 3
1445
1446 async def final_class_foo(b: FinalClass) -> int:
1447 return await b.foo()
1448
1449 def test_final_class() -> None:
1450 assert asyncio.run(final_class_foo(FinalClass())) == 3
1451
1452 class Base2:
1453 async def foo(self) -> int:
1454 return 4
1455
1456 async def bar(self) -> int:
1457 return 5
1458
1459 class Derived2(Base2):
1460 # Does not override "foo"
1461 async def bar(self) -> int:
1462 return 6
1463
1464 async def base2_foo(b: Base2) -> int:
1465 return await b.foo()
1466
1467 def test_no_override() -> None:
1468 assert asyncio.run(base2_foo(Base2())) == 4
1469 assert asyncio.run(base2_foo(Derived2())) == 4
1470
1471 class Base3:
1472 async def foo(self) -> int:
1473 return 7
1474
1475 class Derived3(Base3):
1476 def foo(self) -> Coroutine[Any, Any, int]:
1477 async def inner() -> int:
1478 return 8
1479 return inner()
1480
1481 async def base3_foo(b: Base3) -> int:
1482 return await b.foo()
1483
1484 def test_override_non_async() -> None:
1485 assert asyncio.run(base3_foo(Base3())) == 7
1486 assert asyncio.run(base3_foo(Derived3())) == 8
1487
1488 class Base4: pass
1489
1490 @trait
1491 class TraitBase:
1492 async def foo(self, value: int) -> int:
1493 raise NotImplementedError()
1494
1495 class DerivedFromTrait(Base4, TraitBase):
1496 async def foo(self, value: int) -> int:
1497 return value + 3
1498
1499 async def trait_foo(o: TraitBase, x: int) -> int:
1500 return await o.foo(x)
1501
1502 def test_override_trait() -> None:
1503 assert asyncio.run(trait_foo(DerivedFromTrait(), 7)) == 10
1504
1505 class Base5:
1506 def __init__(self) -> None:
1507 self._name = "test"
1508
1509 async def foo(self, x: int) -> int:
1510 assert self._name == "test"
1511 return x + 11
1512
1513 class Derived5(Base5):
1514 async def foo(self, x: int) -> int:
1515 return await super().foo(x) + 22
1516
1517 def test_call_using_super() -> None:
1518 assert asyncio.run(Derived5().foo(5)) == 38
1519
1520 [file asyncio/__init__.pyi]
1521 def run(x: object) -> object: ...
1522
1523 [case testAsyncIntrospection]
1524 import asyncio
1525 import gc
1526 import inspect
1527 import sys
1528 import weakref
1529
1530 from functools import wraps
1531 from typing import Any, Callable, TypeVar, cast
1532
1533 from testutil import is_gil_disabled
1534
1535 def identity(val: int) -> int:
1536 return val
1537
1538 async def identity_async(val: int) -> int:
1539 return val
1540
1541 F = TypeVar("F", bound=Callable[..., Any])
1542
1543 def wrap(fn: F) -> F:
1544 if is_coroutine(fn):
1545 @wraps(fn)
1546 async def wrapper_async(*args) -> Any:
1547 return await fn(*args) + await fn(*args)
1548
1549 return cast(F, wrapper_async)
1550
1551 @wraps(fn)
1552 def wrapper(*args) -> Any:
1553 return fn(*args) + fn(*args)
1554
1555 return cast(F, wrapper)
1556
1557 @wrap
1558 def wrapped(val: int) -> int:
1559 return val
1560
1561 @wrap
1562 def wrapped2(val: int) -> int:
1563 return val * 2
1564
1565 @wrap
1566 async def wrapped_async(val: int) -> int:
1567 return val
1568
1569 @wrap
1570 async def wrapped2_async(val: int) -> int:
1571 return val * 2
1572
1573 class T:
1574 def returns_one(self) -> int:
1575 return 1
1576
1577 async def returns_one_async(self) -> int:
1578 return 1
1579
1580 @wrap
1581 def returns_two(self) -> int:
1582 return 1
1583
1584 @wrap
1585 async def returns_two_async(self) -> int:
1586 return 1
1587
1588 @staticmethod
1589 def static() -> int:
1590 return 2
1591
1592 @staticmethod
1593 async def static_async() -> int:
1594 return 2
1595
1596 @classmethod
1597 def class_method(cls) -> int:
1598 return 3
1599
1600 @classmethod
1601 async def class_method_async(cls) -> int:
1602 return 3
1603
1604 def is_coroutine(fn):
1605 if sys.version_info >= (3, 10): # type: ignore[operator]
1606 return inspect.iscoroutinefunction(fn)
1607
1608 # inspect on older python versions does not support function-like objects.
1609 # Below is a simplified implementation of iscoroutinefunction.
1610 if not hasattr(fn, "__code__"):
1611 return False
1612 CO_COROUTINE = 0x0080
1613 return bool(fn.__code__.co_flags & CO_COROUTINE)
1614
1615 def test_function() -> None:
1616 assert not is_coroutine(identity)
1617 assert is_coroutine(identity_async)
1618 assert str(identity_async).startswith("<function identity_async"), str(identity_async)
1619 assert asyncio.run(identity_async(42)) == 42
1620
1621 wr = weakref.ref(identity_async)
1622 f = wr()
1623 assert f
1624 assert asyncio.run(f(43)) == 43
1625
1626 assert getattr(identity_async, "__name__") == "identity_async", getattr(identity_async, "__name__")
1627 setattr(identity_async, "__name__", "some custom name")
1628 assert getattr(identity_async, "__name__") == "some custom name", getattr(identity_async, "__name__")
1629 assert getattr(identity_async, "__code__") != None, getattr(identity_async, "__code__")
1630 assert getattr(identity_async, "__defaults__") == None, getattr(identity_async, "__defaults__")
1631 assert getattr(identity_async, "__kwdefaults__") == None, getattr(identity_async, "__kwdefaults__")
1632 assert getattr(identity_async, "__annotations__") == None, getattr(identity_async, "__annotations__")
1633
1634 assert not is_coroutine(wrapped)
1635 assert is_coroutine(wrapped_async)
1636 assert asyncio.run(wrapped_async(22)) == 44
1637
1638 assert getattr(wrapped, "__name__") == "wrapped", getattr(wrapped, "__name__")
1639 assert getattr(wrapped2, "__name__") == "wrapped2", getattr(wrapped2, "__name__")
1640
1641 assert getattr(wrapped_async, "__name__") == "wrapped_async", getattr(wrapped_async, "__name__")
1642 assert getattr(wrapped2_async, "__name__") == "wrapped2_async", getattr(wrapped2_async, "__name__")
1643
1644 setattr(wrapped_async, "__name__", "new name")
1645 assert getattr(wrapped_async, "__name__") == "new name", getattr(wrapped_async, "__name__")
1646 assert getattr(wrapped2_async, "__name__") == "wrapped2_async", getattr(wrapped2_async, "__name__")
1647
1648 def test_method() -> None:
1649 assert not is_coroutine(T.returns_one)
1650 assert is_coroutine(T.returns_one_async)
1651 assert str(T.returns_one_async).startswith("<function T.returns_one_async"), str(T.returns_one_async)
1652
1653 t = T()
1654 # Call through variable to make sure the call is through vectorcall and not optimized to a native call.
1655 f: Any = t.returns_one_async
1656 assert asyncio.run(f()) == 1
1657
1658 assert not is_coroutine(T.returns_two)
1659 assert is_coroutine(T.returns_two_async)
1660 assert asyncio.run(t.returns_two_async()) == 2
1661
1662 assert not is_coroutine(T.static)
1663 assert is_coroutine(T.static_async)
1664 assert asyncio.run(T.static_async()) == 2
1665
1666 assert not is_coroutine(T.class_method)
1667 assert is_coroutine(T.class_method_async)
1668 assert asyncio.run(T.class_method_async()) == 3
1669
1670 def test_nested() -> None:
1671 def nested() -> int:
1672 return 1
1673
1674 async def nested_async() -> int:
1675 return 1
1676
1677 @wrap
1678 def nested_wrapped() -> int:
1679 return 2
1680
1681 @wrap
1682 async def nested_wrapped_async() -> int:
1683 return 2
1684
1685 assert not is_coroutine(nested)
1686 assert is_coroutine(nested_async)
1687 assert asyncio.run(nested_async()) == 1
1688
1689 assert getattr(nested_async, "__name__") == "nested_async", getattr(nested_async, "__name__")
1690 setattr(nested_async, "__name__", "some custom name")
1691 assert getattr(nested_async, "__name__") == "some custom name", getattr(nested_async, "__name__")
1692 assert getattr(nested_async, "__code__") != None, getattr(nested_async, "__code__")
1693 assert getattr(nested_async, "__defaults__") == None, getattr(nested_async, "__defaults__")
1694 assert getattr(nested_async, "__kwdefaults__") == None, getattr(nested_async, "__kwdefaults__")
1695 assert getattr(nested_async, "__annotations__") == None, getattr(nested_async, "__annotations__")
1696
1697 assert not is_coroutine(nested_wrapped)
1698 assert is_coroutine(nested_wrapped_async)
1699 assert asyncio.run(nested_wrapped_async()) == 4
1700
1701 def test_async_function_wrapper_code_refcount() -> None:
1702 if is_gil_disabled():
1703 # On free-threaded builds the code object might be immortal, so the ref count test doesn't work.
1704 return
1705 code = getattr(identity_async, "__code__")
1706 getrefcount = getattr(sys, "getrefcount")
1707 # getrefcount sees the local code variable plus the wrapper-owned reference.
1708 assert getrefcount(code) == 2, getrefcount(code)
1709
1710 def test_nested_async_function_wrapper_code_refcount() -> None:
1711 if is_gil_disabled():
1712 # On free-threaded builds the code object might be immortal, so the ref count test doesn't work.
1713 return
1714 def make_nested() -> Any:
1715 async def nested_refcounted() -> int:
1716 return 1
1717
1718 return nested_refcounted
1719
1720 getrefcount = getattr(sys, "getrefcount")
1721 fn = make_nested()
1722 code = getattr(fn, "__code__")
1723 before = getrefcount(code)
1724 assert asyncio.run(fn()) == 1
1725
1726 del fn
1727 gc.collect()
1728 after = getrefcount(code)
1729 assert before == after + 1, (before, after)
1730 assert after == 1, after
1731
1732 [file asyncio/__init__.pyi]
1733 def run(x: object) -> object: ...
1734
1735 [case testFuture]
1736 import asyncio
1737 from typing import Any, Awaitable
1738
1739 from testutil import assertRaises
1740
1741 from m import (
1742 m_future_with_result,
1743 m_future_with_exception,
1744 m_future_with_caught_exception,
1745 m_future_with_reraised_exception
1746 )
1747
1748 async def set_result(fut: asyncio.Future, result: Any) -> None:
1749 if isinstance(result, Exception):
1750 fut.set_exception(result)
1751 else:
1752 fut.set_result(result)
1753
1754 def make_future(result: Any) -> asyncio.Future:
1755 loop = asyncio.get_running_loop()
1756 fut = loop.create_future()
1757 loop.create_task(set_result(fut, result))
1758 return fut
1759
1760 async def future_with_result(result: int) -> int:
1761 return await make_future(result)
1762
1763 async def future_with_exception(exception: Exception) -> Any:
1764 return await make_future(exception)
1765
1766 async def future_with_caught_exception(exception: Exception) -> None:
1767 try:
1768 return await make_future(exception)
1769 except type(exception):
1770 return None
1771
1772 async def future_with_reraised_exception(first_exc: Exception, second_exc: Exception) -> Any:
1773 try:
1774 return await make_future(first_exc)
1775 except type(first_exc):
1776 raise second_exc
1777
1778 def test_future() -> None:
1779 assert asyncio.run(future_with_result(42)) == 42
1780
1781 with assertRaises(ValueError, "error"):
1782 asyncio.run(future_with_exception(ValueError("error")))
1783
1784 assert asyncio.run(future_with_caught_exception(ValueError("error"))) == None
1785
1786 with assertRaises(RuntimeError, "reraised"):
1787 asyncio.run(future_with_reraised_exception(ValueError("error"), RuntimeError("reraised")))
1788
1789 class ctx_man:
1790 def __enter__(self) -> None:
1791 pass
1792
1793 def __exit__(self, *args: Any) -> None:
1794 pass
1795
1796 async def wrap(f: Awaitable) -> Any:
1797 with ctx_man():
1798 return await f
1799
1800 def test_future_with_context_manager() -> None:
1801 assert asyncio.run(wrap(future_with_result(42))) == 42
1802
1803 with assertRaises(ValueError, "error"):
1804 asyncio.run(wrap(future_with_exception(ValueError("error"))))
1805
1806 assert asyncio.run(wrap(future_with_caught_exception(ValueError("error")))) == None
1807
1808 with assertRaises(RuntimeError, "reraised"):
1809 asyncio.run(wrap(future_with_reraised_exception(ValueError("error"), RuntimeError("reraised"))))
1810
1811 def test_interpreted_future() -> None:
1812 assert asyncio.run(m_future_with_result(42)) == 42
1813
1814 with assertRaises(ValueError, "error"):
1815 asyncio.run(m_future_with_exception(ValueError("error")))
1816
1817 assert asyncio.run(m_future_with_caught_exception(ValueError("error"))) == None
1818
1819 with assertRaises(RuntimeError, "reraised"):
1820 asyncio.run(m_future_with_reraised_exception(ValueError("error"), RuntimeError("reraised")))
1821
1822 def test_interpreted_future_with_context_manager() -> None:
1823 assert asyncio.run(wrap(m_future_with_result(42))) == 42
1824
1825 with assertRaises(ValueError, "error"):
1826 asyncio.run(wrap(m_future_with_exception(ValueError("error"))))
1827
1828 assert asyncio.run(wrap(m_future_with_caught_exception(ValueError("error")))) == None
1829
1830 with assertRaises(RuntimeError, "reraised"):
1831 asyncio.run(wrap(m_future_with_reraised_exception(ValueError("error"), RuntimeError("reraised"))))
1832
1833 [file asyncio/__init__.pyi]
1834 from typing import Any, Generator
1835
1836 def run(x: object) -> object: ...
1837
1838 class Future:
1839 def set_result(self, result: object) -> None: ...
1840 def set_exception(self, exception: object) -> None: ...
1841 def __await__(self) -> Generator[Any, Any, Any]: ...
1842
1843 class Loop:
1844 def create_future(self) -> Future: ...
1845 def create_task(self, x: object) -> None: ...
1846
1847 def get_running_loop() -> Loop: ...
1848
1849 [file m.py]
1850 import asyncio
1851 from typing import Any
1852
1853 async def set_result(fut: asyncio.Future, result: Any) -> None:
1854 if isinstance(result, Exception):
1855 fut.set_exception(result)
1856 else:
1857 fut.set_result(result)
1858
1859 def make_future(result: Any) -> asyncio.Future:
1860 loop = asyncio.get_running_loop()
1861 fut = loop.create_future()
1862 loop.create_task(set_result(fut, result))
1863 return fut
1864
1865 async def m_future_with_result(result: int) -> int:
1866 return await make_future(result)
1867
1868 async def m_future_with_exception(exception: Exception) -> Any:
1869 return await make_future(exception)
1870
1871 async def m_future_with_caught_exception(exception: Exception) -> None:
1872 try:
1873 return await make_future(exception)
1874 except type(exception):
1875 return None
1876
1877 async def m_future_with_reraised_exception(first_exc: Exception, second_exc: Exception) -> Any:
1878 try:
1879 return await make_future(first_exc)
1880 except type(first_exc):
1881 raise second_exc
1882
1883 [case testCPyFunctionWithFreedInstance]
1884 import asyncio
1885
1886 from functools import wraps
1887 from typing import Any
1888
1889 class ctx_man:
1890 async def __aenter__(self) -> None:
1891 pass
1892
1893 async def __aexit__(self, *args: Any) -> None:
1894 pass
1895
1896 def with_ctx_man():
1897 def decorator(f):
1898 @wraps(f)
1899 async def inner():
1900 async with ctx_man():
1901 return await f()
1902
1903 return inner
1904
1905 return decorator
1906
1907 async def func() -> int:
1908 return 33
1909
1910 async def run_wrapped():
1911 wrapped = with_ctx_man()(func)
1912 return await wrapped()
1913
1914 def test_native():
1915 assert asyncio.run(run_wrapped()) == 33
1916
1917 [file driver.py]
1918 import asyncio
1919
1920 from native import test_native, with_ctx_man
1921
1922 async def func() -> int:
1923 return 42
1924
1925 async def run_wrapped():
1926 wrapped = with_ctx_man()(func)
1927 return await wrapped()
1928
1929 def test_interpreted():
1930 assert asyncio.run(run_wrapped()) == 42
1931
1932 # Run multiple times to test that the CPyFunction attribute is still
1933 # set correctly after reusing a freed instance of the inner callable class object.
1934 for i in range(10):
1935 test_interpreted()
1936 test_native()
1937
1938 [file asyncio/__init__.pyi]
1939 from typing import Any, Generator
1940
1941 def run(x: object) -> object: ...
1942
1943 [case testNestedCoroutineCallsAnotherNestedFunction]
1944 import asyncio
1945 import functools
1946 import inspect
1947 from typing import Any, Callable, TypeVar, cast
1948
1949 F = TypeVar("F", bound=Callable[..., Any])
1950
1951
1952 def mult_different_wrapper_names(x: int) -> Callable[[F], F]:
1953 def decorate(fn: F) -> F:
1954 def get_multiplier() -> int:
1955 return x
1956
1957 if inspect.iscoroutinefunction(fn):
1958 @functools.wraps(fn)
1959 async def wrapper_async(*args, **kwargs) -> Any:
1960 return get_multiplier() * await fn(*args, **kwargs)
1961 wrapper = wrapper_async
1962 else:
1963 @functools.wraps(fn)
1964 def wrapper_non_async(*args, **kwargs) -> Any:
1965 return get_multiplier() * fn(*args, **kwargs)
1966 wrapper = wrapper_non_async
1967
1968 return cast(F, wrapper)
1969
1970 return decorate
1971
1972 def mult_same_wrapper_names(x: int) -> Callable[[F], F]:
1973 def decorate(fn: F) -> F:
1974 def get_multiplier() -> int:
1975 return x
1976
1977 if inspect.iscoroutinefunction(fn):
1978 @functools.wraps(fn)
1979 async def wrapper(*args, **kwargs) -> Any:
1980 return get_multiplier() * await fn(*args, **kwargs)
1981 else:
1982 @functools.wraps(fn)
1983 def wrapper(*args, **kwargs) -> Any:
1984 return get_multiplier() * fn(*args, **kwargs)
1985
1986 return cast(F, wrapper)
1987
1988 return decorate
1989
1990 @mult_different_wrapper_names(3)
1991 def identity(x: int):
1992 return x
1993
1994 @mult_different_wrapper_names(5)
1995 async def async_identity(x: int):
1996 return x
1997
1998 @mult_same_wrapper_names(2)
1999 def times_two(x: int):
2000 return x * 2
2001
2002 @mult_same_wrapper_names(4)
2003 async def async_times_two(x: int):
2004 return x * 2
2005
2006 def test_nested_coroutine_calls_another_nested_function():
2007 assert identity(1) == 3
2008 assert asyncio.run(async_identity(2)) == 10
2009
2010 assert times_two(3) == 12
2011 assert asyncio.run(async_times_two(4)) == 32
2012
2013 [file asyncio/__init__.pyi]
2014 from typing import Any, Generator
2015
2016 def run(x: object) -> object: ...
2017
2018 [case testRaiseStopAsyncIteration]
2019 from async_iter import async_iter
2020 from testutil import assertRaises
2021
2022 class AsyncIter:
2023 def __init__(self, vals: list[str]) -> None:
2024 self._iter = iter(vals)
2025
2026 def __aiter__(self) -> AsyncIter:
2027 return self
2028
2029 async def __anext__(self) -> str:
2030 try:
2031 return next(self._iter)
2032 except StopIteration:
2033 raise StopAsyncIteration
2034
2035 async def test_iterator() -> None:
2036 new_list: list[int] = []
2037 async for v in async_iter([1, 2, 3]):
2038 new_list.append(v)
2039 assert new_list == [1, 2, 3]
2040
2041 new_list = []
2042 iter = async_iter([1, 2, 3])
2043 while True:
2044 try:
2045 v = await iter.__anext__()
2046 new_list.append(v)
2047 except StopAsyncIteration:
2048 new_list.append(4)
2049 break
2050 assert new_list == [1, 2, 3, 4]
2051
2052 with assertRaises(StopAsyncIteration):
2053 await async_iter([]).__anext__()
2054
2055 async def test_wrapper() -> None:
2056 new_list: list[str] = []
2057 async for v in AsyncIter(['a', 'b', 'c']):
2058 new_list.append(v)
2059 assert new_list == ['a', 'b', 'c']
2060
2061 new_list = []
2062 iter = AsyncIter(['a', 'b', 'c'])
2063 while True:
2064 try:
2065 v = await iter.__anext__()
2066 new_list.append(v)
2067 except StopAsyncIteration:
2068 new_list.append('d')
2069 break
2070 assert new_list == ['a', 'b', 'c', 'd']
2071
2072 with assertRaises(StopAsyncIteration):
2073 await AsyncIter([]).__anext__()
2074
2075 [file async_iter.py]
2076 from typing import AsyncIterator
2077
2078 async def async_iter(vals: list[int]) -> AsyncIterator[int]:
2079 for v in vals:
2080 yield v
2081
2082 [typing fixtures/typing-full.pyi]
2083
2084 [case testBorrowedFinalAttrAcrossAwait]
2085 from typing import Final
2086 from testutil import async_val
2087
2088 class C:
2089 def __init__(self, s: str) -> None:
2090 self.s: Final = s
2091
2092 async def f(c: C) -> str:
2093 # c.s is a final attr; it must not be borrowed across the await, which is a
2094 # suspension point in the middle of the expression.
2095 return c.s + await async_val("hello")
2096
2097 [file driver.py]
2098 from native import f, C
2099 from testutil import run_generator
2100
2101 for i in range(50):
2102 c = C("value" + str(i))
2103 yields, val = run_generator(f(c), inputs=["world"])
2104 assert yields == ("hello",), yields
2105 assert val == "value" + str(i) + "world", repr(val)
2106
2107 [case testCoroutineClosureOutlivesCompletedCoroutine]
2108 import asyncio
2109 from typing import Callable
2110
2111 async def make_reader() -> Callable[[], int]:
2112 payload = [7]
2113 await asyncio.sleep(0)
2114
2115 def read_payload() -> int:
2116 return payload[0]
2117
2118 return read_payload
2119
2120 async def make_arg_reader(payload: list[int]) -> Callable[[], int]:
2121 await asyncio.sleep(0)
2122
2123 def read_payload() -> int:
2124 return payload[0]
2125
2126 return read_payload
2127
2128 async def make_indirect_reader() -> Callable[[], int]:
2129 def leaf() -> int:
2130 return 17
2131
2132 def reader() -> int:
2133 return leaf()
2134
2135 await asyncio.sleep(0)
2136 return reader
2137
2138 def test_closure_returned_from_completed_coroutine_keeps_capture() -> None:
2139 read_payload = asyncio.run(make_reader())
2140 assert read_payload() == 7
2141
2142 payload = [13]
2143 read_arg_payload = asyncio.run(make_arg_reader(payload))
2144 payload = [0]
2145 assert read_arg_payload() == 13
2146
2147 indirect_reader = asyncio.run(make_indirect_reader())
2148 assert indirect_reader() == 17
2149
2150 async def test_closure_returned_from_awaited_coroutine_keeps_capture() -> None:
2151 read_payload = await make_reader()
2152 assert read_payload() == 7
2153
2154 payload = [13]
2155 read_arg_payload = await make_arg_reader(payload)
2156 payload = [0]
2157 assert read_arg_payload() == 13
2158
2159 indirect_reader = await make_indirect_reader()
2160 assert indirect_reader() == 17
2161
2162 [file asyncio/__init__.pyi]
2163 from typing import Awaitable, TypeVar
2164
2165 T = TypeVar("T")
2166
2167 def run(x: Awaitable[T]) -> T: ...
2168 async def sleep(t: float) -> None: ...
2169
2170 [typing fixtures/typing-full.pyi]
2171
2172 [case testNestedCoroutineOutlivesCompletedCoroutine]
2173 import asyncio
2174 from typing import Awaitable
2175
2176 async def make_nested_coroutine() -> Awaitable[int]:
2177 payload = [11]
2178 await asyncio.sleep(0)
2179
2180 async def read_payload() -> int:
2181 await asyncio.sleep(0)
2182 return payload[0]
2183
2184 return read_payload()
2185
2186 def test_nested_coroutine_returned_from_completed_coroutine_keeps_capture() -> None:
2187 read_payload = asyncio.run(make_nested_coroutine())
2188 assert asyncio.run(read_payload) == 11
2189
2190 [file asyncio/__init__.pyi]
2191 from typing import Awaitable, TypeVar
2192
2193 T = TypeVar("T")
2194
2195 def run(x: Awaitable[T]) -> T: ...
2196 async def sleep(t: float) -> None: ...
2197
2198 [typing fixtures/typing-full.pyi]
2199
2200 [case testBorrowedFinalAttrAcrossAsyncComprehension]
2201 import asyncio
2202 from typing import Final
2203
2204 class C:
2205 def __init__(self, s: str) -> None:
2206 self.s: Final = s
2207
2208 class AsyncRange:
2209 def __init__(self, n: int) -> None:
2210 self.n = n
2211 self.i = 0
2212
2213 def __aiter__(self) -> "AsyncRange":
2214 return self
2215
2216 async def __anext__(self) -> str:
2217 if self.i >= self.n:
2218 raise StopAsyncIteration
2219 i = self.i
2220 self.i += 1
2221 # Suspend in the middle of iteration.
2222 await asyncio.sleep(0)
2223 return "item" + str(i)
2224
2225 async def f(c: C) -> str:
2226 # c.s is a final attr; it must not be borrowed across the async comprehension,
2227 # which suspends via an implicit await on __anext__ that isn't represented as
2228 # an AwaitExpr node in the AST.
2229 return c.s + "".join([x async for x in AsyncRange(3)])
2230
2231 async def test_async_comprehension_borrow() -> None:
2232 for i in range(50):
2233 c = C("value" + str(i))
2234 assert await f(c) == "value" + str(i) + "item0item1item2"
2235
2236 [file asyncio/__init__.pyi]
2237 async def sleep(t: float) -> None: ...
2238
2239 [typing fixtures/typing-full.pyi]
2240
2241 [case testBorrowedFinalAttrAcrossAwaitAfterComprehension]
2242 import asyncio
2243 from typing import Final
2244
2245 class C:
2246 def __init__(self, s: str) -> None:
2247 self.s: Final = s
2248
2249 async def sink() -> str:
2250 await asyncio.sleep(0)
2251 return "z"
2252
2253 async def f(c: C, xs: list[int]) -> str:
2254 # A (sync) comprehension enters a nested borrow scope earlier in the same
2255 # top-level expression. It must not clear the enclosing expression's suspend
2256 # flag, or c.s (a final attr) gets borrowed across the await below, which
2257 # produces invalid C (the borrow does not survive the suspension point).
2258 return str([x for x in xs]) + (c.s + await sink())
2259
2260 async def test_borrow_final_attr_across_await_after_comprehension() -> None:
2261 for i in range(50):
2262 c = C("v" + str(i))
2263 assert await f(c, [1, 2, 3]) == "[1, 2, 3]" + "v" + str(i) + "z"
2264
2265 [file asyncio/__init__.pyi]
2266 async def sleep(t: float) -> None: ...
2267
2268 [typing fixtures/typing-full.pyi]