Debian Codegraph @

test-data/unit/pythoneval-asyncio.test

raw
1 -- Test cases for type checking mypy programs using full stubs and running
2 -- using CPython.
3 --
4 -- These are mostly regression tests -- no attempt is made to make these
5 -- complete.
6 --
7 -- This test file checks Asyncio and await interaction
8
9 [case testImportAsyncio]
10 import asyncio
11 print('Imported')
12 [out]
13 Imported
14
15 [case testSimpleCoroutineSleep]
16 from typing import Any, Generator
17 import asyncio
18 from asyncio import Future
19
20 async def greet_every_two_seconds() -> None:
21 n = 0
22 while n < 5:
23 print('Prev', n)
24 await asyncio.sleep(0.01)
25 print('After', n)
26 n += 1
27
28 asyncio.run(greet_every_two_seconds())
29 [out]
30 Prev 0
31 After 0
32 Prev 1
33 After 1
34 Prev 2
35 After 2
36 Prev 3
37 After 3
38 Prev 4
39 After 4
40
41 [case testCoroutineCallingOtherCoroutine]
42 from typing import Any
43 import asyncio
44 from asyncio import Future
45
46 async def compute(x: int, y: int) -> int:
47 print("Compute %s + %s ..." % (x, y))
48 await asyncio.sleep(0.01)
49 return x + y # Here the int is wrapped in Future[int]
50
51 async def print_sum(x: int, y: int) -> None:
52 result = await compute(x, y) # The type of result will be int (is extracted from Future[int]
53 print("%s + %s = %s" % (x, y, result))
54
55 asyncio.run(print_sum(1, 2))
56 [out]
57 Compute 1 + 2 ...
58 1 + 2 = 3
59
60 [case testCoroutineChangingFuture]
61 from typing import Any
62 import asyncio
63 from asyncio import Future
64
65 async def slow_operation(future: 'Future[str]') -> None:
66 await asyncio.sleep(0.01)
67 future.set_result('Future is done!')
68
69 async def main() -> None:
70 future = asyncio.Future() # type: Future[str]
71 asyncio.Task(slow_operation(future))
72 await future
73 print(future.result())
74
75 asyncio.run(main())
76 [out]
77 Future is done!
78
79 [case testFunctionAssignedAsCallback]
80 import typing
81 from typing import Any
82 import asyncio
83 from asyncio import Future, AbstractEventLoop
84
85 async def slow_operation(future: 'Future[str]') -> None:
86 await asyncio.sleep(1)
87 future.set_result('Callback works!')
88
89 def got_result(future: 'Future[str]') -> None:
90 print(future.result())
91 loop.stop()
92
93 async def main() -> None:
94 future = asyncio.Future() # type: Future[str]
95 asyncio.Task(slow_operation(future)) # Here create a task with the function. (The Task need a Future[T] as first argument)
96 future.add_done_callback(got_result) # and assign the callback to the future
97
98 loop = asyncio.new_event_loop() # type: AbstractEventLoop
99 loop.run_until_complete(main())
100 try:
101 loop.run_forever()
102 finally:
103 loop.close()
104 [out]
105 Callback works!
106
107 [case testMultipleTasks]
108 import typing
109 from typing import Any
110 import asyncio
111 from asyncio import Task, Future
112 async def factorial(name, number) -> None:
113 f = 1
114 for i in range(2, number+1):
115 print("Task %s: Compute factorial(%s)..." % (name, i))
116 await asyncio.sleep(0.01)
117 f *= i
118 print("Task %s: factorial(%s) = %s" % (name, number, f))
119
120 async def main() -> None:
121 tasks = [
122 asyncio.Task(factorial("A", 2)),
123 asyncio.Task(factorial("B", 3)),
124 asyncio.Task(factorial("C", 4))]
125 await asyncio.wait(tasks)
126
127 asyncio.run(main())
128 [out]
129 Task A: Compute factorial(2)...
130 Task B: Compute factorial(2)...
131 Task C: Compute factorial(2)...
132 Task A: factorial(2) = 2
133 Task B: Compute factorial(3)...
134 Task C: Compute factorial(3)...
135 Task B: factorial(3) = 6
136 Task C: Compute factorial(4)...
137 Task C: factorial(4) = 24
138
139
140 [case testConcatenatedCoroutines]
141 import typing
142 from typing import Any
143 import asyncio
144 from asyncio import Future
145
146 future: Future[int]
147
148 async def h4() -> int:
149 x = await future
150 return x
151
152 async def h3() -> int:
153 x = await h4()
154 print("h3: %s" % x)
155 return x
156
157 async def h2() -> int:
158 x = await h3()
159 print("h2: %s" % x)
160 return x
161
162 async def h() -> None:
163 x = await h2()
164 print("h: %s" % x)
165
166 async def main() -> None:
167 global future
168 future = asyncio.Future()
169 future.set_result(42)
170 await h()
171 print("Outside %s" % future.result())
172
173 asyncio.run(main())
174 [out]
175 h3: 42
176 h2: 42
177 h: 42
178 Outside 42
179
180 [case testConcatenatedCoroutinesReturningFutures]
181 import typing
182 from typing import Any
183 import asyncio
184 from asyncio import Future
185
186 async def h4() -> "Future[int]":
187 await asyncio.sleep(0.01)
188 f = asyncio.Future() # type: Future[int]
189 return f
190
191 async def h3() -> "Future[Future[int]]":
192 x = await h4()
193 x.set_result(42)
194 f = asyncio.Future() # type: Future[Future[int]]
195 f.set_result(x)
196 return f
197
198 async def h() -> None:
199 print("Before")
200 x = await h3()
201 y = await x
202 z = await y
203 print(z)
204 def normalize(future):
205 # The str conversion seems inconsistent; not sure exactly why. Normalize
206 # the result.
207 return str(future).replace('<Future finished ', 'Future<')
208 print(normalize(y))
209 print(normalize(x))
210
211 asyncio.run(h())
212 [out]
213 Before
214 42
215 Future<result=42>
216 Future<result=Future<result=42>>
217
218
219 [case testCoroutineWithOwnClass]
220 import typing
221 from typing import Any
222 import asyncio
223 from asyncio import Future
224
225 future: Future["A"]
226
227 class A:
228 def __init__(self, x: int) -> None:
229 self.x = x
230
231 async def h() -> None:
232 x = await future
233 print("h: %s" % x.x)
234
235 async def main() -> None:
236 global future
237 future = asyncio.Future()
238 future.set_result(A(42))
239 await h()
240 print("Outside %s" % future.result().x)
241
242 asyncio.run(main())
243 [out]
244 h: 42
245 Outside 42
246
247
248 -- Errors
249
250 [case testErrorAssigningCoroutineThatDontReturn]
251 from typing import Any
252 import asyncio
253 from asyncio import Future
254
255 async def greet() -> None:
256 await asyncio.sleep(0.2)
257 print('Hello World')
258
259 async def test() -> None:
260 await greet()
261 x = await greet() # Error
262
263 asyncio.run(test())
264 [out]
265 _program.py:11: error: Function does not return a value (it only ever returns None)
266
267 [case testErrorReturnIsNotTheSameType]
268 from typing import Any
269 import asyncio
270 from asyncio import Future
271
272 async def compute(x: int, y: int) -> int:
273 print("Compute %s + %s ..." % (x, y))
274 await asyncio.sleep(0.01)
275 return str(x + y) # Error
276
277 async def print_sum(x: int, y: int) -> None:
278 result = await compute(x, y)
279 print("%s + %s = %s" % (x, y, result))
280
281 asyncio.run(print_sum(1, 2))
282 [out]
283 _program.py:8: error: Incompatible return value type (got "str", expected "int")
284
285 [case testErrorSetFutureDifferentInternalType]
286 from typing import Any
287 import asyncio
288 from asyncio import Future
289
290 async def slow_operation(future: 'Future[str]') -> None:
291 await asyncio.sleep(1)
292 future.set_result(42) # Error
293
294 async def main() -> None:
295 future = asyncio.Future() # type: Future[str]
296 asyncio.Task(slow_operation(future))
297 await future
298 print(future.result())
299
300 asyncio.run(main())
301 [out]
302 _program.py:7: error: Argument 1 to "set_result" of "Future" has incompatible type "int"; expected "str"
303
304
305 [case testErrorUsingDifferentFutureType]
306 from typing import Any
307 import asyncio
308 from asyncio import Future
309
310 async def slow_operation(future: 'Future[int]') -> None:
311 await asyncio.sleep(1)
312 future.set_result(42)
313
314 async def main() -> None:
315 future = asyncio.Future() # type: Future[str]
316 asyncio.Task(slow_operation(future)) # Error
317 await future
318 print(future.result())
319
320 asyncio.run(main())
321 [out]
322 _program.py:11: error: Argument 1 to "slow_operation" has incompatible type "Future[str]"; expected "Future[int]"
323
324 [case testErrorUsingDifferentFutureTypeAndSetFutureDifferentInternalType]
325 from typing import Any
326 import asyncio
327 from asyncio import Future
328
329 async def slow_operation(future: 'Future[int]') -> None:
330 await asyncio.sleep(1)
331 future.set_result('42') # Try to set an str as result to a Future[int]
332
333 async def main() -> None:
334 future = asyncio.Future() # type: Future[str]
335 asyncio.Task(slow_operation(future)) # Error
336 await future
337 print(future.result())
338
339 asyncio.run(main())
340 [out]
341 _program.py:7: error: Argument 1 to "set_result" of "Future" has incompatible type "str"; expected "int"
342 _program.py:11: error: Argument 1 to "slow_operation" has incompatible type "Future[str]"; expected "Future[int]"
343
344 [case testErrorSettingCallbackWithDifferentFutureType]
345 import typing
346 from typing import Any
347 import asyncio
348 from asyncio import Future, AbstractEventLoop
349
350 async def slow_operation(future: 'Future[str]') -> None:
351 await asyncio.sleep(1)
352 future.set_result('Future is done!')
353
354 def got_result(future: 'Future[int]') -> None:
355 print(future.result())
356 loop.stop()
357
358 async def main() -> None:
359 future = asyncio.Future() # type: Future[str]
360 asyncio.Task(slow_operation(future))
361 future.add_done_callback(got_result) # Error
362
363 loop = asyncio.new_event_loop()
364 loop.run_until_complete(main())
365 try:
366 loop.run_forever()
367 finally:
368 loop.close()
369 [out]
370 _program.py:17: error: Argument 1 to "add_done_callback" of "Future" has incompatible type "Callable[[Future[int]], None]"; expected "Callable[[Future[str]], object]"
371
372 [case testErrorOneMoreFutureInReturnType]
373 import typing
374 from typing import Any, Generator
375 import asyncio
376 from asyncio import Future
377
378 async def h4() -> Future[int]:
379 await asyncio.sleep(1)
380 f = asyncio.Future() # type: Future[int]
381 return f
382
383 async def h3() -> Future[Future[Future[int]]]:
384 x = await h4()
385 x.set_result(42)
386 f = asyncio.Future() # type: Future[Future[int]]
387 f.set_result(x)
388 return f
389
390 async def h() -> None:
391 print("Before")
392 x = await h3()
393 y = await x
394 z = await y
395 print(z)
396 print(y)
397 print(x)
398
399 asyncio.run(h())
400 [out]
401 _program.py:16: error: Incompatible return value type (got "Future[Future[int]]", expected "Future[Future[Future[int]]]")
402
403 [case testErrorOneLessFutureInReturnType]
404 import typing
405 from typing import Any
406 import asyncio
407 from asyncio import Future
408
409 async def h4() -> Future[int]:
410 await asyncio.sleep(1)
411 f = asyncio.Future() # type: Future[int]
412 return f
413
414 async def h3() -> Future[int]:
415 x = await h4()
416 x.set_result(42)
417 f = asyncio.Future() # type: Future[Future[int]]
418 f.set_result(x)
419 return f
420
421 async def h() -> None:
422 print("Before")
423 x = await h3()
424 y = await x
425 print(y)
426 print(x)
427
428 asyncio.run(h())
429 [out]
430 _program.py:16: error: Incompatible return value type (got "Future[Future[int]]", expected "Future[int]")
431 _program.py:16: note: Maybe you forgot to use "await"?
432
433 [case testErrorAssignmentDifferentType]
434 import typing
435 from typing import Any
436 import asyncio
437 from asyncio import Future
438
439 future: Future["A"]
440
441 class A:
442 def __init__(self, x: int) -> None:
443 self.x = x
444
445 class B:
446 def __init__(self, x: int) -> None:
447 self.x = x
448
449 async def h() -> None:
450 x = await future # type: B # Error
451 print("h: %s" % x.x)
452
453 async def main() -> None:
454 global future
455 future = asyncio.Future()
456 future.set_result(A(42))
457 await h()
458
459 asyncio.run(main())
460 [out]
461 _program.py:17: error: Incompatible types in assignment (expression has type "A", variable has type "B")
462
463 [case testForwardRefToBadAsyncShouldNotCrash_newsemanal]
464 from typing import TypeVar
465 import asyncio
466
467 T = TypeVar('T')
468 P = whatever # type: ignore
469
470 def test() -> None:
471 reveal_type(bad)
472 bad(0)
473
474 async def bad(arg: P) -> T:
475 pass
476 [out]
477 _program.py:8: note: Revealed type is "def [T] (arg: P?) -> typing.Coroutine[Any, Any, T]"
478 _program.py:9: error: Value of type "Coroutine[Any, Any, Never]" must be used
479 _program.py:9: note: Are you missing an await?
480 _program.py:11: error: Variable "_testForwardRefToBadAsyncShouldNotCrash_newsemanal.P" is not valid as a type
481 _program.py:11: note: See https://mypy.readthedocs.io/en/stable/common_issues.html#variables-vs-type-aliases