| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
from contextlib import AbstractContextManager, contextmanager |
| 4 |
from typing import TYPE_CHECKING |
| 5 |
|
| 6 |
from .. import _core |
| 7 |
|
| 8 |
if TYPE_CHECKING: |
| 9 |
from collections.abc import Generator |
| 10 |
|
| 11 |
|
| 12 |
@contextmanager |
| 13 |
def _assert_yields_or_not(expected: bool) -> Generator[None, None, None]: |
| 14 |
"""Check if checkpoints are executed in a block of code.""" |
| 15 |
__tracebackhide__ = True |
| 16 |
task = _core.current_task() |
| 17 |
orig_cancel = task._cancel_points |
| 18 |
orig_schedule = task._schedule_points |
| 19 |
try: |
| 20 |
yield |
| 21 |
if expected and ( |
| 22 |
task._cancel_points == orig_cancel or task._schedule_points == orig_schedule |
| 23 |
): |
| 24 |
raise AssertionError("assert_checkpoints block did not yield!") |
| 25 |
finally: |
| 26 |
if not expected and ( |
| 27 |
task._cancel_points != orig_cancel or task._schedule_points != orig_schedule |
| 28 |
): |
| 29 |
raise AssertionError("assert_no_checkpoints block yielded!") |
| 30 |
|
| 31 |
|
| 32 |
def assert_checkpoints() -> AbstractContextManager[None]: |
| 33 |
"""Use as a context manager to check that the code inside the ``with`` |
| 34 |
block either exits with an exception or executes at least one |
| 35 |
:ref:`checkpoint <checkpoints>`. |
| 36 |
|
| 37 |
Raises: |
| 38 |
AssertionError: if no checkpoint was executed. |
| 39 |
|
| 40 |
Example: |
| 41 |
Check that :func:`trio.sleep` is a checkpoint, even if it doesn't |
| 42 |
block:: |
| 43 |
|
| 44 |
with trio.testing.assert_checkpoints(): |
| 45 |
await trio.sleep(0) |
| 46 |
|
| 47 |
""" |
| 48 |
__tracebackhide__ = True |
| 49 |
return _assert_yields_or_not(True) |
| 50 |
|
| 51 |
|
| 52 |
def assert_no_checkpoints() -> AbstractContextManager[None]: |
| 53 |
"""Use as a context manager to check that the code inside the ``with`` |
| 54 |
block does not execute any :ref:`checkpoints <checkpoints>`. |
| 55 |
|
| 56 |
Raises: |
| 57 |
AssertionError: if a checkpoint was executed. |
| 58 |
|
| 59 |
Example: |
| 60 |
Synchronous code never contains any checkpoints, but we can double-check |
| 61 |
that:: |
| 62 |
|
| 63 |
send_channel, receive_channel = trio.open_memory_channel(10) |
| 64 |
with trio.testing.assert_no_checkpoints(): |
| 65 |
send_channel.send_nowait(None) |
| 66 |
|
| 67 |
""" |
| 68 |
__tracebackhide__ = True |
| 69 |
return _assert_yields_or_not(False) |