diff --git a/README.rst b/README.rst index 79f65ae28e..c180b8ccd3 100644 --- a/README.rst +++ b/README.rst @@ -142,7 +142,7 @@ Apache 2. See `LICENSE - @_testing for stuff that needs tighter integration? kinda weird that wait_all_tasks_blocked is in hazmat right now - and assert_yields stuff might make more sense in core + and assert_checkpoints stuff might make more sense in core - make @trio_test accept clock_rate=, clock_autojump_threshold= arguments diff --git a/docs/source/history.rst b/docs/source/history.rst index 56d7e605f4..77d8b95056 100644 --- a/docs/source/history.rst +++ b/docs/source/history.rst @@ -8,10 +8,139 @@ Release history Trio 0.2.0 (coming soon) ------------------------ +[this has notes up to 3613ca6df] + +Highlights +~~~~~~~~~~ + +Async I/O for files and filesystem operations: :func:`trio.open_file`, +:func:`trio.Path` + +Complete support for TLS over arbitrary transports, including +STARTTLS, renegotiation during full-duplex usage, and `TLS-over-TLS +`__: +:func:`trio.open_ssl_over_tcp_stream`, +:func:`trio.serve_ssl_over_tcp`, +:func:`trio.open_ssl_over_tcp_listeners`, and :mod:`trio.ssl` + +``nursery.start`` (and rename ``spawn`` to ``start_soon``) + +High-level networking interface + +testing helpers + +Happy eyeballs + +Task- and run-local storage (gh-2) + + +ParkingLot is rewritten to be simpler and faster (gh-272, gh-287) + +trio.socket no longer overrides socket options + +breaking: getprotobyname is now async +getservbyport, getservbyname, getfqdn removed (they're buggy and obsolete) + +controlled way to override hostname resolution and socket behavior in +tests (gh-170) + +using yapf now + +capacity limitation for threads (gh-10, gh-57, gh-156) + +Reliably detect when someone tries to use an incompatible flavor of +async library (e.g. asyncio or curio) and give a helpful error message + +IDNA 2008 support in trio.socket (gh-11) + +rename yield point to checkpoint + +fix minor face condition in IOCP thread shutdown (gh-81) + +switch to using set_wakeup_fd to detect control-C on Windows (gh-42) + +lots of doc improvements + +restrict_keyboard_interrupt_to_checkpoints + +``tiebreaker=`` argument to +:func:`trio.testing.wait_all_tasks_blocked` + +:class:`StrictFIFOLock` + +sendall no longer has partial result notification – this could be +misleading with stream wrappers like :class:`~trio.ssl.SSLStream` + +:class:`ResourceBusyError` + +:meth:`MultiError.catch` now correctly preserves ``__context__``, +despite Python's bets attempts to stop us. (gh-165) + +nursery.child_tasks, nursery.parent_task, task.child_nurseries, +task.parent_nursery + +Fix ``sock.accept()`` for IPv6 sockets (https://github.com/python-trio/trio/issues/164) + + +* ``trio.socket.SocketType`` will no longer be exposed publically in + 0.3.0. Since it had no public constructor, the only thing you could + do with it was ``isinstance(obj, SocketType)``. Instead, use + :func:`trio.socket.is_trio_socket`. (https://github.com/python-trio/trio/issues/170) + +* The following classes and functions have moved from :mod:`trio` to + :mod:`trio.hazmat`: + + - :class:`~trio.hazmat.Task` + - :class:`~trio.hazmat.UnboundedQueue` + - :class:`~trio.hazmat.Result` + - :class:`~trio.hazmat.Error` + - :class:`~trio.hazmat.Value` + - :func:`~trio.hazmat.current_task` + +deprecate most of the task and nursery APIs + +Renames from https://github.com/python-trio/trio/issues/157 + +Note that pypy needs 5.9+ to support deprecations properly + +Breaking changes and deprecations +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Trio is a young project; link to issue #1 + +Breaking changes: + + It turns out + +Upcoming breaking changes without warnings (i.e., stuff that in 0.2.0 +will work, but won't work in 0.3.0): + +* In the next release, the ``bind`` method on Trio socket objects will + become async (XX). Unfortunately, there's no good way to warn about + this. If you switch to the new highlevel networking APIs then + then they'll insulate you from this change. + +Upcoming breaking changes with warnings (i.e., stuff that in 0.2.0 +will work but complain loudly, and won't work in 0.3.0): + +* + +``sendall`` + +``run_in_worker_thread`` → ``run_sync_in_worker_thread`` +``nursery.spawn`` → ``nursery.start_soon`` + +deprecated big chunks of nursery and Task API + + +Features +~~~~~~~~ + * New argument to :func:`trio.run`: ``restrict_keyboard_interrupt_to_checkpoints``. + Trio 0.1.0 (2017-03-10) ----------------------- diff --git a/docs/source/reference-core.rst b/docs/source/reference-core.rst index 687b2d37c5..56ea434743 100644 --- a/docs/source/reference-core.rst +++ b/docs/source/reference-core.rst @@ -176,7 +176,7 @@ If you do want to be careful, or if you have some CPU-bound code that doesn't have enough checkpoints in it, then it's useful to know that ``await trio.sleep(0)`` is an idiomatic way to execute a checkpoint without doing anything else, and that -:func:`trio.testing.assert_yields` can be used to test that an +:func:`trio.testing.assert_checkpoints` can be used to test that an arbitrary block of code contains a checkpoint. diff --git a/docs/source/reference-hazmat.rst b/docs/source/reference-hazmat.rst index 150ed83559..565e2eacd9 100644 --- a/docs/source/reference-hazmat.rst +++ b/docs/source/reference-hazmat.rst @@ -336,19 +336,19 @@ Wait queue abstraction Low-level checkpoint functions ------------------------------ -.. autofunction:: yield_briefly +.. autofunction:: checkpoint The next two functions are used *together* to make up a checkpoint: -.. autofunction:: yield_if_cancelled -.. autofunction:: yield_briefly_no_cancel +.. autofunction:: checkpoint_if_cancelled +.. autofunction:: cancel_shielded_checkpoint These are commonly used in cases where you have an operation that might-or-might-not block, and you want to implement trio's standard checkpoint semantics. Example:: async def operation_that_maybe_blocks(): - await yield_if_cancelled() + await checkpoint_if_cancelled() try: ret = attempt_operation() except BlockingIOError: @@ -356,11 +356,11 @@ checkpoint semantics. Example:: pass except: # some other error, finish the checkpoint then let it propagate - await yield_briefly_no_cancel() + await cancel_shielded_checkpoint() raise else: # operation succeeded, finish the checkpoint then return - await yield_briefly_no_cancel() + await cancel_shielded_checkpoint() return ret while True: await wait_for_operation_to_be_ready() @@ -376,7 +376,7 @@ This logic is a bit convoluted, but accomplishes all of the following: * Our :ref:`cancellation semantics ` say that :exc:`~trio.Cancelled` should only be raised if the operation didn't - happen. Using :func:`yield_briefly_no_cancel` on the early-exit + happen. Using :func:`cancel_shielded_checkpoint` on the early-exit branches accomplishes this. * On the path where we do end up blocking, we don't pass through any @@ -387,29 +387,30 @@ This logic is a bit convoluted, but accomplishes all of the following: ``wait_for_operation_to_be_ready``, by keeping the ``while True:`` loop outside of the ``except BlockingIOError:`` block. -These functions can also be useful in other situations, e.g. if you're -going to call an uncancellable operation like -:func:`trio.run_sync_in_worker_thread` or (potentially) overlapped I/O -operations on Windows, then you can call :func:`yield_if_cancelled` -first to make sure that the whole thing is a checkpoint. +These functions can also be useful in other situations. For example, +when :func:`trio.run_sync_in_worker_thread` schedules some work to run +in a worker thread, it blocks until the work is finished (so it's a +schedule point), but by default it doesn't allow cancellation. So to +make sure that the call always acts as a checkpoint, it calls +:func:`checkpoint_if_cancelled` before starting the thread. Low-level blocking ------------------ -.. autofunction:: yield_indefinitely +.. autofunction:: wait_task_rescheduled .. autoclass:: Abort .. autofunction:: reschedule Here's an example lock class implemented using -:func:`yield_indefinitely` directly. This implementation has a number -of flaws, including lack of fairness, O(n) cancellation, missing error -checking, failure to insert a checkpoint on the non-blocking path, -etc. If you really want to implement your own lock, then you should -study the implementation of :class:`trio.Lock` and use +:func:`wait_task_rescheduled` directly. This implementation has a +number of flaws, including lack of fairness, O(n) cancellation, +missing error checking, failure to insert a checkpoint on the +non-blocking path, etc. If you really want to implement your own lock, +then you should study the implementation of :class:`trio.Lock` and use :class:`ParkingLot`, which handles some of these issues for you. But this does serve to illustrate the basic structure of the -:func:`yield_indefinitely` API:: +:func:`wait_task_rescheduled` API:: class NotVeryGoodLock: def __init__(self): @@ -423,7 +424,7 @@ this does serve to illustrate the basic structure of the def abort_fn(_): self._blocked_tasks.remove(task) return trio.hazmat.Abort.SUCCEEDED - await trio.hazmat.yield_indefinitely(abort_fn) + await trio.hazmat.wait_task_rescheduled(abort_fn) self._held = True def release(self): diff --git a/docs/source/reference-testing.rst b/docs/source/reference-testing.rst index 716dc698bc..2df8f808fd 100644 --- a/docs/source/reference-testing.rst +++ b/docs/source/reference-testing.rst @@ -206,8 +206,5 @@ intended for testing. Testing checkpoints -------------------- -.. autofunction:: assert_yields - :with: - -.. autofunction:: assert_no_yields +.. autofunction:: assert_checkpoints :with: diff --git a/notes-to-self/schedule-timing.py b/notes-to-self/schedule-timing.py index 25ca702806..9e74477acf 100644 --- a/notes-to-self/schedule-timing.py +++ b/notes-to-self/schedule-timing.py @@ -10,7 +10,7 @@ async def reschedule_loop(depth): while RUNNING: LOOPS += 1 await trio.sleep(0) - #await trio.hazmat.yield_briefly_no_cancel() + #await trio.hazmat.cancel_shielded_checkpoint() else: await reschedule_loop(depth - 1) diff --git a/trio/__init__.py b/trio/__init__.py index 96cab098ee..c82ca81e0e 100644 --- a/trio/__init__.py +++ b/trio/__init__.py @@ -102,6 +102,25 @@ ), } +_deprecate.enable_attribute_deprecations(hazmat.__name__) + +hazmat.__deprecated_attributes__ = { + "yield_briefly": + _deprecate.DeprecatedAttribute(hazmat.checkpoint, "0.2.0", issue=157), + "yield_briefly_no_cancel": + _deprecate.DeprecatedAttribute( + hazmat.cancel_shielded_checkpoint, "0.2.0", issue=157 + ), + "yield_if_cancelled": + _deprecate.DeprecatedAttribute( + hazmat.checkpoint_if_cancelled, "0.2.0", issue=157 + ), + "yield_indefinitely": + _deprecate.DeprecatedAttribute( + hazmat.wait_task_rescheduled, "0.2.0", issue=157 + ), +} + # Having the public path in .__module__ attributes is important for: # - exception names in printed tracebacks # - sphinx :show-inheritance: diff --git a/trio/_core/_io_epoll.py b/trio/_core/_io_epoll.py index 02b1627609..bb720d0029 100644 --- a/trio/_core/_io_epoll.py +++ b/trio/_core/_io_epoll.py @@ -101,7 +101,7 @@ async def _epoll_wait(self, fd, attr_name): self._registered[fd] = EpollWaiters() waiters = self._registered[fd] if getattr(waiters, attr_name) is not None: - await _core.yield_briefly() + await _core.checkpoint() raise _core.ResourceBusyError( "another task is already reading / writing this fd" ) @@ -113,7 +113,7 @@ def abort(_): self._update_registrations(fd, True) return _core.Abort.SUCCEEDED - await _core.yield_indefinitely(abort) + await _core.wait_task_rescheduled(abort) @_public @_hazmat diff --git a/trio/_core/_io_kqueue.py b/trio/_core/_io_kqueue.py index 4e626235ea..9715b76d3d 100644 --- a/trio/_core/_io_kqueue.py +++ b/trio/_core/_io_kqueue.py @@ -98,7 +98,7 @@ def monitor_kevent(self, ident, filter): async def wait_kevent(self, ident, filter, abort_func): key = (ident, filter) if key in self._registered: - await _core.yield_briefly() + await _core.checkpoint() raise _core.ResourceBusyError( "attempt to register multiple listeners for same " "ident/filter pair" @@ -111,7 +111,7 @@ def abort(raise_cancel): del self._registered[key] return r - return await _core.yield_indefinitely(abort) + return await _core.wait_task_rescheduled(abort) async def _wait_common(self, fd, filter): if not isinstance(fd, int): diff --git a/trio/_core/_io_windows.py b/trio/_core/_io_windows.py index b882f2f578..cc214ae399 100644 --- a/trio/_core/_io_windows.py +++ b/trio/_core/_io_windows.py @@ -328,7 +328,7 @@ def abort(raise_cancel_): _check(kernel32.CancelIoEx(handle, lpOverlapped)) return _core.Abort.FAILED - await _core.yield_indefinitely(abort) + await _core.wait_task_rescheduled(abort) if lpOverlapped.Internal != 0: if lpOverlapped.Internal == ErrorCodes.ERROR_OPERATION_ABORTED: assert raise_cancel is not None @@ -359,10 +359,10 @@ async def _wait_socket(self, which, sock): # sockets in another thread? And on unix we don't handle this case at # all), but hey, why not. if type(sock) is not stdlib_socket.socket: - await _core.yield_briefly() + await _core.checkpoint() raise TypeError("need a stdlib socket") if sock in self._socket_waiters[which]: - await _core.yield_briefly() + await _core.checkpoint() raise _core.ResourceBusyError( "another task is already waiting to {} this socket" .format(which) @@ -373,7 +373,7 @@ def abort(_): del self._socket_waiters[which][sock] return _core.Abort.SUCCEEDED - await _core.yield_indefinitely(abort) + await _core.wait_task_rescheduled(abort) @_public @_hazmat @@ -393,14 +393,14 @@ async def wait_socket_writable(self, sock): # async def perform_overlapped(self, handle, submit_fn): # # submit_fn(lpOverlapped) submits some I/O # # it may raise an OSError with ERROR_IO_PENDING - # await _core.yield_if_cancelled() + # await _core.checkpoint_if_cancelled() # self.register_with_iocp(handle) # lpOverlapped = ffi.new("LPOVERLAPPED") # try: # submit_fn(lpOverlapped) # except OSError as exc: # if exc.winerror != Error.ERROR_IO_PENDING: - # await _core.yield_briefly_no_cancel() + # await _core.cancel_shielded_checkpoint() # raise # await self.wait_overlapped(handle, lpOverlapped) # return lpOverlapped diff --git a/trio/_core/_parking_lot.py b/trio/_core/_parking_lot.py index 1d3c00b22c..a2205e8ace 100644 --- a/trio/_core/_parking_lot.py +++ b/trio/_core/_parking_lot.py @@ -137,7 +137,7 @@ async def park(self): """ task = _core.current_task() self._parked[task] = None - await _core.yield_indefinitely(self._abort_func_for(task)) + await _core.wait_task_rescheduled(self._abort_func_for(task)) def _pop_several(self, count): for _ in range(min(count, len(self._parked))): diff --git a/trio/_core/_run.py b/trio/_core/_run.py index c6eabd00a9..1261cf1f34 100644 --- a/trio/_core/_run.py +++ b/trio/_core/_run.py @@ -25,9 +25,9 @@ from ._multierror import MultiError from ._result import Result, Error, Value from ._traps import ( - yield_briefly_no_cancel, + cancel_shielded_checkpoint, Abort, - yield_indefinitely, + wait_task_rescheduled, YieldBrieflyNoCancel, YieldIndefinitely, ) @@ -43,8 +43,8 @@ # __all__. These are all re-exported as part of the 'trio' or 'trio.hazmat' # namespaces. __all__ = [ - "Task", "run", "open_nursery", "open_cancel_scope", "yield_briefly", - "current_task", "current_effective_deadline", "yield_if_cancelled", + "Task", "run", "open_nursery", "open_cancel_scope", "checkpoint", + "current_task", "current_effective_deadline", "checkpoint_if_cancelled", "STATUS_IGNORED" ] @@ -454,7 +454,7 @@ async def _clean_up(self, pending_exc): with open_cancel_scope() as clean_up_scope: if not self._children and not self._zombies: try: - await _core.yield_briefly() + await _core.checkpoint() except BaseException as exc: exceptions.append(exc) while self._children or self._zombies or self._pending_starts: @@ -829,18 +829,18 @@ def reschedule(self, task, next_send=Value(None)): """Reschedule the given task with the given :class:`~trio.hazmat.Result`. - See :func:`yield_indefinitely` for the gory details. + See :func:`wait_task_rescheduled` for the gory details. There must be exactly one call to :func:`reschedule` for every call to - :func:`yield_indefinitely`. (And when counting, keep in mind that + :func:`wait_task_rescheduled`. (And when counting, keep in mind that returning :data:`Abort.SUCCEEDED` from an abort callback is equivalent to calling :func:`reschedule` once.) Args: task (trio.hazmat.Task): the task to be rescheduled. Must be blocked - in a call to :func:`yield_indefinitely`. + in a call to :func:`wait_task_rescheduled`. next_send (trio.hazmat.Result): the value (or error) to return (or - raise) from :func:`yield_indefinitely`. + raise) from :func:`wait_task_rescheduled`. """ assert task._runner is self @@ -1217,7 +1217,7 @@ def run_all_bounded(): and not self.call_soon_idempotent_queue): await self.call_soon_wakeup.wait_woken() else: - await yield_briefly() + await checkpoint() except Cancelled: # Keep the work done with this lock held as minimal as possible, # because it doesn't protect us against concurrent signal delivery @@ -1341,7 +1341,7 @@ def abort(_): del self.waiting_for_idle[key] return Abort.SUCCEEDED - await yield_indefinitely(abort) + await wait_task_rescheduled(abort) ################ # Instrumentation @@ -1741,7 +1741,7 @@ def current_effective_deadline(): @_hazmat -async def yield_briefly(): +async def checkpoint(): """A pure :ref:`checkpoint `. This checks for cancellation and allows other tasks to be scheduled, @@ -1752,25 +1752,33 @@ async def yield_briefly(): efficiency). Equivalent to ``await trio.sleep(0)`` (which is implemented by calling - :func:`yield_briefly`.) + :func:`checkpoint`.) """ with open_cancel_scope(deadline=-inf) as scope: - await _core.yield_indefinitely(lambda _: _core.Abort.SUCCEEDED) + await _core.wait_task_rescheduled(lambda _: _core.Abort.SUCCEEDED) @_hazmat -async def yield_if_cancelled(): - """A conditional :ref:`checkpoint `. +async def checkpoint_if_cancelled(): + """Issue a :ref:`checkpoint ` if the calling context has been + cancelled. - If a cancellation is active, then allows other tasks to be scheduled, - and then raises :exc:`trio.Cancelled`. + Equivalent to (but potentially more efficient than):: + + if trio.current_deadline() == -inf: + await trio.hazmat.checkpoint() + + This is either a no-op, or else it allow other tasks to be scheduled and + then raises :exc:`trio.Cancelled`. + + Typically used together with :func:`cancel_shielded_checkpoint`. """ task = current_task() if (task._pending_cancel_scope() is not None or (task is task._runner.main_task and task._runner.ki_pending)): - await _core.yield_briefly() + await _core.checkpoint() assert False # pragma: no cover task._cancel_points += 1 diff --git a/trio/_core/_traps.py b/trio/_core/_traps.py index ed0f89adcd..d153036765 100644 --- a/trio/_core/_traps.py +++ b/trio/_core/_traps.py @@ -8,7 +8,7 @@ from . import _hazmat -__all__ = ["yield_briefly_no_cancel", "Abort", "yield_indefinitely"] +__all__ = ["cancel_shielded_checkpoint", "Abort", "wait_task_rescheduled"] # Decorator to turn a generator into a well-behaved async function: @@ -32,9 +32,18 @@ class YieldBrieflyNoCancel: @_hazmat @asyncfunction -def yield_briefly_no_cancel(): +def cancel_shielded_checkpoint(): """Introduce a schedule point, but not a cancel point. + This is *not* a :ref:`checkpoint `, but it is half of a + checkpoint, and when combined with :func:`checkpoint_if_cancelled` it can + make a full checkpoint. + + Equivalent to (but potentially more efficient than):: + + with trio.open_cancel_scope(shield=True): + await trio.hazmat.checkpoint() + """ return (yield YieldBrieflyNoCancel).unwrap() @@ -44,7 +53,7 @@ def yield_briefly_no_cancel(): class Abort(enum.Enum): """:class:`enum.Enum` used as the return value from abort functions. - See :func:`yield_indefinitely` for details. + See :func:`wait_task_rescheduled` for details. .. data:: SUCCEEDED FAILED @@ -62,11 +71,12 @@ class YieldIndefinitely: @_hazmat @asyncfunction -def yield_indefinitely(abort_func): +def wait_task_rescheduled(abort_func): """Put the current task to sleep, with cancellation support. This is the lowest-level API for blocking in trio. Every time a - :class:`~trio.hazmat.Task` blocks, it does so by calling this function. + :class:`~trio.hazmat.Task` blocks, it does so by calling this function + (usually indirectly via some higher-level API). This is a tricky interface with no guard rails. If you can use :class:`ParkingLot` or the built-in I/O wait functions instead, then you @@ -76,7 +86,7 @@ def yield_indefinitely(abort_func): arrangements for "someone" to call :func:`reschedule` on the current task at some later point. - Then you call :func:`yield_indefinitely`, passing in ``abort_func``, an + Then you call :func:`wait_task_rescheduled`, passing in ``abort_func``, an "abort callback". (Terminology: in trio, "aborting" is the process of attempting to @@ -85,7 +95,7 @@ def yield_indefinitely(abort_func): There are two possibilities for what happens next: 1. "Someone" calls :func:`reschedule` on the current task, and - :func:`yield_indefinitely` returns or raises whatever value or error + :func:`wait_task_rescheduled` returns or raises whatever value or error was passed to :func:`reschedule`. 2. The call's context transitions to a cancelled state (e.g. due to a @@ -136,13 +146,13 @@ def abort(inner_raise_cancel): outer_raise_cancel = inner_raise_cancel TRY_TO_CANCEL_OPERATION() return trio.hazmat.Abort.FAILED - await yield_indefinitely(abort) + await wait_task_rescheduled(abort) if OPERATION_WAS_SUCCESSFULLY_CANCELLED: # raises the error outer_raise_cancel() In any case it's guaranteed that we only call the ``abort_func`` at most - once per call to :func:`yield_indefinitely`. + once per call to :func:`wait_task_rescheduled`. .. warning:: diff --git a/trio/_core/_unbounded_queue.py b/trio/_core/_unbounded_queue.py index 24c39906de..2709a82ee8 100644 --- a/trio/_core/_unbounded_queue.py +++ b/trio/_core/_unbounded_queue.py @@ -118,7 +118,7 @@ async def get_batch(self): non-empty. """ - await _core.yield_if_cancelled() + await _core.checkpoint_if_cancelled() if not self._can_get: await self._lot.park() return self._get_batch_protected() @@ -126,7 +126,7 @@ async def get_batch(self): try: return self._get_batch_protected() finally: - await _core.yield_briefly_no_cancel() + await _core.cancel_shielded_checkpoint() def statistics(self): """Return an object containing debugging information. diff --git a/trio/_core/tests/test_io.py b/trio/_core/tests/test_io.py index f17b31de85..c19c0924b5 100644 --- a/trio/_core/tests/test_io.py +++ b/trio/_core/tests/test_io.py @@ -5,7 +5,7 @@ import random from ... import _core -from ...testing import wait_all_tasks_blocked, Sequencer, assert_yields +from ...testing import wait_all_tasks_blocked, Sequencer, assert_checkpoints # Cross-platform tests for IO handling @@ -89,7 +89,7 @@ async def test_wait_basic(socketpair, wait_readable, wait_writable): a, b = socketpair # They start out writable() - with assert_yields(): + with assert_checkpoints(): await wait_writable(a) # But readable() blocks until data arrives @@ -97,7 +97,7 @@ async def test_wait_basic(socketpair, wait_readable, wait_writable): async def block_on_read(): try: - with assert_yields(): + with assert_checkpoints(): await wait_readable(a) except _core.Cancelled: record.append("cancelled") @@ -114,13 +114,13 @@ async def block_on_read(): fill_socket(a) # Now writable will block, but readable won't - with assert_yields(): + with assert_checkpoints(): await wait_readable(b) record = [] async def block_on_write(): try: - with assert_yields(): + with assert_checkpoints(): await wait_writable(a) except _core.Cancelled: record.append("cancelled") @@ -158,7 +158,7 @@ async def test_double_read(socketpair, wait_readable): async with _core.open_nursery() as nursery: nursery.start_soon(wait_readable, a) await wait_all_tasks_blocked() - with assert_yields(): + with assert_checkpoints(): with pytest.raises(_core.ResourceBusyError): await wait_readable(a) nursery.cancel_scope.cancel() @@ -173,7 +173,7 @@ async def test_double_write(socketpair, wait_writable): async with _core.open_nursery() as nursery: nursery.start_soon(wait_writable, a) await wait_all_tasks_blocked() - with assert_yields(): + with assert_checkpoints(): with pytest.raises(_core.ResourceBusyError): await wait_writable(a) nursery.cancel_scope.cancel() @@ -232,7 +232,7 @@ async def sender(sock, seed, key): print("sent", sent) chunk = bytearray(r.randrange(MAX_CHUNK)) while chunk: - with assert_yields(): + with assert_checkpoints(): await wait_writable(sock) this_chunk_size = sock.send(chunk) sent += this_chunk_size @@ -244,7 +244,7 @@ async def receiver(sock, key): received = 0 while True: print("received", received) - with assert_yields(): + with assert_checkpoints(): await wait_readable(sock) this_chunk_size = len(sock.recv(MAX_CHUNK)) if not this_chunk_size: diff --git a/trio/_core/tests/test_ki.py b/trio/_core/tests/test_ki.py index dd4c732cda..4e9486d80d 100644 --- a/trio/_core/tests/test_ki.py +++ b/trio/_core/tests/test_ki.py @@ -106,7 +106,7 @@ async def child(expected): import traceback traceback.print_stack() assert _core.currently_ki_protected() == expected - await _core.yield_briefly() + await _core.checkpoint() traceback.print_stack() assert _core.currently_ki_protected() == expected @@ -204,7 +204,7 @@ def test_ki_protection_works(): async def sleeper(name, record): try: while True: - await _core.yield_briefly() + await _core.checkpoint() except _core.Cancelled: record.add((name + " ok")) @@ -217,7 +217,7 @@ async def raiser(name, record): except KeyboardInterrupt: print("raised!") # Make sure we aren't getting cancelled as well as siginted - await _core.yield_briefly() + await _core.checkpoint() record.add((name + " raise ok")) raise else: @@ -225,7 +225,9 @@ async def raiser(name, record): # If we didn't raise (b/c protected), then we *should* get # cancelled at the next opportunity try: - await _core.yield_indefinitely(lambda _: _core.Abort.SUCCEEDED) + await _core.wait_task_rescheduled( + lambda _: _core.Abort.SUCCEEDED + ) except _core.Cancelled: record.add((name + " cancel ok")) @@ -290,12 +292,12 @@ def before_run(self): ki_self() async def main(): - await _core.yield_briefly() + await _core.checkpoint() with pytest.raises(KeyboardInterrupt): _core.run(main, instruments=[InstrumentOfDeath()]) - # yield_if_cancelled notices pending KI + # checkpoint_if_cancelled notices pending KI print("check 5") @_core.enable_ki_protection @@ -303,7 +305,7 @@ async def main(): assert _core.currently_ki_protected() ki_self() with pytest.raises(KeyboardInterrupt): - await _core.yield_if_cancelled() + await _core.checkpoint_if_cancelled() _core.run(main) @@ -314,11 +316,11 @@ async def main(): async def main(): assert _core.currently_ki_protected() ki_self() - await _core.yield_briefly_no_cancel() - await _core.yield_briefly_no_cancel() - await _core.yield_briefly_no_cancel() + await _core.cancel_shielded_checkpoint() + await _core.cancel_shielded_checkpoint() + await _core.cancel_shielded_checkpoint() with pytest.raises(KeyboardInterrupt): - await _core.yield_briefly() + await _core.checkpoint() _core.run(main) @@ -335,9 +337,9 @@ def abort(_): _core.reschedule(task, _core.Value(1)) return _core.Abort.FAILED - assert await _core.yield_indefinitely(abort) == 1 + assert await _core.wait_task_rescheduled(abort) == 1 with pytest.raises(KeyboardInterrupt): - await _core.yield_briefly() + await _core.checkpoint() _core.run(main) @@ -356,8 +358,8 @@ def abort(raise_cancel): return _core.Abort.FAILED with pytest.raises(KeyboardInterrupt): - assert await _core.yield_indefinitely(abort) - await _core.yield_briefly() + assert await _core.wait_task_rescheduled(abort) + await _core.checkpoint() _core.run(main) @@ -408,12 +410,12 @@ async def main(): with _core.open_cancel_scope() as cancel_scope: cancel_scope.cancel() with pytest.raises(_core.Cancelled): - await _core.yield_briefly() + await _core.checkpoint() ki_self() with pytest.raises(KeyboardInterrupt): - await _core.yield_briefly() + await _core.checkpoint() with pytest.raises(_core.Cancelled): - await _core.yield_briefly() + await _core.checkpoint() _core.run(main) @@ -548,7 +550,7 @@ async def main(): # but at a moment when we had KI protection enabled, so we # need to execute a checkpoint to ensure it's delivered # before we exit main(). - await _core.yield_briefly() + await _core.checkpoint() finally: print("joining thread", sys.exc_info()) thread.join() diff --git a/trio/_core/tests/test_result.py b/trio/_core/tests/test_result.py index 5bb106b6cf..24f00bbde2 100644 --- a/trio/_core/tests/test_result.py +++ b/trio/_core/tests/test_result.py @@ -94,14 +94,14 @@ def raise_ValueError(x): async def test_Result_acapture(): async def return_arg(x): - await _core.yield_briefly() + await _core.checkpoint() return x v = await Result.acapture(return_arg, 7) assert v == Value(7) async def raise_ValueError(x): - await _core.yield_briefly() + await _core.checkpoint() raise ValueError(x) e = await Result.acapture(raise_ValueError, 9) diff --git a/trio/_core/tests/test_run.py b/trio/_core/tests/test_run.py index 476defb1a8..32f973e1dd 100644 --- a/trio/_core/tests/test_run.py +++ b/trio/_core/tests/test_run.py @@ -15,7 +15,7 @@ from ...testing import ( wait_all_tasks_blocked, Sequencer, - assert_yields, + assert_checkpoints, ) from ..._timeouts import sleep @@ -26,7 +26,7 @@ # its rescheduled with, which is really only useful for tests of # rescheduling... async def sleep_forever(): - return await _core.yield_indefinitely(lambda _: _core.Abort.SUCCEEDED) + return await _core.wait_task_rescheduled(lambda _: _core.Abort.SUCCEEDED) # Some of our tests need to leak coroutines, and thus trigger the @@ -64,7 +64,7 @@ async def trivial(x): _core.run(lambda: None) async def trivial2(x): - await _core.yield_briefly() + await _core.checkpoint() return x assert _core.run(trivial2, 1) == 1 @@ -163,7 +163,7 @@ async def test_basic_interleave(): async def looper(whoami, record): for i in range(3): record.append((whoami, i)) - await _core.yield_briefly() + await _core.checkpoint() record = [] async with _core.open_nursery() as nursery: @@ -183,7 +183,7 @@ async def looper(): try: while True: print("looper sleeping") - await _core.yield_briefly() + await _core.checkpoint() print("looper woke up") except _core.Cancelled: print("looper cancelled") @@ -269,7 +269,7 @@ async def child2(): async with _core.open_nursery() as nursery: nursery.start_soon(child1) # let t1 run and fall asleep - await _core.yield_briefly() + await _core.checkpoint() nursery.start_soon(child2) @@ -409,8 +409,8 @@ async def child(): assert stats.tasks_runnable == 1 # Give the child a chance to die and the call_soon a chance to clear - await _core.yield_briefly() - await _core.yield_briefly() + await _core.checkpoint() + await _core.checkpoint() with _core.open_cancel_scope(deadline=_core.current_time() + 5) as scope: stats = _core.current_statistics() @@ -457,13 +457,13 @@ def test_instruments_deprecated(recwarn): async def main(): for _ in range(4): - await _core.yield_briefly() + await _core.checkpoint() cp = _core.current_instruments() assert cp == [r1, r2] # replace r2 with r3, to test that we can manipulate them as we go cp[1] = r3 for _ in range(1): - await _core.yield_briefly() + await _core.checkpoint() return _core.current_task() task = _core.run(main, instruments=[r1, r2]) @@ -488,7 +488,7 @@ def test_instruments(recwarn): async def main(): for _ in range(4): - await _core.yield_briefly() + await _core.checkpoint() # replace r2 with r3, to test that we can manipulate them as we go _core.remove_instrument(r2) with pytest.raises(KeyError): @@ -497,7 +497,7 @@ async def main(): _core.add_instrument(r3) _core.add_instrument(r3) for _ in range(1): - await _core.yield_briefly() + await _core.checkpoint() return _core.current_task() task = _core.run(main, instruments=[r1, r2]) @@ -520,11 +520,11 @@ def test_instruments_interleave(): async def two_step1(): tasks["t1"] = _core.current_task() - await _core.yield_briefly() + await _core.checkpoint() async def two_step2(): tasks["t2"] = _core.current_task() - await _core.yield_briefly() + await _core.checkpoint() async def main(): async with _core.open_nursery() as nursery: @@ -564,7 +564,7 @@ class NullInstrument: pass async def main(): - await _core.yield_briefly() + await _core.checkpoint() _core.run(main, instruments=[NullInstrument()]) @@ -639,19 +639,19 @@ async def main(): def test_cancel_points(): async def main1(): with _core.open_cancel_scope() as scope: - await _core.yield_if_cancelled() + await _core.checkpoint_if_cancelled() scope.cancel() with pytest.raises(_core.Cancelled): - await _core.yield_if_cancelled() + await _core.checkpoint_if_cancelled() _core.run(main1) async def main2(): with _core.open_cancel_scope() as scope: - await _core.yield_briefly() + await _core.checkpoint() scope.cancel() with pytest.raises(_core.Cancelled): - await _core.yield_briefly() + await _core.checkpoint() _core.run(main2) @@ -666,10 +666,10 @@ async def main3(): async def main4(): with _core.open_cancel_scope() as scope: scope.cancel() - await _core.yield_briefly_no_cancel() - await _core.yield_briefly_no_cancel() + await _core.cancel_shielded_checkpoint() + await _core.cancel_shielded_checkpoint() with pytest.raises(_core.Cancelled): - await _core.yield_briefly() + await _core.checkpoint() _core.run(main4) @@ -679,7 +679,7 @@ async def test_cancel_edge_cases(): # Two cancels in a row -- idempotent scope.cancel() scope.cancel() - await _core.yield_briefly() + await _core.checkpoint() assert scope.cancel_called assert scope.cancelled_caught @@ -753,10 +753,10 @@ async def blocker(): async def test_cancel_shielding(): with _core.open_cancel_scope() as outer: with _core.open_cancel_scope() as inner: - await _core.yield_briefly() + await _core.checkpoint() outer.cancel() with pytest.raises(_core.Cancelled): - await _core.yield_briefly() + await _core.checkpoint() assert inner.shield is False with pytest.raises(TypeError): @@ -766,27 +766,27 @@ async def test_cancel_shielding(): inner.shield = True assert inner.shield is True # shield protects us from 'outer' - await _core.yield_briefly() + await _core.checkpoint() with _core.open_cancel_scope() as innerest: innerest.cancel() # but it doesn't protect us from scope inside inner with pytest.raises(_core.Cancelled): - await _core.yield_briefly() - await _core.yield_briefly() + await _core.checkpoint() + await _core.checkpoint() inner.shield = False # can disable shield again with pytest.raises(_core.Cancelled): - await _core.yield_briefly() + await _core.checkpoint() # re-enable shield inner.shield = True - await _core.yield_briefly() + await _core.checkpoint() # shield doesn't protect us from inner itself inner.cancel() # This should now raise, but be absorbed by the inner scope - await _core.yield_briefly() + await _core.checkpoint() assert inner.cancelled_caught @@ -852,9 +852,9 @@ async def test_basic_timeout(mock_clock): assert scope.deadline == start + 1 assert not scope.cancel_called mock_clock.jump(2) - await _core.yield_briefly() - await _core.yield_briefly() - await _core.yield_briefly() + await _core.checkpoint() + await _core.checkpoint() + await _core.checkpoint() assert not scope.cancel_called start = _core.current_time() @@ -869,16 +869,16 @@ async def test_basic_timeout(mock_clock): # changing deadline start = _core.current_time() with _core.open_cancel_scope() as scope: - await _core.yield_briefly() + await _core.checkpoint() scope.deadline = start + 10 - await _core.yield_briefly() + await _core.checkpoint() mock_clock.jump(5) - await _core.yield_briefly() + await _core.checkpoint() scope.deadline = start + 1 with pytest.raises(_core.Cancelled): - await _core.yield_briefly() + await _core.checkpoint() with pytest.raises(_core.Cancelled): - await _core.yield_briefly() + await _core.checkpoint() async def test_cancel_scope_nesting(): @@ -901,21 +901,21 @@ async def test_cancel_scope_nesting(): with _core.open_cancel_scope() as scope2: scope1.cancel() with pytest.raises(_core.Cancelled): - await _core.yield_briefly() + await _core.checkpoint() with pytest.raises(_core.Cancelled): - await _core.yield_briefly() + await _core.checkpoint() scope2.shield = True - await _core.yield_briefly() + await _core.checkpoint() scope2.cancel() with pytest.raises(_core.Cancelled): - await _core.yield_briefly() + await _core.checkpoint() # if a scope is pending, but then gets popped off the stack, then it # isn't delivered with _core.open_cancel_scope() as scope: scope.cancel() - await _core.yield_briefly_no_cancel() - await _core.yield_briefly() + await _core.cancel_shielded_checkpoint() + await _core.checkpoint() assert not scope.cancelled_caught @@ -949,11 +949,11 @@ async def stubborn_sleeper(): with _core.open_cancel_scope() as scope: stubborn_scope[0] = scope record.append("sleep") - x = await _core.yield_indefinitely(lambda _: _core.Abort.FAILED) + x = await _core.wait_task_rescheduled(lambda _: _core.Abort.FAILED) assert x == 1 record.append("woke") try: - await _core.yield_if_cancelled() + await _core.checkpoint_if_cancelled() except _core.Cancelled: record.append("cancelled") @@ -980,12 +980,12 @@ async def main(): # semi-meaningful error after things have gone totally pear-shaped, so # it's not relevant.) By letting the call_soon_task run first, we # avoid the warning. - await _core.yield_briefly() - await _core.yield_briefly() + await _core.checkpoint() + await _core.checkpoint() with _core.open_cancel_scope() as scope: scope.cancel() # None is not a legal return value here - await _core.yield_indefinitely(lambda _: None) + await _core.wait_task_rescheduled(lambda _: None) with pytest.raises(_core.TrioInternalError): _core.run(main) @@ -1001,7 +1001,7 @@ def test_error_in_run_loop(): async def main(): task = _core.current_task() task._schedule_points = "hello!" - await _core.yield_briefly() + await _core.checkpoint() with ignore_coroutine_never_awaited_warnings(): with pytest.raises(_core.TrioInternalError): @@ -1014,7 +1014,7 @@ async def test_spawn_system_task(): async def system_task(x): record.append(("x", x)) record.append(("ki", _core.currently_ki_protected())) - await _core.yield_briefly() + await _core.checkpoint() _core.spawn_system_task(system_task, 1) await wait_all_tasks_blocked() @@ -1101,7 +1101,7 @@ async def main(): _core.run(main) -# This used to fail because yield_briefly was a yield followed by an immediate +# This used to fail because checkpoint was a yield followed by an immediate # reschedule. So we had: # 1) this task yields # 2) this task is rescheduled @@ -1112,10 +1112,10 @@ async def main(): # the next time that it's blocked. async def test_yield_briefly_checks_for_timeout(mock_clock): with _core.open_cancel_scope(deadline=_core.current_time() + 5) as scope: - await _core.yield_briefly() + await _core.checkpoint() with pytest.raises(_core.Cancelled): mock_clock.jump(10) - await _core.yield_briefly() + await _core.checkpoint() # This tests that sys.exc_info is properly saved/restored as we swap between @@ -1300,9 +1300,9 @@ def redo(call_soon): async def main(): call_soon = _core.current_call_soon_thread_and_signal_safe() call_soon(redo, call_soon, idempotent=True) - await _core.yield_briefly() - await _core.yield_briefly() - await _core.yield_briefly() + await _core.checkpoint() + await _core.checkpoint() + await _core.checkpoint() _core.run(main) @@ -1376,7 +1376,7 @@ async def main(): call_soon(naughty_cb, 0) record.append("starting") for _ in range(20): - await _core.yield_briefly() + await _core.checkpoint() _core.run(main) assert len(record) == 2 @@ -1447,7 +1447,7 @@ def slow_abort(raise_cancel): call_soon(_core.reschedule, task, result) return _core.Abort.FAILED - await _core.yield_indefinitely(slow_abort) + await _core.wait_task_rescheduled(slow_abort) async def test_slow_abort_edge_cases(): @@ -1465,10 +1465,10 @@ def slow_abort(raise_cancel): with pytest.raises(_core.Cancelled): record.append("sleeping") - await _core.yield_indefinitely(slow_abort) + await _core.wait_task_rescheduled(slow_abort) record.append("cancelled") # blocking again, this time it's okay, because we're shielded - await _core.yield_briefly() + await _core.checkpoint() record.append("done") with _core.open_cancel_scope() as outer1: @@ -1690,14 +1690,14 @@ async def misguided(): async def test_trivial_yields(recwarn): - with assert_yields(): - await _core.yield_briefly() + with assert_checkpoints(): + await _core.checkpoint() - with assert_yields(): - await _core.yield_if_cancelled() - await _core.yield_briefly_no_cancel() + with assert_checkpoints(): + await _core.checkpoint_if_cancelled() + await _core.cancel_shielded_checkpoint() - with assert_yields(): + with assert_checkpoints(): async with _core.open_nursery(): pass @@ -1717,7 +1717,7 @@ async def trivial(): async with _core.open_nursery() as nursery: t = nursery.spawn(trivial) assert t.result is not None - with assert_yields(): + with assert_checkpoints(): await t.wait() diff --git a/trio/_core/tests/test_unbounded_queue.py b/trio/_core/tests/test_unbounded_queue.py index 3b57b70f9c..bfe8ace987 100644 --- a/trio/_core/tests/test_unbounded_queue.py +++ b/trio/_core/tests/test_unbounded_queue.py @@ -3,7 +3,7 @@ import pytest from ... import _core -from ...testing import assert_yields, wait_all_tasks_blocked +from ...testing import assert_checkpoints, wait_all_tasks_blocked async def test_UnboundedQueue_basic(): @@ -114,11 +114,11 @@ async def test_UnboundedQueue_trivial_yields(): q = _core.UnboundedQueue() q.put_nowait(None) - with assert_yields(): + with assert_checkpoints(): await q.get_batch() q.put_nowait(None) - with assert_yields(): + with assert_checkpoints(): async for _ in q: # pragma: no branch break diff --git a/trio/_core/tests/test_windows.py b/trio/_core/tests/test_windows.py index 13df26705a..11fbed45f2 100644 --- a/trio/_core/tests/test_windows.py +++ b/trio/_core/tests/test_windows.py @@ -16,7 +16,7 @@ async def post(key): for i in range(10): print("post", i) if i % 3 == 0: - await _core.yield_briefly() + await _core.checkpoint() success = kernel32.PostQueuedCompletionStatus( iocp, i, key, ffi.NULL ) diff --git a/trio/_file_io.py b/trio/_file_io.py index a086c864b0..99ac3b4255 100644 --- a/trio/_file_io.py +++ b/trio/_file_io.py @@ -130,7 +130,7 @@ async def aclose(self): with _core.open_cancel_scope(shield=True): await trio.run_sync_in_worker_thread(self._wrapped.close) - await _core.yield_if_cancelled() + await _core.checkpoint_if_cancelled() async def open_file( diff --git a/trio/_highlevel_socket.py b/trio/_highlevel_socket.py index bce6f080b6..ad1b74b419 100644 --- a/trio/_highlevel_socket.py +++ b/trio/_highlevel_socket.py @@ -102,7 +102,7 @@ def __init__(self, socket): async def send_all(self, data): if self.socket.did_shutdown_SHUT_WR: - await _core.yield_briefly() + await _core.checkpoint() raise ClosedStreamError("can't send data after sending EOF") with self._send_conflict_detector.sync: with _translate_socket_errors_to_stream_errors(): @@ -126,14 +126,14 @@ async def send_eof(self): async def receive_some(self, max_bytes): if max_bytes < 1: - await _core.yield_briefly() + await _core.checkpoint() raise ValueError("max_bytes must be >= 1") with _translate_socket_errors_to_stream_errors(): return await self.socket.recv(max_bytes) async def aclose(self): self.socket.close() - await _core.yield_briefly() + await _core.checkpoint() # __aenter__, __aexit__ inherited from HalfCloseableStream are OK @@ -381,4 +381,4 @@ async def aclose(self): try: self.socket.close() finally: - await _core.yield_briefly() + await _core.checkpoint() diff --git a/trio/_socket.py b/trio/_socket.py index 56dca4481a..ef012482e7 100644 --- a/trio/_socket.py +++ b/trio/_socket.py @@ -42,7 +42,7 @@ def _is_blocking_io_error(self, exc): return self._blocking_exc_override(exc) async def __aenter__(self): - await _core.yield_if_cancelled() + await _core.checkpoint_if_cancelled() async def __aexit__(self, etype, value, tb): if value is not None and self._is_blocking_io_error(value): @@ -50,7 +50,7 @@ async def __aexit__(self, etype, value, tb): # block return True else: - await _core.yield_briefly_no_cancel() + await _core.cancel_shielded_checkpoint() # Let the return or exception propagate return False @@ -540,14 +540,14 @@ def _check_address(self, address, *, require_resolved): # the same representation, but with names resolved to numbers, # etc. async def _resolve_address(self, address, flags): - await _core.yield_if_cancelled() + await _core.checkpoint_if_cancelled() try: self._check_address(address, require_resolved=False) except: - await _core.yield_briefly_no_cancel() + await _core.cancel_shielded_checkpoint() raise if self._sock.family not in (AF_INET, AF_INET6): - await _core.yield_briefly_no_cancel() + await _core.cancel_shielded_checkpoint() return address # Since we always pass in an explicit family here, AI_ADDRCONFIG # doesn't add any value -- if we have no ipv6 connectivity and are @@ -835,7 +835,7 @@ async def sendmsg(self, *args): async def _sendall(self, data, flags=0): with memoryview(data) as data: if not data: - await _core.yield_briefly() + await _core.checkpoint() return total_sent = 0 while total_sent < len(data): diff --git a/trio/_ssl.py b/trio/_ssl.py index 24f36817bb..9efc97a71b 100644 --- a/trio/_ssl.py +++ b/trio/_ssl.py @@ -422,7 +422,7 @@ def _check_status(self): # touch it. The big comment at the top of this file will help explain # too. async def _retry(self, fn, *args, ignore_want_read=False): - await _core.yield_if_cancelled() + await _core.checkpoint_if_cancelled() yielded = False try: finished = False @@ -561,7 +561,7 @@ async def _retry(self, fn, *args, ignore_want_read=False): return ret finally: if not yielded: - await _core.yield_briefly_no_cancel() + await _core.cancel_shielded_checkpoint() async def _do_handshake(self): try: @@ -597,7 +597,7 @@ async def do_handshake(self): try: self._check_status() except: - await _core.yield_briefly() + await _core.checkpoint() raise await self._handshook.ensure(checkpoint=True) @@ -670,7 +670,7 @@ async def send_all(self, data): # SSLObject interprets write(b"") as an EOF for some reason, which # is not what we want. if not data: - await _core.yield_briefly() + await _core.checkpoint() return await self._retry(self._ssl_object.write, data) @@ -714,7 +714,7 @@ async def aclose(self): """ if self._state is _State.CLOSED: - await _core.yield_briefly() + await _core.checkpoint() return if self._state is _State.BROKEN or self._https_compatible: self._state = _State.CLOSED diff --git a/trio/_sync.py b/trio/_sync.py index 82c02477d6..551abb7c81 100644 --- a/trio/_sync.py +++ b/trio/_sync.py @@ -58,7 +58,7 @@ async def wait(self): """ if self._flag: - await _core.yield_briefly() + await _core.checkpoint() else: await self._lot.park() @@ -281,7 +281,7 @@ async def acquire_on_behalf_of(self, borrower): tokens. """ - await _core.yield_if_cancelled() + await _core.checkpoint_if_cancelled() try: self.acquire_on_behalf_of_nowait(borrower) except _core.WouldBlock: @@ -289,10 +289,10 @@ async def acquire_on_behalf_of(self, borrower): self._pending_borrowers[task] = borrower await self._lot.park() except: - await _core.yield_briefly_no_cancel() + await _core.cancel_shielded_checkpoint() raise else: - await _core.yield_briefly_no_cancel() + await _core.cancel_shielded_checkpoint() @_core.enable_ki_protection def release(self): @@ -439,13 +439,13 @@ async def acquire(self): letting it drop below zero. """ - await _core.yield_if_cancelled() + await _core.checkpoint_if_cancelled() try: self.acquire_nowait() except _core.WouldBlock: await self._lot.park() else: - await _core.yield_briefly_no_cancel() + await _core.cancel_shielded_checkpoint() @_core.enable_ki_protection def release(self): @@ -546,7 +546,7 @@ async def acquire(self): """Acquire the lock, blocking if necessary. """ - await _core.yield_if_cancelled() + await _core.checkpoint_if_cancelled() try: self.acquire_nowait() except _core.WouldBlock: @@ -555,7 +555,7 @@ async def acquire(self): # lock as well. await self._lot.park() else: - await _core.yield_briefly_no_cancel() + await _core.cancel_shielded_checkpoint() @_core.enable_ki_protection def release(self): @@ -956,7 +956,7 @@ async def join(self): """ if self._unprocessed == 0: - await _core.yield_briefly() + await _core.checkpoint() else: await self._join_lot.park() diff --git a/trio/_threads.py b/trio/_threads.py index 26fe21bc67..752ffaf8cd 100644 --- a/trio/_threads.py +++ b/trio/_threads.py @@ -279,7 +279,7 @@ async def run_sync_in_worker_thread( Whatever ``sync_fn(*args)`` raises. """ - await _core.yield_if_cancelled() + await _core.checkpoint_if_cancelled() call_soon = _core.current_call_soon_thread_and_signal_safe() if limiter is None: limiter = current_default_worker_thread_limiter() @@ -338,4 +338,4 @@ def abort(_): else: return _core.Abort.FAILED - return await _core.yield_indefinitely(abort) + return await _core.wait_task_rescheduled(abort) diff --git a/trio/_timeouts.py b/trio/_timeouts.py index 7e7964bf87..1437f9f9f6 100644 --- a/trio/_timeouts.py +++ b/trio/_timeouts.py @@ -48,7 +48,7 @@ async def sleep_forever(): Equivalent to calling ``await sleep(math.inf)``. """ - await _core.yield_indefinitely(lambda _: _core.Abort.SUCCEEDED) + await _core.wait_task_rescheduled(lambda _: _core.Abort.SUCCEEDED) async def sleep_until(deadline): @@ -80,7 +80,7 @@ async def sleep(seconds): if seconds < 0: raise ValueError("duration must be non-negative") if seconds == 0: - await _core.yield_briefly() + await _core.checkpoint() else: await sleep_until(_core.current_time() + seconds) diff --git a/trio/_util.py b/trio/_util.py index 8a39aa7765..6cee5f0eef 100644 --- a/trio/_util.py +++ b/trio/_util.py @@ -8,7 +8,7 @@ # There's a dependency loop here... _core is allowed to use this file (in fact # it's the *only* file in the main trio/ package it's allowed to use), but -# ConflictDetector needs yield_briefly so it also has to import +# ConflictDetector needs checkpoint so it also has to import # _core. Possibly we should split this file into two: one for true generic # low-level utility code, and one for higher level helpers? from . import _core @@ -214,7 +214,7 @@ def __init__(self, msg): self.sync = _ConflictDetectorSync(msg) async def __aenter__(self): - await _core.yield_briefly() + await _core.checkpoint() return self.sync.__enter__() async def __aexit__(self, *args): diff --git a/trio/testing/__init__.py b/trio/testing/__init__.py index d656c1642a..113c860826 100644 --- a/trio/testing/__init__.py +++ b/trio/testing/__init__.py @@ -25,6 +25,21 @@ from ._network import * __all__ += _network.__all__ +################################################################ + +from .. import _deprecate + +_deprecate.enable_attribute_deprecations(__name__) + +__deprecated_attributes__ = { + "assert_yields": + _deprecate.DeprecatedAttribute(assert_checkpoints, "0.2.0", issue=157), +} + +del _deprecate + +################################################################ + from .._util import fixup_module_metadata fixup_module_metadata(__name__, globals()) del fixup_module_metadata diff --git a/trio/testing/_check_streams.py b/trio/testing/_check_streams.py index a7effb7c06..d31a44d8fc 100644 --- a/trio/testing/_check_streams.py +++ b/trio/testing/_check_streams.py @@ -8,7 +8,7 @@ BrokenStreamError, ClosedStreamError, aclose_forcefully ) from .._abc import SendStream, ReceiveStream, Stream, HalfCloseableStream -from ._checkpoints import assert_yields +from ._checkpoints import assert_checkpoints __all__ = [ "check_one_way_stream", @@ -66,18 +66,18 @@ async def check_one_way_stream(stream_maker, clogged_stream_maker): assert isinstance(r, ReceiveStream) async def do_send_all(data): - with assert_yields(): + with assert_checkpoints(): assert await s.send_all(data) is None async def do_receive_some(max_bytes): - with assert_yields(): + with assert_checkpoints(): return await r.receive_some(1) async def checked_receive_1(expected): assert await do_receive_some(1) == expected async def do_aclose(resource): - with assert_yields(): + with assert_checkpoints(): await resource.aclose() # Simple sending/receiving @@ -125,7 +125,7 @@ async def send_empty_then_y(): # stream doesn't *have* to have any internal buffering. That's why we # start a concurrent receive_some call, then cancel it.) async def simple_check_wait_send_all_might_not_block(scope): - with assert_yields(): + with assert_checkpoints(): await s.wait_send_all_might_not_block() scope.cancel() @@ -168,7 +168,7 @@ async def expect_broken_stream_on_send(): # ditto for wait_send_all_might_not_block with _assert_raises(ClosedStreamError): - with assert_yields(): + with assert_checkpoints(): await s.wait_send_all_might_not_block() # and again, repeated closing is fine @@ -266,7 +266,7 @@ async def expect_cancelled(afn, *args): async def waiter(cancel_scope): record.append("waiter sleeping") - with assert_yields(): + with assert_checkpoints(): await s.wait_send_all_might_not_block() record.append("waiter wokeup") cancel_scope.cancel() @@ -317,7 +317,7 @@ async def receiver(): async with _ForceCloseBoth(await clogged_stream_maker()) as (s, r): async def sender(): try: - with assert_yields(): + with assert_checkpoints(): await s.wait_send_all_might_not_block() except BrokenStreamError: pass @@ -334,7 +334,7 @@ async def receiver(): async with _ForceCloseBoth(await clogged_stream_maker()) as (s, r): await aclose_forcefully(r) try: - with assert_yields(): + with assert_checkpoints(): await s.wait_send_all_might_not_block() except BrokenStreamError: pass @@ -433,7 +433,7 @@ async def check_half_closeable_stream(stream_maker, clogged_stream_maker): async def send_x_then_eof(s): await s.send_all(b"x") - with assert_yields(): + with assert_checkpoints(): await s.send_eof() async def expect_x_then_eof(r): @@ -450,7 +450,7 @@ async def expect_x_then_eof(r): await s1.send_all(b"y") # but we can do send_eof again - with assert_yields(): + with assert_checkpoints(): await s1.send_eof() # and we can still send stuff back the other way diff --git a/trio/testing/_checkpoints.py b/trio/testing/_checkpoints.py index bd1660e9ee..02411b4ff8 100644 --- a/trio/testing/_checkpoints.py +++ b/trio/testing/_checkpoints.py @@ -1,8 +1,9 @@ from contextlib import contextmanager from .. import _core +from .._deprecate import deprecated -__all__ = ["assert_yields", "assert_no_yields"] +__all__ = ["assert_checkpoints", "assert_no_yields"] @contextmanager @@ -16,13 +17,13 @@ def _assert_yields_or_not(expected): finally: if (expected and (task._cancel_points == orig_cancel or task._schedule_points == orig_schedule)): - raise AssertionError("assert_yields block did not yield!") + raise AssertionError("assert_checkpoints block did not yield!") elif (not expected and (task._cancel_points != orig_cancel or task._schedule_points != orig_schedule)): raise AssertionError("assert_no_yields block yielded!") -def assert_yields(): +def assert_checkpoints(): """Use as a context manager to check that the code inside the ``with`` block executes at least one :ref:`checkpoint `. @@ -33,7 +34,7 @@ def assert_yields(): Check that :func:`trio.sleep` is a checkpoint, even if it doesn't block:: - with trio.testing.assert_yields(): + with trio.testing.assert_checkpoints(): await trio.sleep(0) """ @@ -41,6 +42,7 @@ def assert_yields(): return _assert_yields_or_not(True) +@deprecated("0.2.0", issue=157, instead=None) def assert_no_yields(): """Use as a context manager to check that the code inside the ``with`` block does not execute any :ref:`check points `. diff --git a/trio/testing/_memory_streams.py b/trio/testing/_memory_streams.py index fc79ceb0dc..74760522fa 100644 --- a/trio/testing/_memory_streams.py +++ b/trio/testing/_memory_streams.py @@ -119,7 +119,7 @@ async def send_all(self, data): # lock to give ourselves a chance to detect buggy user code that calls # this twice at the same time. async with self._conflict_detector: - await _core.yield_briefly() + await _core.checkpoint() self._outgoing.put(data) if self.send_all_hook is not None: await self.send_all_hook() @@ -133,7 +133,7 @@ async def wait_send_all_might_not_block(self): # lock to give ourselves a chance to detect buggy user code that calls # this twice at the same time. async with self._conflict_detector: - await _core.yield_briefly() + await _core.checkpoint() # check for being closed: self._outgoing.put(b"") if self.wait_send_all_might_not_block_hook is not None: @@ -153,7 +153,7 @@ async def aclose(self): """ self.close() - await _core.yield_briefly() + await _core.checkpoint() async def get_data(self, max_bytes=None): """Retrieves data from the internal buffer, blocking if necessary. @@ -218,7 +218,7 @@ async def receive_some(self, max_bytes): # lock to give ourselves a chance to detect buggy user code that calls # this twice at the same time. async with self._conflict_detector: - await _core.yield_briefly() + await _core.checkpoint() if max_bytes is None: raise TypeError("max_bytes must not be None") if self._closed: @@ -247,7 +247,7 @@ async def aclose(self): """ self.close() - await _core.yield_briefly() + await _core.checkpoint() def put_data(self, data): """Appends the given data to the internal buffer. @@ -521,7 +521,7 @@ def close(self): async def aclose(self): self.close() - await _core.yield_briefly() + await _core.checkpoint() async def send_all(self, data): await self._lbq.send_all(data) @@ -539,7 +539,7 @@ def close(self): async def aclose(self): self.close() - await _core.yield_briefly() + await _core.checkpoint() async def receive_some(self, max_bytes): return await self._lbq.receive_some(max_bytes) diff --git a/trio/tests/test_abc.py b/trio/tests/test_abc.py index e2b3f96349..c8af0927d6 100644 --- a/trio/tests/test_abc.py +++ b/trio/tests/test_abc.py @@ -2,7 +2,7 @@ import attr -from ..testing import assert_yields +from ..testing import assert_checkpoints from .. import abc as tabc diff --git a/trio/tests/test_highlevel_serve_listeners.py b/trio/tests/test_highlevel_serve_listeners.py index 025fa7474e..13b87a1a57 100644 --- a/trio/tests/test_highlevel_serve_listeners.py +++ b/trio/tests/test_highlevel_serve_listeners.py @@ -24,7 +24,7 @@ async def connect(self): return client async def accept(self): - await trio.hazmat.yield_briefly() + await trio.hazmat.checkpoint() assert not self.closed if self.accept_hook is not None: await self.accept_hook() @@ -34,7 +34,7 @@ async def accept(self): async def aclose(self): self.closed = True - await trio.hazmat.yield_briefly() + await trio.hazmat.checkpoint() async def test_serve_listeners_basic(): diff --git a/trio/tests/test_highlevel_socket.py b/trio/tests/test_highlevel_socket.py index 2686ca3e81..561a2cd07c 100644 --- a/trio/tests/test_highlevel_socket.py +++ b/trio/tests/test_highlevel_socket.py @@ -6,7 +6,7 @@ from .. import _core from ..testing import ( - check_half_closeable_stream, wait_all_tasks_blocked, assert_yields + check_half_closeable_stream, wait_all_tasks_blocked, assert_checkpoints ) from .._highlevel_generic import ClosedListenerError from .._highlevel_socket import * @@ -117,19 +117,19 @@ async def test_SocketListener(): client_sock = tsocket.socket() await client_sock.connect(listen_sock.getsockname()) - with assert_yields(): + with assert_checkpoints(): server_stream = await listener.accept() assert isinstance(server_stream, SocketStream) assert server_stream.socket.getsockname() == listen_sock.getsockname() assert server_stream.socket.getpeername() == client_sock.getsockname() - with assert_yields(): + with assert_checkpoints(): await listener.aclose() - with assert_yields(): + with assert_checkpoints(): await listener.aclose() - with assert_yields(): + with assert_checkpoints(): with pytest.raises(ClosedListenerError): await listener.accept() @@ -147,7 +147,7 @@ async def test_SocketListener_socket_closed_underfoot(): listen_sock.close() # SocketListener gives correct error - with assert_yields(): + with assert_checkpoints(): with pytest.raises(ClosedListenerError): await listener.accept() @@ -171,7 +171,7 @@ def getpeername(self): pass async def accept(self): - await _core.yield_briefly() + await _core.checkpoint() event = next(self._events) if isinstance(event, BaseException): raise event @@ -201,16 +201,16 @@ def is_trio_socket(self, obj): l = SocketListener(fake_listen_sock) - with assert_yields(): + with assert_checkpoints(): s = await l.accept() assert s.socket is fake_server_sock for code in [errno.EMFILE, errno.EFAULT, errno.ENOBUFS]: - with assert_yields(): + with assert_checkpoints(): with pytest.raises(OSError) as excinfo: await l.accept() assert excinfo.value.errno == code - with assert_yields(): + with assert_checkpoints(): s = await l.accept() assert s.socket is fake_server_sock diff --git a/trio/tests/test_socket.py b/trio/tests/test_socket.py index 8b93356bf6..faeef9c494 100644 --- a/trio/tests/test_socket.py +++ b/trio/tests/test_socket.py @@ -7,7 +7,7 @@ from .. import _core from .. import socket as tsocket from .._socket import _NUMERIC_ONLY, _try_sync, _SocketType -from ..testing import assert_yields, wait_all_tasks_blocked +from ..testing import assert_checkpoints, wait_all_tasks_blocked ################################################################ # utils @@ -53,11 +53,11 @@ def monkeygai(monkeypatch): async def test__try_sync(): - with assert_yields(): + with assert_checkpoints(): async with _try_sync(): pass - with assert_yields(): + with assert_checkpoints(): with pytest.raises(KeyError): async with _try_sync(): raise KeyError @@ -71,7 +71,7 @@ def _is_ValueError(exc): async with _try_sync(_is_ValueError): raise ValueError - with assert_yields(): + with assert_checkpoints(): with pytest.raises(BlockingIOError): async with _try_sync(_is_ValueError): raise BlockingIOError @@ -104,7 +104,7 @@ def without_proto(gai_tup): assert got == expected or got == expected2 # Simple non-blocking non-error cases, ipv4 and ipv6: - with assert_yields(): + with assert_checkpoints(): res = await tsocket.getaddrinfo( "127.0.0.1", "12345", type=tsocket.SOCK_STREAM ) @@ -117,7 +117,7 @@ def without_proto(gai_tup): ("127.0.0.1", 12345)), ]) # yapf: disable - with assert_yields(): + with assert_checkpoints(): res = await tsocket.getaddrinfo( "::1", "12345", type=tsocket.SOCK_DGRAM ) @@ -130,13 +130,13 @@ def without_proto(gai_tup): ]) # yapf: disable monkeygai.set("x", b"host", "port", family=0, type=0, proto=0, flags=0) - with assert_yields(): + with assert_checkpoints(): res = await tsocket.getaddrinfo("host", "port") assert res == "x" assert monkeygai.record[-1] == (b"host", "port", 0, 0, 0, 0) # check raising an error from a non-blocking getaddrinfo - with assert_yields(): + with assert_checkpoints(): with pytest.raises(tsocket.gaierror) as excinfo: await tsocket.getaddrinfo("::1", "12345", type=-1) # Linux, Windows @@ -149,7 +149,7 @@ def without_proto(gai_tup): # check raising an error from a blocking getaddrinfo (exploits the fact # that monkeygai raises if it gets a non-numeric request it hasn't been # given an answer for) - with assert_yields(): + with assert_checkpoints(): with pytest.raises(RuntimeError): await tsocket.getaddrinfo("asdf", "12345") @@ -157,16 +157,16 @@ def without_proto(gai_tup): async def test_getnameinfo(): # Trivial test: ni_numeric = stdlib_socket.NI_NUMERICHOST | stdlib_socket.NI_NUMERICSERV - with assert_yields(): + with assert_checkpoints(): got = await tsocket.getnameinfo(("127.0.0.1", 1234), ni_numeric) assert got == ("127.0.0.1", "1234") # getnameinfo requires a numeric address as input: - with assert_yields(): + with assert_checkpoints(): with pytest.raises(tsocket.gaierror): await tsocket.getnameinfo(("google.com", 80), 0) - with assert_yields(): + with assert_checkpoints(): with pytest.raises(tsocket.gaierror): await tsocket.getnameinfo(("localhost", 80), 0) @@ -378,19 +378,19 @@ async def test_SocketType_simple_server(address, socket_type): async def test_SocketType_resolve(): sock4 = tsocket.socket(family=tsocket.AF_INET) - with assert_yields(): + with assert_checkpoints(): got = await sock4.resolve_local_address((None, 80)) assert got == ("0.0.0.0", 80) - with assert_yields(): + with assert_checkpoints(): got = await sock4.resolve_remote_address((None, 80)) assert got == ("127.0.0.1", 80) sock6 = tsocket.socket(family=tsocket.AF_INET6) - with assert_yields(): + with assert_checkpoints(): got = await sock6.resolve_local_address((None, 80)) assert got == ("::", 80, 0, 0) - with assert_yields(): + with assert_checkpoints(): got = await sock6.resolve_remote_address((None, 80)) assert got == ("::1", 80, 0, 0) @@ -399,11 +399,11 @@ async def test_SocketType_resolve(): for res in ["resolve_local_address", "resolve_remote_address"]: async def s4res(*args): - with assert_yields(): + with assert_checkpoints(): return await getattr(sock4, res)(*args) async def s6res(*args): - with assert_yields(): + with assert_checkpoints(): return await getattr(sock6, res)(*args) assert await s4res(("1.2.3.4", "http")) == ("1.2.3.4", 80) @@ -481,20 +481,20 @@ async def test_SocketType_non_blocking_paths(): b.send(b"1") with _core.open_cancel_scope() as cscope: cscope.cancel() - with assert_yields(): + with assert_checkpoints(): with pytest.raises(_core.Cancelled): await ta.recv(10) # immedate success (also checks that the previous attempt didn't # actually read anything) - with assert_yields(): + with assert_checkpoints(): await ta.recv(10) == b"1" # immediate failure - with assert_yields(): + with assert_checkpoints(): with pytest.raises(TypeError): await ta.recv("haha") # block then succeed async def do_successful_blocking_recv(): - with assert_yields(): + with assert_checkpoints(): assert await ta.recv(10) == b"2" async with _core.open_nursery() as nursery: @@ -503,7 +503,7 @@ async def do_successful_blocking_recv(): b.send(b"2") # block then cancelled async def do_cancelled_blocking_recv(): - with assert_yields(): + with assert_checkpoints(): with pytest.raises(_core.Cancelled): await ta.recv(10) @@ -521,15 +521,15 @@ async def do_cancelled_blocking_recv(): tb = tsocket.from_stdlib_socket(b) async def t1(): - with assert_yields(): + with assert_checkpoints(): assert await ta.recv(1) == b"a" - with assert_yields(): + with assert_checkpoints(): assert await tb.recv(1) == b"b" async def t2(): - with assert_yields(): + with assert_checkpoints(): assert await tb.recv(1) == b"b" - with assert_yields(): + with assert_checkpoints(): assert await ta.recv(1) == b"a" async with _core.open_nursery() as nursery: @@ -546,14 +546,14 @@ async def t2(): # This tests the complicated paths through connect async def test_SocketType_connect_paths(): with tsocket.socket() as sock: - with assert_yields(): + with assert_checkpoints(): with pytest.raises(ValueError): # Should be a tuple await sock.connect("localhost") # cancelled before we start with tsocket.socket() as sock: - with assert_yields(): + with assert_checkpoints(): with _core.open_cancel_scope() as cancel_scope: cancel_scope.cancel() with pytest.raises(_core.Cancelled): @@ -581,14 +581,14 @@ def connect(self, *args, **kwargs): sock._sock.close() sock._sock = CancelSocket() - with assert_yields(): + with assert_checkpoints(): with pytest.raises(_core.Cancelled): await sock.connect(listener.getsockname()) assert sock.fileno() == -1 # Failed connect (hopefully after raising BlockingIOError) with tsocket.socket() as sock: - with assert_yields(): + with assert_checkpoints(): with pytest.raises(OSError): # TCP port 2 is not assigned. Pretty sure nothing will be # listening there. (We used to bind a port and then *not* call diff --git a/trio/tests/test_ssl.py b/trio/tests/test_ssl.py index e28e11873b..c20035259c 100644 --- a/trio/tests/test_ssl.py +++ b/trio/tests/test_ssl.py @@ -25,7 +25,7 @@ from .._core.tests.tutil import slow from ..testing import ( - assert_yields, + assert_checkpoints, Sequencer, memory_stream_pair, lockstep_stream_pair, @@ -202,13 +202,13 @@ def renegotiate(self): async def wait_send_all_might_not_block(self): async with self._send_all_conflict_detector: - await _core.yield_briefly() + await _core.checkpoint() await self.sleeper("wait_send_all_might_not_block") async def send_all(self, data): print(" --> transport_stream.send_all") async with self._send_all_conflict_detector: - await _core.yield_briefly() + await _core.checkpoint() await self.sleeper("send_all") self._conn.bio_write(data) while True: @@ -231,7 +231,7 @@ async def receive_some(self, nbytes): print(" --> transport_stream.receive_some") async with self._receive_some_conflict_detector: try: - await _core.yield_briefly() + await _core.checkpoint() while True: await self.sleeper("receive_some") try: @@ -565,23 +565,23 @@ async def sleeper(_): async def clear(): while s.transport_stream.renegotiate_pending(): - with assert_yields(): + with assert_checkpoints(): await send(b"-") - with assert_yields(): + with assert_checkpoints(): await expect(b"-") print("-- clear --") async def send(byte): await s.transport_stream.sleeper("outer send") print("calling SSLStream.send_all", byte) - with assert_yields(): + with assert_checkpoints(): await s.send_all(byte) async def expect(expected): await s.transport_stream.sleeper("expect") print("calling SSLStream.receive_some, expecting", expected) assert len(expected) == 1 - with assert_yields(): + with assert_checkpoints(): assert await s.receive_some(1) == expected with virtual_ssl_echo_server(sleeper=sleeper) as s: @@ -668,15 +668,15 @@ async def sleeper_with_slow_wait_writable_and_expect(method): async def test_resource_busy_errors(): async def do_send_all(): - with assert_yields(): + with assert_checkpoints(): await s.send_all(b"x") async def do_receive_some(): - with assert_yields(): + with assert_checkpoints(): await s.receive_some(1) async def do_wait_send_all_might_not_block(): - with assert_yields(): + with assert_checkpoints(): await s.wait_send_all_might_not_block() s, _ = ssl_lockstep_stream_pair() @@ -723,30 +723,30 @@ async def wait_send_all_might_not_block(self): async def test_checkpoints(): async with ssl_echo_server() as s: - with assert_yields(): + with assert_checkpoints(): await s.do_handshake() - with assert_yields(): + with assert_checkpoints(): await s.do_handshake() - with assert_yields(): + with assert_checkpoints(): await s.wait_send_all_might_not_block() - with assert_yields(): + with assert_checkpoints(): await s.send_all(b"xxx") - with assert_yields(): + with assert_checkpoints(): await s.receive_some(1) # These receive_some's in theory could return immediately, because the # "xxx" was sent in a single record and after the first # receive_some(1) the rest are sitting inside the SSLObject's internal # buffers. - with assert_yields(): + with assert_checkpoints(): await s.receive_some(1) - with assert_yields(): + with assert_checkpoints(): await s.receive_some(1) - with assert_yields(): + with assert_checkpoints(): await s.unwrap() async with ssl_echo_server() as s: await s.do_handshake() - with assert_yields(): + with assert_checkpoints(): await s.aclose() @@ -756,9 +756,9 @@ async def test_send_all_empty_string(): # underlying SSLObject interprets writing b"" as indicating an EOF, # for some reason. Make sure we don't inherit this. - with assert_yields(): + with assert_checkpoints(): await s.send_all(b"") - with assert_yields(): + with assert_checkpoints(): await s.send_all(b"") await s.send_all(b"x") assert await s.receive_some(1) == b"x" @@ -853,13 +853,13 @@ async def test_closing_nice_case(): # Both the handshake and the close require back-and-forth discussion, so # we need to run them concurrently async def client_closer(): - with assert_yields(): + with assert_checkpoints(): await client_ssl.aclose() async def server_closer(): assert await server_ssl.receive_some(10) == b"" assert await server_ssl.receive_some(10) == b"" - with assert_yields(): + with assert_checkpoints(): await server_ssl.aclose() async with _core.open_nursery() as nursery: @@ -871,27 +871,27 @@ async def server_closer(): await client_transport.send_all(b"123") # once closed, it's OK to close again - with assert_yields(): + with assert_checkpoints(): await client_ssl.aclose() - with assert_yields(): + with assert_checkpoints(): await client_ssl.aclose() # Trying to send more data does not work - with assert_yields(): + with assert_checkpoints(): with pytest.raises(ClosedStreamError): await server_ssl.send_all(b"123") # And once the connection is has been closed *locally*, then instead of # getting empty bytestrings we get a proper error - with assert_yields(): + with assert_checkpoints(): with pytest.raises(ClosedStreamError): await client_ssl.receive_some(10) == b"" - with assert_yields(): + with assert_checkpoints(): with pytest.raises(ClosedStreamError): await client_ssl.unwrap() - with assert_yields(): + with assert_checkpoints(): with pytest.raises(ClosedStreamError): await client_ssl.do_handshake() @@ -900,9 +900,9 @@ async def server_closer(): client_ssl, server_ssl = ssl_memory_stream_pair() async def expect_eof_server(): - with assert_yields(): + with assert_checkpoints(): assert await server_ssl.receive_some(10) == b"" - with assert_yields(): + with assert_checkpoints(): await server_ssl.aclose() async with _core.open_nursery() as nursery: @@ -1094,11 +1094,11 @@ async def bad_hook(): client.transport_stream.send_stream.send_all_hook = bad_hook with pytest.raises(KeyError): - with assert_yields(): + with assert_checkpoints(): await client.do_handshake() with pytest.raises(BrokenStreamError): - with assert_yields(): + with assert_checkpoints(): await client.do_handshake() @@ -1112,7 +1112,7 @@ async def bad_hook(): async def client_side(cancel_scope): with pytest.raises(KeyError): - with assert_yields(): + with assert_checkpoints(): await client.do_handshake() cancel_scope.cancel() @@ -1121,7 +1121,7 @@ async def client_side(cancel_scope): nursery.start_soon(server.do_handshake) with pytest.raises(BrokenStreamError): - with assert_yields(): + with assert_checkpoints(): await client.do_handshake() diff --git a/trio/tests/test_sync.py b/trio/tests/test_sync.py index accc893604..7787d157f4 100644 --- a/trio/tests/test_sync.py +++ b/trio/tests/test_sync.py @@ -1,6 +1,6 @@ import pytest -from ..testing import wait_all_tasks_blocked, assert_yields +from ..testing import wait_all_tasks_blocked, assert_checkpoints from .. import _core from .._timeouts import sleep_forever @@ -14,7 +14,7 @@ async def test_Event(): e.set() assert e.is_set() - with assert_yields(): + with assert_checkpoints(): await e.wait() e.clear() @@ -65,13 +65,13 @@ async def test_CapacityLimiter(): with pytest.raises(RuntimeError): c.acquire_nowait() assert c.borrowed_tokens == 1 - with assert_yields(): + with assert_checkpoints(): with pytest.raises(RuntimeError): await c.acquire() assert c.borrowed_tokens == 1 # We can acquire on behalf of someone else though - with assert_yields(): + with assert_checkpoints(): await c.acquire_on_behalf_of("someone") # But then we've run out of capacity @@ -87,7 +87,7 @@ async def test_CapacityLimiter(): c.release_on_behalf_of("someone") assert c.borrowed_tokens == 0 - with assert_yields(): + with assert_checkpoints(): async with c: assert c.borrowed_tokens == 1 @@ -158,7 +158,7 @@ async def test_Semaphore(): assert s.statistics().tasks_waiting == 0 s.acquire_nowait() assert s.value == 1 - with assert_yields(): + with assert_checkpoints(): await s.acquire() assert s.value == 0 with pytest.raises(_core.WouldBlock): @@ -166,7 +166,7 @@ async def test_Semaphore(): s.release() assert s.value == 1 - with assert_yields(): + with assert_checkpoints(): async with s: assert s.value == 0 assert s.value == 1 @@ -218,7 +218,7 @@ async def test_Lock_and_StrictFIFOLock(lockcls): repr(l) # smoke test # make sure repr uses the right name for subclasses assert lockcls.__name__ in repr(l) - with assert_yields(): + with assert_checkpoints(): async with l: assert l.locked() repr(l) # smoke test (repr branches on locked/unlocked) @@ -227,7 +227,7 @@ async def test_Lock_and_StrictFIFOLock(lockcls): assert l.locked() l.release() assert not l.locked() - with assert_yields(): + with assert_checkpoints(): await l.acquire() assert l.locked() l.release() @@ -291,7 +291,7 @@ async def test_Condition(): c = Condition(l) assert not l.locked() assert not c.locked() - with assert_yields(): + with assert_checkpoints(): await c.acquire() assert l.locked() assert c.locked() @@ -386,7 +386,7 @@ async def test_Queue(): assert not q.empty() assert not q.full() - with assert_yields(): + with assert_checkpoints(): await q.put(2) assert q.qsize() == 2 with pytest.raises(_core.WouldBlock): @@ -395,7 +395,7 @@ async def test_Queue(): assert not q.empty() assert q.full() - with assert_yields(): + with assert_checkpoints(): assert await q.get() == 1 assert q.get_nowait() == 2 with pytest.raises(_core.WouldBlock): @@ -405,7 +405,7 @@ async def test_Queue(): async def test_Queue_join(): q = Queue(2) - with assert_yields(): + with assert_checkpoints(): await q.join() record = [] @@ -617,8 +617,8 @@ async def worker(lock_like): acquires += 1 assert not in_critical_section in_critical_section = True - await _core.yield_briefly() - await _core.yield_briefly() + await _core.checkpoint() + await _core.checkpoint() assert in_critical_section in_critical_section = False diff --git a/trio/tests/test_testing.py b/trio/tests/test_testing.py index 19228509df..af282a56f3 100644 --- a/trio/tests/test_testing.py +++ b/trio/tests/test_testing.py @@ -21,7 +21,7 @@ async def test_wait_all_tasks_blocked(): async def busy_bee(): for _ in range(10): - await _core.yield_briefly() + await _core.checkpoint() record.append("busy bee exhausted") async def waiting_for_bee_to_leave(): @@ -133,40 +133,53 @@ async def do_wait(cushion, tiebreaker): ################################################################ -async def test_assert_yields(): - with assert_yields(): - await _core.yield_briefly() +async def test_assert_checkpoints(recwarn): + with assert_checkpoints(): + await _core.checkpoint() with pytest.raises(AssertionError): - with assert_yields(): + with assert_checkpoints(): 1 + 1 + # partial yield cases + # if you have a schedule point but not a cancel point, or vice-versa, then + # that's not a checkpoint. + for partial_yield in [_core.checkpoint_if_cancelled, + _core.cancel_shielded_checkpoint]: + print(partial_yield) + with pytest.raises(AssertionError): + with assert_checkpoints(): + await partial_yield() + + # But both together count as a checkpoint + with assert_checkpoints(): + await _core.checkpoint_if_cancelled() + await _core.cancel_shielded_checkpoint() + + +async def test_assert_no_yields(recwarn): with assert_no_yields(): 1 + 1 with pytest.raises(AssertionError): with assert_no_yields(): - await _core.yield_briefly() + await _core.checkpoint() # partial yield cases # if you have a schedule point but not a cancel point, or vice-versa, then # that doesn't make *either* version of assert_{no_,}yields happy. - for partial_yield in [_core.yield_if_cancelled, - _core.yield_briefly_no_cancel]: - for block in [assert_yields, assert_no_yields]: - print(partial_yield, block) - with pytest.raises(AssertionError): - with block(): - await partial_yield() - - # But both together count as a checkpoint - with assert_yields(): - await _core.yield_if_cancelled() - await _core.yield_briefly() + for partial_yield in [_core.checkpoint_if_cancelled, + _core.cancel_shielded_checkpoint]: + print(partial_yield) + with pytest.raises(AssertionError): + with assert_no_yields(): + await partial_yield() + + # And both together also count as a checkpoint with pytest.raises(AssertionError): with assert_no_yields(): - await _core.yield_if_cancelled() - await _core.yield_briefly() + await _core.checkpoint_if_cancelled() + await _core.cancel_shielded_checkpoint() ################################################################ @@ -431,13 +444,13 @@ async def test__UnboundeByteQueue(): ubq.put("string") ubq.put(b"abc") - with assert_yields(): + with assert_checkpoints(): assert await ubq.get(10) == b"abc" ubq.put(b"def") ubq.put(b"ghi") - with assert_yields(): + with assert_checkpoints(): assert await ubq.get(1) == b"d" - with assert_yields(): + with assert_checkpoints(): assert await ubq.get() == b"efghi" async def putter(data): @@ -445,7 +458,7 @@ async def putter(data): ubq.put(data) async def getter(expect): - with assert_yields(): + with assert_checkpoints(): assert await ubq.get() == expect async with _core.open_nursery() as nursery: @@ -488,14 +501,14 @@ async def test_MemorySendStream(): mss = MemorySendStream() async def do_send_all(data): - with assert_yields(): + with assert_checkpoints(): await mss.send_all(data) await do_send_all(b"123") assert mss.get_data_nowait(1) == b"1" assert mss.get_data_nowait() == b"23" - with assert_yields(): + with assert_checkpoints(): await mss.wait_send_all_might_not_block() with pytest.raises(_core.WouldBlock): @@ -504,7 +517,7 @@ async def do_send_all(data): mss.get_data_nowait(10) await do_send_all(b"456") - with assert_yields(): + with assert_checkpoints(): assert await mss.get_data() == b"456" with pytest.raises(_core.ResourceBusyError): @@ -512,7 +525,7 @@ async def do_send_all(data): nursery.start_soon(do_send_all, b"xxx") nursery.start_soon(do_send_all, b"xxx") - with assert_yields(): + with assert_checkpoints(): await mss.aclose() assert await mss.get_data() == b"xxx" @@ -566,7 +579,7 @@ async def test_MemoryRecieveStream(): mrs = MemoryReceiveStream() async def do_receive_some(max_bytes): - with assert_yields(): + with assert_checkpoints(): return await mrs.receive_some(max_bytes) mrs.put_data(b"abc") @@ -615,7 +628,7 @@ def close_hook(): assert await mrs2.receive_some(10) == b"zzz" mrs2.put_data(b"lost on close") - with assert_yields(): + with assert_checkpoints(): await mrs2.aclose() assert record == ["closed"] diff --git a/trio/tests/test_threads.py b/trio/tests/test_threads.py index 93c5ab0e41..47e84847d4 100644 --- a/trio/tests/test_threads.py +++ b/trio/tests/test_threads.py @@ -61,7 +61,7 @@ def f(record): async def f(record): assert not _core.currently_ki_protected() - await _core.yield_briefly() + await _core.checkpoint() record.append(("f", threading.current_thread())) return 3 @@ -69,7 +69,7 @@ async def f(record): async def f(record): assert not _core.currently_ki_protected() - await _core.yield_briefly() + await _core.checkpoint() record.append(("f", threading.current_thread())) raise KeyError @@ -145,7 +145,7 @@ def test_await_in_trio_thread_while_main_exits(): async def trio_fn(): record.append("sleeping") ev.set() - await _core.yield_indefinitely(lambda _: _core.Abort.SUCCEEDED) + await _core.wait_task_rescheduled(lambda _: _core.Abort.SUCCEEDED) def thread_fn(await_in_trio_thread): try: @@ -208,8 +208,8 @@ async def child(q, cancellable): async with _core.open_nursery() as nursery: nursery.start_soon(child, q, True) # Give it a chance to get started. (This is important because - # run_sync_in_worker_thread does a yield_if_cancelled before blocking - # on the thread, and we don't want to trigger this.) + # run_sync_in_worker_thread does a checkpoint_if_cancelled before + # blocking on the thread, and we don't want to trigger this.) await wait_all_tasks_blocked() assert record == ["start"] # Then cancel it. @@ -230,7 +230,7 @@ async def child(q, cancellable): nursery.cancel_scope.cancel() with _core.open_cancel_scope(shield=True): for _ in range(10): - await _core.yield_briefly() + await _core.checkpoint() # It's still running assert record == ["start"] q.put(None) diff --git a/trio/tests/test_timeouts.py b/trio/tests/test_timeouts.py index 97a558b6d7..a0d1c53c74 100644 --- a/trio/tests/test_timeouts.py +++ b/trio/tests/test_timeouts.py @@ -2,7 +2,7 @@ import time from .. import _core -from ..testing import assert_yields +from ..testing import assert_checkpoints from .._timeouts import * @@ -36,7 +36,7 @@ async def sleep_2(): with pytest.raises(ValueError): await sleep(-1) - with assert_yields(): + with assert_checkpoints(): await sleep(0) # This also serves as a test of the trivial move_on_at with move_on_at(_core.current_time()): diff --git a/trio/tests/test_util.py b/trio/tests/test_util.py index 6847161dba..b0c273c873 100644 --- a/trio/tests/test_util.py +++ b/trio/tests/test_util.py @@ -8,7 +8,7 @@ from .._util import * from .. import _core -from ..testing import wait_all_tasks_blocked, assert_yields +from ..testing import wait_all_tasks_blocked, assert_checkpoints def test_signal_raise(): @@ -30,13 +30,13 @@ async def test_ConflictDetector(): ul2 = ConflictDetector("ul2") async with ul1: - with assert_yields(): + with assert_checkpoints(): async with ul2: print("ok") with pytest.raises(_core.ResourceBusyError) as excinfo: async with ul1: - with assert_yields(): + with assert_checkpoints(): async with ul1: pass # pragma: no cover assert "ul1" in str(excinfo.value) @@ -54,7 +54,7 @@ async def wait_with_ul1(): # mixing sync and async entry with pytest.raises(_core.ResourceBusyError) as excinfo: with ul1.sync: - with assert_yields(): + with assert_checkpoints(): async with ul1: pass # pragma: no cover assert "ul1" in str(excinfo.value) @@ -169,6 +169,6 @@ def test_module_metadata_is_fixed_up(): assert trio.open_cancel_scope.__module__ == "trio" assert trio.ssl.SSLStream.__module__ == "trio.ssl" assert trio.abc.Stream.__module__ == "trio.abc" - assert trio.hazmat.yield_indefinitely.__module__ == "trio.hazmat" + assert trio.hazmat.wait_task_rescheduled.__module__ == "trio.hazmat" import trio.testing assert trio.testing.trio_test.__module__ == "trio.testing"