|
1 | 1 | import sys
|
2 |
| -from asyncio import Event, ensure_future, CancelledError, sleep, Queue |
| 2 | +from asyncio import CancelledError, Event, ensure_future, sleep |
3 | 3 |
|
4 | 4 | from pytest import mark, raises
|
5 | 5 |
|
@@ -459,39 +459,47 @@ async def aclose(self):
|
459 | 459 | assert not iterator.is_closed
|
460 | 460 |
|
461 | 461 | @mark.asyncio
|
462 |
| - async def cancel_async_iterator_while_waiting(): |
| 462 | + async def can_cancel_async_iterator_while_waiting(): |
463 | 463 | class Iterator:
|
464 | 464 | def __init__(self):
|
465 |
| - self.queue: Queue[int] = Queue() |
466 |
| - self.queue.put_nowait(1) # suppress coverage warning |
467 |
| - self.cancelled = False |
| 465 | + self.is_closed = False |
| 466 | + self.value = 1 |
468 | 467 |
|
469 | 468 | def __aiter__(self):
|
470 | 469 | return self
|
471 | 470 |
|
472 | 471 | async def __anext__(self):
|
473 | 472 | try:
|
474 |
| - return await self.queue.get() |
475 |
| - except BaseException: |
476 |
| - self.cancelled = True |
| 473 | + await sleep(0.5) |
| 474 | + return self.value # pragma: no cover |
| 475 | + except CancelledError: |
| 476 | + self.value = -1 |
| 477 | + raise |
| 478 | + |
| 479 | + async def aclose(self): |
| 480 | + self.is_closed = True |
477 | 481 |
|
478 | 482 | iterator = Iterator()
|
479 |
| - doubles = MapAsyncIterator(iterator, lambda x: x + x) |
| 483 | + doubles = MapAsyncIterator(iterator, lambda x: x + x) # pragma: no cover exit |
| 484 | + cancelled = False |
480 | 485 |
|
481 | 486 | async def iterator_task():
|
| 487 | + nonlocal cancelled |
482 | 488 | try:
|
483 |
| - async for double in doubles: |
484 |
| - pass |
485 |
| - # If cancellation is handled using StopAsyncIteration, it will reach |
486 |
| - # here. |
487 |
| - except CancelledError: # pragma: no cover |
488 |
| - # Otherwise it should reach here |
489 |
| - pass |
| 489 | + async for _ in doubles: |
| 490 | + assert False # pragma: no cover |
| 491 | + except CancelledError: |
| 492 | + cancelled = True |
490 | 493 |
|
491 | 494 | task = ensure_future(iterator_task())
|
492 |
| - await sleep(0.1) |
493 |
| - await doubles.aclose() |
| 495 | + await sleep(0.05) |
| 496 | + assert not cancelled |
| 497 | + assert not doubles.is_closed |
| 498 | + assert iterator.value == 1 |
| 499 | + assert not iterator.is_closed |
494 | 500 | task.cancel()
|
495 |
| - await sleep(0.1) |
496 |
| - assert iterator.cancelled |
| 501 | + await sleep(0.05) |
| 502 | + assert cancelled |
| 503 | + assert iterator.value == -1 |
497 | 504 | assert doubles.is_closed
|
| 505 | + assert iterator.is_closed |
0 commit comments