|
15 | 15 |
|
16 | 16 | import pytest |
17 | 17 | from pytest import FixtureRequest, MonkeyPatch |
| 18 | +from pytest_mock import MockerFixture |
18 | 19 |
|
19 | 20 | import anyio |
20 | 21 | from anyio import ( |
@@ -360,6 +361,41 @@ async def middle_task() -> None: |
360 | 361 | assert len(outer_cancel_spy.call_args_list) < 10 |
361 | 362 |
|
362 | 363 |
|
| 364 | +@pytest.mark.parametrize("anyio_backend", asyncio_params) |
| 365 | +async def test_no_spin_on_done_task_in_cancel_scope(mocker: MockerFixture) -> None: |
| 366 | + """Regression test for #1111. |
| 367 | +
|
| 368 | + When a task group is entered but never exited (e.g. it is abandoned because |
| 369 | + the task owning it finishes without unwinding it), its cancel scope is left |
| 370 | + with the now-finished host task still in its set of contained tasks. |
| 371 | + Cancelling such a scope used to make ``_deliver_cancellation`` treat that |
| 372 | + finished task as still cancellable and reschedule itself via ``call_soon`` |
| 373 | + forever, pinning the event loop at 100% CPU. |
| 374 | + """ |
| 375 | + from anyio._backends import _asyncio |
| 376 | + |
| 377 | + # To allow the mocker to override a @final class |
| 378 | + class EditableCancelScope(_asyncio.CancelScope): |
| 379 | + pass |
| 380 | + |
| 381 | + async def owner() -> EditableCancelScope: |
| 382 | + return cast(EditableCancelScope, EditableCancelScope().__enter__()) |
| 383 | + |
| 384 | + scope = await asyncio.create_task(owner()) |
| 385 | + spy = mocker.spy(scope, "_deliver_cancellation") |
| 386 | + scope.cancel() |
| 387 | + |
| 388 | + # Give any rescheduled _deliver_cancellation callbacks the chance to fire. |
| 389 | + # With the bug present this reschedules forever (the test timeout would |
| 390 | + # trip); the fix leaves no pending cancellation callback since the only |
| 391 | + # remaining task is done. |
| 392 | + for _ in range(5): |
| 393 | + await checkpoint() |
| 394 | + |
| 395 | + assert scope._cancel_handle is None |
| 396 | + spy.assert_called_once() |
| 397 | + |
| 398 | + |
363 | 399 | @pytest.mark.parametrize("return_handle", [False, True]) |
364 | 400 | async def test_start_exception_delivery(return_handle: bool) -> None: |
365 | 401 | def task_fn(*, task_status: TaskStatus[str] = TASK_STATUS_IGNORED) -> None: |
|
0 commit comments