Debian Codegraph @

tests/execution/test_map_async_iterator.py

raw
1 import platform
2 import sys
3 from asyncio import CancelledError, Event, ensure_future, sleep
4
5 from graphql.execution import MapAsyncIterator
6 from pytest import mark, raises
7
8 is_pypy = platform.python_implementation() == "PyPy"
9
10 try: # pragma: no cover
11 anext
12 except NameError: # pragma: no cover (Python < 3.10)
13 # noinspection PyShadowingBuiltins
14 async def anext(iterator):
15 """Return the next item from an async iterator."""
16 return await iterator.__anext__()
17
18
19 def describe_map_async_iterator():
20 @mark.asyncio
21 async def maps_over_async_generator():
22 async def source():
23 yield 1
24 yield 2
25 yield 3
26
27 doubles = MapAsyncIterator(source(), lambda x: x + x)
28
29 assert await anext(doubles) == 2
30 assert await anext(doubles) == 4
31 assert await anext(doubles) == 6
32 with raises(StopAsyncIteration):
33 assert await anext(doubles)
34
35 @mark.asyncio
36 async def maps_over_async_iterable():
37 items = [1, 2, 3]
38
39 class Iterable:
40 def __aiter__(self):
41 return self
42
43 async def __anext__(self):
44 try:
45 return items.pop(0)
46 except IndexError:
47 raise StopAsyncIteration
48
49 doubles = MapAsyncIterator(Iterable(), lambda x: x + x)
50
51 values = [value async for value in doubles]
52
53 assert not items
54 assert values == [2, 4, 6]
55
56 @mark.asyncio
57 async def compatible_with_async_for():
58 async def source():
59 yield 1
60 yield 2
61 yield 3
62
63 doubles = MapAsyncIterator(source(), lambda x: x + x)
64
65 values = [value async for value in doubles]
66
67 assert values == [2, 4, 6]
68
69 @mark.asyncio
70 async def maps_over_async_values_with_async_function():
71 async def source():
72 yield 1
73 yield 2
74 yield 3
75
76 async def double(x):
77 return x + x
78
79 doubles = MapAsyncIterator(source(), double)
80
81 values = [value async for value in doubles]
82
83 assert values == [2, 4, 6]
84
85 @mark.asyncio
86 async def allows_returning_early_from_mapped_async_generator():
87 async def source():
88 yield 1
89 yield 2
90 yield 3 # pragma: no cover
91
92 doubles = MapAsyncIterator(source(), lambda x: x + x)
93
94 assert await anext(doubles) == 2
95 assert await anext(doubles) == 4
96
97 # Early return
98 await doubles.aclose()
99
100 # Subsequent next calls
101 with raises(StopAsyncIteration):
102 await anext(doubles)
103 with raises(StopAsyncIteration):
104 await anext(doubles)
105
106 @mark.asyncio
107 async def allows_returning_early_from_mapped_async_iterable():
108 items = [1, 2, 3]
109
110 class Iterable:
111 def __aiter__(self):
112 return self
113
114 async def __anext__(self):
115 try:
116 return items.pop(0)
117 except IndexError: # pragma: no cover
118 raise StopAsyncIteration
119
120 doubles = MapAsyncIterator(Iterable(), lambda x: x + x)
121
122 assert await anext(doubles) == 2
123 assert await anext(doubles) == 4
124
125 # Early return
126 await doubles.aclose()
127
128 # Subsequent next calls
129 with raises(StopAsyncIteration):
130 await anext(doubles)
131 with raises(StopAsyncIteration):
132 await anext(doubles)
133
134 @mark.asyncio
135 async def passes_through_early_return_from_async_values():
136 async def source():
137 try:
138 yield 1
139 yield 2
140 yield 3 # pragma: no cover
141 finally:
142 yield "Done"
143 yield "Last"
144
145 doubles = MapAsyncIterator(source(), lambda x: x + x)
146
147 assert await anext(doubles) == 2
148 assert await anext(doubles) == 4
149
150 # Early return
151 await doubles.aclose()
152
153 # Subsequent next calls may yield from finally block
154 assert await anext(doubles) == "LastLast"
155 with raises(GeneratorExit):
156 assert await anext(doubles)
157
158 @mark.asyncio
159 async def allows_throwing_errors_through_async_iterable():
160 items = [1, 2, 3]
161
162 class Iterable:
163 def __aiter__(self):
164 return self
165
166 async def __anext__(self):
167 try:
168 return items.pop(0)
169 except IndexError: # pragma: no cover
170 raise StopAsyncIteration
171
172 doubles = MapAsyncIterator(Iterable(), lambda x: x + x)
173
174 assert await anext(doubles) == 2
175 assert await anext(doubles) == 4
176
177 # Throw error
178 with raises(RuntimeError, match="Ouch") as exc_info:
179 await doubles.athrow(RuntimeError("Ouch"))
180
181 assert str(exc_info.value) == "Ouch"
182
183 with raises(StopAsyncIteration):
184 await anext(doubles)
185 with raises(StopAsyncIteration):
186 await anext(doubles)
187
188 @mark.asyncio
189 async def allows_throwing_errors_with_values_through_async_iterators():
190 class Iterator:
191 def __aiter__(self):
192 return self
193
194 async def __anext__(self):
195 return 1
196
197 one = MapAsyncIterator(Iterator(), lambda x: x)
198
199 assert await anext(one) == 1
200
201 # Throw error with value passed separately
202 try:
203 raise RuntimeError("Ouch")
204 except RuntimeError as error:
205 with raises(RuntimeError, match="Ouch") as exc_info:
206 await one.athrow(error.__class__, error)
207
208 assert exc_info.value is error
209 assert exc_info.tb is error.__traceback__
210
211 with raises(StopAsyncIteration):
212 await anext(one)
213
214 @mark.asyncio
215 async def allows_throwing_errors_with_traceback_through_async_iterators():
216 class Iterator:
217 def __aiter__(self):
218 return self
219
220 async def __anext__(self):
221 return 1
222
223 one = MapAsyncIterator(Iterator(), lambda x: x)
224
225 assert await anext(one) == 1
226
227 # Throw error with traceback passed separately
228 try:
229 raise RuntimeError("Ouch")
230 except RuntimeError as error:
231 with raises(RuntimeError) as exc_info:
232 await one.athrow(error.__class__, None, error.__traceback__)
233
234 assert exc_info.tb and error.__traceback__
235 assert exc_info.tb.tb_frame is error.__traceback__.tb_frame
236
237 with raises(StopAsyncIteration):
238 await anext(one)
239
240 @mark.asyncio
241 async def passes_through_caught_errors_through_async_generators():
242 async def source():
243 try:
244 yield 1
245 yield 2
246 yield 3 # pragma: no cover
247 except Exception as e:
248 yield e
249
250 doubles = MapAsyncIterator(source(), lambda x: x + x)
251
252 assert await anext(doubles) == 2
253 assert await anext(doubles) == 4
254
255 # Throw error
256 await doubles.athrow(RuntimeError("ouch"))
257
258 with raises(StopAsyncIteration):
259 await anext(doubles)
260 with raises(StopAsyncIteration):
261 await anext(doubles)
262
263 @mark.asyncio
264 async def does_not_normally_map_over_thrown_errors():
265 async def source():
266 yield "Hello"
267 raise RuntimeError("Goodbye")
268
269 doubles = MapAsyncIterator(source(), lambda x: x + x)
270
271 assert await anext(doubles) == "HelloHello"
272
273 with raises(RuntimeError) as exc_info:
274 await anext(doubles)
275
276 assert str(exc_info.value) == "Goodbye"
277
278 @mark.asyncio
279 async def does_not_normally_map_over_externally_thrown_errors():
280 async def source():
281 yield "Hello"
282
283 doubles = MapAsyncIterator(source(), lambda x: x + x)
284
285 assert await anext(doubles) == "HelloHello"
286
287 with raises(RuntimeError) as exc_info:
288 await doubles.athrow(RuntimeError("Goodbye"))
289
290 assert str(exc_info.value) == "Goodbye"
291
292 @mark.asyncio
293 async def can_use_simple_iterator_instead_of_generator():
294 async def source():
295 yield 1
296 yield 2
297 yield 3
298
299 class Source:
300 def __init__(self):
301 self.counter = 0
302
303 def __aiter__(self):
304 return self
305
306 async def __anext__(self):
307 self.counter += 1
308 if self.counter > 3:
309 raise StopAsyncIteration
310 return self.counter
311
312 def double(x):
313 return x + x
314
315 for iterator in source, Source:
316 doubles = MapAsyncIterator(iterator(), double)
317
318 await doubles.aclose()
319
320 with raises(StopAsyncIteration):
321 await anext(doubles)
322
323 doubles = MapAsyncIterator(iterator(), double)
324
325 assert await anext(doubles) == 2
326 assert await anext(doubles) == 4
327 assert await anext(doubles) == 6
328
329 with raises(StopAsyncIteration):
330 await anext(doubles)
331
332 doubles = MapAsyncIterator(iterator(), double)
333
334 assert await anext(doubles) == 2
335 assert await anext(doubles) == 4
336
337 # Throw error
338 with raises(RuntimeError) as exc_info:
339 await doubles.athrow(RuntimeError("ouch"))
340
341 assert str(exc_info.value) == "ouch"
342
343 with raises(StopAsyncIteration):
344 await anext(doubles)
345 with raises(StopAsyncIteration):
346 await anext(doubles)
347
348 # no more exceptions should be thrown
349 if is_pypy:
350 # need to investigate why this is needed with PyPy
351 await doubles.aclose() # pragma: no cover
352 await doubles.athrow(RuntimeError("no more ouch"))
353
354 with raises(StopAsyncIteration):
355 await anext(doubles)
356
357 await doubles.aclose()
358
359 doubles = MapAsyncIterator(iterator(), double)
360
361 assert await anext(doubles) == 2
362 assert await anext(doubles) == 4
363
364 try:
365 raise ValueError("bad")
366 except ValueError:
367 tb = sys.exc_info()[2]
368
369 # Throw error
370 with raises(ValueError):
371 await doubles.athrow(ValueError, None, tb)
372
373 await sleep(0)
374
375 @mark.asyncio
376 async def stops_async_iteration_on_close():
377 async def source():
378 yield 1
379 await Event().wait() # Block forever
380 yield 2 # pragma: no cover
381 yield 3 # pragma: no cover
382
383 singles = source()
384 doubles = MapAsyncIterator(singles, lambda x: x * 2)
385
386 result = await anext(doubles)
387 assert result == 2
388
389 # Make sure it is blocked
390 doubles_future = ensure_future(anext(doubles))
391 await sleep(0.05)
392 assert not doubles_future.done()
393
394 # Unblock and watch StopAsyncIteration propagate
395 await doubles.aclose()
396 await sleep(0.05)
397 assert doubles_future.done()
398 assert isinstance(doubles_future.exception(), StopAsyncIteration)
399
400 with raises(StopAsyncIteration):
401 await anext(singles)
402
403 @mark.asyncio
404 async def can_unset_closed_state_of_async_iterator():
405 items = [1, 2, 3]
406
407 class Iterator:
408 def __init__(self):
409 self.is_closed = False
410
411 def __aiter__(self):
412 return self
413
414 async def __anext__(self):
415 if self.is_closed:
416 raise StopAsyncIteration
417 try:
418 return items.pop(0)
419 except IndexError:
420 raise StopAsyncIteration
421
422 async def aclose(self):
423 self.is_closed = True
424
425 iterator = Iterator()
426 doubles = MapAsyncIterator(iterator, lambda x: x + x)
427
428 assert await anext(doubles) == 2
429 assert await anext(doubles) == 4
430 assert not iterator.is_closed
431 await doubles.aclose()
432 assert iterator.is_closed
433 with raises(StopAsyncIteration):
434 await anext(iterator)
435 with raises(StopAsyncIteration):
436 await anext(doubles)
437 assert doubles.is_closed
438
439 iterator.is_closed = False
440 doubles.is_closed = False
441 assert not doubles.is_closed
442
443 assert await anext(doubles) == 6
444 assert not doubles.is_closed
445 assert not iterator.is_closed
446 with raises(StopAsyncIteration):
447 await anext(iterator)
448 with raises(StopAsyncIteration):
449 await anext(doubles)
450 assert not doubles.is_closed
451 assert not iterator.is_closed
452
453 @mark.asyncio
454 async def can_cancel_async_iterator_while_waiting():
455 class Iterator:
456 def __init__(self):
457 self.is_closed = False
458 self.value = 1
459
460 def __aiter__(self):
461 return self
462
463 async def __anext__(self):
464 try:
465 await sleep(0.5)
466 return self.value # pragma: no cover
467 except CancelledError:
468 self.value = -1
469 raise
470
471 async def aclose(self):
472 self.is_closed = True
473
474 iterator = Iterator()
475 doubles = MapAsyncIterator(iterator, lambda x: x + x) # pragma: no cover exit
476 cancelled = False
477
478 async def iterator_task():
479 nonlocal cancelled
480 try:
481 async for _ in doubles:
482 assert False # pragma: no cover
483 except CancelledError:
484 cancelled = True
485
486 task = ensure_future(iterator_task())
487 await sleep(0.05)
488 assert not cancelled
489 assert not doubles.is_closed
490 assert iterator.value == 1
491 assert not iterator.is_closed
492 task.cancel()
493 await sleep(0.05)
494 assert cancelled
495 assert iterator.value == -1
496 assert doubles.is_closed
497 assert iterator.is_closed