| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from typing import TYPE_CHECKING |
| 4 |
|
| 5 |
import trio |
| 6 |
|
| 7 |
if TYPE_CHECKING: |
| 8 |
from collections.abc import AsyncGenerator |
| 9 |
|
| 10 |
|
| 11 |
async def coro1(event: trio.Event) -> None: |
| 12 |
event.set() |
| 13 |
await trio.sleep_forever() |
| 14 |
|
| 15 |
|
| 16 |
async def coro2(event: trio.Event) -> None: |
| 17 |
await coro1(event) |
| 18 |
|
| 19 |
|
| 20 |
async def coro3(event: trio.Event) -> None: |
| 21 |
await coro2(event) |
| 22 |
|
| 23 |
|
| 24 |
async def coro2_async_gen(event: trio.Event) -> AsyncGenerator[None, None]: |
| 25 |
# mypy does not like `yield await trio.lowlevel.checkpoint()` - but that |
| 26 |
# should be equivalent to splitting the statement |
| 27 |
await trio.lowlevel.checkpoint() |
| 28 |
yield |
| 29 |
await coro1(event) |
| 30 |
yield # pragma: no cover |
| 31 |
await trio.lowlevel.checkpoint() # pragma: no cover |
| 32 |
yield # pragma: no cover |
| 33 |
|
| 34 |
|
| 35 |
async def coro3_async_gen(event: trio.Event) -> None: |
| 36 |
async for _ in coro2_async_gen(event): |
| 37 |
pass |
| 38 |
|
| 39 |
|
| 40 |
async def test_task_iter_await_frames() -> None: |
| 41 |
async with trio.open_nursery() as nursery: |
| 42 |
event = trio.Event() |
| 43 |
nursery.start_soon(coro3, event) |
| 44 |
await event.wait() |
| 45 |
|
| 46 |
(task,) = nursery.child_tasks |
| 47 |
|
| 48 |
assert [frame.f_code.co_name for frame, _ in task.iter_await_frames()][:3] == [ |
| 49 |
"coro3", |
| 50 |
"coro2", |
| 51 |
"coro1", |
| 52 |
] |
| 53 |
|
| 54 |
nursery.cancel_scope.cancel() |
| 55 |
|
| 56 |
|
| 57 |
async def test_task_iter_await_frames_async_gen() -> None: |
| 58 |
async with trio.open_nursery() as nursery: |
| 59 |
event = trio.Event() |
| 60 |
nursery.start_soon(coro3_async_gen, event) |
| 61 |
await event.wait() |
| 62 |
|
| 63 |
(task,) = nursery.child_tasks |
| 64 |
|
| 65 |
assert [frame.f_code.co_name for frame, _ in task.iter_await_frames()][:3] == [ |
| 66 |
"coro3_async_gen", |
| 67 |
"coro2_async_gen", |
| 68 |
"coro1", |
| 69 |
] |
| 70 |
|
| 71 |
nursery.cancel_scope.cancel() |
| 72 |
|
| 73 |
|
| 74 |
async def test_closed_task_iter_await_frames() -> None: |
| 75 |
async with trio.open_nursery() as nursery: |
| 76 |
task = object() |
| 77 |
|
| 78 |
async def capture_task() -> None: |
| 79 |
nonlocal task |
| 80 |
task = trio.lowlevel.current_task() |
| 81 |
await trio.lowlevel.checkpoint() |
| 82 |
|
| 83 |
nursery.start_soon(capture_task) |
| 84 |
|
| 85 |
# Task has completed, so coro.cr_frame should be None, thus no frames |
| 86 |
assert isinstance(task, trio.lowlevel.Task) # Ran `capture_task` |
| 87 |
assert task.coro.cr_frame is None # and the task was over, but |
| 88 |
assert list(task.iter_await_frames()) == [] # look, no crash! |