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 async def sleep() -> None:
411 # Non-zero value hangs on Windows.
412 time = 0 if platform.system() == "Windows" else 0.0001
413 await asyncio.sleep(time)
414
415 async def assert_no_leaks(fn, max_new):
416 # Warm-up, in case asyncio allocates something on first use
417 await fn()
418
419 gc.collect()
420 old_objs = gc.get_objects()
421
422 for i in range(10):
423 await fn()
424
425 gc.collect()
426 new_objs = gc.get_objects()
427
428 delta = len(new_objs) - len(old_objs)
429 # Often a few persistent objects get allocated, which may be unavoidable.
430 # The main thing we care about is that each iteration does not leak an
431 # additional object.
432 assert delta <= max_new, delta
433
434 async def concat_one(x: str) -> str:
435 return x + "1"
436
437 async def foo(n: int) -> str:
438 s = ""
439 while len(s) < n:
440 s = await concat_one(s)
441 return s
442
443 async def test_trivial() -> None:
444 await assert_no_leaks(lambda: foo(1000), 5)
445
446 async def make_list(a: list[int]) -> list[int]:
447 await concat_one("foobar")
448 return [a[0]]
449
450 async def spill() -> list[int]:
451 a: list[int] = []
452 for i in range(5):
453 await sleep()
454 a = (await make_list(a + [1])) + a + (await make_list(a + [2]))
455 return a
456
457 async def bar(n: int) -> None:
458 for i in range(n):
459 await spill()
460
461 async def test_spilled() -> None:
462 await assert_no_leaks(lambda: bar(80), 13)
463
464 async def raise_deep(n: int) -> str:
465 if n == 0:
466 await sleep()
467 raise TypeError(str(n))
468 else:
469 if n == 2:
470 await sleep()
471 return await raise_deep(n - 1)
472
473 async def maybe_raise(n: int) -> str:
474 if n % 3 == 0:
475 await raise_deep(5)
476 elif n % 29 == 0:
477 await sleep()
478 return str(n)
479
480 async def exc(n: int) -> list[str]:
481 a = []
482 for i in range(n):
483 try:
484 a.append(str(int()) + await maybe_raise(n))
485 except TypeError:
486 a.append(str(int() + 5))
487 return a
488
489 async def test_exception() -> None:
490 await assert_no_leaks(lambda: exc(50), 2)
491
492 class C:
493 def __init__(self, s: str) -> None:
494 self.s = s
495
496 async def id(c: C) -> C:
497 return c
498
499 async def stolen_helper(c: C, s: str) -> str:
500 await sleep()
501 (await id(c)).s = await concat_one(s)
502 await sleep()
503 return c.s
504
505 async def stolen(n: int) -> int:
506 for i in range(n):
507 c = C(str(i))
508 s = await stolen_helper(c, str(i + 2))
509 assert s == str(i + 2) + "1"
510 return n
511
512 async def test_stolen() -> None:
513 await assert_no_leaks(lambda: stolen(200), 16)
514
515 [file asyncio/__init__.pyi]
516 async def sleep(t: float) -> None: ...
517
518 [case testRunAsyncMiscTypesInEnvironment]
519 # Here we test that values of various kinds of types can be spilled to the
520 # environment. In particular, types with "overlapping error values" such as
521 # i64 can be tricky, since they require extra work to support undefined
522 # attribute values (which raise AttributeError when accessed). For these,
523 # the object struct has a bitfield which keeps track of whether certain
524 # attributes have an assigned value.
525 #
526 # In practice we mark these attributes as "always defined", which causes these
527 # checks to be skipped on attribute access, and thus we don't require the
528 # bitfield to exist.
529 #
530 # See the comment of RType.error_overlap for more information.
531
532 import asyncio
533
534 from mypy_extensions import i64, i32, i16, u8
535
536 async def inc_float(x: float) -> float:
537 return x + 1.0
538
539 async def inc_i64(x: i64) -> i64:
540 return x + 1
541
542 async def inc_i32(x: i32) -> i32:
543 return x + 1
544
545 async def inc_i16(x: i16) -> i16:
546 return x + 1
547
548 async def inc_u8(x: u8) -> u8:
549 return x + 1
550
551 async def inc_tuple(x: tuple[i64, float]) -> tuple[i64, float]:
552 return x[0] + 1, x[1] + 1.5
553
554 async def neg_bool(b: bool) -> bool:
555 return not b
556
557 async def float_ops(x: float) -> float:
558 n = x
559 n = await inc_float(n)
560 n = float("0.5") + await inc_float(n)
561 return n
562
563 async def test_float() -> None:
564 assert await float_ops(2.5) == 5.0
565
566 async def i64_ops(x: i64) -> i64:
567 n = x
568 n = await inc_i64(n)
569 n = i64("1") + await inc_i64(n)
570 return n
571
572 async def test_i64() -> None:
573 assert await i64_ops(2) == 5
574
575 async def i32_ops(x: i32) -> i32:
576 n = x
577 n = await inc_i32(n)
578 n = i32("1") + await inc_i32(n)
579 return n
580
581 async def test_i32() -> None:
582 assert await i32_ops(3) == 6
583
584 async def i16_ops(x: i16) -> i16:
585 n = x
586 n = await inc_i16(n)
587 n = i16("1") + await inc_i16(n)
588 return n
589
590 async def test_i16() -> None:
591 assert await i16_ops(4) == 7
592
593 async def u8_ops(x: u8) -> u8:
594 n = x
595 n = await inc_u8(n)
596 n = u8("1") + await inc_u8(n)
597 return n
598
599 async def test_u8() -> None:
600 assert await u8_ops(5) == 8
601
602 async def tuple_ops(x: tuple[i64, float]) -> tuple[i64, float]:
603 n = x
604 n = await inc_tuple(n)
605 m = ((i64("1"), float("0.5")), await inc_tuple(n))
606 return m[1]
607
608 async def test_tuple() -> None:
609 assert await tuple_ops((1, 2.5)) == (3, 5.5)
610
611 async def bool_ops(x: bool) -> bool:
612 n = x
613 n = await neg_bool(n)
614 m = (bool("1"), await neg_bool(n))
615 return m[0] and m[1]
616
617 async def test_bool() -> None:
618 assert await bool_ops(True) is True
619 assert await bool_ops(False) is False
620
621 [file asyncio/__init__.pyi]
622 def run(x: object) -> object: ...
623
624 [case testRunAsyncNestedFunctions]
625 from __future__ import annotations
626
627 import asyncio
628 from typing import cast, Iterator, overload, Awaitable, Any, TypeVar
629
630 from testutil import assertRaises
631
632 def normal_contains_async_def(x: int) -> int:
633 async def f(y: int) -> int:
634 return x + y
635
636 return 5 + cast(int, asyncio.run(f(6)))
637
638 def test_def_contains_async_def() -> None:
639 assert normal_contains_async_def(3) == 14
640
641 async def inc(x: int) -> int:
642 return x + 1
643
644 async def async_def_contains_normal(x: int) -> int:
645 def nested(y: int, z: int) -> int:
646 return x + y + z
647
648 a = x
649 a += nested((await inc(3)), (await inc(4)))
650 return a
651
652 async def test_async_def_contains_normal() -> None:
653 assert await async_def_contains_normal(2) == (2 + 2 + 4 + 5)
654
655 async def async_def_contains_async_def(x: int) -> int:
656 async def f(y: int) -> int:
657 return (await inc(x)) + (await inc(y))
658
659 return (await f(1)) + (await f(2))
660
661 async def test_async_def_contains_async_def() -> None:
662 assert await async_def_contains_async_def(3) == (3 + 1 + 1 + 1) + (3 + 1 + 2 + 1)
663
664 async def async_def_contains_generator(x: int) -> tuple[int, int, int]:
665 def gen(y: int) -> Iterator[int]:
666 yield x + 1
667 yield x + y
668
669 it = gen(4)
670 res = x + 10, next(it), next(it)
671
672 with assertRaises(StopIteration):
673 next(it)
674
675 return res
676
677 async def test_async_def_contains_generator() -> None:
678 assert await async_def_contains_generator(3) == (13, 4, 7)
679
680 def generator_contains_async_def(x: int) -> Iterator[int]:
681 async def f(y: int) -> int:
682 return (await inc(x)) + (await inc(y))
683
684 yield cast(int, asyncio.run(f(2)))
685 yield cast(int, asyncio.run(f(3)))
686 yield x + 10
687
688 def test_generator_contains_async_def() -> None:
689 assert list(generator_contains_async_def(5)) == [6 + 3, 6 + 4, 15]
690
691 async def async_def_contains_two_nested_functions(x: int, y: int) -> tuple[int, int]:
692 def f(a: int) -> int:
693 return x + a
694
695 def g(b: int, c: int) -> int:
696 return y + b + c
697
698 return (await inc(f(3))), (await inc(g(4, 10)))
699
700 async def test_async_def_contains_two_nested_functions() -> None:
701 assert await async_def_contains_two_nested_functions(5, 7) == (
702 (5 + 3 + 1), (7 + 4 + 10 + 1)
703 )
704
705 async def async_def_contains_overloaded_async_def(n: int) -> int:
706 @overload
707 async def f(x: int) -> int: ...
708
709 @overload
710 async def f(x: str) -> str: ...
711
712 async def f(x: int | str) -> Any:
713 return x
714
715 return (await f(n)) + 1
716
717
718 async def test_async_def_contains_overloaded_async_def() -> None:
719 assert await async_def_contains_overloaded_async_def(5) == 6
720
721 T = TypeVar("T")
722
723 def deco(f: T) -> T:
724 return f
725
726 async def async_def_contains_decorated_async_def(n: int) -> int:
727 @deco
728 async def f(x: int) -> int:
729 return x + 2
730
731 return (await f(n)) + 1
732
733
734 async def test_async_def_contains_decorated_async_def() -> None:
735 assert await async_def_contains_decorated_async_def(7) == 10
736
737 [file asyncio/__init__.pyi]
738 def run(x: object) -> object: ...
739
740 [case testAsyncTryFinallyMixedReturn]
741 # This used to raise an AttributeError, when:
742 # - the try block contains multiple paths
743 # - at least one of those explicitly returns
744 # - at least one of those does not explicitly return
745 # - the non-returning path is taken at runtime
746
747 async def mixed_return(b: bool) -> bool:
748 try:
749 if b:
750 return b
751 finally:
752 pass
753 return b
754
755
756 async def test_async_try_finally_mixed_return() -> None:
757 # Test return path
758 result1 = await mixed_return(True)
759 assert result1 == True
760
761 # Test non-return path
762 result2 = await mixed_return(False)
763 assert result2 == False
764
765 [case testAsyncWithMixedReturn]
766 # This used to raise an AttributeError, related to
767 # testAsyncTryFinallyMixedReturn, this is essentially
768 # a far more extensive version of that test surfacing
769 # more edge cases
770
771 from typing import Optional, Type, Literal
772
773
774 class AsyncContextManager:
775 async def __aenter__(self) -> "AsyncContextManager":
776 return self
777
778 async def __aexit__(
779 self,
780 t: Optional[Type[BaseException]],
781 v: Optional[BaseException],
782 tb: object,
783 ) -> Literal[False]:
784 return False
785
786
787 # Simple async functions (generator class)
788 async def gen_1(b: bool) -> bool:
789 async with AsyncContextManager():
790 if b:
791 return b
792 return b
793
794
795 async def gen_2(b: bool) -> bool:
796 async with AsyncContextManager():
797 if b:
798 return b
799 else:
800 return b
801
802
803 async def gen_3(b: bool) -> bool:
804 async with AsyncContextManager():
805 if b:
806 return b
807 else:
808 pass
809 return b
810
811
812 async def gen_4(b: bool) -> bool:
813 ret: bool
814 async with AsyncContextManager():
815 if b:
816 ret = b
817 else:
818 ret = b
819 return ret
820
821
822 async def gen_5(i: int) -> int:
823 async with AsyncContextManager():
824 if i == 1:
825 return i
826 elif i == 2:
827 pass
828 elif i == 3:
829 return i
830 return i
831
832
833 async def gen_6(i: int) -> int:
834 async with AsyncContextManager():
835 if i == 1:
836 return i
837 elif i == 2:
838 return i
839 elif i == 3:
840 return i
841 return i
842
843
844 async def gen_7(i: int) -> int:
845 async with AsyncContextManager():
846 if i == 1:
847 return i
848 elif i == 2:
849 return i
850 elif i == 3:
851 return i
852 else:
853 return i
854
855
856 # Async functions with nested functions (environment class)
857 async def env_1(b: bool) -> bool:
858 def helper() -> bool:
859 return True
860
861 async with AsyncContextManager():
862 if b:
863 return helper()
864 return b
865
866
867 async def env_2(b: bool) -> bool:
868 def helper() -> bool:
869 return True
870
871 async with AsyncContextManager():
872 if b:
873 return helper()
874 else:
875 return b
876
877
878 async def env_3(b: bool) -> bool:
879 def helper() -> bool:
880 return True
881
882 async with AsyncContextManager():
883 if b:
884 return helper()
885 else:
886 pass
887 return b
888
889
890 async def env_4(b: bool) -> bool:
891 def helper() -> bool:
892 return True
893
894 ret: bool
895 async with AsyncContextManager():
896 if b:
897 ret = helper()
898 else:
899 ret = b
900 return ret
901
902
903 async def env_5(i: int) -> int:
904 def helper() -> int:
905 return 1
906
907 async with AsyncContextManager():
908 if i == 1:
909 return helper()
910 elif i == 2:
911 pass
912 elif i == 3:
913 return i
914 return i
915
916
917 async def env_6(i: int) -> int:
918 def helper() -> int:
919 return 1
920
921 async with AsyncContextManager():
922 if i == 1:
923 return helper()
924 elif i == 2:
925 return i
926 elif i == 3:
927 return i
928 return i
929
930
931 async def env_7(i: int) -> int:
932 def helper() -> int:
933 return 1
934
935 async with AsyncContextManager():
936 if i == 1:
937 return helper()
938 elif i == 2:
939 return i
940 elif i == 3:
941 return i
942 else:
943 return i
944
945
946 async def test_async_with_mixed_return() -> None:
947 # Test simple async functions (generator class)
948 # env_1: mixed return/no-return
949 assert await gen_1(True) is True
950 assert await gen_1(False) is False
951
952 # gen_2: all branches return
953 assert await gen_2(True) is True
954 assert await gen_2(False) is False
955
956 # gen_3: mixed return/pass
957 assert await gen_3(True) is True
958 assert await gen_3(False) is False
959
960 # gen_4: no returns in async with
961 assert await gen_4(True) is True
962 assert await gen_4(False) is False
963
964 # gen_5: multiple branches, some return
965 assert await gen_5(0) == 0
966 assert await gen_5(1) == 1
967 assert await gen_5(2) == 2
968 assert await gen_5(3) == 3
969
970 # gen_6: all explicit branches return, implicit fallthrough
971 assert await gen_6(0) == 0
972 assert await gen_6(1) == 1
973 assert await gen_6(2) == 2
974 assert await gen_6(3) == 3
975
976 # gen_7: all branches return including else
977 assert await gen_7(0) == 0
978 assert await gen_7(1) == 1
979 assert await gen_7(2) == 2
980 assert await gen_7(3) == 3
981
982 # Test async functions with nested functions (environment class)
983 # env_1: mixed return/no-return
984 assert await env_1(True) is True
985 assert await env_1(False) is False
986
987 # env_2: all branches return
988 assert await env_2(True) is True
989 assert await env_2(False) is False
990
991 # env_3: mixed return/pass
992 assert await env_3(True) is True
993 assert await env_3(False) is False
994
995 # env_4: no returns in async with
996 assert await env_4(True) is True
997 assert await env_4(False) is False
998
999 # env_5: multiple branches, some return
1000 assert await env_5(0) == 0
1001 assert await env_5(1) == 1
1002 assert await env_5(2) == 2
1003 assert await env_5(3) == 3
1004
1005 # env_6: all explicit branches return, implicit fallthrough
1006 assert await env_6(0) == 0
1007 assert await env_6(1) == 1
1008 assert await env_6(2) == 2
1009 assert await env_6(3) == 3
1010
1011 # env_7: all branches return including else
1012 assert await env_7(0) == 0
1013 assert await env_7(1) == 1
1014 assert await env_7(2) == 2
1015 assert await env_7(3) == 3
1016
1017 [case testAsyncTryExceptFinallyAwait]
1018 import asyncio
1019 from testutil import assertRaises
1020
1021 class TestError(Exception):
1022 pass
1023
1024 # Test 0: Simplest case - just try/finally with raise and await
1025 async def simple_try_finally_await() -> None:
1026 try:
1027 raise ValueError("simple error")
1028 finally:
1029 await asyncio.sleep(0)
1030
1031 # Test 1: Raise inside try, catch in except, don't re-raise
1032 async def async_try_except_no_reraise() -> int:
1033 try:
1034 raise ValueError("test error")
1035 return 1 # Never reached
1036 except ValueError:
1037 return 2 # Should return this
1038 finally:
1039 await asyncio.sleep(0)
1040 return 3 # Should not reach this
1041
1042 # Test 2: Raise inside try, catch in except, re-raise
1043 async def async_try_except_reraise() -> int:
1044 try:
1045 raise ValueError("test error")
1046 return 1 # Never reached
1047 except ValueError:
1048 raise # Re-raise the exception
1049 finally:
1050 await asyncio.sleep(0)
1051 return 2 # Should not reach this
1052
1053 # Test 3: Raise inside try, catch in except, raise different error
1054 async def async_try_except_raise_different() -> int:
1055 try:
1056 raise ValueError("original error")
1057 return 1 # Never reached
1058 except ValueError:
1059 raise RuntimeError("different error")
1060 finally:
1061 await asyncio.sleep(0)
1062 return 2 # Should not reach this
1063
1064 # Test 4: Another try/except block inside finally
1065 async def async_try_except_inside_finally() -> int:
1066 try:
1067 raise ValueError("outer error")
1068 return 1 # Never reached
1069 finally:
1070 await asyncio.sleep(0)
1071 try:
1072 raise RuntimeError("inner error")
1073 except RuntimeError:
1074 pass # Catch inner error
1075 return 2 # What happens after finally with inner exception handled?
1076
1077 # Test 5: Another try/finally block inside finally
1078 async def async_try_finally_inside_finally() -> int:
1079 try:
1080 raise ValueError("outer error")
1081 return 1 # Never reached
1082 finally:
1083 await asyncio.sleep(0)
1084 try:
1085 raise RuntimeError("inner error")
1086 finally:
1087 await asyncio.sleep(0)
1088 return 2 # Should not reach this
1089
1090 # Control case: No await in finally - should work correctly
1091 async def async_exception_no_await_in_finally() -> None:
1092 """Control case: This works correctly - exception propagates"""
1093 try:
1094 raise TestError("This exception will propagate!")
1095 finally:
1096 pass # No await here
1097
1098 # Test function with no exception to check normal flow
1099 async def async_no_exception_with_await_in_finally() -> int:
1100 try:
1101 return 1 # Normal return
1102 finally:
1103 await asyncio.sleep(0)
1104 return 2 # Should not reach this
1105
1106 async def test_async_try_except_finally_await() -> None:
1107 # Test 0: Simplest case - just try/finally with exception
1108 # Expected: ValueError propagates
1109 with assertRaises(ValueError):
1110 await simple_try_finally_await()
1111
1112 # Test 1: Exception caught, not re-raised
1113 # Expected: return 2 (from except block)
1114 result = await async_try_except_no_reraise()
1115 assert result == 2, f"Expected 2, got {result}"
1116
1117 # Test 2: Exception caught and re-raised
1118 # Expected: ValueError propagates
1119 with assertRaises(ValueError):
1120 await async_try_except_reraise()
1121
1122 # Test 3: Exception caught, different exception raised
1123 # Expected: RuntimeError propagates
1124 with assertRaises(RuntimeError):
1125 await async_try_except_raise_different()
1126
1127 # Test 4: Try/except inside finally
1128 # Expected: ValueError propagates (outer exception)
1129 with assertRaises(ValueError):
1130 await async_try_except_inside_finally()
1131
1132 # Test 5: Try/finally inside finally
1133 # Expected: RuntimeError propagates (inner error)
1134 with assertRaises(RuntimeError):
1135 await async_try_finally_inside_finally()
1136
1137 # Control case: No await in finally (should work correctly)
1138 with assertRaises(TestError):
1139 await async_exception_no_await_in_finally()
1140
1141 # Test normal flow (no exception)
1142 # Expected: return 1
1143 result = await async_no_exception_with_await_in_finally()
1144 assert result == 1, f"Expected 1, got {result}"
1145
1146 [file asyncio/__init__.pyi]
1147 async def sleep(t: float) -> None: ...
1148
1149 [case testAsyncContextManagerExceptionHandling]
1150 import asyncio
1151 from typing import Optional, Type
1152 from testutil import assertRaises
1153
1154 # Test 1: Basic async context manager that doesn't suppress exceptions
1155 class AsyncContextManager:
1156 async def __aenter__(self) -> 'AsyncContextManager':
1157 return self
1158
1159 async def __aexit__(self, exc_type: Optional[Type[BaseException]],
1160 exc_val: Optional[BaseException],
1161 exc_tb: object) -> None:
1162 # This await in __aexit__ is like await in finally
1163 await asyncio.sleep(0)
1164 # Don't suppress the exception (return None/False)
1165
1166 async def func_with_async_context_manager() -> str:
1167 async with AsyncContextManager():
1168 raise ValueError("Exception inside async with")
1169 return "should not reach" # Never reached
1170 return "should not reach either" # Never reached
1171
1172 async def test_basic_exception() -> str:
1173 try:
1174 await func_with_async_context_manager()
1175 return "func_a returned normally - bug!"
1176 except ValueError:
1177 return "caught ValueError - correct!"
1178 except Exception as e:
1179 return f"caught different exception: {type(e).__name__}"
1180
1181 # Test 2: Async context manager that raises a different exception in __aexit__
1182 class AsyncContextManagerRaisesInExit:
1183 async def __aenter__(self) -> 'AsyncContextManagerRaisesInExit':
1184 return self
1185
1186 async def __aexit__(self, exc_type: Optional[Type[BaseException]],
1187 exc_val: Optional[BaseException],
1188 exc_tb: object) -> None:
1189 # This await in __aexit__ is like await in finally
1190 await asyncio.sleep(0)
1191 # Raise a different exception - this should replace the original exception
1192 raise RuntimeError("Exception in __aexit__")
1193
1194 async def func_with_raising_context_manager() -> str:
1195 async with AsyncContextManagerRaisesInExit():
1196 raise ValueError("Original exception")
1197 return "should not reach" # Never reached
1198 return "should not reach either" # Never reached
1199
1200 async def test_exception_in_aexit() -> str:
1201 try:
1202 await func_with_raising_context_manager()
1203 return "func returned normally - unexpected!"
1204 except RuntimeError:
1205 return "caught RuntimeError - correct!"
1206 except ValueError:
1207 return "caught ValueError - original exception not replaced!"
1208 except Exception as e:
1209 return f"caught different exception: {type(e).__name__}"
1210
1211 async def test_async_context_manager_exception_handling() -> None:
1212 # Test 1: Basic exception propagation
1213 result = await test_basic_exception()
1214 # Expected: "caught ValueError - correct!"
1215 assert result == "caught ValueError - correct!", f"Expected exception to propagate, got: {result}"
1216
1217 # Test 2: Exception raised in __aexit__ replaces original exception
1218 result = await test_exception_in_aexit()
1219 # Expected: "caught RuntimeError - correct!"
1220 # (The RuntimeError from __aexit__ should replace the ValueError)
1221 assert result == "caught RuntimeError - correct!", f"Expected RuntimeError from __aexit__, got: {result}"
1222
1223 [file asyncio/__init__.pyi]
1224 async def sleep(t: float) -> None: ...
1225
1226 [case testCallableArgWithSameNameAsHelperMethod]
1227 import asyncio
1228 from typing import Awaitable, Callable
1229
1230
1231 MyCallable = Callable[[int, int], Awaitable[int]]
1232
1233 async def add(a: int, b: int) -> int:
1234 return a + b
1235
1236 async def await_send(send: MyCallable) -> int:
1237 return await send(1, 2)
1238
1239 async def await_throw(throw: MyCallable) -> int:
1240 return await throw(3, 4)
1241
1242 async def tests() -> None:
1243 assert await await_send(add) == 3
1244 assert await await_throw(add) == 7
1245
1246 def test_callable_arg_same_name_as_helper() -> None:
1247 asyncio.run(tests())
1248
1249 [file asyncio/__init__.pyi]
1250 def run(x: object) -> object: ...
1251
1252 [case testRunAsyncCancelFinallySpecialCase]
1253 import asyncio
1254
1255 from testutil import assertRaises
1256
1257 # Greatly simplified from asyncio.Condition
1258 class Condition:
1259 async def acquire(self) -> None: pass
1260
1261 async def wait(self) -> bool:
1262 l = asyncio.get_running_loop()
1263 fut = l.create_future()
1264 a = []
1265 try:
1266 try:
1267 a.append(fut)
1268 try:
1269 await fut
1270 return True
1271 finally:
1272 a.pop()
1273 finally:
1274 err = None
1275 while True:
1276 try:
1277 await self.acquire()
1278 break
1279 except asyncio.CancelledError as e:
1280 err = e
1281
1282 if err is not None:
1283 try:
1284 raise err
1285 finally:
1286 err = None
1287 except BaseException:
1288 raise
1289
1290 async def do_cancel() -> None:
1291 cond = Condition()
1292 wait = asyncio.create_task(cond.wait())
1293 asyncio.get_running_loop().call_soon(wait.cancel)
1294 with assertRaises(asyncio.CancelledError):
1295 await wait
1296
1297 def test_cancel_special_case() -> None:
1298 asyncio.run(do_cancel())
1299
1300 [file asyncio/__init__.pyi]
1301 from typing import Any
1302
1303 class CancelledError(Exception): ...
1304
1305 def run(x: object) -> object: ...
1306 def get_running_loop() -> Any: ...
1307 def create_task(x: object) -> Any: ...
1308
1309 [case testAsyncInheritance1]
1310 from typing import final, Coroutine, Any, TypeVar
1311
1312 import asyncio
1313
1314 from mypy_extensions import trait
1315
1316 class Base1:
1317 async def foo(self) -> int:
1318 return 1
1319
1320 class Derived1(Base1):
1321 async def foo(self) -> int:
1322 return await super().foo() + 1
1323
1324 async def base1_foo(b: Base1) -> int:
1325 return await b.foo()
1326
1327 async def derived1_foo(b: Derived1) -> int:
1328 return await b.foo()
1329
1330 def test_async_inheritance() -> None:
1331 assert asyncio.run(base1_foo(Base1())) == 1
1332 assert asyncio.run(base1_foo(Derived1())) == 2
1333 assert asyncio.run(derived1_foo(Derived1())) == 2
1334
1335 @final
1336 class FinalClass:
1337 async def foo(self) -> int:
1338 return 3
1339
1340 async def final_class_foo(b: FinalClass) -> int:
1341 return await b.foo()
1342
1343 def test_final_class() -> None:
1344 assert asyncio.run(final_class_foo(FinalClass())) == 3
1345
1346 class Base2:
1347 async def foo(self) -> int:
1348 return 4
1349
1350 async def bar(self) -> int:
1351 return 5
1352
1353 class Derived2(Base2):
1354 # Does not override "foo"
1355 async def bar(self) -> int:
1356 return 6
1357
1358 async def base2_foo(b: Base2) -> int:
1359 return await b.foo()
1360
1361 def test_no_override() -> None:
1362 assert asyncio.run(base2_foo(Base2())) == 4
1363 assert asyncio.run(base2_foo(Derived2())) == 4
1364
1365 class Base3:
1366 async def foo(self) -> int:
1367 return 7
1368
1369 class Derived3(Base3):
1370 def foo(self) -> Coroutine[Any, Any, int]:
1371 async def inner() -> int:
1372 return 8
1373 return inner()
1374
1375 async def base3_foo(b: Base3) -> int:
1376 return await b.foo()
1377
1378 def test_override_non_async() -> None:
1379 assert asyncio.run(base3_foo(Base3())) == 7
1380 assert asyncio.run(base3_foo(Derived3())) == 8
1381
1382 class Base4: pass
1383
1384 @trait
1385 class TraitBase:
1386 async def foo(self, value: int) -> int:
1387 raise NotImplementedError()
1388
1389 class DerivedFromTrait(Base4, TraitBase):
1390 async def foo(self, value: int) -> int:
1391 return value + 3
1392
1393 async def trait_foo(o: TraitBase, x: int) -> int:
1394 return await o.foo(x)
1395
1396 def test_override_trait() -> None:
1397 assert asyncio.run(trait_foo(DerivedFromTrait(), 7)) == 10
1398
1399 class Base5:
1400 def __init__(self) -> None:
1401 self._name = "test"
1402
1403 async def foo(self, x: int) -> int:
1404 assert self._name == "test"
1405 return x + 11
1406
1407 class Derived5(Base5):
1408 async def foo(self, x: int) -> int:
1409 return await super().foo(x) + 22
1410
1411 def test_call_using_super() -> None:
1412 assert asyncio.run(Derived5().foo(5)) == 38
1413
1414 [file asyncio/__init__.pyi]
1415 def run(x: object) -> object: ...
1416
1417 [case testAsyncIntrospection]
1418 import asyncio
1419 import inspect
1420 import sys
1421 import weakref
1422
1423 from functools import wraps
1424 from typing import Any, Callable, TypeVar, cast
1425
1426 def identity(val: int) -> int:
1427 return val
1428
1429 async def identity_async(val: int) -> int:
1430 return val
1431
1432 F = TypeVar("F", bound=Callable[..., Any])
1433
1434 def wrap(fn: F) -> F:
1435 if is_coroutine(fn):
1436 @wraps(fn)
1437 async def wrapper_async(*args) -> Any:
1438 return await fn(*args) + await fn(*args)
1439
1440 return cast(F, wrapper_async)
1441
1442 @wraps(fn)
1443 def wrapper(*args) -> Any:
1444 return fn(*args) + fn(*args)
1445
1446 return cast(F, wrapper)
1447
1448 @wrap
1449 def wrapped(val: int) -> int:
1450 return val
1451
1452 @wrap
1453 def wrapped2(val: int) -> int:
1454 return val * 2
1455
1456 @wrap
1457 async def wrapped_async(val: int) -> int:
1458 return val
1459
1460 @wrap
1461 async def wrapped2_async(val: int) -> int:
1462 return val * 2
1463
1464 class T:
1465 def returns_one(self) -> int:
1466 return 1
1467
1468 async def returns_one_async(self) -> int:
1469 return 1
1470
1471 @wrap
1472 def returns_two(self) -> int:
1473 return 1
1474
1475 @wrap
1476 async def returns_two_async(self) -> int:
1477 return 1
1478
1479 @staticmethod
1480 def static() -> int:
1481 return 2
1482
1483 @staticmethod
1484 async def static_async() -> int:
1485 return 2
1486
1487 @classmethod
1488 def class_method(cls) -> int:
1489 return 3
1490
1491 @classmethod
1492 async def class_method_async(cls) -> int:
1493 return 3
1494
1495 def is_coroutine(fn):
1496 if sys.version_info >= (3, 10): # type: ignore[operator]
1497 return inspect.iscoroutinefunction(fn)
1498
1499 # inspect on older python versions does not support function-like objects.
1500 # Below is a simplified implementation of iscoroutinefunction.
1501 if not hasattr(fn, "__code__"):
1502 return False
1503 CO_COROUTINE = 0x0080
1504 return bool(fn.__code__.co_flags & CO_COROUTINE)
1505
1506 def test_function() -> None:
1507 assert not is_coroutine(identity)
1508 assert is_coroutine(identity_async)
1509 assert str(identity_async).startswith("<function identity_async"), str(identity_async)
1510 assert asyncio.run(identity_async(42)) == 42
1511
1512 wr = weakref.ref(identity_async)
1513 f = wr()
1514 assert f
1515 assert asyncio.run(f(43)) == 43
1516
1517 assert getattr(identity_async, "__name__") == "identity_async", getattr(identity_async, "__name__")
1518 setattr(identity_async, "__name__", "some custom name")
1519 assert getattr(identity_async, "__name__") == "some custom name", getattr(identity_async, "__name__")
1520 assert getattr(identity_async, "__code__") != None, getattr(identity_async, "__code__")
1521 assert getattr(identity_async, "__defaults__") == None, getattr(identity_async, "__defaults__")
1522 assert getattr(identity_async, "__kwdefaults__") == None, getattr(identity_async, "__kwdefaults__")
1523 assert getattr(identity_async, "__annotations__") == None, getattr(identity_async, "__annotations__")
1524
1525 assert not is_coroutine(wrapped)
1526 assert is_coroutine(wrapped_async)
1527 assert asyncio.run(wrapped_async(22)) == 44
1528
1529 assert getattr(wrapped, "__name__") == "wrapped", getattr(wrapped, "__name__")
1530 assert getattr(wrapped2, "__name__") == "wrapped2", getattr(wrapped2, "__name__")
1531
1532 assert getattr(wrapped_async, "__name__") == "wrapped_async", getattr(wrapped_async, "__name__")
1533 assert getattr(wrapped2_async, "__name__") == "wrapped2_async", getattr(wrapped2_async, "__name__")
1534
1535 setattr(wrapped_async, "__name__", "new name")
1536 assert getattr(wrapped_async, "__name__") == "new name", getattr(wrapped_async, "__name__")
1537 assert getattr(wrapped2_async, "__name__") == "wrapped2_async", getattr(wrapped2_async, "__name__")
1538
1539 def test_method() -> None:
1540 assert not is_coroutine(T.returns_one)
1541 assert is_coroutine(T.returns_one_async)
1542 assert str(T.returns_one_async).startswith("<function T.returns_one_async"), str(T.returns_one_async)
1543
1544 t = T()
1545 # Call through variable to make sure the call is through vectorcall and not optimized to a native call.
1546 f: Any = t.returns_one_async
1547 assert asyncio.run(f()) == 1
1548
1549 assert not is_coroutine(T.returns_two)
1550 assert is_coroutine(T.returns_two_async)
1551 assert asyncio.run(t.returns_two_async()) == 2
1552
1553 assert not is_coroutine(T.static)
1554 assert is_coroutine(T.static_async)
1555 assert asyncio.run(T.static_async()) == 2
1556
1557 assert not is_coroutine(T.class_method)
1558 assert is_coroutine(T.class_method_async)
1559 assert asyncio.run(T.class_method_async()) == 3
1560
1561 def test_nested() -> None:
1562 def nested() -> int:
1563 return 1
1564
1565 async def nested_async() -> int:
1566 return 1
1567
1568 @wrap
1569 def nested_wrapped() -> int:
1570 return 2
1571
1572 @wrap
1573 async def nested_wrapped_async() -> int:
1574 return 2
1575
1576 assert not is_coroutine(nested)
1577 assert is_coroutine(nested_async)
1578 assert asyncio.run(nested_async()) == 1
1579
1580 assert getattr(nested_async, "__name__") == "nested_async", getattr(nested_async, "__name__")
1581 setattr(nested_async, "__name__", "some custom name")
1582 assert getattr(nested_async, "__name__") == "some custom name", getattr(nested_async, "__name__")
1583 assert getattr(nested_async, "__code__") != None, getattr(nested_async, "__code__")
1584 assert getattr(nested_async, "__defaults__") == None, getattr(nested_async, "__defaults__")
1585 assert getattr(nested_async, "__kwdefaults__") == None, getattr(nested_async, "__kwdefaults__")
1586 assert getattr(nested_async, "__annotations__") == None, getattr(nested_async, "__annotations__")
1587
1588 assert not is_coroutine(nested_wrapped)
1589 assert is_coroutine(nested_wrapped_async)
1590 assert asyncio.run(nested_wrapped_async()) == 4
1591
1592 [file asyncio/__init__.pyi]
1593 def run(x: object) -> object: ...
1594
1595 [case testFuture]
1596 import asyncio
1597 from typing import Any, Awaitable
1598
1599 from testutil import assertRaises
1600
1601 from m import (
1602 m_future_with_result,
1603 m_future_with_exception,
1604 m_future_with_caught_exception,
1605 m_future_with_reraised_exception
1606 )
1607
1608 async def set_result(fut: asyncio.Future, result: Any) -> None:
1609 if isinstance(result, Exception):
1610 fut.set_exception(result)
1611 else:
1612 fut.set_result(result)
1613
1614 def make_future(result: Any) -> asyncio.Future:
1615 loop = asyncio.get_running_loop()
1616 fut = loop.create_future()
1617 loop.create_task(set_result(fut, result))
1618 return fut
1619
1620 async def future_with_result(result: int) -> int:
1621 return await make_future(result)
1622
1623 async def future_with_exception(exception: Exception) -> Any:
1624 return await make_future(exception)
1625
1626 async def future_with_caught_exception(exception: Exception) -> None:
1627 try:
1628 return await make_future(exception)
1629 except type(exception):
1630 return None
1631
1632 async def future_with_reraised_exception(first_exc: Exception, second_exc: Exception) -> Any:
1633 try:
1634 return await make_future(first_exc)
1635 except type(first_exc):
1636 raise second_exc
1637
1638 def test_future() -> None:
1639 assert asyncio.run(future_with_result(42)) == 42
1640
1641 with assertRaises(ValueError, "error"):
1642 asyncio.run(future_with_exception(ValueError("error")))
1643
1644 assert asyncio.run(future_with_caught_exception(ValueError("error"))) == None
1645
1646 with assertRaises(RuntimeError, "reraised"):
1647 asyncio.run(future_with_reraised_exception(ValueError("error"), RuntimeError("reraised")))
1648
1649 class ctx_man:
1650 def __enter__(self) -> None:
1651 pass
1652
1653 def __exit__(self, *args: Any) -> None:
1654 pass
1655
1656 async def wrap(f: Awaitable) -> Any:
1657 with ctx_man():
1658 return await f
1659
1660 def test_future_with_context_manager() -> None:
1661 assert asyncio.run(wrap(future_with_result(42))) == 42
1662
1663 with assertRaises(ValueError, "error"):
1664 asyncio.run(wrap(future_with_exception(ValueError("error"))))
1665
1666 assert asyncio.run(wrap(future_with_caught_exception(ValueError("error")))) == None
1667
1668 with assertRaises(RuntimeError, "reraised"):
1669 asyncio.run(wrap(future_with_reraised_exception(ValueError("error"), RuntimeError("reraised"))))
1670
1671 def test_interpreted_future() -> None:
1672 assert asyncio.run(m_future_with_result(42)) == 42
1673
1674 with assertRaises(ValueError, "error"):
1675 asyncio.run(m_future_with_exception(ValueError("error")))
1676
1677 assert asyncio.run(m_future_with_caught_exception(ValueError("error"))) == None
1678
1679 with assertRaises(RuntimeError, "reraised"):
1680 asyncio.run(m_future_with_reraised_exception(ValueError("error"), RuntimeError("reraised")))
1681
1682 def test_interpreted_future_with_context_manager() -> None:
1683 assert asyncio.run(wrap(m_future_with_result(42))) == 42
1684
1685 with assertRaises(ValueError, "error"):
1686 asyncio.run(wrap(m_future_with_exception(ValueError("error"))))
1687
1688 assert asyncio.run(wrap(m_future_with_caught_exception(ValueError("error")))) == None
1689
1690 with assertRaises(RuntimeError, "reraised"):
1691 asyncio.run(wrap(m_future_with_reraised_exception(ValueError("error"), RuntimeError("reraised"))))
1692
1693 [file asyncio/__init__.pyi]
1694 from typing import Any, Generator
1695
1696 def run(x: object) -> object: ...
1697
1698 class Future:
1699 def set_result(self, result: object) -> None: ...
1700 def set_exception(self, exception: object) -> None: ...
1701 def __await__(self) -> Generator[Any, Any, Any]: ...
1702
1703 class Loop:
1704 def create_future(self) -> Future: ...
1705 def create_task(self, x: object) -> None: ...
1706
1707 def get_running_loop() -> Loop: ...
1708
1709 [file m.py]
1710 import asyncio
1711 from typing import Any
1712
1713 async def set_result(fut: asyncio.Future, result: Any) -> None:
1714 if isinstance(result, Exception):
1715 fut.set_exception(result)
1716 else:
1717 fut.set_result(result)
1718
1719 def make_future(result: Any) -> asyncio.Future:
1720 loop = asyncio.get_running_loop()
1721 fut = loop.create_future()
1722 loop.create_task(set_result(fut, result))
1723 return fut
1724
1725 async def m_future_with_result(result: int) -> int:
1726 return await make_future(result)
1727
1728 async def m_future_with_exception(exception: Exception) -> Any:
1729 return await make_future(exception)
1730
1731 async def m_future_with_caught_exception(exception: Exception) -> None:
1732 try:
1733 return await make_future(exception)
1734 except type(exception):
1735 return None
1736
1737 async def m_future_with_reraised_exception(first_exc: Exception, second_exc: Exception) -> Any:
1738 try:
1739 return await make_future(first_exc)
1740 except type(first_exc):
1741 raise second_exc
1742
1743 [case testCPyFunctionWithFreedInstance]
1744 import asyncio
1745
1746 from functools import wraps
1747 from typing import Any
1748
1749 class ctx_man:
1750 async def __aenter__(self) -> None:
1751 pass
1752
1753 async def __aexit__(self, *args: Any) -> None:
1754 pass
1755
1756 def with_ctx_man():
1757 def decorator(f):
1758 @wraps(f)
1759 async def inner():
1760 async with ctx_man():
1761 return await f()
1762
1763 return inner
1764
1765 return decorator
1766
1767 async def func() -> int:
1768 return 33
1769
1770 async def run_wrapped():
1771 wrapped = with_ctx_man()(func)
1772 return await wrapped()
1773
1774 def test_native():
1775 assert asyncio.run(run_wrapped()) == 33
1776
1777 [file driver.py]
1778 import asyncio
1779
1780 from native import test_native, with_ctx_man
1781
1782 async def func() -> int:
1783 return 42
1784
1785 async def run_wrapped():
1786 wrapped = with_ctx_man()(func)
1787 return await wrapped()
1788
1789 def test_interpreted():
1790 assert asyncio.run(run_wrapped()) == 42
1791
1792 # Run multiple times to test that the CPyFunction attribute is still
1793 # set correctly after reusing a freed instance of the inner callable class object.
1794 for i in range(10):
1795 test_interpreted()
1796 test_native()
1797
1798 [file asyncio/__init__.pyi]
1799 from typing import Any, Generator
1800
1801 def run(x: object) -> object: ...
1802
1803 [case testNestedCoroutineCallsAnotherNestedFunction]
1804 import asyncio
1805 import functools
1806 import inspect
1807 from typing import Any, Callable, TypeVar, cast
1808
1809 F = TypeVar("F", bound=Callable[..., Any])
1810
1811
1812 def mult_different_wrapper_names(x: int) -> Callable[[F], F]:
1813 def decorate(fn: F) -> F:
1814 def get_multiplier() -> int:
1815 return x
1816
1817 if inspect.iscoroutinefunction(fn):
1818 @functools.wraps(fn)
1819 async def wrapper_async(*args, **kwargs) -> Any:
1820 return get_multiplier() * await fn(*args, **kwargs)
1821 wrapper = wrapper_async
1822 else:
1823 @functools.wraps(fn)
1824 def wrapper_non_async(*args, **kwargs) -> Any:
1825 return get_multiplier() * fn(*args, **kwargs)
1826 wrapper = wrapper_non_async
1827
1828 return cast(F, wrapper)
1829
1830 return decorate
1831
1832 def mult_same_wrapper_names(x: int) -> Callable[[F], F]:
1833 def decorate(fn: F) -> F:
1834 def get_multiplier() -> int:
1835 return x
1836
1837 if inspect.iscoroutinefunction(fn):
1838 @functools.wraps(fn)
1839 async def wrapper(*args, **kwargs) -> Any:
1840 return get_multiplier() * await fn(*args, **kwargs)
1841 else:
1842 @functools.wraps(fn)
1843 def wrapper(*args, **kwargs) -> Any:
1844 return get_multiplier() * fn(*args, **kwargs)
1845
1846 return cast(F, wrapper)
1847
1848 return decorate
1849
1850 @mult_different_wrapper_names(3)
1851 def identity(x: int):
1852 return x
1853
1854 @mult_different_wrapper_names(5)
1855 async def async_identity(x: int):
1856 return x
1857
1858 @mult_same_wrapper_names(2)
1859 def times_two(x: int):
1860 return x * 2
1861
1862 @mult_same_wrapper_names(4)
1863 async def async_times_two(x: int):
1864 return x * 2
1865
1866 def test_nested_coroutine_calls_another_nested_function():
1867 assert identity(1) == 3
1868 assert asyncio.run(async_identity(2)) == 10
1869
1870 assert times_two(3) == 12
1871 assert asyncio.run(async_times_two(4)) == 32
1872
1873 [file asyncio/__init__.pyi]
1874 from typing import Any, Generator
1875
1876 def run(x: object) -> object: ...
1877
1878 [case testRaiseStopAsyncIteration]
1879 from async_iter import async_iter
1880 from testutil import assertRaises
1881
1882 class AsyncIter:
1883 def __init__(self, vals: list[str]) -> None:
1884 self._iter = iter(vals)
1885
1886 def __aiter__(self) -> AsyncIter:
1887 return self
1888
1889 async def __anext__(self) -> str:
1890 try:
1891 return next(self._iter)
1892 except StopIteration:
1893 raise StopAsyncIteration
1894
1895 async def test_iterator() -> None:
1896 new_list: list[int] = []
1897 async for v in async_iter([1, 2, 3]):
1898 new_list.append(v)
1899 assert new_list == [1, 2, 3]
1900
1901 new_list = []
1902 iter = async_iter([1, 2, 3])
1903 while True:
1904 try:
1905 v = await iter.__anext__()
1906 new_list.append(v)
1907 except StopAsyncIteration:
1908 new_list.append(4)
1909 break
1910 assert new_list == [1, 2, 3, 4]
1911
1912 with assertRaises(StopAsyncIteration):
1913 await async_iter([]).__anext__()
1914
1915 async def test_wrapper() -> None:
1916 new_list: list[str] = []
1917 async for v in AsyncIter(['a', 'b', 'c']):
1918 new_list.append(v)
1919 assert new_list == ['a', 'b', 'c']
1920
1921 new_list = []
1922 iter = AsyncIter(['a', 'b', 'c'])
1923 while True:
1924 try:
1925 v = await iter.__anext__()
1926 new_list.append(v)
1927 except StopAsyncIteration:
1928 new_list.append('d')
1929 break
1930 assert new_list == ['a', 'b', 'c', 'd']
1931
1932 with assertRaises(StopAsyncIteration):
1933 await AsyncIter([]).__anext__()
1934
1935 [file async_iter.py]
1936 from typing import AsyncIterator
1937
1938 async def async_iter(vals: list[int]) -> AsyncIterator[int]:
1939 for v in vals:
1940 yield v
1941
1942 [typing fixtures/typing-full.pyi]