diff --git a/.style.yapf b/.style.yapf deleted file mode 100644 index 745ec88d70..0000000000 --- a/.style.yapf +++ /dev/null @@ -1,185 +0,0 @@ -[style] -# Align closing bracket with visual indentation. -align_closing_bracket_with_visual_indent=True - -# Allow dictionary keys to exist on multiple lines. For example: -# -# x = { -# ('this is the first element of a tuple', -# 'this is the second element of a tuple'): -# value, -# } -allow_multiline_dictionary_keys=False - -# Allow lambdas to be formatted on more than one line. -allow_multiline_lambdas=False - -# Insert a blank line before a class-level docstring. -blank_line_before_class_docstring=False - -# Insert a blank line before a 'def' or 'class' immediately nested -# within another 'def' or 'class'. For example: -# -# class Foo: -# # <------ this blank line -# def method(): -# ... -blank_line_before_nested_class_or_def=False - -# Do not split consecutive brackets. Only relevant when -# dedent_closing_brackets is set. For example: -# -# call_func_that_takes_a_dict( -# { -# 'key1': 'value1', -# 'key2': 'value2', -# } -# ) -# -# would reformat to: -# -# call_func_that_takes_a_dict({ -# 'key1': 'value1', -# 'key2': 'value2', -# }) -coalesce_brackets=False - -# The column limit. -column_limit=79 - -# Indent width used for line continuations. -continuation_indent_width=4 - -# Put closing brackets on a separate line, dedented, if the bracketed -# expression can't fit in a single line. Applies to all kinds of brackets, -# including function definitions and calls. For example: -# -# config = { -# 'key1': 'value1', -# 'key2': 'value2', -# } # <--- this bracket is dedented and on a separate line -# -# time_series = self.remote_client.query_entity_counters( -# entity='dev3246.region1', -# key='dns.query_latency_tcp', -# transform=Transformation.AVERAGE(window=timedelta(seconds=60)), -# start_ts=now()-timedelta(days=3), -# end_ts=now(), -# ) # <--- this bracket is dedented and on a separate line -dedent_closing_brackets=True - -# Place each dictionary entry onto its own line. -each_dict_entry_on_separate_line=True - -# The regex for an i18n comment. The presence of this comment stops -# reformatting of that line, because the comments are required to be -# next to the string they translate. -i18n_comment= - -# The i18n function call names. The presence of this function stops -# reformattting on that line, because the string it has cannot be moved -# away from the i18n comment. -i18n_function_call= - -# Indent the dictionary value if it cannot fit on the same line as the -# dictionary key. For example: -# -# config = { -# 'key1': -# 'value1', -# 'key2': value1 + -# value2, -# } -indent_dictionary_value=True - -# The number of columns to use for indentation. -indent_width=4 - -# Join short lines into one line. E.g., single line 'if' statements. -join_multiple_lines=False - -# Use spaces around default or named assigns. -spaces_around_default_or_named_assign=False - -# Use spaces around the power operator. -spaces_around_power_operator=False - -# The number of spaces required before a trailing comment. -spaces_before_comment=2 - -# Insert a space between the ending comma and closing bracket of a list, -# etc. -space_between_ending_comma_and_closing_bracket=False - -# Split before arguments if the argument list is terminated by a -# comma. -split_arguments_when_comma_terminated=True - -# Set to True to prefer splitting before '&', '|' or '^' rather than -# after. -split_before_bitwise_operator=True - -# Split before a dictionary or set generator (comp_for). For example, note -# the split before the 'for': -# -# foo = { -# variable: 'Hello world, have a nice day!' -# for variable in bar if variable != 42 -# } -split_before_dict_set_generator=True - -# If an argument / parameter list is going to be split, then split before -# the first argument. -split_before_first_argument=False - -# Set to True to prefer splitting before 'and' or 'or' rather than -# after. -split_before_logical_operator=True - -# Split named assignments onto individual lines. -split_before_named_assigns=True - -# The penalty for splitting right after the opening bracket. -split_penalty_after_opening_bracket=30 - -# The penalty for splitting the line after a unary operator. -split_penalty_after_unary_operator=10000 - -# The penalty for splitting right before an if expression. -split_penalty_before_if_expr=0 - -# The penalty of splitting the line around the '&', '|', and '^' -# operators. -split_penalty_bitwise_operator=300 - -# The penalty for characters over the column limit. -split_penalty_excess_character=4500 - -# The penalty incurred by adding a line split to the unwrapped line. The -# more line splits added the higher the penalty. -split_penalty_for_added_line_split=30 - -# The penalty of splitting a list of "import as" names. For example: -# -# from a_very_long_or_indented_module_name_yada_yad import (long_argument_1, -# long_argument_2, -# long_argument_3) -# -# would reformat to something like: -# -# from a_very_long_or_indented_module_name_yada_yad import ( -# long_argument_1, long_argument_2, long_argument_3) -split_penalty_import_names=0 - -# The penalty of splitting the line around the 'and' and 'or' -# operators. -split_penalty_logical_operator=0 - -# Use the Tab character for indentation. -use_tabs=False - -# Without this, yapf likes to write things like -# "foo bar {}". -# format(...) -# which is just awful. -split_before_dot=True diff --git a/check.sh b/check.sh index 09a2b8d927..92e4d6d805 100644 --- a/check.sh +++ b/check.sh @@ -5,7 +5,7 @@ set -ex EXIT_STATUS=0 # Autoformatter *first*, to avoid double-reporting errors -yapf -rpd setup.py trio \ +black --diff setup.py trio \ || EXIT_STATUS=$? # Run flake8 without pycodestyle and import-related errors @@ -23,7 +23,7 @@ Problems were found by static analysis (listed above). To fix formatting and see remaining errors, run pip install -r test-requirements.txt - yapf -rpi setup.py trio + black setup.py trio ./check.sh in your local checkout. diff --git a/docs/source/contributing.rst b/docs/source/contributing.rst index 8f7567a3a8..c0ed7aded1 100644 --- a/docs/source/contributing.rst +++ b/docs/source/contributing.rst @@ -130,7 +130,7 @@ in separate sections below: adding a test to make sure it stays fixed. * :ref:`pull-request-formatting`: If you changed Python code, then did - you run ``yapf -rpi setup.py trio``? (Or for other packages, replace + you run ``black setup.py trio``? (Or for other packages, replace ``trio`` with the package name.) * :ref:`pull-request-release-notes`: If your change affects @@ -273,31 +273,27 @@ of eyes can be helpful when trying to come up with devious tricks. Code formatting ~~~~~~~~~~~~~~~ -Instead of wasting time arguing about code formatting, we use `yapf -`__ to automatically format all our +Instead of wasting time arguing about code formatting, we use black` +`__ to automatically format all our code to a standard style. While you're editing code you can be as sloppy as you like about whitespace; and then before you commit, just run:: - pip install -U yapf - yapf -rpi setup.py trio + pip install -U black + black setup.py trio to fix it up. (And don't worry if you forget – when you submit a pull request then we'll automatically check and remind you.) Hopefully this will let you focus on more important style issues like choosing good names, writing useful comments, and making sure your docstrings are -nicely formatted. (Yapf doesn't reformat comments or docstrings.) +nicely formatted. (black doesn't reformat comments or docstrings.) -Very occasionally, yapf will generate really ugly and unreadable -formatting (usually for large literal structures like dicts nested -inside dicts). In these cases, you can add a ``# yapf: disable`` -comment to tell it to leave that particular statement alone. +If you want to see what changes black will make, you can use:: -If you want to see what changes yapf will make, you can use:: + black --diff setup.py trio - yapf -rpd setup.py trio - -(``-d`` displays a diff, versus ``-i`` which fixes files in-place.) +(``--diff`` displays a diff, versus the default mode which fixes files +in-place.) .. _pull-request-release-notes: diff --git a/setup.py b/setup.py index 73ac00ab8e..3096619614 100644 --- a/setup.py +++ b/setup.py @@ -82,7 +82,7 @@ "sniffio", # PEP 508 style, but: # https://bitbucket.org/pypa/wheel/issues/181/bdist_wheel-silently-discards-pep-508 - #"cffi; os_name == 'nt'", # "cffi is required on windows" + # "cffi; os_name == 'nt'", # "cffi is required on windows" ], # This means, just install *everything* you see under trio/, even if it # doesn't look like a source file, so long as it appears in MANIFEST.in: @@ -93,7 +93,7 @@ # recent extras_require={ ":os_name == 'nt'": ["cffi"], # "cffi is required on windows", - ":python_version < '3.7'": ["contextvars>=2.1"] + ":python_version < '3.7'": ["contextvars>=2.1"], }, python_requires=">=3.5", keywords=["async", "io", "networking", "trio"], diff --git a/test-requirements.in b/test-requirements.in index 9f28aec952..c6a69a72c6 100644 --- a/test-requirements.in +++ b/test-requirements.in @@ -9,7 +9,7 @@ pylint # for pylint finding all symbols tests jedi # for jedi code completion tests # Tools -yapf == 0.24.0 # formatting +black;python_version>="3.6" # formatting flake8 # https://github.com/python-trio/trio/pull/654#issuecomment-420518745 diff --git a/test-requirements.txt b/test-requirements.txt index d1dd837219..e23bed85f7 100644 --- a/test-requirements.txt +++ b/test-requirements.txt @@ -4,12 +4,16 @@ # # pip-compile --output-file test-requirements.txt test-requirements.in # +appdirs==1.4.3 # via black +appnope==0.1.0 # via ipython asn1crypto==0.24.0 # via cryptography astroid==2.0.4 # via pylint atomicwrites==1.2.1 # via pytest -attrs==18.2.0 # via pytest +attrs==18.2.0 # via black, pytest backcall==0.1.0 # via ipython +black==18.9b0 ; python_version >= "3.6" cffi==1.11.5 # via cryptography +click==7.0 # via black coverage==4.5.1 # via pytest-cov cryptography==2.3.1 # via pyopenssl, trustme decorator==4.3.0 # via ipython, traitlets @@ -39,9 +43,9 @@ pytest-cov==2.6.0 pytest-faulthandler==1.5.0 pytest==3.10.0 six==1.11.0 # via astroid, cryptography, more-itertools, prompt-toolkit, pyopenssl, pytest, traitlets +toml==0.10.0 # via black traitlets==4.3.2 # via ipython trustme==0.4.0 typed-ast==1.1.0 ; python_version < "3.7" and implementation_name == "cpython" wcwidth==0.1.7 # via prompt-toolkit wrapt==1.10.11 # via astroid -yapf==0.24.0 diff --git a/trio/__init__.py b/trio/__init__.py index e9b6f54448..482f552b4d 100644 --- a/trio/__init__.py +++ b/trio/__init__.py @@ -16,24 +16,49 @@ from ._version import __version__ from ._core import ( - TrioInternalError, RunFinishedError, WouldBlock, Cancelled, - BusyResourceError, ClosedResourceError, MultiError, run, open_nursery, - open_cancel_scope, current_effective_deadline, TASK_STATUS_IGNORED, - current_time, BrokenResourceError, EndOfChannel, NoHandshakeError + TrioInternalError, + RunFinishedError, + WouldBlock, + Cancelled, + BusyResourceError, + ClosedResourceError, + MultiError, + run, + open_nursery, + open_cancel_scope, + current_effective_deadline, + TASK_STATUS_IGNORED, + current_time, + BrokenResourceError, + EndOfChannel, + NoHandshakeError, ) from ._timeouts import ( - move_on_at, move_on_after, sleep_forever, sleep_until, sleep, fail_at, - fail_after, TooSlowError + move_on_at, + move_on_after, + sleep_forever, + sleep_until, + sleep, + fail_at, + fail_after, + TooSlowError, ) from ._sync import ( - Event, CapacityLimiter, Semaphore, Lock, StrictFIFOLock, Condition, Queue + Event, + CapacityLimiter, + Semaphore, + Lock, + StrictFIFOLock, + Condition, + Queue, ) from ._threads import ( - run_sync_in_worker_thread, current_default_worker_thread_limiter, - BlockingTrioPortal + run_sync_in_worker_thread, + current_default_worker_thread_limiter, + BlockingTrioPortal, ) from ._highlevel_generic import aclose_forcefully, StapledStream @@ -57,7 +82,9 @@ from ._highlevel_open_unix_stream import open_unix_socket from ._highlevel_ssl_helpers import ( - open_ssl_over_tcp_stream, open_ssl_over_tcp_listeners, serve_ssl_over_tcp + open_ssl_over_tcp_stream, + open_ssl_over_tcp_listeners, + serve_ssl_over_tcp, ) from ._deprecate import TrioDeprecationWarning @@ -67,37 +94,25 @@ from . import socket from . import abc from . import ssl + # Not imported by default: testing if False: from . import testing _deprecate.enable_attribute_deprecations(__name__) __deprecated_attributes__ = { - "ClosedStreamError": - _deprecate.DeprecatedAttribute( - ClosedResourceError, - "0.5.0", - issue=36, - instead=ClosedResourceError - ), - "ClosedListenerError": - _deprecate.DeprecatedAttribute( - ClosedResourceError, - "0.5.0", - issue=36, - instead=ClosedResourceError - ), - "BrokenStreamError": - _deprecate.DeprecatedAttribute( - BrokenResourceError, - "0.8.0", - issue=620, - instead=BrokenResourceError - ), - "ResourceBusyError": - _deprecate.DeprecatedAttribute( - BusyResourceError, "0.8.0", issue=620, instead=BusyResourceError - ), + "ClosedStreamError": _deprecate.DeprecatedAttribute( + ClosedResourceError, "0.5.0", issue=36, instead=ClosedResourceError + ), + "ClosedListenerError": _deprecate.DeprecatedAttribute( + ClosedResourceError, "0.5.0", issue=36, instead=ClosedResourceError + ), + "BrokenStreamError": _deprecate.DeprecatedAttribute( + BrokenResourceError, "0.8.0", issue=620, instead=BrokenResourceError + ), + "ResourceBusyError": _deprecate.DeprecatedAttribute( + BusyResourceError, "0.8.0", issue=620, instead=BusyResourceError + ), } _deprecate.enable_attribute_deprecations(hazmat.__name__) @@ -107,21 +122,15 @@ from ._core import _result hazmat.__deprecated_attributes__ = { - "Result": - _deprecate.DeprecatedAttribute( - _core._result.Result, - "0.5.0", - issue=494, - instead="outcome.Outcome" - ), - "Value": - _deprecate.DeprecatedAttribute( - _core._result.Value, "0.5.0", issue=494, instead="outcome.Value" - ), - "Error": - _deprecate.DeprecatedAttribute( - _core._result.Error, "0.5.0", issue=494, instead="outcome.Error" - ) + "Result": _deprecate.DeprecatedAttribute( + _core._result.Result, "0.5.0", issue=494, instead="outcome.Outcome" + ), + "Value": _deprecate.DeprecatedAttribute( + _core._result.Value, "0.5.0", issue=494, instead="outcome.Value" + ), + "Error": _deprecate.DeprecatedAttribute( + _core._result.Error, "0.5.0", issue=494, instead="outcome.Error" + ), } # Having the public path in .__module__ attributes is important for: @@ -131,6 +140,7 @@ # - pickle # - probably other stuff from ._util import fixup_module_metadata + fixup_module_metadata(__name__, globals()) fixup_module_metadata(hazmat.__name__, hazmat.__dict__) fixup_module_metadata(socket.__name__, socket.__dict__) diff --git a/trio/_abc.py b/trio/_abc.py index 704622cf50..8bb7fc9a43 100644 --- a/trio/_abc.py +++ b/trio/_abc.py @@ -9,6 +9,7 @@ class Clock(metaclass=ABCMeta): """The interface for custom run loop clocks. """ + __slots__ = () @abstractmethod @@ -63,6 +64,7 @@ class Instrument(metaclass=ABCMeta): of these methods are optional. This class serves mostly as documentation. """ + __slots__ = () def before_run(self): @@ -144,12 +146,11 @@ class HostnameResolver(metaclass=ABCMeta): See :func:`trio.socket.set_custom_hostname_resolver`. """ + __slots__ = () @abstractmethod - async def getaddrinfo( - self, host, port, family=0, type=0, proto=0, flags=0 - ): + async def getaddrinfo(self, host, port, family=0, type=0, proto=0, flags=0): """A custom implementation of :func:`~trio.socket.getaddrinfo`. Called by :func:`trio.socket.getaddrinfo`. @@ -225,6 +226,7 @@ class AsyncResource(metaclass=ABCMeta): ``__aenter__`` and ``__aexit__`` should be adequate for all subclasses. """ + __slots__ = () @abstractmethod @@ -278,6 +280,7 @@ class SendStream(AsyncResource): :class:`SendChannel`. """ + __slots__ = () @abstractmethod @@ -378,6 +381,7 @@ class ReceiveStream(AsyncResource): :class:`ReceiveChannel`. """ + __slots__ = () @abstractmethod @@ -423,6 +427,7 @@ class Stream(SendStream, ReceiveStream): step further and implement :class:`HalfCloseableStream`. """ + __slots__ = () @@ -431,6 +436,7 @@ class HalfCloseableStream(Stream): part of the stream without closing the receive part. """ + __slots__ = () @abstractmethod @@ -491,6 +497,7 @@ class Listener(AsyncResource): or using an ``async with`` block. """ + __slots__ = () @abstractmethod @@ -532,6 +539,7 @@ class SendChannel(AsyncResource): :class:`ReceiveStream`. """ + __slots__ = () @abstractmethod @@ -615,6 +623,7 @@ class ReceiveChannel(AsyncResource): :class:`ReceiveStream`. """ + __slots__ = () @abstractmethod diff --git a/trio/_channel.py b/trio/_channel.py index 87c2714a78..bb718a14ed 100644 --- a/trio/_channel.py +++ b/trio/_channel.py @@ -109,10 +109,8 @@ def __attrs_post_init__(self): self._state.open_send_channels += 1 def __repr__(self): - return ( - "".format( - id(self), id(self._state) - ) + return "".format( + id(self), id(self._state) ) def statistics(self): diff --git a/trio/_core/__init__.py b/trio/_core/__init__.py index 5c7e46c941..5a48dc8f9a 100644 --- a/trio/_core/__init__.py +++ b/trio/_core/__init__.py @@ -15,25 +15,32 @@ def _public(fn): from ._exceptions import ( - TrioInternalError, RunFinishedError, WouldBlock, Cancelled, - BusyResourceError, ClosedResourceError, BrokenResourceError, EndOfChannel, - NoHandshakeError + TrioInternalError, + RunFinishedError, + WouldBlock, + Cancelled, + BusyResourceError, + ClosedResourceError, + BrokenResourceError, + EndOfChannel, + NoHandshakeError, ) from ._multierror import MultiError -from ._ki import ( - enable_ki_protection, disable_ki_protection, currently_ki_protected -) +from ._ki import enable_ki_protection, disable_ki_protection, currently_ki_protected # TODO: make the _run namespace a lot less magical from ._run import * # Has to come after _run to resolve a circular import from ._traps import ( - cancel_shielded_checkpoint, Abort, wait_task_rescheduled, - temporarily_detach_coroutine_object, permanently_detach_coroutine_object, - reattach_detached_coroutine_object + cancel_shielded_checkpoint, + Abort, + wait_task_rescheduled, + temporarily_detach_coroutine_object, + permanently_detach_coroutine_object, + reattach_detached_coroutine_object, ) from ._entry_queue import TrioToken diff --git a/trio/_core/_entry_queue.py b/trio/_core/_entry_queue.py index c562de4474..3585262873 100644 --- a/trio/_core/_entry_queue.py +++ b/trio/_core/_entry_queue.py @@ -191,6 +191,4 @@ def run_sync_soon(self, sync_fn, *args, idempotent=False): exits.) """ - self._reentry_queue.run_sync_soon( - sync_fn, *args, idempotent=idempotent - ) + self._reentry_queue.run_sync_soon(sync_fn, *args, idempotent=idempotent) diff --git a/trio/_core/_exceptions.py b/trio/_core/_exceptions.py index 482c6e2c30..e0317b2ba8 100644 --- a/trio/_core/_exceptions.py +++ b/trio/_core/_exceptions.py @@ -13,6 +13,7 @@ class TrioInternalError(Exception): tasks.) Again, though, this shouldn't happen. """ + pass @@ -21,6 +22,7 @@ class RunFinishedError(RuntimeError): corresponding call to :func:`trio.run` has already finished. """ + pass @@ -28,6 +30,7 @@ class WouldBlock(Exception): """Raised by ``X_nowait`` functions if ``X`` would block. """ + pass @@ -65,14 +68,15 @@ class Cancelled(BaseException): everywhere. """ + _scope = None __marker = object() def __init__(self, _marker=None): if _marker is not self.__marker: raise RuntimeError( - 'Cancelled should not be raised directly. Use the cancel() ' - 'method on your cancel scope.' + "Cancelled should not be raised directly. Use the cancel() " + "method on your cancel scope." ) super().__init__() diff --git a/trio/_core/_io_epoll.py b/trio/_core/_io_epoll.py index 45d8b8c5c5..abb3fd8243 100644 --- a/trio/_core/_io_epoll.py +++ b/trio/_core/_io_epoll.py @@ -98,7 +98,7 @@ def _update_registrations(self, fd, currently_registered): async def _epoll_wait(self, fd, attr_name): if not isinstance(fd, int): fd = fd.fileno() - currently_registered = (fd in self._registered) + currently_registered = fd in self._registered if not currently_registered: self._registered[fd] = EpollWaiters() waiters = self._registered[fd] diff --git a/trio/_core/_io_kqueue.py b/trio/_core/_io_kqueue.py index 4c4ac69879..43b369baa5 100644 --- a/trio/_core/_io_kqueue.py +++ b/trio/_core/_io_kqueue.py @@ -29,10 +29,7 @@ def statistics(self): tasks_waiting += 1 else: monitors += 1 - return _KqueueStatistics( - tasks_waiting=tasks_waiting, - monitors=monitors, - ) + return _KqueueStatistics(tasks_waiting=tasks_waiting, monitors=monitors) def close(self): self._kqueue.close() @@ -83,8 +80,7 @@ def monitor_kevent(self, ident, filter): key = (ident, filter) if key in self._registered: raise _core.BusyResourceError( - "attempt to register multiple listeners for same " - "ident/filter pair" + "attempt to register multiple listeners for same " "ident/filter pair" ) q = _core.UnboundedQueue() self._registered[key] = q @@ -99,8 +95,7 @@ async def wait_kevent(self, ident, filter, abort_func): if key in self._registered: await _core.checkpoint() raise _core.BusyResourceError( - "attempt to register multiple listeners for same " - "ident/filter pair" + "attempt to register multiple listeners for same " "ident/filter pair" ) self._registered[key] = _core.current_task() diff --git a/trio/_core/_io_windows.py b/trio/_core/_io_windows.py index 44d298c469..94165ce26f 100644 --- a/trio/_core/_io_windows.py +++ b/trio/_core/_io_windows.py @@ -118,9 +118,7 @@ def __init__(self): # https://msdn.microsoft.com/en-us/library/windows/desktop/aa363862(v=vs.85).aspx self._closed = True self._iocp = _check( - kernel32.CreateIoCompletionPort( - INVALID_HANDLE_VALUE, ffi.NULL, 0, 0 - ) + kernel32.CreateIoCompletionPort(INVALID_HANDLE_VALUE, ffi.NULL, 0, 0) ) self._closed = False self._iocp_queue = deque() @@ -244,8 +242,7 @@ def do_select(): overlapped = int(ffi.cast("uintptr_t", entry.lpOverlapped)) transferred = entry.dwNumberOfBytesTransferred info = CompletionKeyEventInfo( - lpOverlapped=overlapped, - dwNumberOfBytesTransferred=transferred, + lpOverlapped=overlapped, dwNumberOfBytesTransferred=transferred ) queue.put_nowait(info) @@ -270,7 +267,7 @@ def _iocp_thread_fn(self): try: _check( kernel32.GetQueuedCompletionStatusEx( - self._iocp, batch, max_events, received, 0xffffffff, 0 + self._iocp, batch, max_events, received, 0xFFFFFFFF, 0 ) ) except OSError as exc: @@ -341,8 +338,7 @@ async def _wait_socket(self, which, sock): if sock in self._socket_waiters[which]: await _core.checkpoint() raise _core.BusyResourceError( - "another task is already waiting to {} this socket" - .format(which) + "another task is already waiting to {} this socket".format(which) ) self._socket_waiters[which][sock] = _core.current_task() @@ -367,9 +363,7 @@ def notify_socket_close(self, sock): for mode in ["read", "write"]: if sock in self._socket_waiters[mode]: task = self._socket_waiters[mode].pop(sock) - exc = _core.ClosedResourceError( - "another task closed this socket" - ) + exc = _core.ClosedResourceError("another task closed this socket") _core.reschedule(task, outcome.Error(exc)) # This has cffi-isms in it and is untested... but it demonstrates the diff --git a/trio/_core/_ki.py b/trio/_core/_ki.py index 25788617d5..1a87ba6cf1 100644 --- a/trio/_core/_ki.py +++ b/trio/_core/_ki.py @@ -10,13 +10,10 @@ if False: from typing import Any, TypeVar, Callable - F = TypeVar('F', bound=Callable[..., Any]) -__all__ = [ - "enable_ki_protection", - "disable_ki_protection", - "currently_ki_protected", -] + F = TypeVar("F", bound=Callable[..., Any]) + +__all__ = ["enable_ki_protection", "disable_ki_protection", "currently_ki_protected"] # In ordinary single-threaded Python code, when you hit control-C, it raises # an exception and automatically does all the regular unwinding stuff. @@ -83,7 +80,7 @@ # We use this special string as a unique key into the frame locals dictionary. # The @ ensures it is not a valid identifier and can't clash with any possible # real local name. See: https://github.com/python-trio/trio/issues/469 -LOCALS_KEY_KI_PROTECTION_ENABLED = '@TRIO_KI_PROTECTION_ENABLED' +LOCALS_KEY_KI_PROTECTION_ENABLED = "@TRIO_KI_PROTECTION_ENABLED" # NB: according to the signal.signal docs, 'frame' can be None on entry to @@ -123,8 +120,7 @@ def decorator(fn): def wrapper(*args, **kwargs): # See the comment for regular generators below coro = fn(*args, **kwargs) - coro.cr_frame.f_locals[LOCALS_KEY_KI_PROTECTION_ENABLED - ] = enabled + coro.cr_frame.f_locals[LOCALS_KEY_KI_PROTECTION_ENABLED] = enabled return coro return wrapper @@ -141,8 +137,7 @@ def wrapper(*args, **kwargs): # thrown into! See: # https://bugs.python.org/issue29590 gen = fn(*args, **kwargs) - gen.gi_frame.f_locals[LOCALS_KEY_KI_PROTECTION_ENABLED - ] = enabled + gen.gi_frame.f_locals[LOCALS_KEY_KI_PROTECTION_ENABLED] = enabled return gen return wrapper @@ -152,8 +147,7 @@ def wrapper(*args, **kwargs): def wrapper(*args, **kwargs): # See the comment for regular generators above agen = fn(*args, **kwargs) - agen.ag_frame.f_locals[LOCALS_KEY_KI_PROTECTION_ENABLED - ] = enabled + agen.ag_frame.f_locals[LOCALS_KEY_KI_PROTECTION_ENABLED] = enabled return agen return wrapper @@ -172,9 +166,7 @@ def wrapper(*args, **kwargs): enable_ki_protection = _ki_protection_decorator(True) # type: Callable[[F], F] enable_ki_protection.__name__ = "enable_ki_protection" -disable_ki_protection = _ki_protection_decorator( - False -) # type: Callable[[F], F] +disable_ki_protection = _ki_protection_decorator(False) # type: Callable[[F], F] disable_ki_protection.__name__ = "disable_ki_protection" diff --git a/trio/_core/_local.py b/trio/_core/_local.py index 777273600f..ddfa6d3424 100644 --- a/trio/_core/_local.py +++ b/trio/_core/_local.py @@ -40,8 +40,7 @@ def get(self, default=_NO_DEFAULT): try: return _run.GLOBAL_RUN_CONTEXT.runner._locals[self] except AttributeError: - raise RuntimeError("Cannot be used outside of a run context") \ - from None + raise RuntimeError("Cannot be used outside of a run context") from None except KeyError: # contextvars consistency if default is not self._NO_DEFAULT: @@ -95,4 +94,4 @@ def reset(self, token): token.redeemed = True def __repr__(self): - return ("".format(self._name)) + return "".format(self._name) diff --git a/trio/_core/_multierror.py b/trio/_core/_multierror.py index 960bc4ebfa..20311499f6 100644 --- a/trio/_core/_multierror.py +++ b/trio/_core/_multierror.py @@ -173,9 +173,7 @@ def __new__(cls, exceptions): exceptions = list(exceptions) for exc in exceptions: if not isinstance(exc, BaseException): - raise TypeError( - "Expected an exception object, not {!r}".format(exc) - ) + raise TypeError("Expected an exception object, not {!r}".format(exc)) if len(exceptions) == 1: return exceptions[0] else: @@ -260,16 +258,20 @@ def controller(operation): # no missing test we could add, and no value in coverage nagging # us about adding one. if operation.opname in [ - "__getattribute__", "__getattr__" + "__getattribute__", + "__getattr__", ]: # pragma: no cover if operation.args[0] == "tb_next": return tb_next return operation.delegate() return tputil.make_proxy(controller, type(base_tb), base_tb) + + else: # ctypes it is import ctypes + # How to handle refcounting? I don't want to use ctypes.py_object because # I don't understand or trust it, and I don't want to use # ctypes.pythonapi.Py_{Inc,Dec}Ref because we might clash with user code @@ -368,7 +370,7 @@ def traceback_exception_init( limit=limit, lookup_lines=lookup_lines, capture_locals=capture_locals, - _seen=_seen + _seen=_seen, ) # Capture each of the exceptions in the MultiError along with each of their causes and contexts @@ -384,7 +386,7 @@ def traceback_exception_init( capture_locals=capture_locals, # copy the set of _seen exceptions so that duplicates # shared between sub-exceptions are not omitted - _seen=set(_seen) + _seen=set(_seen), ) ) self.embedded = embedded @@ -401,9 +403,7 @@ def traceback_exception_format(self, *, chain=True): for i, exc in enumerate(self.embedded): yield "\nDetails of embedded exception {}:\n\n".format(i + 1) - yield from ( - textwrap.indent(line, " " * 2) for line in exc.format(chain=chain) - ) + yield from (textwrap.indent(line, " " * 2) for line in exc.format(chain=chain)) traceback.TracebackException.format = traceback_exception_format @@ -418,6 +418,7 @@ def trio_excepthook(etype, value, tb): warning_given = False if "IPython" in sys.modules: import IPython + ip = IPython.get_ipython() if ip is not None: if ip.custom_exceptions != (): @@ -426,7 +427,7 @@ def trio_excepthook(etype, value, tb): "handler installed. I'll skip installing trio's custom " "handler, but this means MultiErrors will not show full " "tracebacks.", - category=RuntimeWarning + category=RuntimeWarning, ) warning_given = True else: @@ -447,5 +448,5 @@ def trio_show_traceback(self, etype, value, tb, tb_offset=None): "You seem to already have a custom sys.excepthook handler " "installed. I'll skip installing trio's custom handler, but this " "means MultiErrors will not show full tracebacks.", - category=RuntimeWarning + category=RuntimeWarning, ) diff --git a/trio/_core/_result.py b/trio/_core/_result.py index 30b916ff0d..9a87747cf7 100644 --- a/trio/_core/_result.py +++ b/trio/_core/_result.py @@ -7,16 +7,12 @@ class Result(outcome.Outcome): @classmethod - @_deprecate.deprecated( - version="0.5.0", issue=494, instead="outcome.capture" - ) + @_deprecate.deprecated(version="0.5.0", issue=494, instead="outcome.capture") def capture(cls, sync_fn, *args): return outcome.capture(sync_fn, *args) @classmethod - @_deprecate.deprecated( - version="0.5.0", issue=494, instead="outcome.acapture" - ) + @_deprecate.deprecated(version="0.5.0", issue=494, instead="outcome.acapture") async def acapture(cls, async_fn, *args): return await outcome.acapture(async_fn, *args) diff --git a/trio/_core/_run.py b/trio/_core/_run.py index d6dc92841f..8b233d122f 100644 --- a/trio/_core/_run.py +++ b/trio/_core/_run.py @@ -22,10 +22,8 @@ from . import _public from ._entry_queue import EntryQueue, TrioToken -from ._exceptions import (TrioInternalError, RunFinishedError, Cancelled) -from ._ki import ( - LOCALS_KEY_KI_PROTECTION_ENABLED, ki_manager, enable_ki_protection -) +from ._exceptions import TrioInternalError, RunFinishedError, Cancelled +from ._ki import LOCALS_KEY_KI_PROTECTION_ENABLED, ki_manager, enable_ki_protection from ._multierror import MultiError from ._traps import ( Abort, @@ -41,9 +39,15 @@ # __all__. These are all re-exported as part of the 'trio' or 'trio.hazmat' # namespaces. __all__ = [ - "Task", "run", "open_nursery", "open_cancel_scope", "checkpoint", - "current_task", "current_effective_deadline", "checkpoint_if_cancelled", - "TASK_STATUS_IGNORED" + "Task", + "run", + "open_nursery", + "open_cancel_scope", + "checkpoint", + "current_task", + "current_effective_deadline", + "checkpoint_if_cancelled", + "TASK_STATUS_IGNORED", ] GLOBAL_RUN_CONTEXT = threading.local() @@ -292,9 +296,7 @@ def __repr__(self): def started(self, value=None): if self._called_started: - raise RuntimeError( - "called 'started' twice on the same task status" - ) + raise RuntimeError("called 'started' twice on the same task status") self._called_started = True self._value = value @@ -329,12 +331,12 @@ def started(self, value=None): task._parent_nursery = self._new_nursery self._new_nursery._children.add(task) # Everyone needs their cancel scopes fixed up... - assert task._cancel_stack[:len(old_stack)] == old_stack - task._cancel_stack[:len(old_stack)] = new_stack + assert task._cancel_stack[: len(old_stack)] == old_stack + task._cancel_stack[: len(old_stack)] = new_stack # ...and their nurseries' cancel scopes fixed up. for nursery in task._child_nurseries: - assert nursery._cancel_stack[:len(old_stack)] == old_stack - nursery._cancel_stack[:len(old_stack)] = new_stack + assert nursery._cancel_stack[: len(old_stack)] == old_stack + nursery._cancel_stack[: len(old_stack)] = new_stack # And then add all the nursery's children to our todo list todo.extend(nursery._children) # And make a note to check for cancellation later @@ -455,9 +457,7 @@ def _add_exc(self, exc): self.cancel_scope.cancel() def _check_nursery_closed(self): - if not any( - [self._nested_child_running, self._children, self._pending_starts] - ): + if not any([self._nested_child_running, self._children, self._pending_starts]): self._closed = True if self._parent_waiting_in_aexit: self._parent_waiting_in_aexit = False @@ -518,9 +518,7 @@ async def start(self, async_fn, *args, name=None): # normally. The complicated logic is all in _TaskStatus.started(). # (Any exceptions propagate directly out of the above.) if not task_status._called_started: - raise RuntimeError( - "child exited without calling task_status.started()" - ) + raise RuntimeError("child exited without calling task_status.started()") return task_status._value finally: self._pending_starts -= 1 @@ -576,7 +574,7 @@ class Task: _schedule_points = attr.ib(default=0) def __repr__(self): - return ("".format(self.name, id(self))) + return "".format(self.name, id(self)) @property def parent_nursery(self): @@ -852,8 +850,9 @@ def _return_value_looks_like_wrong_library(value): "Instead, you want (notice the parentheses!):\n" "\n" " trio.run({async_fn.__name__}, ...) # correct!\n" - " nursery.start_soon({async_fn.__name__}, ...) # correct!" - .format(async_fn=async_fn) + " nursery.start_soon({async_fn.__name__}, ...) # correct!".format( + async_fn=async_fn + ) ) from None # Give good error for: nursery.start_soon(future) @@ -862,8 +861,7 @@ def _return_value_looks_like_wrong_library(value): "trio was expecting an async function, but instead it got " "{!r} – are you trying to use a library written for " "asyncio/twisted/tornado or similar? That won't work " - "without some sort of compatibility shim." - .format(async_fn) + "without some sort of compatibility shim.".format(async_fn) ) from None raise @@ -878,8 +876,9 @@ def _return_value_looks_like_wrong_library(value): raise TypeError( "start_soon got unexpected {!r} – are you trying to use a " "library written for asyncio/twisted/tornado or similar? " - "That won't work without some sort of compatibility shim." - .format(coro) + "That won't work without some sort of compatibility shim.".format( + coro + ) ) if isasyncgen(coro): @@ -891,9 +890,7 @@ def _return_value_looks_like_wrong_library(value): # Give good error for: nursery.start_soon(some_sync_fn) raise TypeError( "trio expected an async function, but {!r} appears to be " - "synchronous".format( - getattr(async_fn, "__qualname__", async_fn) - ) + "synchronous".format(getattr(async_fn, "__qualname__", async_fn)) ) ###### @@ -916,16 +913,10 @@ def _return_value_looks_like_wrong_library(value): context = copy_context() task = Task( - coro=coro, - parent_nursery=nursery, - runner=self, - name=name, - context=context, + coro=coro, parent_nursery=nursery, runner=self, name=name, context=context ) self.tasks.add(task) - coro.cr_frame.f_locals.setdefault( - LOCALS_KEY_KI_PROTECTION_ENABLED, system_task - ) + coro.cr_frame.f_locals.setdefault(LOCALS_KEY_KI_PROTECTION_ENABLED, system_task) if nursery is not None: nursery._children.add(task) @@ -1015,9 +1006,7 @@ async def init(self, async_fn, args): async with open_nursery() as system_nursery: self.system_nursery = system_nursery try: - self.main_task = self.spawn_impl( - async_fn, args, system_nursery, None - ) + self.main_task = self.spawn_impl(async_fn, args, system_nursery, None) except BaseException as exc: self.main_task_outcome = Error(exc) system_nursery.cancel_scope.cancel() @@ -1166,7 +1155,9 @@ def instrument(self, method_name, *args): self.instruments.remove(instrument) INSTRUMENT_LOGGER.exception( "Exception raised when calling %r on instrument %r. " - "Instrument has been disabled.", method_name, instrument + "Instrument has been disabled.", + method_name, + instrument, ) @_public @@ -1314,9 +1305,7 @@ def run( # where KeyboardInterrupt would be allowed and converted into an # TrioInternalError: try: - with ki_manager( - runner.deliver_ki, restrict_keyboard_interrupt_to_checkpoints - ): + with ki_manager(runner.deliver_ki, restrict_keyboard_interrupt_to_checkpoints): try: with closing(runner): # The main reason this is split off into its own function @@ -1356,11 +1345,7 @@ def run_impl(runner, async_fn, args): runner.instrument("before_run") runner.clock.start_clock() runner.init_task = runner.spawn_impl( - runner.init, - (async_fn, args), - None, - "", - system_task=True, + runner.init, (async_fn, args), None, "", system_task=True ) # You know how people talk about "event loops"? This 'while' loop right @@ -1607,9 +1592,8 @@ async def checkpoint_if_cancelled(): """ task = current_task() - if ( - task._pending_cancel_scope() is not None or - (task is task._runner.main_task and task._runner.ki_pending) + if task._pending_cancel_scope() is not None or ( + task is task._runner.main_task and task._runner.ki_pending ): await _core.checkpoint() assert False # pragma: no cover @@ -1635,10 +1619,8 @@ def _generate_method_wrappers(cls, path_to_instance): # it. exec() is a bit ugly but the resulting code is faster and # simpler than doing some loop over getattr. ns = { - "GLOBAL_RUN_CONTEXT": - GLOBAL_RUN_CONTEXT, - "LOCALS_KEY_KI_PROTECTION_ENABLED": - LOCALS_KEY_KI_PROTECTION_ENABLED + "GLOBAL_RUN_CONTEXT": GLOBAL_RUN_CONTEXT, + "LOCALS_KEY_KI_PROTECTION_ENABLED": LOCALS_KEY_KI_PROTECTION_ENABLED, } exec(_WRAPPER_TEMPLATE.format(path_to_instance, methname), ns) wrapper = ns["wrapper"] @@ -1646,9 +1628,11 @@ def _generate_method_wrappers(cls, path_to_instance): # function has the same API as the *bound* version of the # method. So create a dummy bound method object: from types import MethodType + bound_fn = MethodType(fn, object()) # Then set exported function's metadata to match it: from functools import update_wrapper + update_wrapper(wrapper, bound_fn) # And finally export it: globals()[methname] = wrapper diff --git a/trio/_core/_traps.py b/trio/_core/_traps.py index c51cd252ea..9379645694 100644 --- a/trio/_core/_traps.py +++ b/trio/_core/_traps.py @@ -54,6 +54,7 @@ class Abort(enum.Enum): FAILED """ + SUCCEEDED = 1 FAILED = 2 diff --git a/trio/_core/_unbounded_queue.py b/trio/_core/_unbounded_queue.py index 57ea47d5ed..2b398b4879 100644 --- a/trio/_core/_unbounded_queue.py +++ b/trio/_core/_unbounded_queue.py @@ -48,7 +48,7 @@ class UnboundedQueue: "0.9.0", issue=497, thing="trio.hazmat.UnboundedQueue", - instead="trio.open_memory_channel(math.inf)" + instead="trio.open_memory_channel(math.inf)", ) def __init__(self): self._lot = _core.ParkingLot() @@ -144,8 +144,7 @@ def statistics(self): """ return _UnboundedQueueStats( - qsize=len(self._data), - tasks_waiting=self._lot.statistics().tasks_waiting + qsize=len(self._data), tasks_waiting=self._lot.statistics().tasks_waiting ) @aiter_compat diff --git a/trio/_core/_wakeup_socketpair.py b/trio/_core/_wakeup_socketpair.py index 9010898bda..0239d380ff 100644 --- a/trio/_core/_wakeup_socketpair.py +++ b/trio/_core/_wakeup_socketpair.py @@ -21,9 +21,7 @@ def __init__(self): # On Windows this is a TCP socket so this might matter. On other # platforms this fails b/c AF_UNIX sockets aren't actually TCP. try: - self.write_sock.setsockopt( - socket.IPPROTO_TCP, socket.TCP_NODELAY, 1 - ) + self.write_sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) except OSError: pass @@ -40,7 +38,7 @@ async def wait_woken(self): def drain(self): try: while True: - self.wakeup_sock.recv(2**16) + self.wakeup_sock.recv(2 ** 16) except BlockingIOError: pass diff --git a/trio/_core/tests/test_io.py b/trio/_core/tests/test_io.py index 797e3500a9..4691195526 100644 --- a/trio/_core/tests/test_io.py +++ b/trio/_core/tests/test_io.py @@ -59,7 +59,9 @@ def fileno_wrapper(fileobj): assert _core.notify_socket_close is _core.notify_fd_close for options_list in [ - wait_readable_options, wait_writable_options, notify_close_options + wait_readable_options, + wait_writable_options, + notify_close_options, ]: options_list += [using_fileno(f) for f in options_list] @@ -204,9 +206,7 @@ async def writer(): @read_socket_test @write_socket_test -async def test_socket_simultaneous_read_write( - socketpair, wait_readable, wait_writable -): +async def test_socket_simultaneous_read_write(socketpair, wait_readable, wait_writable): record = [] async def r_task(sock): @@ -234,9 +234,7 @@ async def w_task(sock): @read_socket_test @write_socket_test -async def test_socket_actual_streaming( - socketpair, wait_readable, wait_writable -): +async def test_socket_actual_streaming(socketpair, wait_readable, wait_writable): a, b = socketpair # Use a small send buffer on one of the sockets to increase the chance of diff --git a/trio/_core/tests/test_ki.py b/trio/_core/tests/test_ki.py index 6c95325735..6d4dd1947d 100644 --- a/trio/_core/tests/test_ki.py +++ b/trio/_core/tests/test_ki.py @@ -8,7 +8,10 @@ import time from async_generator import ( - async_generator, yield_, isasyncgenfunction, asynccontextmanager + async_generator, + yield_, + isasyncgenfunction, + asynccontextmanager, ) from ... import _core @@ -107,6 +110,7 @@ async def unprotected(): async def child(expected): import traceback + traceback.print_stack() assert _core.currently_ki_protected() == expected await _core.checkpoint() @@ -228,9 +232,7 @@ 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.wait_task_rescheduled( - lambda _: _core.Abort.SUCCEEDED - ) + await _core.wait_task_rescheduled(lambda _: _core.Abort.SUCCEEDED) except _core.Cancelled: record.add((name + " cancel ok")) @@ -257,9 +259,7 @@ async def check_protected_kill(): async with _core.open_nursery() as nursery: nursery.start_soon(sleeper, "s1", record) nursery.start_soon(sleeper, "s2", record) - nursery.start_soon( - _core.enable_ki_protection(raiser), "r1", record - ) + nursery.start_soon(_core.enable_ki_protection(raiser), "r1", record) # __aexit__ blocks, and then receives the KI with pytest.raises(KeyboardInterrupt): @@ -456,9 +456,7 @@ def test_ki_with_broken_threads(): @_core.enable_ki_protection async def inner(): - assert signal.getsignal( - signal.SIGINT - ) != signal.default_int_handler + assert signal.getsignal(signal.SIGINT) != signal.default_int_handler _core.run(inner) finally: @@ -513,8 +511,10 @@ def test_ki_wakes_us_up(): # https://bugs.python.org/issue31119 # https://bitbucket.org/pypy/pypy/issues/2623 import platform + buggy_wakeup_fd = ( - os.name == "nt" and platform.python_implementation() == "CPython" + os.name == "nt" + and platform.python_implementation() == "CPython" and sys.version_info < (3, 6, 2) ) diff --git a/trio/_core/tests/test_multierror.py b/trio/_core/tests/test_multierror.py index 29b912c7fd..98932efe95 100644 --- a/trio/_core/tests/test_multierror.py +++ b/trio/_core/tests/test_multierror.py @@ -169,9 +169,9 @@ def simple_filter(exc): assert isinstance(orig.exceptions[0].exceptions[1], KeyError) # get original traceback summary orig_extracted = ( - extract_tb(orig.__traceback__) + extract_tb( - orig.exceptions[0].__traceback__ - ) + extract_tb(orig.exceptions[0].exceptions[1].__traceback__) + extract_tb(orig.__traceback__) + + extract_tb(orig.exceptions[0].__traceback__) + + extract_tb(orig.exceptions[0].exceptions[1].__traceback__) ) def p(exc): @@ -424,7 +424,7 @@ def einfo(exc): r"in raiser3", r"NameError", ], - formatted + formatted, ) # Prints duplicate exceptions in sub-exceptions @@ -485,7 +485,7 @@ def raise2_raiser1(): r"in raise2_raiser1", r" KeyError: 'bar'", ], - formatted + formatted, ) @@ -501,15 +501,14 @@ def test_logging(caplog): except MultiError as exc: logging.getLogger().exception(message) # Join lines together - formatted = "".join( - format_exception(type(exc), exc, exc.__traceback__) - ) + formatted = "".join(format_exception(type(exc), exc, exc.__traceback__)) assert message in caplog.text assert formatted in caplog.text def run_script(name, use_ipython=False): import trio + trio_path = Path(trio.__file__).parent.parent script_path = Path(__file__).parent / "test_multierror_scripts" / name @@ -532,7 +531,7 @@ def run_script(name, use_ipython=False): "IPython", # no startup files "--quick", - "--TerminalIPythonApp.code_to_run=" + '\n'.join(lines), + "--TerminalIPythonApp.code_to_run=" + "\n".join(lines), ] else: cmd = [sys.executable, "-u", str(script_path)] @@ -556,7 +555,8 @@ def check_simple_excepthook(completed): "Details of embedded exception 2", "in exc2_fn", "KeyError", - ], completed.stdout.decode("utf-8") + ], + completed.stdout.decode("utf-8"), ) @@ -579,7 +579,7 @@ def test_custom_excepthook(): # The MultiError "MultiError:", ], - completed.stdout.decode("utf-8") + completed.stdout.decode("utf-8"), ) @@ -624,7 +624,7 @@ def test_ipython_custom_exc_handler(): "ValueError", "KeyError", ], - completed.stdout.decode("utf-8") + completed.stdout.decode("utf-8"), ) # Make sure our other warning doesn't show up assert "custom sys.excepthook" not in completed.stdout.decode("utf-8") diff --git a/trio/_core/tests/test_multierror_scripts/ipython_custom_exc.py b/trio/_core/tests/test_multierror_scripts/ipython_custom_exc.py index 59a447d32a..4ce067694b 100644 --- a/trio/_core/tests/test_multierror_scripts/ipython_custom_exc.py +++ b/trio/_core/tests/test_multierror_scripts/ipython_custom_exc.py @@ -14,6 +14,7 @@ def custom_excepthook(*args): sys.excepthook = custom_excepthook import IPython + ip = IPython.get_ipython() diff --git a/trio/_core/tests/test_parking_lot.py b/trio/_core/tests/test_parking_lot.py index de6de63081..30a4f28fcb 100644 --- a/trio/_core/tests/test_parking_lot.py +++ b/trio/_core/tests/test_parking_lot.py @@ -32,10 +32,7 @@ async def waiter(i, lot): assert len(record) == 6 check_sequence_matches( - record, [ - {"sleep 0", "sleep 1", "sleep 2"}, - {"wake 0", "wake 1", "wake 2"}, - ] + record, [{"sleep 0", "sleep 1", "sleep 2"}, {"wake 0", "wake 1", "wake 2"}] ) async with _core.open_nursery() as nursery: @@ -48,14 +45,7 @@ async def waiter(i, lot): lot.unpark() await wait_all_tasks_blocked() # 1-by-1 wakeups are strict FIFO - assert record == [ - "sleep 0", - "sleep 1", - "sleep 2", - "wake 0", - "wake 1", - "wake 2", - ] + assert record == ["sleep 0", "sleep 1", "sleep 2", "wake 0", "wake 1", "wake 2"] # It's legal (but a no-op) to try and unpark while there's nothing parked lot.unpark() @@ -71,12 +61,7 @@ async def waiter(i, lot): lot.unpark(count=2) await wait_all_tasks_blocked() check_sequence_matches( - record, [ - "sleep 0", - "sleep 1", - "sleep 2", - {"wake 0", "wake 1"}, - ] + record, ["sleep 0", "sleep 1", "sleep 2", {"wake 0", "wake 1"}] ) lot.unpark_all() @@ -115,13 +100,7 @@ async def test_parking_lot_cancel(): assert len(record) == 6 check_sequence_matches( - record, [ - "sleep 1", - "sleep 2", - "sleep 3", - "cancelled 2", - {"wake 1", "wake 3"}, - ] + record, ["sleep 1", "sleep 2", "sleep 3", "cancelled 2", {"wake 1", "wake 3"}] ) @@ -159,14 +138,17 @@ async def test_parking_lot_repark(): scopes[2].cancel() await wait_all_tasks_blocked() assert len(lot2) == 1 - assert record == [ - "sleep 1", "sleep 2", "sleep 3", "wake 1", "cancelled 2" - ] + assert record == ["sleep 1", "sleep 2", "sleep 3", "wake 1", "cancelled 2"] lot2.unpark_all() await wait_all_tasks_blocked() assert record == [ - "sleep 1", "sleep 2", "sleep 3", "wake 1", "cancelled 2", "wake 3" + "sleep 1", + "sleep 2", + "sleep 3", + "wake 1", + "cancelled 2", + "wake 3", ] @@ -192,11 +174,5 @@ async def test_parking_lot_repark_with_count(): while lot2: lot2.unpark() await wait_all_tasks_blocked() - assert record == [ - "sleep 1", - "sleep 2", - "sleep 3", - "wake 1", - "wake 2", - ] + assert record == ["sleep 1", "sleep 2", "sleep 3", "wake 1", "wake 2"] lot1.unpark_all() diff --git a/trio/_core/tests/test_run.py b/trio/_core/tests/test_run.py index c959fff558..4bbd868515 100644 --- a/trio/_core/tests/test_run.py +++ b/trio/_core/tests/test_run.py @@ -19,11 +19,7 @@ from ... import _core from ..._timeouts import sleep from ..._util import aiter_compat -from ...testing import ( - wait_all_tasks_blocked, - Sequencer, - assert_checkpoints, -) +from ...testing import wait_all_tasks_blocked, Sequencer, assert_checkpoints # slightly different from _timeouts.sleep_forever because it returns the value @@ -42,9 +38,7 @@ async def sleep_forever(): @contextmanager def ignore_coroutine_never_awaited_warnings(): with warnings.catch_warnings(): - warnings.filterwarnings( - "ignore", message="coroutine '.*' was never awaited" - ) + warnings.filterwarnings("ignore", message="coroutine '.*' was never awaited") try: yield finally: @@ -144,8 +138,7 @@ async def looper(whoami, record): nursery.start_soon(looper, "b", record) check_sequence_matches( - record, - [{("a", 0), ("b", 0)}, {("a", 1), ("b", 1)}, {("a", 2), ("b", 2)}] + record, [{("a", 0), ("b", 0)}, {("a", 1), ("b", 1)}, {("a", 2), ("b", 2)}] ) @@ -189,8 +182,7 @@ async def main(): with pytest.raises(_core.MultiError) as excinfo: _core.run(main) print(excinfo.value) - assert set(type(exc) - for exc in excinfo.value.exceptions) == {ValueError, KeyError} + assert set(type(exc) for exc in excinfo.value.exceptions) == {ValueError, KeyError} def test_two_child_crashes(): @@ -204,8 +196,7 @@ async def main(): with pytest.raises(_core.MultiError) as excinfo: _core.run(main) - assert set(type(exc) - for exc in excinfo.value.exceptions) == {ValueError, KeyError} + assert set(type(exc) for exc in excinfo.value.exceptions) == {ValueError, KeyError} async def test_child_crash_wakes_parent(): @@ -408,10 +399,9 @@ async def main(): # It sleeps 5 times, so it runs 6 times expected = ( - [("before_run",)] + - 6 * [("schedule", task), - ("before", task), - ("after", task)] + [("after_run",)] + [("before_run",)] + + 6 * [("schedule", task), ("before", task), ("after", task)] + + [("after_run",)] ) assert len(r1.record) > len(r2.record) > len(r3.record) assert r1.record == r2.record + r3.record @@ -445,7 +435,7 @@ async def main(): ("before", tasks["t1"]), ("after", tasks["t1"]), ("before", tasks["t2"]), - ("after", tasks["t2"]) + ("after", tasks["t2"]), }, { ("schedule", tasks["t1"]), @@ -453,10 +443,10 @@ async def main(): ("after", tasks["t1"]), ("schedule", tasks["t2"]), ("before", tasks["t2"]), - ("after", tasks["t2"]) + ("after", tasks["t2"]), }, ("after_run",), - ] # yapf: disable + ] print(list(r.filter_tasks(tasks.values()))) check_sequence_matches(list(r.filter_tasks(tasks.values())), expected) @@ -1078,9 +1068,14 @@ async def child2(): nursery.start_soon(child2) assert record == [ - "child1 raise", "child1 sleep", "child2 wake", "child2 sleep again", - "child1 re-raise", "child1 success", "child2 re-raise", - "child2 success" + "child1 raise", + "child1 sleep", + "child2 wake", + "child2 sleep again", + "child1 re-raise", + "child1 success", + "child2 re-raise", + "child2 success", ] @@ -1210,10 +1205,7 @@ def cb(x): for i in range(100): token.run_sync_soon(cb, i, idempotent=True) await wait_all_tasks_blocked() - if ( - sys.version_info < (3, 6) - and platform.python_implementation() == "CPython" - ): + if sys.version_info < (3, 6) and platform.python_implementation() == "CPython": # no order guarantees record.sort() # Otherwise, we guarantee FIFO @@ -1610,6 +1602,7 @@ async def async_gen(arg): # pragma: no cover def test_calling_asyncio_function_gives_nice_error(): async def misguided(): import asyncio + await asyncio.Future() with pytest.raises(TypeError) as excinfo: @@ -1637,7 +1630,8 @@ async def test_trivial_yields(): raise KeyError assert len(excinfo.value.exceptions) == 2 assert set(type(e) for e in excinfo.value.exceptions) == { - KeyError, _core.Cancelled + KeyError, + _core.Cancelled, } @@ -1650,9 +1644,7 @@ async def no_args(): # pragma: no cover with pytest.raises(TypeError): await nursery.start(no_args) - async def sleep_then_start( - seconds, *, task_status=_core.TASK_STATUS_IGNORED - ): + async def sleep_then_start(seconds, *, task_status=_core.TASK_STATUS_IGNORED): repr(task_status) # smoke test await sleep(seconds) task_status.started(seconds) @@ -1716,9 +1708,7 @@ async def just_started(task_status=_core.TASK_STATUS_IGNORED): # and if after the no-op started(), the child crashes, the error comes out # of start() - async def raise_keyerror_after_started( - task_status=_core.TASK_STATUS_IGNORED - ): + async def raise_keyerror_after_started(task_status=_core.TASK_STATUS_IGNORED): task_status.started() raise KeyError("whoopsiedaisy") @@ -1727,9 +1717,7 @@ async def raise_keyerror_after_started( cs.cancel() with pytest.raises(_core.MultiError) as excinfo: await nursery.start(raise_keyerror_after_started) - assert set(type(e) for e in excinfo.value.exceptions) == { - _core.Cancelled, KeyError - } + assert set(type(e) for e in excinfo.value.exceptions) == {_core.Cancelled, KeyError} # trying to start in a closed nursery raises an error immediately async with _core.open_nursery() as closed_nursery: @@ -1870,9 +1858,7 @@ def __aiter__(self): async def __anext__(self): nexts = self.nexts - items = [ - None, - ] * len(nexts) + items = [None] * len(nexts) got_stop = False def handle(exc): @@ -1962,7 +1948,7 @@ async def t2(): def test_system_task_contexts(): - cvar = contextvars.ContextVar('qwilfish') + cvar = contextvars.ContextVar("qwilfish") cvar.set("water") async def system_task(): @@ -1983,7 +1969,7 @@ async def inner(): def test_Cancelled_init(): check_Cancelled_error = pytest.raises( - RuntimeError, match='should not be raised directly' + RuntimeError, match="should not be raised directly" ) with check_Cancelled_error: @@ -2037,9 +2023,7 @@ async def detachable_coroutine(task_outcome, yield_value): await async_yield(yield_value) async with _core.open_nursery() as nursery: - nursery.start_soon( - detachable_coroutine, outcome.Value(None), "I'm free!" - ) + nursery.start_soon(detachable_coroutine, outcome.Value(None), "I'm free!") # If we get here then Trio thinks the task has exited... but the coroutine # is still iterable @@ -2054,9 +2038,7 @@ async def detachable_coroutine(task_outcome, yield_value): pdco_outcome = None with pytest.raises(KeyError): async with _core.open_nursery() as nursery: - nursery.start_soon( - detachable_coroutine, outcome.Error(KeyError()), "uh oh" - ) + nursery.start_soon(detachable_coroutine, outcome.Error(KeyError()), "uh oh") throw_in = ValueError() assert task.coro.throw(throw_in) == "uh oh" assert pdco_outcome == outcome.Error(throw_in) @@ -2066,9 +2048,7 @@ async def detachable_coroutine(task_outcome, yield_value): async def bad_detach(): async with _core.open_nursery(): with pytest.raises(RuntimeError) as excinfo: - await _core.permanently_detach_coroutine_object( - outcome.Value(None) - ) + await _core.permanently_detach_coroutine_object(outcome.Value(None)) assert "open nurser" in str(excinfo.value) async with _core.open_nursery() as nursery: @@ -2099,9 +2079,7 @@ def abort_fn(_): # pragma: no cover await async_yield(2) with pytest.raises(RuntimeError) as excinfo: - await _core.reattach_detached_coroutine_object( - unrelated_task, None - ) + await _core.reattach_detached_coroutine_object(unrelated_task, None) assert "does not match" in str(excinfo.value) await _core.reattach_detached_coroutine_object(task, "byebye") diff --git a/trio/_core/tests/test_windows.py b/trio/_core/tests/test_windows.py index 18436c7704..e18eb3b96b 100644 --- a/trio/_core/tests/test_windows.py +++ b/trio/_core/tests/test_windows.py @@ -2,11 +2,12 @@ import pytest -on_windows = (os.name == "nt") +on_windows = os.name == "nt" # Mark all the tests in this file as being windows-only pytestmark = pytest.mark.skipif(not on_windows, reason="windows only") from ... import _core + if on_windows: from .._windows_cffi import ffi, kernel32 @@ -14,9 +15,7 @@ # The undocumented API that this is testing should be changed to stop using # UnboundedQueue (or just removed until we have time to redo it), but until # then we filter out the warning. -@pytest.mark.filterwarnings( - "ignore:.*UnboundedQueue:trio.TrioDeprecationWarning" -) +@pytest.mark.filterwarnings("ignore:.*UnboundedQueue:trio.TrioDeprecationWarning") async def test_completion_key_listen(): async def post(key): iocp = ffi.cast("HANDLE", _core.current_iocp()) @@ -24,9 +23,7 @@ async def post(key): print("post", i) if i % 3 == 0: await _core.checkpoint() - success = kernel32.PostQueuedCompletionStatus( - iocp, i, key, ffi.NULL - ) + success = kernel32.PostQueuedCompletionStatus(iocp, i, key, ffi.NULL) assert success with _core.monitor_completion_key() as (key, queue): diff --git a/trio/_core/tests/tutil.py b/trio/_core/tests/tutil.py index bbf758c0eb..d49062e88b 100644 --- a/trio/_core/tests/tutil.py +++ b/trio/_core/tests/tutil.py @@ -15,7 +15,7 @@ with stdlib_socket.socket( stdlib_socket.AF_INET6, stdlib_socket.SOCK_STREAM, 0 ) as s: - s.bind(('::1', 0)) + s.bind(("::1", 0)) have_ipv6 = True except OSError: have_ipv6 = False @@ -44,6 +44,6 @@ def check_sequence_matches(seq, template): for pattern in template: if not isinstance(pattern, set): pattern = {pattern} - got = set(seq[i:i + len(pattern)]) + got = set(seq[i : i + len(pattern)]) assert got == pattern i += len(got) diff --git a/trio/_deprecate.py b/trio/_deprecate.py index 8f7fc56118..e680182645 100644 --- a/trio/_deprecate.py +++ b/trio/_deprecate.py @@ -117,9 +117,7 @@ def __getattr__(self, name): if instead is DeprecatedAttribute._not_set: instead = info.value thing = "{}.{}".format(self.__name__, name) - warn_deprecated( - thing, info.version, issue=info.issue, instead=instead - ) + warn_deprecated(thing, info.version, issue=info.issue, instead=instead) return info.value raise AttributeError(name) diff --git a/trio/_file_io.py b/trio/_file_io.py index e0cc01c36e..001adeb9b0 100644 --- a/trio/_file_io.py +++ b/trio/_file_io.py @@ -6,47 +6,47 @@ from .abc import AsyncResource from ._util import aiter_compat, async_wraps, fspath -__all__ = ['open_file', 'wrap_file'] +__all__ = ["open_file", "wrap_file"] # This list is also in the docs, make sure to keep them in sync _FILE_SYNC_ATTRS = { - 'closed', - 'encoding', - 'errors', - 'fileno', - 'isatty', - 'newlines', - 'readable', - 'seekable', - 'writable', + "closed", + "encoding", + "errors", + "fileno", + "isatty", + "newlines", + "readable", + "seekable", + "writable", # not defined in *IOBase: - 'buffer', - 'raw', - 'line_buffering', - 'closefd', - 'name', - 'mode', - 'getvalue', - 'getbuffer', + "buffer", + "raw", + "line_buffering", + "closefd", + "name", + "mode", + "getvalue", + "getbuffer", } # This list is also in the docs, make sure to keep them in sync _FILE_ASYNC_METHODS = { - 'flush', - 'read', - 'read1', - 'readall', - 'readinto', - 'readline', - 'readlines', - 'seek', - 'tell', - 'truncate', - 'write', - 'writelines', + "flush", + "read", + "read1", + "readall", + "readinto", + "readline", + "readlines", + "seek", + "tell", + "truncate", + "write", + "writelines", # not defined in *IOBase: - 'readinto1', - 'peek', + "readinto1", + "peek", } @@ -91,9 +91,7 @@ async def wrapper(*args, **kwargs): def __dir__(self): attrs = set(super().__dir__()) attrs.update(a for a in _FILE_SYNC_ATTRS if hasattr(self.wrapped, a)) - attrs.update( - a for a in _FILE_ASYNC_METHODS if hasattr(self.wrapped, a) - ) + attrs.update(a for a in _FILE_ASYNC_METHODS if hasattr(self.wrapped, a)) return attrs @aiter_compat @@ -135,13 +133,13 @@ async def aclose(self): async def open_file( file, - mode='r', + mode="r", buffering=-1, encoding=None, errors=None, newline=None, closefd=True, - opener=None + opener=None, ): """Asynchronous version of :func:`io.open`. @@ -166,8 +164,7 @@ async def open_file( _file = wrap_file( await trio.run_sync_in_worker_thread( - io.open, file, mode, buffering, encoding, errors, newline, closefd, - opener + io.open, file, mode, buffering, encoding, errors, newline, closefd, opener ) ) return _file @@ -194,10 +191,10 @@ def wrap_file(file): def has(attr): return hasattr(file, attr) and callable(getattr(file, attr)) - if not (has('close') and (has('read') or has('write'))): + if not (has("close") and (has("read") or has("write"))): raise TypeError( - '{} does not implement required duck-file methods: ' - 'close and (read or write)'.format(file) + "{} does not implement required duck-file methods: " + "close and (read or write)".format(file) ) return AsyncIOWrapper(file) diff --git a/trio/_highlevel_generic.py b/trio/_highlevel_generic.py index 3a0aa51814..e0a835253c 100644 --- a/trio/_highlevel_generic.py +++ b/trio/_highlevel_generic.py @@ -69,6 +69,7 @@ class StapledStream(HalfCloseableStream): is delegated to this object. """ + send_stream = attr.ib() receive_stream = attr.ib() diff --git a/trio/_highlevel_open_tcp_listeners.py b/trio/_highlevel_open_tcp_listeners.py index 99da6a1eac..3b31a64023 100644 --- a/trio/_highlevel_open_tcp_listeners.py +++ b/trio/_highlevel_open_tcp_listeners.py @@ -40,7 +40,7 @@ def _compute_backlog(backlog): # Many systems (Linux, BSDs, ...) store the backlog in a uint16 and are # missing overflow protection, so we apply our own overflow protection. # https://github.com/golang/go/issues/5030 - return min(backlog, 0xffff) + return min(backlog, 0xFFFF) async def open_tcp_listeners(port, *, host=None, backlog=None): @@ -93,10 +93,7 @@ async def open_tcp_listeners(port, *, host=None, backlog=None): backlog = _compute_backlog(backlog) addresses = await tsocket.getaddrinfo( - host, - port, - type=tsocket.SOCK_STREAM, - flags=tsocket.AI_PASSIVE, + host, port, type=tsocket.SOCK_STREAM, flags=tsocket.AI_PASSIVE ) listeners = [] @@ -106,18 +103,12 @@ async def open_tcp_listeners(port, *, host=None, backlog=None): try: # See https://github.com/python-trio/trio/issues/39 if sys.platform == "win32": - sock.setsockopt( - tsocket.SOL_SOCKET, tsocket.SO_EXCLUSIVEADDRUSE, 1 - ) + sock.setsockopt(tsocket.SOL_SOCKET, tsocket.SO_EXCLUSIVEADDRUSE, 1) else: - sock.setsockopt( - tsocket.SOL_SOCKET, tsocket.SO_REUSEADDR, 1 - ) + sock.setsockopt(tsocket.SOL_SOCKET, tsocket.SO_REUSEADDR, 1) if family == tsocket.AF_INET6: - sock.setsockopt( - tsocket.IPPROTO_IPV6, tsocket.IPV6_V6ONLY, 1 - ) + sock.setsockopt(tsocket.IPPROTO_IPV6, tsocket.IPV6_V6ONLY, 1) await sock.bind(sockaddr) sock.listen(backlog) @@ -208,8 +199,5 @@ async def serve_tcp( """ listeners = await trio.open_tcp_listeners(port, host=host, backlog=backlog) await trio.serve_listeners( - handler, - listeners, - handler_nursery=handler_nursery, - task_status=task_status + handler, listeners, handler_nursery=handler_nursery, task_status=task_status ) diff --git a/trio/_highlevel_open_unix_stream.py b/trio/_highlevel_open_unix_stream.py index 522ddb7104..4216bdacc8 100644 --- a/trio/_highlevel_open_unix_stream.py +++ b/trio/_highlevel_open_unix_stream.py @@ -4,6 +4,7 @@ try: from trio.socket import AF_UNIX + has_unix = True except ImportError: has_unix = False diff --git a/trio/_highlevel_serve_listeners.py b/trio/_highlevel_serve_listeners.py index 958624a6f4..4c8a3315dc 100644 --- a/trio/_highlevel_serve_listeners.py +++ b/trio/_highlevel_serve_listeners.py @@ -8,12 +8,7 @@ # Errors that accept(2) can return, and which indicate that the system is # overloaded -ACCEPT_CAPACITY_ERRNOS = { - errno.EMFILE, - errno.ENFILE, - errno.ENOMEM, - errno.ENOBUFS, -} +ACCEPT_CAPACITY_ERRNOS = {errno.EMFILE, errno.ENFILE, errno.ENOMEM, errno.ENOBUFS} # How long to sleep when we get one of those errors SLEEP_TIME = 0.100 @@ -41,7 +36,7 @@ async def _serve_one_listener(listener, handler_nursery, handler): errno.errorcode[exc.errno], os.strerror(exc.errno), SLEEP_TIME, - exc_info=True + exc_info=True, ) await trio.sleep(SLEEP_TIME) else: @@ -51,11 +46,7 @@ async def _serve_one_listener(listener, handler_nursery, handler): async def serve_listeners( - handler, - listeners, - *, - handler_nursery=None, - task_status=trio.TASK_STATUS_IGNORED + handler, listeners, *, handler_nursery=None, task_status=trio.TASK_STATUS_IGNORED ): r"""Listen for incoming connections on ``listeners``, and for each one start a task running ``handler(stream)``. @@ -120,9 +111,7 @@ async def serve_listeners( if handler_nursery is None: handler_nursery = nursery for listener in listeners: - nursery.start_soon( - _serve_one_listener, listener, handler_nursery, handler - ) + nursery.start_soon(_serve_one_listener, listener, handler_nursery, handler) # The listeners are already queueing connections when we're called, # but we wait until the end to call started() just in case we get an # error or whatever. diff --git a/trio/_highlevel_socket.py b/trio/_highlevel_socket.py index fef9762203..8f131ecddf 100644 --- a/trio/_highlevel_socket.py +++ b/trio/_highlevel_socket.py @@ -24,9 +24,7 @@ def _translate_socket_errors_to_stream_errors(): yield except OSError as exc: if exc.errno in _closed_stream_errnos: - raise _core.ClosedResourceError( - "this socket was already closed" - ) from None + raise _core.ClosedResourceError("this socket was already closed") from None else: raise _core.BrokenResourceError( "socket connection broken: {}".format(exc) @@ -87,18 +85,14 @@ def __init__(self, socket): # http://devstreaming.apple.com/videos/wwdc/2015/719ui2k57m/719/719_your_app_and_next_generation_networks.pdf?dl=1 # ). The theory is that you want it to be bandwidth * # rescheduling interval. - self.setsockopt( - tsocket.IPPROTO_TCP, tsocket.TCP_NOTSENT_LOWAT, 2**14 - ) + self.setsockopt(tsocket.IPPROTO_TCP, tsocket.TCP_NOTSENT_LOWAT, 2 ** 14) except OSError: pass async def send_all(self, data): if self.socket.did_shutdown_SHUT_WR: await _core.checkpoint() - raise _core.ClosedResourceError( - "can't send data after sending EOF" - ) + raise _core.ClosedResourceError("can't send data after sending EOF") with self._send_conflict_detector.sync: with _translate_socket_errors_to_stream_errors(): with memoryview(data) as data: @@ -337,9 +331,7 @@ def __init__(self, socket): if socket.type != tsocket.SOCK_STREAM: raise ValueError("SocketListener requires a SOCK_STREAM socket") try: - listening = socket.getsockopt( - tsocket.SOL_SOCKET, tsocket.SO_ACCEPTCONN - ) + listening = socket.getsockopt(tsocket.SOL_SOCKET, tsocket.SO_ACCEPTCONN) except OSError: # SO_ACCEPTCONN fails on macOS; we just have to trust the user. pass diff --git a/trio/_highlevel_ssl_helpers.py b/trio/_highlevel_ssl_helpers.py index 1d7b80d708..dcbc0b5f3c 100644 --- a/trio/_highlevel_ssl_helpers.py +++ b/trio/_highlevel_ssl_helpers.py @@ -3,8 +3,9 @@ from ._highlevel_open_tcp_stream import DEFAULT_DELAY __all__ = [ - "open_ssl_over_tcp_stream", "open_ssl_over_tcp_listeners", - "serve_ssl_over_tcp" + "open_ssl_over_tcp_stream", + "open_ssl_over_tcp_listeners", + "serve_ssl_over_tcp", ] @@ -57,17 +58,12 @@ async def open_ssl_over_tcp_stream( """ tcp_stream = await trio.open_tcp_stream( - host, - port, - happy_eyeballs_delay=happy_eyeballs_delay, + host, port, happy_eyeballs_delay=happy_eyeballs_delay ) if ssl_context is None: ssl_context = trio.ssl.create_default_context() return trio.ssl.SSLStream( - tcp_stream, - ssl_context, - server_hostname=host, - https_compatible=https_compatible, + tcp_stream, ssl_context, server_hostname=host, https_compatible=https_compatible ) @@ -86,15 +82,12 @@ async def open_ssl_over_tcp_listeners( backlog (int or None): See :class:`~trio.ssl.SSLStream` for details. """ - tcp_listeners = await trio.open_tcp_listeners( - port, host=host, backlog=backlog - ) + tcp_listeners = await trio.open_tcp_listeners(port, host=host, backlog=backlog) ssl_listeners = [ trio.ssl.SSLListener( - tcp_listener, - ssl_context, - https_compatible=https_compatible, - ) for tcp_listener in tcp_listeners + tcp_listener, ssl_context, https_compatible=https_compatible + ) + for tcp_listener in tcp_listeners ] return ssl_listeners @@ -158,15 +151,8 @@ async def serve_ssl_over_tcp( """ listeners = await trio.open_ssl_over_tcp_listeners( - port, - ssl_context, - host=host, - https_compatible=https_compatible, - backlog=backlog + port, ssl_context, host=host, https_compatible=https_compatible, backlog=backlog ) await trio.serve_listeners( - handler, - listeners, - handler_nursery=handler_nursery, - task_status=task_status + handler, listeners, handler_nursery=handler_nursery, task_status=task_status ) diff --git a/trio/_path.py b/trio/_path.py index abaf9f7ee0..699b2da4f6 100644 --- a/trio/_path.py +++ b/trio/_path.py @@ -6,7 +6,7 @@ import trio from trio._util import async_wraps, fspath -__all__ = ['Path'] +__all__ = ["Path"] # python3.5 compat: __fspath__ does not exist in 3.5, so unwrap any trio.Path @@ -77,7 +77,7 @@ def __init__(cls, name, bases, attrs): def generate_forwards(cls, attrs): # forward functions of _forwards for attr_name, attr in cls._forwards.__dict__.items(): - if attr_name.startswith('_') or attr_name in attrs: + if attr_name.startswith("_") or attr_name in attrs: continue if isinstance(attr, property): @@ -91,7 +91,7 @@ def generate_forwards(cls, attrs): def generate_wraps(cls, attrs): # generate wrappers for functions of _wraps for attr_name, attr in cls._wraps.__dict__.items(): - if attr_name.startswith('_') or attr_name in attrs: + if attr_name.startswith("_") or attr_name in attrs: continue if isinstance(attr, classmethod): @@ -119,8 +119,15 @@ class Path(metaclass=AsyncAutoWrapperType): _wraps = pathlib.Path _forwards = pathlib.PurePath _forward_magic = [ - '__str__', '__bytes__', '__truediv__', '__rtruediv__', '__eq__', - '__lt__', '__le__', '__gt__', '__ge__' + "__str__", + "__bytes__", + "__truediv__", + "__rtruediv__", + "__eq__", + "__lt__", + "__le__", + "__gt__", + "__ge__", ] def __init__(self, *args): @@ -160,7 +167,7 @@ def __dir__(self): return super().__dir__() + self._forward def __repr__(self): - return 'trio.Path({})'.format(repr(str(self))) + return "trio.Path({})".format(repr(str(self))) def __fspath__(self): return fspath(self._wrapped) @@ -183,5 +190,5 @@ async def open(self, *args, **kwargs): del Path.absolute.__doc__ # python3.5 compat -if hasattr(os, 'PathLike'): +if hasattr(os, "PathLike"): os.PathLike.register(Path) diff --git a/trio/_signals.py b/trio/_signals.py index 3b910a92d1..eef7532914 100644 --- a/trio/_signals.py +++ b/trio/_signals.py @@ -4,9 +4,7 @@ from . import _core from ._sync import Event -from ._util import ( - signal_raise, aiter_compat, is_main_thread, ConflictDetector -) +from ._util import signal_raise, aiter_compat, is_main_thread, ConflictDetector from ._deprecate import deprecated __all__ = ["open_signal_receiver", "catch_signals"] @@ -177,7 +175,7 @@ def __aiter__(self): return self async def __anext__(self): - return { await self._signal_queue.__anext__()} + return {await self._signal_queue.__anext__()} @deprecated("0.7.0", issue=354, instead=open_signal_receiver) diff --git a/trio/_socket.py b/trio/_socket.py index cb0475611f..116bffac28 100644 --- a/trio/_socket.py +++ b/trio/_socket.py @@ -150,8 +150,10 @@ async def getaddrinfo(host, port, family=0, type=0, proto=0, flags=0): # with the _NUMERIC_ONLY flags set, and then only spawn a thread if that # fails with EAI_NONAME: def numeric_only_failure(exc): - return isinstance(exc, _stdlib_socket.gaierror) and \ - exc.errno == _stdlib_socket.EAI_NONAME + return ( + isinstance(exc, _stdlib_socket.gaierror) + and exc.errno == _stdlib_socket.EAI_NONAME + ) async with _try_sync(numeric_only_failure): return _stdlib_socket.getaddrinfo( @@ -185,7 +187,7 @@ def numeric_only_failure(exc): type, proto, flags, - cancellable=True + cancellable=True, ) @@ -262,10 +264,7 @@ def socketpair(*args, **kwargs): @_wraps(_stdlib_socket.socket, assigned=(), updated=()) def socket( - family=_stdlib_socket.AF_INET, - type=_stdlib_socket.SOCK_STREAM, - proto=0, - fileno=None + family=_stdlib_socket.AF_INET, type=_stdlib_socket.SOCK_STREAM, proto=0, fileno=None ): """Create a new trio socket, like :func:`socket.socket`. @@ -314,10 +313,10 @@ def _make_simple_sock_method_wrapper(methname, wait_fn, maybe_avail=False): async def wrapper(self, *args, **kwargs): return await self._nonblocking_helper(fn, args, kwargs, wait_fn) - wrapper.__doc__ = ( - """Like :meth:`socket.socket.{}`, but async. + wrapper.__doc__ = """Like :meth:`socket.socket.{}`, but async. - """.format(methname) + """.format( + methname ) if maybe_avail: wrapper.__doc__ += ( @@ -427,7 +426,8 @@ async def bind(self, address): address = await self._resolve_local_address(address) if ( hasattr(_stdlib_socket, "AF_UNIX") - and self.family == _stdlib_socket.AF_UNIX and address[0] + and self.family == _stdlib_socket.AF_UNIX + and address[0] ): # Use a thread for the filesystem traversal (unless it's an # abstract domain socket) @@ -466,8 +466,7 @@ async def _resolve_address(self, address, flags): if not isinstance(address, tuple) or not 2 <= len(address) <= 4: await _core.checkpoint() raise ValueError( - "address should be a (host, port, [flowinfo, [scopeid]]) " - "tuple" + "address should be a (host, port, [flowinfo, [scopeid]]) " "tuple" ) elif self._sock.family == _stdlib_socket.AF_UNIX: await _core.checkpoint() @@ -491,9 +490,7 @@ async def _resolve_address(self, address, flags): # no ipv6. # flags |= AI_ADDRCONFIG if self._sock.family == _stdlib_socket.AF_INET6: - if not self._sock.getsockopt( - IPPROTO_IPV6, _stdlib_socket.IPV6_V6ONLY - ): + if not self._sock.getsockopt(IPPROTO_IPV6, _stdlib_socket.IPV6_V6ONLY): flags |= _stdlib_socket.AI_V4MAPPED gai_res = await getaddrinfo( host, port, self._sock.family, self.type, self._sock.proto, flags @@ -559,9 +556,7 @@ async def _nonblocking_helper(self, fn, args, kwargs, wait_fn): # accept ################################################################ - _accept = _make_simple_sock_method_wrapper( - "accept", _core.wait_socket_readable - ) + _accept = _make_simple_sock_method_wrapper("accept", _core.wait_socket_readable) async def accept(self): """Like :meth:`socket.socket.accept`, but async. @@ -640,9 +635,7 @@ async def connect(self, address): self._sock.close() raise # Okay, the connect finished, but it might have failed: - err = self._sock.getsockopt( - _stdlib_socket.SOL_SOCKET, _stdlib_socket.SO_ERROR - ) + err = self._sock.getsockopt(_stdlib_socket.SOL_SOCKET, _stdlib_socket.SO_ERROR) if err != 0: raise OSError(err, "Error in connect: " + _os.strerror(err)) @@ -664,9 +657,7 @@ async def connect(self, address): # recvfrom ################################################################ - recvfrom = _make_simple_sock_method_wrapper( - "recvfrom", _core.wait_socket_readable - ) + recvfrom = _make_simple_sock_method_wrapper("recvfrom", _core.wait_socket_readable) ################################################################ # recvfrom_into @@ -737,8 +728,7 @@ async def sendmsg(self, *args): args = list(args) args[-1] = await self._resolve_remote_address(args[-1]) return await self._nonblocking_helper( - _stdlib_socket.socket.sendmsg, args, {}, - _core.wait_socket_writable + _stdlib_socket.socket.sendmsg, args, {}, _core.wait_socket_writable ) ################################################################ diff --git a/trio/_ssl.py b/trio/_ssl.py index 6183f70732..a62bbed84f 100644 --- a/trio/_ssl.py +++ b/trio/_ssl.py @@ -366,7 +366,7 @@ def __init__( self._incoming, self._outgoing, server_side=server_side, - server_hostname=server_hostname + server_hostname=server_hostname, ) # Tracks whether we've already done the initial handshake self._handshook = _Once(self._do_handshake) @@ -477,9 +477,7 @@ async def _retry(self, fn, *args, ignore_want_read=False): ret = fn(*args) except _stdlib_ssl.SSLWantReadError: want_read = True - except ( - _stdlib_ssl.SSLError, _stdlib_ssl.CertificateError - ) as exc: + except (_stdlib_ssl.SSLError, _stdlib_ssl.CertificateError) as exc: self._state = _State.BROKEN raise _core.BrokenResourceError from exc else: @@ -652,11 +650,9 @@ async def receive_some(self, max_bytes): # For some reason, EOF before handshake sometimes raises # SSLSyscallError instead of SSLEOFError (e.g. on my linux # laptop, but not on appveyor). Thanks openssl. - if ( - self._https_compatible and isinstance( - exc.__cause__, - (_stdlib_ssl.SSLEOFError, _stdlib_ssl.SSLSyscallError) - ) + if self._https_compatible and isinstance( + exc.__cause__, + (_stdlib_ssl.SSLEOFError, _stdlib_ssl.SSLSyscallError), ): return b"" else: @@ -672,9 +668,8 @@ async def receive_some(self, max_bytes): # BROKEN. But that's actually fine, because after getting an # EOF on TLS then the only thing you can do is close the # stream, and closing doesn't care about the state. - if ( - self._https_compatible - and isinstance(exc.__cause__, _stdlib_ssl.SSLEOFError) + if self._https_compatible and isinstance( + exc.__cause__, _stdlib_ssl.SSLEOFError ): return b"" else: @@ -718,8 +713,7 @@ async def unwrap(self): ``transport_stream.receive_some(...)``. """ - async with self._outer_recv_conflict_detector, \ - self._outer_send_conflict_detector: + async with self._outer_recv_conflict_detector, self._outer_send_conflict_detector: self._check_status() await self._handshook.ensure(checkpoint=False) await self._retry(self._ssl_object.unwrap) @@ -802,9 +796,7 @@ async def aclose(self): # going to be able to do a clean shutdown. If that happens, we'll # just do an unclean shutdown. try: - await self._retry( - self._ssl_object.unwrap, ignore_want_read=True - ) + await self._retry(self._ssl_object.unwrap, ignore_want_read=True) except (_core.BrokenResourceError, _core.BusyResourceError): pass except: diff --git a/trio/_subprocess/linux_waitpid.py b/trio/_subprocess/linux_waitpid.py index b9319865ec..f7a99835e8 100644 --- a/trio/_subprocess/linux_waitpid.py +++ b/trio/_subprocess/linux_waitpid.py @@ -26,9 +26,7 @@ async def _task(state: WaitpidState) -> None: """The waitpid thread runner task. This must be spawned as a system task.""" partial = functools.partial( - os.waitpid, # function - state.pid, # pid - 0 # no options + os.waitpid, state.pid, 0 # function # pid # no options ) tresult = await run_sync_in_worker_thread( diff --git a/trio/_subprocess/unix_pipes.py b/trio/_subprocess/unix_pipes.py index 7d7c94891e..a53e8db8c0 100644 --- a/trio/_subprocess/unix_pipes.py +++ b/trio/_subprocess/unix_pipes.py @@ -11,9 +11,7 @@ class _PipeMixin: def __init__(self, pipefd: int) -> None: if not isinstance(pipefd, int): - raise TypeError( - "{0.__class__.__name__} needs a pipe fd".format(self) - ) + raise TypeError("{0.__class__.__name__} needs a pipe fd".format(self)) self._pipe = pipefd self._closed = False diff --git a/trio/_sync.py b/trio/_sync.py index ab475b9471..5614c1b4ed 100644 --- a/trio/_sync.py +++ b/trio/_sync.py @@ -176,11 +176,8 @@ def __init__(self, total_tokens): assert self._total_tokens == total_tokens def __repr__(self): - return ( - "".format( - id(self), len(self._borrowers), self._total_tokens, - len(self._lot) - ) + return "".format( + id(self), len(self._borrowers), self._total_tokens, len(self._lot) ) @property @@ -200,9 +197,7 @@ def total_tokens(self): @total_tokens.setter def total_tokens(self, new_total_tokens): - if not isinstance( - new_total_tokens, int - ) and new_total_tokens != math.inf: + if not isinstance(new_total_tokens, int) and new_total_tokens != math.inf: raise TypeError("total_tokens must be an int or math.inf") if new_total_tokens < 1: raise ValueError("total_tokens must be >= 1") @@ -334,8 +329,7 @@ def release_on_behalf_of(self, borrower): """ if borrower not in self._borrowers: raise RuntimeError( - "this borrower isn't holding any of this CapacityLimiter's " - "tokens" + "this borrower isn't holding any of this CapacityLimiter's " "tokens" ) self._borrowers.remove(borrower) self._wake_waiters() @@ -418,10 +412,8 @@ def __repr__(self): max_value_str = "" else: max_value_str = ", max_value={}".format(self._max_value) - return ( - "".format( - self._value, max_value_str, id(self) - ) + return "".format( + self._value, max_value_str, id(self) ) @property @@ -528,10 +520,8 @@ def __repr__(self): else: s1 = "unlocked" s2 = "" - return ( - "<{} {} object at {:#x}{}>".format( - s1, self.__class__.__name__, id(self), s2 - ) + return "<{} {} object at {:#x}{}>".format( + s1, self.__class__.__name__, id(self), s2 ) def locked(self): @@ -606,9 +596,7 @@ def statistics(self): """ return _LockStatistics( - locked=self.locked(), - owner=self._owner, - tasks_waiting=len(self._lot), + locked=self.locked(), owner=self._owner, tasks_waiting=len(self._lot) ) @@ -808,8 +796,7 @@ def statistics(self): """ return _ConditionStatistics( - tasks_waiting=len(self._lot), - lock_statistics=self._lock.statistics(), + tasks_waiting=len(self._lot), lock_statistics=self._lock.statistics() ) @@ -848,10 +835,7 @@ class Queue: """ @deprecated( - "0.9.0", - issue=497, - thing="trio.Queue", - instead="trio.open_memory_channel" + "0.9.0", issue=497, thing="trio.Queue", instead="trio.open_memory_channel" ) def __init__(self, capacity): if not isinstance(capacity, int): @@ -869,10 +853,8 @@ def __init__(self, capacity): self._data = deque() def __repr__(self): - return ( - "".format( - self.capacity, id(self), len(self._data) - ) + return "".format( + self.capacity, id(self), len(self._data) ) def qsize(self): diff --git a/trio/_threads.py b/trio/_threads.py index d421b8dd1d..b569363820 100644 --- a/trio/_threads.py +++ b/trio/_threads.py @@ -78,9 +78,7 @@ def _do_it(self, cb, fn, *args): except RuntimeError: pass else: - raise RuntimeError( - "this is a blocking function; call it from a thread" - ) + raise RuntimeError("this is a blocking function; call it from a thread") q = stdlib_queue.Queue() self._trio_token.run_sync_soon(cb, q, fn, args) return q.get().unwrap() @@ -254,9 +252,7 @@ class ThreadPlaceholder: @_core.enable_ki_protection -async def run_sync_in_worker_thread( - sync_fn, *args, cancellable=False, limiter=None -): +async def run_sync_in_worker_thread(sync_fn, *args, cancellable=False, limiter=None): """Convert a blocking operation into an async operation using a thread. These two lines are equivalent:: @@ -382,9 +378,7 @@ def worker_thread_fn(): try: # daemon=True because it might get left behind if we cancel, and in # this case shouldn't block process exit. - thread = threading.Thread( - target=worker_thread_fn, name=name, daemon=True - ) + thread = threading.Thread(target=worker_thread_fn, name=name, daemon=True) thread.start() except: limiter.release_on_behalf_of(placeholder) diff --git a/trio/_timeouts.py b/trio/_timeouts.py index e835ce4b66..c8498c59c2 100644 --- a/trio/_timeouts.py +++ b/trio/_timeouts.py @@ -90,6 +90,7 @@ class TooSlowError(Exception): expires. """ + pass diff --git a/trio/_util.py b/trio/_util.py index bfe7138191..7d78dd5add 100644 --- a/trio/_util.py +++ b/trio/_util.py @@ -82,6 +82,8 @@ async def __aiter__(*args, **kwargs): return aiter_impl(*args, **kwargs) return __aiter__ + + else: def aiter_compat(aiter_impl): @@ -157,7 +159,7 @@ def async_wraps(cls, wrapped_cls, attr_name): def decorator(func): func.__name__ = attr_name - func.__qualname__ = '.'.join((cls.__qualname__, attr_name)) + func.__qualname__ = ".".join((cls.__qualname__, attr_name)) func.__doc__ = """Like :meth:`~{}.{}.{}`, but async. @@ -223,7 +225,7 @@ def fspath(path) -> t.Union[str, bytes]: try: path_repr = path_type.__fspath__(path) except AttributeError: - if hasattr(path_type, '__fspath__'): + if hasattr(path_type, "__fspath__"): raise else: raise TypeError( @@ -235,8 +237,7 @@ def fspath(path) -> t.Union[str, bytes]: else: raise TypeError( "expected {}.__fspath__() to return str or bytes, " - "not {}".format(path_type.__name__, - type(path_repr).__name__) + "not {}".format(path_type.__name__, type(path_repr).__name__) ) diff --git a/trio/_wait_for_object.py b/trio/_wait_for_object.py index a719d6b807..e0bd080f3b 100644 --- a/trio/_wait_for_object.py +++ b/trio/_wait_for_object.py @@ -56,9 +56,7 @@ def WaitForMultipleObjects_sync(*handles): handle_arr = ffi.new("HANDLE[{}]".format(n)) for i in range(n): handle_arr[i] = handles[i] - timeout = 0xffffffff # INFINITE - retcode = kernel32.WaitForMultipleObjects( - n, handle_arr, False, timeout - ) # blocking + timeout = 0xFFFFFFFF # INFINITE + retcode = kernel32.WaitForMultipleObjects(n, handle_arr, False, timeout) # blocking if retcode == ErrorCodes.WAIT_FAILED: raise_winerror() diff --git a/trio/abc.py b/trio/abc.py index 5eb4ec8ef4..23b24f6a8f 100644 --- a/trio/abc.py +++ b/trio/abc.py @@ -5,7 +5,16 @@ # implementation in an underscored module, and then re-export the public parts # here. from ._abc import ( - Clock, Instrument, AsyncResource, SendStream, ReceiveStream, Stream, - HalfCloseableStream, SocketFactory, HostnameResolver, Listener, - SendChannel, ReceiveChannel + Clock, + Instrument, + AsyncResource, + SendStream, + ReceiveStream, + Stream, + HalfCloseableStream, + SocketFactory, + HostnameResolver, + Listener, + SendChannel, + ReceiveChannel, ) diff --git a/trio/hazmat.py b/trio/hazmat.py index d39e51d715..5dfeea0ac3 100644 --- a/trio/hazmat.py +++ b/trio/hazmat.py @@ -54,6 +54,7 @@ ] from . import _core + # Some hazmat symbols are platform specific for _sym in list(__all__): if hasattr(_core, _sym): @@ -70,4 +71,5 @@ # Import bits from trio/*.py if sys.platform.startswith("win"): from ._wait_for_object import WaitForSingleObject + __all__ += ["WaitForSingleObject"] diff --git a/trio/socket.py b/trio/socket.py index e5408397d7..f6e9012b19 100644 --- a/trio/socket.py +++ b/trio/socket.py @@ -21,86 +21,363 @@ # kept up to date. try: from socket import ( - CMSG_LEN, CMSG_SPACE, CAPI, AF_UNSPEC, AF_INET, AF_UNIX, AF_IPX, - AF_APPLETALK, AF_INET6, AF_ROUTE, AF_LINK, AF_SNA, PF_SYSTEM, - AF_SYSTEM, SOCK_STREAM, SOCK_DGRAM, SOCK_RAW, SOCK_SEQPACKET, SOCK_RDM, - SO_DEBUG, SO_ACCEPTCONN, SO_REUSEADDR, SO_KEEPALIVE, SO_DONTROUTE, - SO_BROADCAST, SO_USELOOPBACK, SO_LINGER, SO_OOBINLINE, SO_REUSEPORT, - SO_SNDBUF, SO_RCVBUF, SO_SNDLOWAT, SO_RCVLOWAT, SO_SNDTIMEO, - SO_RCVTIMEO, SO_ERROR, SO_TYPE, LOCAL_PEERCRED, SOMAXCONN, SCM_RIGHTS, - SCM_CREDS, MSG_OOB, MSG_PEEK, MSG_DONTROUTE, MSG_DONTWAIT, MSG_EOR, - MSG_TRUNC, MSG_CTRUNC, MSG_WAITALL, MSG_EOF, SOL_SOCKET, SOL_IP, - SOL_TCP, SOL_UDP, IPPROTO_IP, IPPROTO_HOPOPTS, IPPROTO_ICMP, - IPPROTO_IGMP, IPPROTO_GGP, IPPROTO_IPV4, IPPROTO_IPIP, IPPROTO_TCP, - IPPROTO_EGP, IPPROTO_PUP, IPPROTO_UDP, IPPROTO_IDP, IPPROTO_HELLO, - IPPROTO_ND, IPPROTO_TP, IPPROTO_ROUTING, IPPROTO_FRAGMENT, - IPPROTO_RSVP, IPPROTO_GRE, IPPROTO_ESP, IPPROTO_AH, IPPROTO_ICMPV6, - IPPROTO_NONE, IPPROTO_DSTOPTS, IPPROTO_XTP, IPPROTO_EON, IPPROTO_PIM, - IPPROTO_IPCOMP, IPPROTO_SCTP, IPPROTO_RAW, IPPROTO_MAX, - SYSPROTO_CONTROL, IPPORT_RESERVED, IPPORT_USERRESERVED, INADDR_ANY, - INADDR_BROADCAST, INADDR_LOOPBACK, INADDR_UNSPEC_GROUP, - INADDR_ALLHOSTS_GROUP, INADDR_MAX_LOCAL_GROUP, INADDR_NONE, IP_OPTIONS, - IP_HDRINCL, IP_TOS, IP_TTL, IP_RECVOPTS, IP_RECVRETOPTS, - IP_RECVDSTADDR, IP_RETOPTS, IP_MULTICAST_IF, IP_MULTICAST_TTL, - IP_MULTICAST_LOOP, IP_ADD_MEMBERSHIP, IP_DROP_MEMBERSHIP, - IP_DEFAULT_MULTICAST_TTL, IP_DEFAULT_MULTICAST_LOOP, - IP_MAX_MEMBERSHIPS, IPV6_JOIN_GROUP, IPV6_LEAVE_GROUP, - IPV6_MULTICAST_HOPS, IPV6_MULTICAST_IF, IPV6_MULTICAST_LOOP, - IPV6_UNICAST_HOPS, IPV6_V6ONLY, IPV6_CHECKSUM, IPV6_RECVTCLASS, - IPV6_RTHDR_TYPE_0, IPV6_TCLASS, TCP_NODELAY, TCP_MAXSEG, TCP_KEEPINTVL, - TCP_KEEPCNT, TCP_FASTOPEN, TCP_NOTSENT_LOWAT, EAI_ADDRFAMILY, - EAI_AGAIN, EAI_BADFLAGS, EAI_FAIL, EAI_FAMILY, EAI_MEMORY, EAI_NODATA, - EAI_NONAME, EAI_OVERFLOW, EAI_SERVICE, EAI_SOCKTYPE, EAI_SYSTEM, - EAI_BADHINTS, EAI_PROTOCOL, EAI_MAX, AI_PASSIVE, AI_CANONNAME, - AI_NUMERICHOST, AI_NUMERICSERV, AI_MASK, AI_ALL, AI_V4MAPPED_CFG, - AI_ADDRCONFIG, AI_V4MAPPED, AI_DEFAULT, NI_MAXHOST, NI_MAXSERV, - NI_NOFQDN, NI_NUMERICHOST, NI_NAMEREQD, NI_NUMERICSERV, NI_DGRAM, - SHUT_RD, SHUT_WR, SHUT_RDWR, EBADF, EAGAIN, EWOULDBLOCK, AF_ASH, - AF_ATMPVC, AF_ATMSVC, AF_AX25, AF_BLUETOOTH, AF_BRIDGE, AF_ECONET, - AF_IRDA, AF_KEY, AF_LLC, AF_NETBEUI, AF_NETLINK, AF_NETROM, AF_PACKET, - AF_PPPOX, AF_ROSE, AF_SECURITY, AF_WANPIPE, AF_X25, BDADDR_ANY, - BDADDR_LOCAL, FD_SETSIZE, IPV6_DSTOPTS, IPV6_HOPLIMIT, IPV6_HOPOPTS, - IPV6_NEXTHOP, IPV6_PKTINFO, IPV6_RECVDSTOPTS, IPV6_RECVHOPLIMIT, - IPV6_RECVHOPOPTS, IPV6_RECVPKTINFO, IPV6_RECVRTHDR, IPV6_RTHDR, - IPV6_RTHDRDSTOPTS, MSG_ERRQUEUE, NETLINK_DNRTMSG, NETLINK_FIREWALL, - NETLINK_IP6_FW, NETLINK_NFLOG, NETLINK_ROUTE, NETLINK_USERSOCK, - NETLINK_XFRM, PACKET_BROADCAST, PACKET_FASTROUTE, PACKET_HOST, - PACKET_LOOPBACK, PACKET_MULTICAST, PACKET_OTHERHOST, PACKET_OUTGOING, - POLLERR, POLLHUP, POLLIN, POLLMSG, POLLNVAL, POLLOUT, POLLPRI, - POLLRDBAND, POLLRDNORM, POLLWRNORM, SIOCGIFINDEX, SIOCGIFNAME, - SOCK_CLOEXEC, TCP_CORK, TCP_DEFER_ACCEPT, TCP_INFO, TCP_KEEPIDLE, - TCP_LINGER2, TCP_QUICKACK, TCP_SYNCNT, TCP_WINDOW_CLAMP, AF_ALG, - AF_CAN, AF_RDS, AF_TIPC, AF_VSOCK, ALG_OP_DECRYPT, ALG_OP_ENCRYPT, - ALG_OP_SIGN, ALG_OP_VERIFY, ALG_SET_AEAD_ASSOCLEN, - ALG_SET_AEAD_AUTHSIZE, ALG_SET_IV, ALG_SET_KEY, ALG_SET_OP, - ALG_SET_PUBKEY, CAN_BCM, CAN_BCM_RX_CHANGED, CAN_BCM_RX_DELETE, - CAN_BCM_RX_READ, CAN_BCM_RX_SETUP, CAN_BCM_RX_STATUS, - CAN_BCM_RX_TIMEOUT, CAN_BCM_TX_DELETE, CAN_BCM_TX_EXPIRED, - CAN_BCM_TX_READ, CAN_BCM_TX_SEND, CAN_BCM_TX_SETUP, CAN_BCM_TX_STATUS, - CAN_EFF_FLAG, CAN_EFF_MASK, CAN_ERR_FLAG, CAN_ERR_MASK, CAN_ISOTP, - CAN_RAW, CAN_RAW_ERR_FILTER, CAN_RAW_FD_FRAMES, CAN_RAW_FILTER, - CAN_RAW_LOOPBACK, CAN_RAW_RECV_OWN_MSGS, CAN_RTR_FLAG, CAN_SFF_MASK, - IOCTL_VM_SOCKETS_GET_LOCAL_CID, IPV6_DONTFRAG, IPV6_PATHMTU, - IPV6_RECVPATHMTU, IP_TRANSPARENT, MSG_CMSG_CLOEXEC, MSG_CONFIRM, - MSG_FASTOPEN, MSG_MORE, MSG_NOSIGNAL, NETLINK_CRYPTO, PF_CAN, - PF_PACKET, PF_RDS, SCM_CREDENTIALS, SOCK_NONBLOCK, SOL_ALG, - SOL_CAN_BASE, SOL_CAN_RAW, SOL_TIPC, SO_BINDTODEVICE, SO_DOMAIN, - SO_MARK, SO_PASSCRED, SO_PASSSEC, SO_PEERCRED, SO_PEERSEC, SO_PRIORITY, - SO_PROTOCOL, SO_VM_SOCKETS_BUFFER_MAX_SIZE, - SO_VM_SOCKETS_BUFFER_MIN_SIZE, SO_VM_SOCKETS_BUFFER_SIZE, - TCP_CONGESTION, TCP_USER_TIMEOUT, TIPC_ADDR_ID, TIPC_ADDR_NAME, - TIPC_ADDR_NAMESEQ, TIPC_CFG_SRV, TIPC_CLUSTER_SCOPE, TIPC_CONN_TIMEOUT, - TIPC_CRITICAL_IMPORTANCE, TIPC_DEST_DROPPABLE, TIPC_HIGH_IMPORTANCE, - TIPC_IMPORTANCE, TIPC_LOW_IMPORTANCE, TIPC_MEDIUM_IMPORTANCE, - TIPC_NODE_SCOPE, TIPC_PUBLISHED, TIPC_SRC_DROPPABLE, - TIPC_SUBSCR_TIMEOUT, TIPC_SUB_CANCEL, TIPC_SUB_PORTS, TIPC_SUB_SERVICE, - TIPC_TOP_SRV, TIPC_WAIT_FOREVER, TIPC_WITHDRAWN, TIPC_ZONE_SCOPE, - VMADDR_CID_ANY, VMADDR_CID_HOST, VMADDR_PORT_ANY, - VM_SOCKETS_INVALID_VERSION, MSG_BCAST, MSG_MCAST, RCVALL_MAX, - RCVALL_OFF, RCVALL_ON, RCVALL_SOCKETLEVELONLY, SIO_KEEPALIVE_VALS, - SIO_LOOPBACK_FAST_PATH, SIO_RCVALL, SO_EXCLUSIVEADDRUSE, HCI_FILTER, - BTPROTO_SCO, BTPROTO_HCI, HCI_TIME_STAMP, SOL_RDS, BTPROTO_L2CAP, - BTPROTO_RFCOMM, HCI_DATA_DIR, SOL_HCI + CMSG_LEN, + CMSG_SPACE, + CAPI, + AF_UNSPEC, + AF_INET, + AF_UNIX, + AF_IPX, + AF_APPLETALK, + AF_INET6, + AF_ROUTE, + AF_LINK, + AF_SNA, + PF_SYSTEM, + AF_SYSTEM, + SOCK_STREAM, + SOCK_DGRAM, + SOCK_RAW, + SOCK_SEQPACKET, + SOCK_RDM, + SO_DEBUG, + SO_ACCEPTCONN, + SO_REUSEADDR, + SO_KEEPALIVE, + SO_DONTROUTE, + SO_BROADCAST, + SO_USELOOPBACK, + SO_LINGER, + SO_OOBINLINE, + SO_REUSEPORT, + SO_SNDBUF, + SO_RCVBUF, + SO_SNDLOWAT, + SO_RCVLOWAT, + SO_SNDTIMEO, + SO_RCVTIMEO, + SO_ERROR, + SO_TYPE, + LOCAL_PEERCRED, + SOMAXCONN, + SCM_RIGHTS, + SCM_CREDS, + MSG_OOB, + MSG_PEEK, + MSG_DONTROUTE, + MSG_DONTWAIT, + MSG_EOR, + MSG_TRUNC, + MSG_CTRUNC, + MSG_WAITALL, + MSG_EOF, + SOL_SOCKET, + SOL_IP, + SOL_TCP, + SOL_UDP, + IPPROTO_IP, + IPPROTO_HOPOPTS, + IPPROTO_ICMP, + IPPROTO_IGMP, + IPPROTO_GGP, + IPPROTO_IPV4, + IPPROTO_IPIP, + IPPROTO_TCP, + IPPROTO_EGP, + IPPROTO_PUP, + IPPROTO_UDP, + IPPROTO_IDP, + IPPROTO_HELLO, + IPPROTO_ND, + IPPROTO_TP, + IPPROTO_ROUTING, + IPPROTO_FRAGMENT, + IPPROTO_RSVP, + IPPROTO_GRE, + IPPROTO_ESP, + IPPROTO_AH, + IPPROTO_ICMPV6, + IPPROTO_NONE, + IPPROTO_DSTOPTS, + IPPROTO_XTP, + IPPROTO_EON, + IPPROTO_PIM, + IPPROTO_IPCOMP, + IPPROTO_SCTP, + IPPROTO_RAW, + IPPROTO_MAX, + SYSPROTO_CONTROL, + IPPORT_RESERVED, + IPPORT_USERRESERVED, + INADDR_ANY, + INADDR_BROADCAST, + INADDR_LOOPBACK, + INADDR_UNSPEC_GROUP, + INADDR_ALLHOSTS_GROUP, + INADDR_MAX_LOCAL_GROUP, + INADDR_NONE, + IP_OPTIONS, + IP_HDRINCL, + IP_TOS, + IP_TTL, + IP_RECVOPTS, + IP_RECVRETOPTS, + IP_RECVDSTADDR, + IP_RETOPTS, + IP_MULTICAST_IF, + IP_MULTICAST_TTL, + IP_MULTICAST_LOOP, + IP_ADD_MEMBERSHIP, + IP_DROP_MEMBERSHIP, + IP_DEFAULT_MULTICAST_TTL, + IP_DEFAULT_MULTICAST_LOOP, + IP_MAX_MEMBERSHIPS, + IPV6_JOIN_GROUP, + IPV6_LEAVE_GROUP, + IPV6_MULTICAST_HOPS, + IPV6_MULTICAST_IF, + IPV6_MULTICAST_LOOP, + IPV6_UNICAST_HOPS, + IPV6_V6ONLY, + IPV6_CHECKSUM, + IPV6_RECVTCLASS, + IPV6_RTHDR_TYPE_0, + IPV6_TCLASS, + TCP_NODELAY, + TCP_MAXSEG, + TCP_KEEPINTVL, + TCP_KEEPCNT, + TCP_FASTOPEN, + TCP_NOTSENT_LOWAT, + EAI_ADDRFAMILY, + EAI_AGAIN, + EAI_BADFLAGS, + EAI_FAIL, + EAI_FAMILY, + EAI_MEMORY, + EAI_NODATA, + EAI_NONAME, + EAI_OVERFLOW, + EAI_SERVICE, + EAI_SOCKTYPE, + EAI_SYSTEM, + EAI_BADHINTS, + EAI_PROTOCOL, + EAI_MAX, + AI_PASSIVE, + AI_CANONNAME, + AI_NUMERICHOST, + AI_NUMERICSERV, + AI_MASK, + AI_ALL, + AI_V4MAPPED_CFG, + AI_ADDRCONFIG, + AI_V4MAPPED, + AI_DEFAULT, + NI_MAXHOST, + NI_MAXSERV, + NI_NOFQDN, + NI_NUMERICHOST, + NI_NAMEREQD, + NI_NUMERICSERV, + NI_DGRAM, + SHUT_RD, + SHUT_WR, + SHUT_RDWR, + EBADF, + EAGAIN, + EWOULDBLOCK, + AF_ASH, + AF_ATMPVC, + AF_ATMSVC, + AF_AX25, + AF_BLUETOOTH, + AF_BRIDGE, + AF_ECONET, + AF_IRDA, + AF_KEY, + AF_LLC, + AF_NETBEUI, + AF_NETLINK, + AF_NETROM, + AF_PACKET, + AF_PPPOX, + AF_ROSE, + AF_SECURITY, + AF_WANPIPE, + AF_X25, + BDADDR_ANY, + BDADDR_LOCAL, + FD_SETSIZE, + IPV6_DSTOPTS, + IPV6_HOPLIMIT, + IPV6_HOPOPTS, + IPV6_NEXTHOP, + IPV6_PKTINFO, + IPV6_RECVDSTOPTS, + IPV6_RECVHOPLIMIT, + IPV6_RECVHOPOPTS, + IPV6_RECVPKTINFO, + IPV6_RECVRTHDR, + IPV6_RTHDR, + IPV6_RTHDRDSTOPTS, + MSG_ERRQUEUE, + NETLINK_DNRTMSG, + NETLINK_FIREWALL, + NETLINK_IP6_FW, + NETLINK_NFLOG, + NETLINK_ROUTE, + NETLINK_USERSOCK, + NETLINK_XFRM, + PACKET_BROADCAST, + PACKET_FASTROUTE, + PACKET_HOST, + PACKET_LOOPBACK, + PACKET_MULTICAST, + PACKET_OTHERHOST, + PACKET_OUTGOING, + POLLERR, + POLLHUP, + POLLIN, + POLLMSG, + POLLNVAL, + POLLOUT, + POLLPRI, + POLLRDBAND, + POLLRDNORM, + POLLWRNORM, + SIOCGIFINDEX, + SIOCGIFNAME, + SOCK_CLOEXEC, + TCP_CORK, + TCP_DEFER_ACCEPT, + TCP_INFO, + TCP_KEEPIDLE, + TCP_LINGER2, + TCP_QUICKACK, + TCP_SYNCNT, + TCP_WINDOW_CLAMP, + AF_ALG, + AF_CAN, + AF_RDS, + AF_TIPC, + AF_VSOCK, + ALG_OP_DECRYPT, + ALG_OP_ENCRYPT, + ALG_OP_SIGN, + ALG_OP_VERIFY, + ALG_SET_AEAD_ASSOCLEN, + ALG_SET_AEAD_AUTHSIZE, + ALG_SET_IV, + ALG_SET_KEY, + ALG_SET_OP, + ALG_SET_PUBKEY, + CAN_BCM, + CAN_BCM_RX_CHANGED, + CAN_BCM_RX_DELETE, + CAN_BCM_RX_READ, + CAN_BCM_RX_SETUP, + CAN_BCM_RX_STATUS, + CAN_BCM_RX_TIMEOUT, + CAN_BCM_TX_DELETE, + CAN_BCM_TX_EXPIRED, + CAN_BCM_TX_READ, + CAN_BCM_TX_SEND, + CAN_BCM_TX_SETUP, + CAN_BCM_TX_STATUS, + CAN_EFF_FLAG, + CAN_EFF_MASK, + CAN_ERR_FLAG, + CAN_ERR_MASK, + CAN_ISOTP, + CAN_RAW, + CAN_RAW_ERR_FILTER, + CAN_RAW_FD_FRAMES, + CAN_RAW_FILTER, + CAN_RAW_LOOPBACK, + CAN_RAW_RECV_OWN_MSGS, + CAN_RTR_FLAG, + CAN_SFF_MASK, + IOCTL_VM_SOCKETS_GET_LOCAL_CID, + IPV6_DONTFRAG, + IPV6_PATHMTU, + IPV6_RECVPATHMTU, + IP_TRANSPARENT, + MSG_CMSG_CLOEXEC, + MSG_CONFIRM, + MSG_FASTOPEN, + MSG_MORE, + MSG_NOSIGNAL, + NETLINK_CRYPTO, + PF_CAN, + PF_PACKET, + PF_RDS, + SCM_CREDENTIALS, + SOCK_NONBLOCK, + SOL_ALG, + SOL_CAN_BASE, + SOL_CAN_RAW, + SOL_TIPC, + SO_BINDTODEVICE, + SO_DOMAIN, + SO_MARK, + SO_PASSCRED, + SO_PASSSEC, + SO_PEERCRED, + SO_PEERSEC, + SO_PRIORITY, + SO_PROTOCOL, + SO_VM_SOCKETS_BUFFER_MAX_SIZE, + SO_VM_SOCKETS_BUFFER_MIN_SIZE, + SO_VM_SOCKETS_BUFFER_SIZE, + TCP_CONGESTION, + TCP_USER_TIMEOUT, + TIPC_ADDR_ID, + TIPC_ADDR_NAME, + TIPC_ADDR_NAMESEQ, + TIPC_CFG_SRV, + TIPC_CLUSTER_SCOPE, + TIPC_CONN_TIMEOUT, + TIPC_CRITICAL_IMPORTANCE, + TIPC_DEST_DROPPABLE, + TIPC_HIGH_IMPORTANCE, + TIPC_IMPORTANCE, + TIPC_LOW_IMPORTANCE, + TIPC_MEDIUM_IMPORTANCE, + TIPC_NODE_SCOPE, + TIPC_PUBLISHED, + TIPC_SRC_DROPPABLE, + TIPC_SUBSCR_TIMEOUT, + TIPC_SUB_CANCEL, + TIPC_SUB_PORTS, + TIPC_SUB_SERVICE, + TIPC_TOP_SRV, + TIPC_WAIT_FOREVER, + TIPC_WITHDRAWN, + TIPC_ZONE_SCOPE, + VMADDR_CID_ANY, + VMADDR_CID_HOST, + VMADDR_PORT_ANY, + VM_SOCKETS_INVALID_VERSION, + MSG_BCAST, + MSG_MCAST, + RCVALL_MAX, + RCVALL_OFF, + RCVALL_ON, + RCVALL_SOCKETLEVELONLY, + SIO_KEEPALIVE_VALS, + SIO_LOOPBACK_FAST_PATH, + SIO_RCVALL, + SO_EXCLUSIVEADDRUSE, + HCI_FILTER, + BTPROTO_SCO, + BTPROTO_HCI, + HCI_TIME_STAMP, + SOL_RDS, + BTPROTO_L2CAP, + BTPROTO_RFCOMM, + HCI_DATA_DIR, + SOL_HCI, ) except ImportError: pass @@ -112,15 +389,23 @@ globals().update( { _name: getattr(_stdlib_socket, _name) - for _name in _stdlib_socket.__all__ if _name.isupper() + for _name in _stdlib_socket.__all__ + if _name.isupper() } ) # import the overwrites from ._socket import ( - fromfd, from_stdlib_socket, getprotobyname, socketpair, getnameinfo, - socket, getaddrinfo, set_custom_hostname_resolver, - set_custom_socket_factory, SocketType + fromfd, + from_stdlib_socket, + getprotobyname, + socketpair, + getnameinfo, + socket, + getaddrinfo, + set_custom_hostname_resolver, + set_custom_socket_factory, + SocketType, ) # not always available so expose only if @@ -145,13 +430,11 @@ # not always available so expose only if try: - from socket import ( - sethostname, if_nameindex, if_nametoindex, if_indextoname - ) + from socket import sethostname, if_nameindex, if_nametoindex, if_indextoname except ImportError: pass -if _sys.platform == 'win32': +if _sys.platform == "win32": # See https://github.com/python-trio/trio/issues/39 # Do not import for windows platform # (you can still get it from stdlib socket, of course, if you want it) diff --git a/trio/testing/__init__.py b/trio/testing/__init__.py index df150ec62b..8c730ffeb5 100644 --- a/trio/testing/__init__.py +++ b/trio/testing/__init__.py @@ -9,13 +9,19 @@ from ._sequencer import Sequencer from ._check_streams import ( - check_one_way_stream, check_two_way_stream, check_half_closeable_stream + check_one_way_stream, + check_two_way_stream, + check_half_closeable_stream, ) from ._memory_streams import ( - MemorySendStream, MemoryReceiveStream, memory_stream_pump, - memory_stream_one_way_pair, memory_stream_pair, - lockstep_stream_one_way_pair, lockstep_stream_pair + MemorySendStream, + MemoryReceiveStream, + memory_stream_pump, + memory_stream_one_way_pair, + memory_stream_pair, + lockstep_stream_one_way_pair, + lockstep_stream_pair, ) from ._network import open_stream_to_socket_listener @@ -23,5 +29,6 @@ ################################################################ 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 0beb1ef1d8..64d5928bc6 100644 --- a/trio/testing/_check_streams.py +++ b/trio/testing/_check_streams.py @@ -129,8 +129,7 @@ async def simple_check_wait_send_all_might_not_block(scope): async with _core.open_nursery() as nursery: nursery.start_soon( - simple_check_wait_send_all_might_not_block, - nursery.cancel_scope + simple_check_wait_send_all_might_not_block, nursery.cancel_scope ) nursery.start_soon(do_receive_some, 1) @@ -295,11 +294,7 @@ async def receiver(): await _core.wait_all_tasks_blocked() nursery.start_soon(receiver) - assert record == [ - "waiter sleeping", - "receiver starting", - "waiter wokeup", - ] + assert record == ["waiter sleeping", "receiver starting", "waiter wokeup"] async with _ForceCloseBoth(await clogged_stream_maker()) as (s, r): # simultaneous wait_send_all_might_not_block fails @@ -393,19 +388,18 @@ async def flipped_stream_maker(): async def flipped_clogged_stream_maker(): return reversed(await clogged_stream_maker()) + else: flipped_clogged_stream_maker = None - await check_one_way_stream( - flipped_stream_maker, flipped_clogged_stream_maker - ) + await check_one_way_stream(flipped_stream_maker, flipped_clogged_stream_maker) async with _ForceCloseBoth(await stream_maker()) as (s1, s2): assert isinstance(s1, Stream) assert isinstance(s2, Stream) # Duplex can be a bit tricky, might as well check it as well - DUPLEX_TEST_SIZE = 2**20 - CHUNK_SIZE_MAX = 2**14 + DUPLEX_TEST_SIZE = 2 ** 20 + CHUNK_SIZE_MAX = 2 ** 14 r = random.Random(0) i = r.getrandbits(8 * DUPLEX_TEST_SIZE) diff --git a/trio/testing/_checkpoints.py b/trio/testing/_checkpoints.py index 61598f78fb..5a9dac4eb8 100644 --- a/trio/testing/_checkpoints.py +++ b/trio/testing/_checkpoints.py @@ -14,18 +14,12 @@ def _assert_yields_or_not(expected): try: yield finally: - if ( - expected and ( - task._cancel_points == orig_cancel - or task._schedule_points == orig_schedule - ) + if expected and ( + task._cancel_points == orig_cancel or task._schedule_points == orig_schedule ): raise AssertionError("assert_checkpoints block did not yield!") - elif ( - not expected and ( - task._cancel_points != orig_cancel - or task._schedule_points != orig_schedule - ) + elif not expected and ( + task._cancel_points != orig_cancel or task._schedule_points != orig_schedule ): raise AssertionError("assert_no_yields block yielded!") diff --git a/trio/testing/_memory_streams.py b/trio/testing/_memory_streams.py index 9e080e8e91..cccc24a671 100644 --- a/trio/testing/_memory_streams.py +++ b/trio/testing/_memory_streams.py @@ -106,7 +106,7 @@ def __init__( self, send_all_hook=None, wait_send_all_might_not_block_hook=None, - close_hook=None + close_hook=None, ): self._conflict_detector = _util.ConflictDetector( "another task is using this stream" @@ -278,9 +278,7 @@ def put_eof(self): self._incoming.close() -def memory_stream_pump( - memory_send_stream, memory_receive_stream, *, max_bytes=None -): +def memory_stream_pump(memory_send_stream, memory_receive_stream, *, max_bytes=None): """Take data out of the given :class:`MemorySendStream`'s internal buffer, and put it into the given :class:`MemoryReceiveStream`'s internal buffer. diff --git a/trio/testing/_mock_clock.py b/trio/testing/_mock_clock.py index 2647d8909b..5b90a07c50 100644 --- a/trio/testing/_mock_clock.py +++ b/trio/testing/_mock_clock.py @@ -99,10 +99,8 @@ def __init__(self, rate=0.0, autojump_threshold=inf): self.autojump_threshold = autojump_threshold def __repr__(self): - return ( - "".format( - self.current_time(), self._rate, id(self) - ) + return "".format( + self.current_time(), self._rate, id(self) ) @property @@ -143,9 +141,7 @@ async def _autojumper(self): # to raise Cancelled, which is absorbed by the cancel # scope above, and effectively just causes us to skip back # to the start the loop, like a 'continue'. - await _core.wait_all_tasks_blocked( - self._autojump_threshold, inf - ) + await _core.wait_all_tasks_blocked(self._autojump_threshold, inf) statistics = _core.current_statistics() jump = statistics.seconds_to_next_deadline if jump < inf: diff --git a/trio/testing/_sequencer.py b/trio/testing/_sequencer.py index 9360d4c575..7a4ee405cc 100644 --- a/trio/testing/_sequencer.py +++ b/trio/testing/_sequencer.py @@ -64,9 +64,7 @@ async def main(): @async_generator async def __call__(self, position: int): if position in self._claimed: - raise RuntimeError( - "Attempted to re-use sequence point {}".format(position) - ) + raise RuntimeError("Attempted to re-use sequence point {}".format(position)) if self._broken: raise RuntimeError("sequence broken!") self._claimed.add(position) @@ -77,9 +75,7 @@ async def __call__(self, position: int): self._broken = True for event in self._sequence_points.values(): event.set() - raise RuntimeError( - "Sequencer wait cancelled -- sequence broken" - ) + raise RuntimeError("Sequencer wait cancelled -- sequence broken") else: if self._broken: raise RuntimeError("sequence broken!") diff --git a/trio/testing/_trio_test.py b/trio/testing/_trio_test.py index 9215084955..dcada1feb3 100644 --- a/trio/testing/_trio_test.py +++ b/trio/testing/_trio_test.py @@ -26,8 +26,6 @@ def wrapper(**kwargs): else: raise ValueError("too many clocks spoil the broth!") instruments = [i for i in kwargs.values() if isinstance(i, Instrument)] - return _core.run( - partial(fn, **kwargs), clock=clock, instruments=instruments - ) + return _core.run(partial(fn, **kwargs), clock=clock, instruments=instruments) return wrapper diff --git a/trio/tests/module_with_deprecations.py b/trio/tests/module_with_deprecations.py index d194b6a5bd..73184d11e8 100644 --- a/trio/tests/module_with_deprecations.py +++ b/trio/tests/module_with_deprecations.py @@ -8,22 +8,14 @@ # attributes in between calling enable_attribute_deprecations and defining # __deprecated_attributes__: import sys + this_mod = sys.modules[__name__] assert this_mod.regular == "hi" assert not hasattr(this_mod, "dep1") __deprecated_attributes__ = { - "dep1": - _deprecate.DeprecatedAttribute( - "value1", - "1.1", - issue=1, - ), - "dep2": - _deprecate.DeprecatedAttribute( - "value2", - "1.2", - issue=1, - instead="instead-string", - ), + "dep1": _deprecate.DeprecatedAttribute("value1", "1.1", issue=1), + "dep2": _deprecate.DeprecatedAttribute( + "value2", "1.2", issue=1, instead="instead-string" + ), } diff --git a/trio/tests/subprocess/test_unix_pipes.py b/trio/tests/subprocess/test_unix_pipes.py index b8cc2d496a..29e5085cc3 100644 --- a/trio/tests/subprocess/test_unix_pipes.py +++ b/trio/tests/subprocess/test_unix_pipes.py @@ -6,18 +6,14 @@ from trio._core.tests.tutil import gc_collect_harder from ... import _core -from ...testing import (wait_all_tasks_blocked, check_one_way_stream) +from ...testing import wait_all_tasks_blocked, check_one_way_stream posix = os.name == "posix" -pytestmark = pytest.mark.skipif( - not posix, reason="pipes are only supported on posix" -) +pytestmark = pytest.mark.skipif(not posix, reason="pipes are only supported on posix") if posix: - from ..._subprocess.unix_pipes import ( - PipeSendStream, PipeReceiveStream, make_pipe - ) + from ..._subprocess.unix_pipes import PipeSendStream, PipeReceiveStream, make_pipe async def test_send_pipe(): @@ -46,7 +42,7 @@ async def test_receive_pipe(): async def test_pipes_combined(): write, read = await make_pipe() - count = 2**20 + count = 2 ** 20 async def sender(): big = bytearray(count) diff --git a/trio/tests/test_deprecate.py b/trio/tests/test_deprecate.py index c945b91d01..4e5afe5c0d 100644 --- a/trio/tests/test_deprecate.py +++ b/trio/tests/test_deprecate.py @@ -5,7 +5,10 @@ from types import ModuleType from .._deprecate import ( - TrioDeprecationWarning, warn_deprecated, deprecated, deprecated_alias + TrioDeprecationWarning, + warn_deprecated, + deprecated, + deprecated_alias, ) from . import module_with_deprecations @@ -26,7 +29,7 @@ def test_warn_deprecated(recwarn_always): def deprecated_thing(): warn_deprecated("ice", "1.2", issue=1, instead="water") - filename, lineno = _here() # https://github.com/google/yapf/issues/447 + filename, lineno = _here() deprecated_thing() assert len(recwarn_always) == 1 got = recwarn_always.pop(TrioDeprecationWarning) @@ -55,7 +58,7 @@ def nested1(): def nested2(): warn_deprecated("x", "1.3", issue=7, instead="y", stacklevel=3) - filename, lineno = _here() # https://github.com/google/yapf/issues/447 + filename, lineno = _here() nested1() got = recwarn_always.pop(TrioDeprecationWarning) assert got.filename == filename @@ -182,40 +185,52 @@ def docstring_test4(): # pragma: no cover def test_deprecated_docstring_munging(): - assert docstring_test1.__doc__ == """Hello! + assert ( + docstring_test1.__doc__ + == """Hello! .. deprecated:: 2.1 Use hi instead. For details, see `issue #1 `__. """ + ) - assert docstring_test2.__doc__ == """Hello! + assert ( + docstring_test2.__doc__ + == """Hello! .. deprecated:: 2.1 Use hi instead. """ + ) - assert docstring_test3.__doc__ == """Hello! + assert ( + docstring_test3.__doc__ + == """Hello! .. deprecated:: 2.1 For details, see `issue #1 `__. """ + ) - assert docstring_test4.__doc__ == """Hello! + assert ( + docstring_test4.__doc__ + == """Hello! .. deprecated:: 2.1 """ + ) def test_module_with_deprecations(recwarn_always): assert module_with_deprecations.regular == "hi" assert len(recwarn_always) == 0 - filename, lineno = _here() # https://github.com/google/yapf/issues/447 + filename, lineno = _here() assert module_with_deprecations.dep1 == "value1" got = recwarn_always.pop(TrioDeprecationWarning) assert got.filename == filename diff --git a/trio/tests/test_exports.py b/trio/tests/test_exports.py index fce55a9ebd..f038c8565b 100644 --- a/trio/tests/test_exports.py +++ b/trio/tests/test_exports.py @@ -16,13 +16,12 @@ def test_core_is_properly_reexported(): # three modules: sources = [trio, trio.hazmat, trio.testing] for symbol in dir(_core): - if symbol.startswith('_') or symbol == 'tests': + if symbol.startswith("_") or symbol == "tests": continue found = 0 for source in sources: - if ( - symbol in dir(source) - and getattr(source, symbol) is getattr(_core, symbol) + if symbol in dir(source) and getattr(source, symbol) is getattr( + _core, symbol ): found += 1 print(symbol, found) @@ -77,11 +76,13 @@ def no_underscores(symbols): if tool == "pylint": from pylint.lint import PyLinter + linter = PyLinter() ast = linter.get_ast(module.__file__, modname) static_names = no_underscores(ast) elif tool == "jedi": import jedi + # Simulate typing "import trio; trio." script = jedi.Script("import {}; {}.".format(modname, modname)) completions = script.completions() diff --git a/trio/tests/test_file_io.py b/trio/tests/test_file_io.py index 844097a0a7..d7e4dea550 100644 --- a/trio/tests/test_file_io.py +++ b/trio/tests/test_file_io.py @@ -13,7 +13,7 @@ @pytest.fixture def path(tmpdir): - return fspath(tmpdir.join('test')) + return fspath(tmpdir.join("test")) @pytest.fixture @@ -59,9 +59,7 @@ def test_dir_matches_wrapped(async_file, wrapped): attrs = _FILE_SYNC_ATTRS.union(_FILE_ASYNC_METHODS) # all supported attrs in wrapped should be available in async_file - assert all( - attr in dir(async_file) for attr in attrs if attr in dir(wrapped) - ) + assert all(attr in dir(async_file) for attr in attrs if attr in dir(wrapped)) # all supported attrs not in wrapped should not be available in async_file assert not any( attr in dir(async_file) for attr in attrs if attr not in dir(wrapped) @@ -75,10 +73,10 @@ def unsupported_attr(self): # pragma: no cover async_file = trio.wrap_file(FakeFile()) - assert hasattr(async_file.wrapped, 'unsupported_attr') + assert hasattr(async_file.wrapped, "unsupported_attr") with pytest.raises(AttributeError): - getattr(async_file, 'unsupported_attr') + getattr(async_file, "unsupported_attr") def test_sync_attrs_forwarded(async_file, wrapped): @@ -111,10 +109,10 @@ def test_async_methods_generated_once(async_file): def test_async_methods_signature(async_file): # use read as a representative of all async methods - assert async_file.read.__name__ == 'read' - assert async_file.read.__qualname__ == 'AsyncIOWrapper.read' + assert async_file.read.__name__ == "read" + assert async_file.read.__qualname__ == "AsyncIOWrapper.read" - assert 'io.StringIO.read' in async_file.read.__doc__ + assert "io.StringIO.read" in async_file.read.__doc__ async def test_async_methods_wrap(async_file, wrapped): @@ -148,7 +146,7 @@ async def test_async_methods_match_wrapper(async_file, wrapped): async def test_open(path): - f = await trio.open_file(path, 'w') + f = await trio.open_file(path, "w") assert isinstance(f, AsyncIOWrapper) @@ -156,7 +154,7 @@ async def test_open(path): async def test_open_context_manager(path): - async with await trio.open_file(path, 'w') as f: + async with await trio.open_file(path, "w") as f: assert isinstance(f, AsyncIOWrapper) assert not f.closed @@ -164,7 +162,7 @@ async def test_open_context_manager(path): async def test_async_iter(): - async_file = trio.wrap_file(io.StringIO('test\nfoo\nbar')) + async_file = trio.wrap_file(io.StringIO("test\nfoo\nbar")) expected = list(async_file.wrapped) result = [] async_file.wrapped.seek(0) @@ -177,11 +175,11 @@ async def test_async_iter(): async def test_aclose_cancelled(path): with _core.open_cancel_scope() as cscope: - f = await trio.open_file(path, 'w') + f = await trio.open_file(path, "w") cscope.cancel() with pytest.raises(_core.Cancelled): - await f.write('a') + await f.write("a") with pytest.raises(_core.Cancelled): await f.aclose() diff --git a/trio/tests/test_highlevel_generic.py b/trio/tests/test_highlevel_generic.py index b115d3b270..a3531baa73 100644 --- a/trio/tests/test_highlevel_generic.py +++ b/trio/tests/test_highlevel_generic.py @@ -41,10 +41,7 @@ async def test_StapledStream(): await stapled.send_all(b"foo") await stapled.wait_send_all_might_not_block() - assert send_stream.record == [ - ("send_all", b"foo"), - "wait_send_all_might_not_block", - ] + assert send_stream.record == [("send_all", b"foo"), "wait_send_all_might_not_block"] send_stream.record.clear() await stapled.send_eof() diff --git a/trio/tests/test_highlevel_open_tcp_listeners.py b/trio/tests/test_highlevel_open_tcp_listeners.py index 81fa64d0dd..5db5fd7e3e 100644 --- a/trio/tests/test_highlevel_open_tcp_listeners.py +++ b/trio/tests/test_highlevel_open_tcp_listeners.py @@ -5,9 +5,7 @@ import attr import trio -from trio import ( - open_tcp_listeners, serve_tcp, SocketListener, open_tcp_stream -) +from trio import open_tcp_listeners, serve_tcp, SocketListener, open_tcp_stream from trio.testing import open_stream_to_socket_listener from .. import socket as tsocket from .._core.tests.tutil import slow, need_ipv6 @@ -146,14 +144,7 @@ async def test_open_tcp_listeners_rebind(): assert s_established.socket.getsockname() == sockaddr2 assert c_time_wait.socket.getpeername() == sockaddr2 - for resource in [ - l1, - l2, - c_established, - s_established, - c_time_wait, - s_time_wait, - ]: + for resource in [l1, l2, c_established, s_established, c_time_wait, s_time_wait]: await resource.aclose() diff --git a/trio/tests/test_highlevel_open_tcp_stream.py b/trio/tests/test_highlevel_open_tcp_stream.py index 707f57ecbb..648ffe92b9 100644 --- a/trio/tests/test_highlevel_open_tcp_stream.py +++ b/trio/tests/test_highlevel_open_tcp_stream.py @@ -31,9 +31,7 @@ def close(self): def test_reorder_for_rfc_6555_section_5_4(): def fake4(i): - return ( - AF_INET, SOCK_STREAM, IPPROTO_TCP, "", ("10.0.0.{}".format(i), 80) - ) + return (AF_INET, SOCK_STREAM, IPPROTO_TCP, "", ("10.0.0.{}".format(i), 80)) def fake6(i): return (AF_INET6, SOCK_STREAM, IPPROTO_TCP, "", ("::{}".format(i), 80)) @@ -262,11 +260,7 @@ async def test_basic_fallthrough(autojump_clock): ) assert sock.ip == "3.3.3.3" assert trio.current_time() == (0.300 + 0.300 + 0.2) - assert scenario.connect_times == { - "1.1.1.1": 0, - "2.2.2.2": 0.300, - "3.3.3.3": 0.600, - } + assert scenario.connect_times == {"1.1.1.1": 0, "2.2.2.2": 0.300, "3.3.3.3": 0.600} async def test_early_success(autojump_clock): @@ -300,11 +294,7 @@ async def test_custom_delay(autojump_clock): ) assert sock.ip == "1.1.1.1" assert trio.current_time() == 1 - assert scenario.connect_times == { - "1.1.1.1": 0, - "2.2.2.2": 0.450, - "3.3.3.3": 0.900, - } + assert scenario.connect_times == {"1.1.1.1": 0, "2.2.2.2": 0.450, "3.3.3.3": 0.900} async def test_custom_errors_expedite(autojump_clock): @@ -392,10 +382,7 @@ async def test_does_reorder(autojump_clock): ) assert sock.ip == "::3" assert trio.current_time() == 1 + 0.5 - assert scenario.connect_times == { - "1.1.1.1": 0, - "::3": 1, - } + assert scenario.connect_times == {"1.1.1.1": 0, "::3": 1} async def test_handles_no_ipv6(autojump_clock): @@ -414,10 +401,7 @@ async def test_handles_no_ipv6(autojump_clock): ) assert sock.ip == "4.4.4.4" assert trio.current_time() == 1 + 0.1 - assert scenario.connect_times == { - "2.2.2.2": 0, - "4.4.4.4": 1.0, - } + assert scenario.connect_times == {"2.2.2.2": 0, "4.4.4.4": 1.0} async def test_no_hosts(autojump_clock): diff --git a/trio/tests/test_highlevel_serve_listeners.py b/trio/tests/test_highlevel_serve_listeners.py index a0fc80589d..0b423b8734 100644 --- a/trio/tests/test_highlevel_serve_listeners.py +++ b/trio/tests/test_highlevel_serve_listeners.py @@ -139,7 +139,7 @@ async def connection_watcher(*, task_status=trio.TASK_STATUS_IGNORED): trio.serve_listeners, handler, [listener], - handler_nursery=handler_nursery + handler_nursery=handler_nursery, ) ) for _ in range(10): diff --git a/trio/tests/test_highlevel_socket.py b/trio/tests/test_highlevel_socket.py index 90f8ebd077..d4a12ad11f 100644 --- a/trio/tests/test_highlevel_socket.py +++ b/trio/tests/test_highlevel_socket.py @@ -6,7 +6,9 @@ from .. import _core from ..testing import ( - check_half_closeable_stream, wait_all_tasks_blocked, assert_checkpoints + check_half_closeable_stream, + wait_all_tasks_blocked, + assert_checkpoints, ) from .._highlevel_socket import * from .. import socket as tsocket diff --git a/trio/tests/test_highlevel_ssl_helpers.py b/trio/tests/test_highlevel_ssl_helpers.py index 41cdb2dc25..53c97ca6fb 100644 --- a/trio/tests/test_highlevel_ssl_helpers.py +++ b/trio/tests/test_highlevel_ssl_helpers.py @@ -10,7 +10,9 @@ from .test_ssl import CLIENT_CTX, SERVER_CTX from .._highlevel_ssl_helpers import ( - open_ssl_over_tcp_stream, open_ssl_over_tcp_listeners, serve_ssl_over_tcp + open_ssl_over_tcp_stream, + open_ssl_over_tcp_listeners, + serve_ssl_over_tcp, ) @@ -43,13 +45,7 @@ async def getnameinfo(self, *args): # pragma: no cover async def test_open_ssl_over_tcp_stream_and_everything_else(): async with trio.open_nursery() as nursery: (listener,) = await nursery.start( - partial( - serve_ssl_over_tcp, - echo_handler, - 0, - SERVER_CTX, - host="127.0.0.1" - ) + partial(serve_ssl_over_tcp, echo_handler, 0, SERVER_CTX, host="127.0.0.1") ) sockaddr = listener.transport_listener.socket.getsockname() hostname_resolver = FakeHostnameResolver(sockaddr) @@ -64,18 +60,14 @@ async def test_open_ssl_over_tcp_stream_and_everything_else(): # We have the trust but not the hostname # (checks custom ssl_context + hostname checking) stream = await open_ssl_over_tcp_stream( - "xyzzy.example.org", - 80, - ssl_context=CLIENT_CTX, + "xyzzy.example.org", 80, ssl_context=CLIENT_CTX ) with pytest.raises(trio.BrokenResourceError): await stream.do_handshake() # This one should work! stream = await open_ssl_over_tcp_stream( - "trio-test-1.example.org", - 80, - ssl_context=CLIENT_CTX, + "trio-test-1.example.org", 80, ssl_context=CLIENT_CTX ) assert isinstance(stream, trio.ssl.SSLStream) assert stream.server_hostname == "trio-test-1.example.org" @@ -100,9 +92,7 @@ async def test_open_ssl_over_tcp_stream_and_everything_else(): async def test_open_ssl_over_tcp_listeners(): - (listener,) = await open_ssl_over_tcp_listeners( - 0, SERVER_CTX, host="127.0.0.1" - ) + (listener,) = await open_ssl_over_tcp_listeners(0, SERVER_CTX, host="127.0.0.1") async with listener: assert isinstance(listener, trio.ssl.SSLListener) tl = listener.transport_listener diff --git a/trio/tests/test_path.py b/trio/tests/test_path.py index 5bd950f0ab..04176936a2 100644 --- a/trio/tests/test_path.py +++ b/trio/tests/test_path.py @@ -11,7 +11,7 @@ @pytest.fixture def path(tmpdir): - p = str(tmpdir.join('test')) + p = str(tmpdir.join("test")) return trio.Path(p) @@ -22,33 +22,33 @@ def method_pair(path, method_name): async def test_open_is_async_context_manager(path): - async with await path.open('w') as f: + async with await path.open("w") as f: assert isinstance(f, AsyncIOWrapper) assert f.closed async def test_magic(): - path = trio.Path('test') + path = trio.Path("test") - assert str(path) == 'test' - assert bytes(path) == b'test' + assert str(path) == "test" + assert bytes(path) == b"test" cls_pairs = [ (trio.Path, pathlib.Path), (pathlib.Path, trio.Path), - (trio.Path, trio.Path) + (trio.Path, trio.Path), ] -@pytest.mark.parametrize('cls_a,cls_b', cls_pairs) +@pytest.mark.parametrize("cls_a,cls_b", cls_pairs) async def test_cmp_magic(cls_a, cls_b): - a, b = cls_a(''), cls_b('') + a, b = cls_a(""), cls_b("") assert a == b assert not a != b - a, b = cls_a('a'), cls_b('b') + a, b = cls_a("a"), cls_b("b") assert a < b assert b > a @@ -65,39 +65,39 @@ async def test_cmp_magic(cls_a, cls_b): (trio.Path, pathlib.Path), (trio.Path, trio.Path), (trio.Path, str), - (str, trio.Path) + (str, trio.Path), ] -@pytest.mark.parametrize('cls_a,cls_b', cls_pairs) +@pytest.mark.parametrize("cls_a,cls_b", cls_pairs) async def test_div_magic(cls_a, cls_b): - a, b = cls_a('a'), cls_b('b') + a, b = cls_a("a"), cls_b("b") result = a / b assert isinstance(result, trio.Path) - assert str(result) == os.path.join('a', 'b') + assert str(result) == os.path.join("a", "b") async def test_forwarded_properties(path): # use `name` as a representative of forwarded properties - assert 'name' in dir(path) - assert path.name == 'test' + assert "name" in dir(path) + assert path.name == "test" async def test_async_method_signature(path): # use `resolve` as a representative of wrapped methods - assert path.resolve.__name__ == 'resolve' - assert path.resolve.__qualname__ == 'Path.resolve' + assert path.resolve.__name__ == "resolve" + assert path.resolve.__qualname__ == "Path.resolve" - assert 'pathlib.Path.resolve' in path.resolve.__doc__ + assert "pathlib.Path.resolve" in path.resolve.__doc__ -@pytest.mark.parametrize('method_name', ['is_dir', 'is_file']) +@pytest.mark.parametrize("method_name", ["is_dir", "is_file"]) async def test_compare_async_stat_methods(method_name): - method, async_method = method_pair('.', method_name) + method, async_method = method_pair(".", method_name) result = method() async_result = await async_method() @@ -107,13 +107,13 @@ async def test_compare_async_stat_methods(method_name): async def test_invalid_name_not_wrapped(path): with pytest.raises(AttributeError): - getattr(path, 'invalid_fake_attr') + getattr(path, "invalid_fake_attr") -@pytest.mark.parametrize('method_name', ['absolute', 'resolve']) +@pytest.mark.parametrize("method_name", ["absolute", "resolve"]) async def test_async_methods_rewrap(method_name): - method, async_method = method_pair('.', method_name) + method, async_method = method_pair(".", method_name) result = method() async_result = await async_method() @@ -123,13 +123,13 @@ async def test_async_methods_rewrap(method_name): async def test_forward_methods_rewrap(path, tmpdir): - with_name = path.with_name('foo') - with_suffix = path.with_suffix('.py') + with_name = path.with_name("foo") + with_suffix = path.with_suffix(".py") assert isinstance(with_name, trio.Path) - assert with_name == tmpdir.join('foo') + assert with_name == tmpdir.join("foo") assert isinstance(with_suffix, trio.Path) - assert with_suffix == tmpdir.join('test.py') + assert with_suffix == tmpdir.join("test.py") async def test_forward_properties_rewrap(path): @@ -139,18 +139,18 @@ async def test_forward_properties_rewrap(path): async def test_forward_methods_without_rewrap(path, tmpdir): path = await path.parent.resolve() - assert path.as_uri().startswith('file:///') + assert path.as_uri().startswith("file:///") async def test_repr(): - path = trio.Path('.') + path = trio.Path(".") assert repr(path) == "trio.Path('.')" class MockWrapped: - unsupported = 'unsupported' - _private = 'private' + unsupported = "unsupported" + _private = "private" class MockWrapper: @@ -169,18 +169,18 @@ async def test_type_wraps_unsupported(): async def test_type_forwards_private(): - Type.generate_forwards(MockWrapper, {'unsupported': None}) + Type.generate_forwards(MockWrapper, {"unsupported": None}) - assert not hasattr(MockWrapper, '_private') + assert not hasattr(MockWrapper, "_private") async def test_type_wraps_private(): - Type.generate_wraps(MockWrapper, {'unsupported': None}) + Type.generate_wraps(MockWrapper, {"unsupported": None}) - assert not hasattr(MockWrapper, '_private') + assert not hasattr(MockWrapper, "_private") -@pytest.mark.parametrize('meth', [trio.Path.__init__, trio.Path.joinpath]) +@pytest.mark.parametrize("meth", [trio.Path.__init__, trio.Path.joinpath]) async def test_path_wraps_path(path, meth): wrapped = await path.absolute() result = meth(path, wrapped) @@ -196,19 +196,19 @@ async def test_path_nonpath(): async def test_open_file_can_open_path(path): - async with await trio.open_file(path, 'w') as f: + async with await trio.open_file(path, "w") as f: assert f.name == fspath(path) async def test_iterdir(path): # Populate a directory await path.mkdir() - await (path / 'foo').mkdir() - await (path / 'bar.txt').write_bytes(b'') + await (path / "foo").mkdir() + await (path / "bar.txt").write_bytes(b"") entries = set() for entry in await path.iterdir(): assert isinstance(entry, trio.Path) entries.add(entry.name) - assert entries == {'bar.txt', 'foo'} + assert entries == {"bar.txt", "foo"} diff --git a/trio/tests/test_signals.py b/trio/tests/test_signals.py index d97a1e36d1..fc647e2d27 100644 --- a/trio/tests/test_signals.py +++ b/trio/tests/test_signals.py @@ -125,6 +125,7 @@ async def test_open_signal_receiver_no_starvation(): # open_signal_receiver block might cause the signal to be # redelivered and give us a core dump instead of a traceback... import traceback + traceback.print_exc() @@ -181,9 +182,7 @@ def raise_handler(signum, _): with _signal_handler({signal.SIGILL, signal.SIGFPE}, raise_handler): with pytest.raises(RuntimeError) as excinfo: - with open_signal_receiver( - signal.SIGILL, signal.SIGFPE - ) as receiver: + with open_signal_receiver(signal.SIGILL, signal.SIGFPE) as receiver: signal_raise(signal.SIGILL) signal_raise(signal.SIGFPE) await wait_run_sync_soon_idempotent_queue_barrier() diff --git a/trio/tests/test_socket.py b/trio/tests/test_socket.py index 6dd3d68fe5..362c5d9323 100644 --- a/trio/tests/test_socket.py +++ b/trio/tests/test_socket.py @@ -43,9 +43,7 @@ def getaddrinfo(self, *args, **kwargs): elif bound[-1] & stdlib_socket.AI_NUMERICHOST: return self._orig_getaddrinfo(*args, **kwargs) else: - raise RuntimeError( - "gai called with unexpected arguments {}".format(bound) - ) + raise RuntimeError("gai called with unexpected arguments {}".format(bound)) @pytest.fixture @@ -108,29 +106,35 @@ def without_proto(gai_tup): # Simple non-blocking non-error cases, ipv4 and ipv6: with assert_checkpoints(): - res = await tsocket.getaddrinfo( - "127.0.0.1", "12345", type=tsocket.SOCK_STREAM - ) - - check(res, [ - (tsocket.AF_INET, # 127.0.0.1 is ipv4 - tsocket.SOCK_STREAM, - tsocket.IPPROTO_TCP, - "", - ("127.0.0.1", 12345)), - ]) # yapf: disable + res = await tsocket.getaddrinfo("127.0.0.1", "12345", type=tsocket.SOCK_STREAM) + + check( + res, + [ + ( + tsocket.AF_INET, # 127.0.0.1 is ipv4 + tsocket.SOCK_STREAM, + tsocket.IPPROTO_TCP, + "", + ("127.0.0.1", 12345), + ) + ], + ) with assert_checkpoints(): - res = await tsocket.getaddrinfo( - "::1", "12345", type=tsocket.SOCK_DGRAM - ) - check(res, [ - (tsocket.AF_INET6, - tsocket.SOCK_DGRAM, - tsocket.IPPROTO_UDP, - "", - ("::1", 12345, 0, 0)), - ]) # yapf: disable + res = await tsocket.getaddrinfo("::1", "12345", type=tsocket.SOCK_DGRAM) + check( + res, + [ + ( + tsocket.AF_INET6, + tsocket.SOCK_DGRAM, + tsocket.IPPROTO_UDP, + "", + ("::1", 12345, 0, 0), + ) + ], + ) monkeygai.set("x", b"host", "port", family=0, type=0, proto=0, flags=0) with assert_checkpoints(): @@ -355,10 +359,11 @@ async def test_SocketType_shutdown(): @pytest.mark.parametrize( - "address, socket_type", [ - ('127.0.0.1', tsocket.AF_INET), - pytest.param('::1', tsocket.AF_INET6, marks=need_ipv6) - ] + "address, socket_type", + [ + ("127.0.0.1", tsocket.AF_INET), + pytest.param("::1", tsocket.AF_INET6, marks=need_ipv6), + ], ) async def test_SocketType_simple_server(address, socket_type): # listen, bind, accept, connect, getpeername, getsockname @@ -633,7 +638,7 @@ async def _resolve_remote_address(self, *args, **kwargs): sock._resolve_remote_address = _resolve_remote_address with assert_checkpoints(): with pytest.raises(_core.Cancelled): - await sock.connect('') + await sock.connect("") assert sock.fileno() == -1 @@ -779,9 +784,11 @@ async def getnameinfo(self, sockaddr, flags): (0, 0, tsocket.IPPROTO_TCP, 0), (0, 0, 0, tsocket.AI_CANONNAME), ]: - assert ( - await tsocket.getaddrinfo("localhost", "foo", *vals) == - ("custom_gai", b"localhost", "foo", *vals) + assert await tsocket.getaddrinfo("localhost", "foo", *vals) == ( + "custom_gai", + b"localhost", + "foo", + *vals, ) # IDNA encoding is handled before calling the special object @@ -789,7 +796,7 @@ async def getnameinfo(self, sockaddr, flags): expected = ("custom_gai", b"xn--f-1gaa", "foo", 0, 0, 0, 0) assert got == expected - assert (await tsocket.getnameinfo("a", 0) == ("custom_gni", "a", 0)) + assert await tsocket.getnameinfo("a", 0) == ("custom_gni", "a", 0) # We can set it back to None assert tsocket.set_custom_hostname_resolver(None) is cr @@ -832,9 +839,7 @@ async def test_SocketType_is_abstract(): tsocket.SocketType() -@pytest.mark.skipif( - not hasattr(tsocket, "AF_UNIX"), reason="no unix domain sockets" -) +@pytest.mark.skipif(not hasattr(tsocket, "AF_UNIX"), reason="no unix domain sockets") async def test_unix_domain_socket(): # Bind has a special branch to use a thread, since it has to do filesystem # traversal. Maybe connect should too? Not sure. diff --git a/trio/tests/test_ssl.py b/trio/tests/test_ssl.py index 93eee560d1..5cbef70fb5 100644 --- a/trio/tests/test_ssl.py +++ b/trio/tests/test_ssl.py @@ -106,7 +106,7 @@ async def ssl_echo_server_raw(**kwargs): with a, b: nursery.start_soon( trio.run_sync_in_worker_thread, - partial(ssl_echo_serve_sync, b, **kwargs) + partial(ssl_echo_serve_sync, b, **kwargs), ) await yield_(SocketStream(tsocket.from_stdlib_socket(a))) @@ -119,9 +119,7 @@ async def ssl_echo_server_raw(**kwargs): async def ssl_echo_server(**kwargs): async with ssl_echo_server_raw(**kwargs) as sock: await yield_( - tssl.SSLStream( - sock, CLIENT_CTX, server_hostname="trio-test-1.example.org" - ) + tssl.SSLStream(sock, CLIENT_CTX, server_hostname="trio-test-1.example.org") ) @@ -359,9 +357,7 @@ async def test_ssl_client_basics(): # Didn't configure the CA file, should fail async with ssl_echo_server_raw(expect_fail=True) as sock: client_ctx = stdlib_ssl.create_default_context() - s = tssl.SSLStream( - sock, client_ctx, server_hostname="trio-test-1.example.org" - ) + s = tssl.SSLStream(sock, client_ctx, server_hostname="trio-test-1.example.org") assert not s.server_side with pytest.raises(BrokenResourceError) as excinfo: await s.send_all(b"x") @@ -369,9 +365,7 @@ async def test_ssl_client_basics(): # Trusted CA, but wrong host name async with ssl_echo_server_raw(expect_fail=True) as sock: - s = tssl.SSLStream( - sock, CLIENT_CTX, server_hostname="trio-test-2.example.org" - ) + s = tssl.SSLStream(sock, CLIENT_CTX, server_hostname="trio-test-2.example.org") assert not s.server_side with pytest.raises(BrokenResourceError) as excinfo: await s.send_all(b"x") @@ -412,9 +406,7 @@ async def test_attributes(): async with ssl_echo_server_raw(expect_fail=True) as sock: good_ctx = CLIENT_CTX bad_ctx = stdlib_ssl.create_default_context() - s = tssl.SSLStream( - sock, good_ctx, server_hostname="trio-test-1.example.org" - ) + s = tssl.SSLStream(sock, good_ctx, server_hostname="trio-test-1.example.org") assert s.transport_stream is sock @@ -541,6 +533,7 @@ async def test_renegotiation_randomized(mock_clock): mock_clock.autojump_threshold = 0 import random + r = random.Random(0) async def sleeper(_): @@ -577,8 +570,8 @@ async def expect(expected): await clear() for i in range(100): - b1 = bytes([i % 0xff]) - b2 = bytes([(2 * i) % 0xff]) + b1 = bytes([i % 0xFF]) + b2 = bytes([(2 * i) % 0xFF]) s.transport_stream.renegotiate() async with _core.open_nursery() as nursery: nursery.start_soon(send, b1) @@ -589,8 +582,8 @@ async def expect(expected): await clear() for i in range(100): - b1 = bytes([i % 0xff]) - b2 = bytes([(2 * i) % 0xff]) + b1 = bytes([i % 0xFF]) + b2 = bytes([(2 * i) % 0xFF]) await send(b1) s.transport_stream.renegotiate() await expect(b1) @@ -971,7 +964,7 @@ async def test_ssl_bad_shutdown(): async def test_ssl_bad_shutdown_but_its_ok(): client, server = ssl_memory_stream_pair( server_kwargs={"https_compatible": True}, - client_kwargs={"https_compatible": True} + client_kwargs={"https_compatible": True}, ) async with _core.open_nursery() as nursery: @@ -995,9 +988,7 @@ async def test_ssl_handshake_failure_during_aclose(): async with ssl_echo_server_raw(expect_fail=True) as sock: # Don't configure trust correctly client_ctx = stdlib_ssl.create_default_context() - s = tssl.SSLStream( - sock, client_ctx, server_hostname="trio-test-1.example.org" - ) + s = tssl.SSLStream(sock, client_ctx, server_hostname="trio-test-1.example.org") # It's a little unclear here whether aclose should swallow the error # or let it escape. We *do* swallow the error if it arrives when we're # sending close_notify, because both sides closing the connection @@ -1036,7 +1027,7 @@ def close_hook(): async def test_ssl_https_compatibility_disagreement(): client, server = ssl_memory_stream_pair( server_kwargs={"https_compatible": False}, - client_kwargs={"https_compatible": True} + client_kwargs={"https_compatible": True}, ) async with _core.open_nursery() as nursery: @@ -1058,7 +1049,7 @@ async def receive_and_expect_error(): async def test_https_mode_eof_before_handshake(): client, server = ssl_memory_stream_pair( server_kwargs={"https_compatible": True}, - client_kwargs={"https_compatible": True} + client_kwargs={"https_compatible": True}, ) async def server_expect_clean_eof(): @@ -1131,8 +1122,7 @@ async def test_selected_alpn_protocol_when_not_set(): assert client.selected_alpn_protocol() is None assert server.selected_alpn_protocol() is None - assert client.selected_alpn_protocol() == \ - server.selected_alpn_protocol() + assert client.selected_alpn_protocol() == server.selected_alpn_protocol() async def test_selected_npn_protocol_before_handshake(): @@ -1157,8 +1147,7 @@ async def test_selected_npn_protocol_when_not_set(): assert client.selected_npn_protocol() is None assert server.selected_npn_protocol() is None - assert client.selected_npn_protocol() == \ - server.selected_npn_protocol() + assert client.selected_npn_protocol() == server.selected_npn_protocol() async def test_get_channel_binding_before_handshake(): @@ -1181,8 +1170,7 @@ async def test_get_channel_binding_after_handshake(): assert client.get_channel_binding() is not None assert server.get_channel_binding() is not None - assert client.get_channel_binding() == \ - server.get_channel_binding() + assert client.get_channel_binding() == server.get_channel_binding() async def test_getpeercert(): @@ -1195,10 +1183,7 @@ async def test_getpeercert(): assert server.getpeercert() is None print(client.getpeercert()) - assert ( - ("DNS", - "trio-test-1.example.org") in client.getpeercert()["subjectAltName"] - ) + assert ("DNS", "trio-test-1.example.org") in client.getpeercert()["subjectAltName"] async def test_SSLListener(): @@ -1211,9 +1196,7 @@ async def setup(**kwargs): transport_client = await open_tcp_stream(*listen_sock.getsockname()) ssl_client = tssl.SSLStream( - transport_client, - CLIENT_CTX, - server_hostname="trio-test-1.example.org" + transport_client, CLIENT_CTX, server_hostname="trio-test-1.example.org" ) return listen_sock, ssl_listener, ssl_client @@ -1238,8 +1221,7 @@ async def setup(**kwargs): # Test https_compatible and max_refill_bytes _, ssl_listener, ssl_client = await setup( - https_compatible=True, - max_refill_bytes=100, + https_compatible=True, max_refill_bytes=100 ) ssl_server = await ssl_listener.accept() diff --git a/trio/tests/test_sync.py b/trio/tests/test_sync.py index 272e97fc4b..d96edc5fa8 100644 --- a/trio/tests/test_sync.py +++ b/trio/tests/test_sync.py @@ -117,6 +117,7 @@ async def test_CapacityLimiter(): async def test_CapacityLimiter_inf(): from math import inf + c = CapacityLimiter(inf) repr(c) # smoke test assert c.total_tokens == inf @@ -246,10 +247,7 @@ async def test_Semaphore_bounded(): assert bs.value == 1 -@pytest.mark.parametrize( - "lockcls", - [Lock, StrictFIFOLock], ids=lambda fn: fn.__name__ -) +@pytest.mark.parametrize("lockcls", [Lock, StrictFIFOLock], ids=lambda fn: fn.__name__) async def test_Lock_and_StrictFIFOLock(lockcls): l = lockcls() # noqa assert not l.locked() @@ -796,7 +794,7 @@ async def loopy(name, lock_like): # The first three could be in any order due to scheduling randomness, # but after that they should repeat in the same order for i in range(LOOPS): - assert record[3 * i:3 * (i + 1)] == initial_order + assert record[3 * i : 3 * (i + 1)] == initial_order @generic_lock_test diff --git a/trio/tests/test_testing.py b/trio/tests/test_testing.py index c4fe714b1e..21dfcdbf8d 100644 --- a/trio/tests/test_testing.py +++ b/trio/tests/test_testing.py @@ -121,14 +121,7 @@ async def do_wait(cushion, tiebreaker): nursery.start_soon(do_wait, 0.0001, -10) assert record == sorted(record) - assert record == [ - (0, -1), - (0, -1), - (0, 0), - (0, 1), - (0.0001, -10), - (0.0001, 10), - ] + assert record == [(0, -1), (0, -1), (0, 0), (0, 1), (0.0001, -10), (0.0001, 10)] ################################################################ @@ -146,7 +139,8 @@ async def test_assert_checkpoints(recwarn): # 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 + _core.checkpoint_if_cancelled, + _core.cancel_shielded_checkpoint, ]: print(partial_yield) with pytest.raises(AssertionError): @@ -171,7 +165,8 @@ async def test_assert_no_checkpoints(recwarn): # 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.checkpoint_if_cancelled, _core.cancel_shielded_checkpoint + _core.checkpoint_if_cancelled, + _core.cancel_shielded_checkpoint, ]: print(partial_yield) with pytest.raises(AssertionError): @@ -215,9 +210,7 @@ async def f2(seq): nursery.start_soon(f2, seq) async with seq(5): await wait_all_tasks_blocked() - assert record == [ - ("f2", 0), ("f1", 1), ("f2", 2), ("f1", 3), ("f1", 4) - ] + assert record == [("f2", 0), ("f1", 1), ("f2", 2), ("f1", 3), ("f1", 4)] seq = Sequencer() # Catches us if we try to re-use a sequence point: @@ -321,11 +314,7 @@ async def test_mock_clock_autojump(mock_clock): virtual_start = _core.current_time() real_duration = time.perf_counter() - real_start - print( - "Slept {} seconds in {} seconds".format( - 10 * sum(range(10)), real_duration - ) - ) + print("Slept {} seconds in {} seconds".format(10 * sum(range(10)), real_duration)) assert real_duration < 1 mock_clock.autojump_threshold = 0.02 @@ -571,9 +560,7 @@ def close_hook(): record.append("close_hook") mss2 = MemorySendStream( - send_all_hook, - wait_send_all_might_not_block_hook, - close_hook, + send_all_hook, wait_send_all_might_not_block_hook, close_hook ) assert mss2.send_all_hook is send_all_hook diff --git a/trio/tests/test_threads.py b/trio/tests/test_threads.py index 9f7fac118b..657fe52113 100644 --- a/trio/tests/test_threads.py +++ b/trio/tests/test_threads.py @@ -36,10 +36,7 @@ def threadfn(): while child_thread.is_alive(): print("yawn") await sleep(0.01) - assert record == [ - ("start", child_thread), - ("f", trio_thread), expected - ] + assert record == [("start", child_thread), ("f", trio_thread), expected] portal = BlockingTrioPortal() @@ -116,6 +113,7 @@ def trio_thread_fn(): ki_self() finally: import sys + print("finally", sys.exc_info()) async def trio_thread_afn(): @@ -206,9 +204,7 @@ def f(q): async def child(q, cancellable): record.append("start") try: - return await run_sync_in_worker_thread( - f, q, cancellable=cancellable - ) + return await run_sync_in_worker_thread(f, q, cancellable=cancellable) finally: record.append("exit") @@ -349,15 +345,9 @@ def thread_fn(cancel_scope): async def run_thread(event): with _core.open_cancel_scope() as cancel_scope: await run_sync_in_worker_thread( - thread_fn, - cancel_scope, - limiter=limiter_arg, - cancellable=cancel + thread_fn, cancel_scope, limiter=limiter_arg, cancellable=cancel ) - print( - "run_thread finished, cancelled:", - cancel_scope.cancelled_caught - ) + print("run_thread finished, cancelled:", cancel_scope.cancelled_caught) event.set() async with _core.open_nursery() as nursery: diff --git a/trio/tests/test_util.py b/trio/tests/test_util.py index 06bf86b66b..463aeb77af 100644 --- a/trio/tests/test_util.py +++ b/trio/tests/test_util.py @@ -68,12 +68,14 @@ async def wait_with_ul1(): def test_module_metadata_is_fixed_up(): import trio + assert trio.Cancelled.__module__ == "trio" assert trio.open_cancel_scope.__module__ == "trio" assert trio.ssl.SSLStream.__module__ == "trio.ssl" assert trio.abc.Stream.__module__ == "trio.abc" assert trio.hazmat.wait_task_rescheduled.__module__ == "trio.hazmat" import trio.testing + assert trio.testing.trio_test.__module__ == "trio.testing" # Also check methods @@ -102,15 +104,11 @@ class TestFspath(object): # based on: # https://github.com/python/cpython/blob/da6c3da6c33c6bf794f741e348b9c6d86cc43ec5/Lib/test/test_os.py#L3527-L3571 - @pytest.mark.parametrize( - "path", (b'hello', b'goodbye', b'some/path/and/file') - ) + @pytest.mark.parametrize("path", (b"hello", b"goodbye", b"some/path/and/file")) def test_return_bytes(self, path): assert path == fspath(path) - @pytest.mark.parametrize( - "path", ('hello', 'goodbye', 'some/path/and/file') - ) + @pytest.mark.parametrize("path", ("hello", "goodbye", "some/path/and/file")) def test_return_string(self, path): assert path == fspath(path) @@ -147,16 +145,22 @@ def test_throw_error_at_non_pathlike(self, klass): "exception, method", [ (TypeError, 1), # __fspath__ is not callable - (TypeError, lambda x: 23 - ), # __fspath__ returns a value other than str or bytes - (Exception, lambda x: raise_(Exception) - ), # __fspath__raises a random exception - (AttributeError, lambda x: raise_(AttributeError) - ), # __fspath__ raises AttributeError - ] + ( + TypeError, + lambda x: 23, + ), # __fspath__ returns a value other than str or bytes + ( + Exception, + lambda x: raise_(Exception), + ), # __fspath__raises a random exception + ( + AttributeError, + lambda x: raise_(AttributeError), + ), # __fspath__ raises AttributeError + ], ) def test_bad_pathlike_implementation(self, exception, method): - klass = type('foo', (), {}) + klass = type("foo", (), {}) klass.__fspath__ = method with pytest.raises(exception): fspath(klass()) diff --git a/trio/tests/test_wait_for_object.py b/trio/tests/test_wait_for_object.py index 3a83e454e0..a12425dcb3 100644 --- a/trio/tests/test_wait_for_object.py +++ b/trio/tests/test_wait_for_object.py @@ -3,16 +3,21 @@ import pytest -on_windows = (os.name == "nt") +on_windows = os.name == "nt" # Mark all the tests in this file as being windows-only pytestmark = pytest.mark.skipif(not on_windows, reason="windows only") from .._core.tests.tutil import slow from .. import _core from .. import _timeouts + if on_windows: from .._core._windows_cffi import ffi, kernel32 - from .._wait_for_object import WaitForSingleObject, WaitForMultipleObjects_sync, run_sync_in_worker_thread + from .._wait_for_object import ( + WaitForSingleObject, + WaitForMultipleObjects_sync, + run_sync_in_worker_thread, + ) async def test_WaitForMultipleObjects_sync(): @@ -29,7 +34,7 @@ async def test_WaitForMultipleObjects_sync(): kernel32.SetEvent(handle1) WaitForMultipleObjects_sync(handle1) kernel32.CloseHandle(handle1) - print('test_WaitForMultipleObjects_sync one OK') + print("test_WaitForMultipleObjects_sync one OK") # Two handles, signal first handle1 = kernel32.CreateEventA(ffi.NULL, True, False, ffi.NULL) @@ -38,7 +43,7 @@ async def test_WaitForMultipleObjects_sync(): WaitForMultipleObjects_sync(handle1, handle2) kernel32.CloseHandle(handle1) kernel32.CloseHandle(handle2) - print('test_WaitForMultipleObjects_sync set first OK') + print("test_WaitForMultipleObjects_sync set first OK") # Two handles, signal second handle1 = kernel32.CreateEventA(ffi.NULL, True, False, ffi.NULL) @@ -47,7 +52,7 @@ async def test_WaitForMultipleObjects_sync(): WaitForMultipleObjects_sync(handle1, handle2) kernel32.CloseHandle(handle1) kernel32.CloseHandle(handle2) - print('test_WaitForMultipleObjects_sync set second OK') + print("test_WaitForMultipleObjects_sync set second OK") # Two handles, close first handle1 = kernel32.CreateEventA(ffi.NULL, True, False, ffi.NULL) @@ -56,7 +61,7 @@ async def test_WaitForMultipleObjects_sync(): with pytest.raises(OSError): WaitForMultipleObjects_sync(handle1, handle2) kernel32.CloseHandle(handle2) - print('test_WaitForMultipleObjects_sync close first OK') + print("test_WaitForMultipleObjects_sync close first OK") # Two handles, close second handle1 = kernel32.CreateEventA(ffi.NULL, True, False, ffi.NULL) @@ -65,7 +70,7 @@ async def test_WaitForMultipleObjects_sync(): with pytest.raises(OSError): WaitForMultipleObjects_sync(handle1, handle2) kernel32.CloseHandle(handle1) - print('test_WaitForMultipleObjects_sync close second OK') + print("test_WaitForMultipleObjects_sync close second OK") @slow @@ -89,7 +94,7 @@ async def test_WaitForMultipleObjects_sync_slow(): t1 = _core.current_time() assert TIMEOUT <= (t1 - t0) < 2.0 * TIMEOUT kernel32.CloseHandle(handle1) - print('test_WaitForMultipleObjects_sync_slow one OK') + print("test_WaitForMultipleObjects_sync_slow one OK") # Two handles, signal first handle1 = kernel32.CreateEventA(ffi.NULL, True, False, ffi.NULL) @@ -97,8 +102,7 @@ async def test_WaitForMultipleObjects_sync_slow(): t0 = _core.current_time() async with _core.open_nursery() as nursery: nursery.start_soon( - run_sync_in_worker_thread, WaitForMultipleObjects_sync, handle1, - handle2 + run_sync_in_worker_thread, WaitForMultipleObjects_sync, handle1, handle2 ) await _timeouts.sleep(TIMEOUT) kernel32.SetEvent(handle1) @@ -106,7 +110,7 @@ async def test_WaitForMultipleObjects_sync_slow(): assert TIMEOUT <= (t1 - t0) < 2.0 * TIMEOUT kernel32.CloseHandle(handle1) kernel32.CloseHandle(handle2) - print('test_WaitForMultipleObjects_sync_slow thread-set first OK') + print("test_WaitForMultipleObjects_sync_slow thread-set first OK") # Two handles, signal second handle1 = kernel32.CreateEventA(ffi.NULL, True, False, ffi.NULL) @@ -114,8 +118,7 @@ async def test_WaitForMultipleObjects_sync_slow(): t0 = _core.current_time() async with _core.open_nursery() as nursery: nursery.start_soon( - run_sync_in_worker_thread, WaitForMultipleObjects_sync, handle1, - handle2 + run_sync_in_worker_thread, WaitForMultipleObjects_sync, handle1, handle2 ) await _timeouts.sleep(TIMEOUT) kernel32.SetEvent(handle2) @@ -123,7 +126,7 @@ async def test_WaitForMultipleObjects_sync_slow(): assert TIMEOUT <= (t1 - t0) < 2.0 * TIMEOUT kernel32.CloseHandle(handle1) kernel32.CloseHandle(handle2) - print('test_WaitForMultipleObjects_sync_slow thread-set second OK') + print("test_WaitForMultipleObjects_sync_slow thread-set second OK") async def test_WaitForSingleObject(): @@ -135,7 +138,7 @@ async def test_WaitForSingleObject(): kernel32.SetEvent(handle) await WaitForSingleObject(handle) # should return at once kernel32.CloseHandle(handle) - print('test_WaitForSingleObject already set OK') + print("test_WaitForSingleObject already set OK") # Test already set, as int handle = kernel32.CreateEventA(ffi.NULL, True, False, ffi.NULL) @@ -143,21 +146,21 @@ async def test_WaitForSingleObject(): kernel32.SetEvent(handle) await WaitForSingleObject(handle_int) # should return at once kernel32.CloseHandle(handle) - print('test_WaitForSingleObject already set OK') + print("test_WaitForSingleObject already set OK") # Test already closed handle = kernel32.CreateEventA(ffi.NULL, True, False, ffi.NULL) kernel32.CloseHandle(handle) with pytest.raises(OSError): await WaitForSingleObject(handle) # should return at once - print('test_WaitForSingleObject already closed OK') + print("test_WaitForSingleObject already closed OK") # Not a handle with pytest.raises(TypeError): await WaitForSingleObject("not a handle") # Wrong type # with pytest.raises(OSError): # await WaitForSingleObject(99) # If you're unlucky, it actually IS a handle :( - print('test_WaitForSingleObject not a handle OK') + print("test_WaitForSingleObject not a handle OK") @slow @@ -185,7 +188,7 @@ async def signal_soon_async(handle): kernel32.CloseHandle(handle) t1 = _core.current_time() assert TIMEOUT <= (t1 - t0) < 2.0 * TIMEOUT - print('test_WaitForSingleObject_slow set from task OK') + print("test_WaitForSingleObject_slow set from task OK") # Test handle is SET after TIMEOUT in separate coroutine, as int @@ -200,7 +203,7 @@ async def signal_soon_async(handle): kernel32.CloseHandle(handle) t1 = _core.current_time() assert TIMEOUT <= (t1 - t0) < 2.0 * TIMEOUT - print('test_WaitForSingleObject_slow set from task as int OK') + print("test_WaitForSingleObject_slow set from task as int OK") # Test handle is CLOSED after 1 sec - NOPE see comment above @@ -217,4 +220,4 @@ async def signal_soon_async(handle): kernel32.CloseHandle(handle) t1 = _core.current_time() assert TIMEOUT <= (t1 - t0) < 2.0 * TIMEOUT - print('test_WaitForSingleObject_slow cancellation OK') + print("test_WaitForSingleObject_slow cancellation OK")