From b1f37f3b4405abc696b1c1a7d5cde2fbf1c8d189 Mon Sep 17 00:00:00 2001 From: "Dennis K. Paulsen" Date: Wed, 9 Sep 2026 16:12:24 -0500 Subject: [PATCH] Match ruff's rule set to pyguitest/pyguitest-recorder (docstrings, complexity, simplification, unused-argument checks), fixing the 8 suppressible try/except/pass patterns and ~40 missing docstrings it surfaced -- mostly one-liners on event dataclasses naming which numbering scheme a field uses --- CHANGELOG.md | 13 +++++ pyproject.toml | 33 +++++++++++- src/libei/_capi/__init__.py | 7 ++- src/libei/ei.py | 86 ++++++++++++++++++++++++++------ src/libei/eis.py | 82 +++++++++++++++++++++++------- src/libei/oeffis.py | 9 +++- src/libei/portal.py | 33 ++++++++---- tests/test_ei_objects.py | 5 +- tests/test_eis_objects.py | 5 +- tests/test_inputcapture.py | 5 +- tests/test_integration_extras.py | 8 +-- tests/test_oeffis.py | 6 +-- tests/test_portal.py | 11 ++-- 13 files changed, 234 insertions(+), 69 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index c04b06b..40e8c61 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,6 +7,19 @@ All notable changes to python-libei are recorded here. The format follows ## [Unreleased] +### Changed + +- **Ruff now enforces pydocstyle plus the same complexity/simplification/ + argument rules pyguitest and pyguitest-recorder already gate on** (`D`, + `C4`, `SIM`, `RET`, `ARG`, `C901`, ceiling 15) -- this repo's config had + never turned them on. Closing the gap surfaced two real things: eight + `try`/`except OSError: pass` blocks (tests plus two `__del__` methods in + `portal.py`) rewritten as `contextlib.suppress(OSError)`, and ~40 missing + docstrings, mostly one-line additions to the per-event dataclasses in + `ei.py`/`eis.py` naming the numbering scheme a field uses (e.g. + `KeyEvent.key` is a Linux `KEY_*` code, matching `Device.keyboard_key()`) + since that wasn't stated on the class itself. + ### Fixed - **`_wait_for_signal` (used by `InputCaptureSession.wait_for_activation`/ diff --git a/pyproject.toml b/pyproject.toml index a71a1bc..6231bde 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -87,8 +87,39 @@ select = [ "E", "W", # pycodestyle "F", # pyflakes "I", # isort - "UP", # pyupgrade + "D", # pydocstyle "B", # bugbear + "UP", # pyupgrade + "C4", # comprehensions + "SIM", # simplification + "RET", # return consistency + "ARG", # unused arguments + "C901", # cyclomatic complexity +] +ignore = [ + "D203", # incompatible with D211; keep no blank line before class docstring + "D213", # incompatible with D212; keep the summary on the first line + "D401", # properties read better as noun phrases than imperatives + "D105", # __enter__/__exit__ and friends document themselves +] + +[tool.ruff.lint.mccabe] +# pyguitest's ceiling; python-libei's own worst case (InputCaptureSession. +# negotiate(), forking on portal version) sits at 14, just under it. A +# ceiling on what gets added, not a claim everything else is close to it. +max-complexity = 15 + +[tool.ruff.lint.pydocstyle] +convention = "pep257" + +[tool.ruff.lint.per-file-ignores] +# Tests use fakes with deliberately unused arguments and multi-with blocks +# that read better nested; matching pyguitest's/pyguitest-recorder's own +# per-file-ignores for the same reasons. +"tests/*" = [ + "ARG001", "ARG002", "ARG003", "ARG005", # fakes accept arguments they ignore + "SIM117", # nested with-blocks read better in tests + "D100", "D101", "D102", "D103", "D104", "D107", ] [tool.mypy] diff --git a/src/libei/_capi/__init__.py b/src/libei/_capi/__init__.py index f76884a..55d8fbd 100644 --- a/src/libei/_capi/__init__.py +++ b/src/libei/_capi/__init__.py @@ -1,5 +1,8 @@ -"""Low-level ctypes bindings. Not part of the public API -- use -``libei.ei``, ``libei.eis`` and ``libei.oeffis`` instead.""" +"""Low-level ctypes bindings. + +Not part of the public API -- use ``libei.ei``, ``libei.eis`` and +``libei.oeffis`` instead. +""" from . import libei, libeis, liboeffis diff --git a/src/libei/ei.py b/src/libei/ei.py index 5a4f307..99f9203 100644 --- a/src/libei/ei.py +++ b/src/libei/ei.py @@ -87,6 +87,7 @@ class Error(Exception): """ def __init__(self, message: str, errno: int | None = None) -> None: + """Record the failure message and, where libei reported one, errno.""" super().__init__(message) self.message = message self.errno = errno @@ -199,6 +200,12 @@ class _LogPriority(enum.IntEnum): @dataclasses.dataclass(frozen=True, slots=True) class XkbModifiersEvent: + """XKB modifier state from a KEYBOARD_MODIFIERS event. + + ``depressed``/``latched``/``locked`` are XKB's own mod-state bitmasks; + ``group`` is the active keyboard layout group. + """ + depressed: int latched: int locked: int @@ -207,48 +214,76 @@ class XkbModifiersEvent: @dataclasses.dataclass(frozen=True, slots=True) class KeyEvent: + """Key code and press state from a KEYBOARD_KEY event. + + ``key`` is a Linux ``KEY_*`` code, the same numbering + :meth:`Device.keyboard_key` sends. + """ + key: int is_press: bool @dataclasses.dataclass(frozen=True, slots=True) class ButtonEvent: + """Button code and press state from a BUTTON_BUTTON event. + + ``button`` is a Linux ``BTN_*`` code, the same numbering + :meth:`Device.button` sends. + """ + button: int is_press: bool @dataclasses.dataclass(frozen=True, slots=True) class PointerEvent: + """Relative motion deltas, in logical pixels, from a POINTER_MOTION event.""" + dx: float dy: float @dataclasses.dataclass(frozen=True, slots=True) class PointerAbsoluteEvent: + """Absolute position from a POINTER_MOTION_ABSOLUTE event. + + In the logical pixel space of the :class:`Region` the emitting device + covers -- see :meth:`Event.pointer_absolute_event`. + """ + x: float y: float @dataclasses.dataclass(frozen=True, slots=True) class ScrollEvent: + """Smooth scroll deltas from a SCROLL_DELTA event.""" + dx: float dy: float @dataclasses.dataclass(frozen=True, slots=True) class ScrollDiscreteEvent: + """Detent scroll deltas (120 per detent) from a SCROLL_DISCRETE event.""" + dx: int dy: int @dataclasses.dataclass(frozen=True, slots=True) class ScrollStopEvent: + """Which axes stopped scrolling, from a SCROLL_STOP/SCROLL_CANCEL event.""" + stop_x: bool stop_y: bool @dataclasses.dataclass(frozen=True, slots=True) class TouchEvent: + """Touch id and position from a TOUCH_DOWN or TOUCH_MOTION event.""" + touchid: int x: float y: float @@ -256,17 +291,26 @@ class TouchEvent: @dataclasses.dataclass(frozen=True, slots=True) class TouchUpEvent: + """Touch id and cancellation flag from a TOUCH_UP event. + + See :meth:`Event.touch_up_event` for when ``is_cancel`` is trustworthy. + """ + touchid: int is_cancel: bool @dataclasses.dataclass(frozen=True, slots=True) class TextUtf8Event: + """UTF-8 text carried by a TEXT_UTF8 event.""" + text: str @dataclasses.dataclass(frozen=True, slots=True) class TextKeysymEvent: + """Keysym and press state from a TEXT_KEYSYM event.""" + keysym: int is_press: bool @@ -545,9 +589,10 @@ def stop_emulating(self) -> Device: return self def frame(self, timestamp: int | None = None) -> Device: - """Commit the events queued since the last frame as one logical - hardware event. ``timestamp`` defaults to the context's current - time.""" + """Commit the events queued since the last frame as one logical hardware event. + + ``timestamp`` defaults to the context's current time. + """ if timestamp is None: timestamp = _capi.libei.now(_capi.libei.device_get_context(self)) _capi.libei.device_frame(self, timestamp) @@ -564,8 +609,10 @@ def pointer_motion_absolute(self, x: float, y: float) -> Device: return self def button(self, button: int, is_press: bool) -> Device: - """Queue a button press or release. ``button`` is a Linux - ``BTN_*`` code (e.g. ``0x110`` for ``BTN_LEFT``).""" + """Queue a button press or release. + + ``button`` is a Linux ``BTN_*`` code (e.g. ``0x110`` for ``BTN_LEFT``). + """ _capi.libei.device_button_button(self, button, is_press) return self @@ -760,8 +807,11 @@ def __repr__(self) -> str: @property def event_type(self) -> EventType | int: - """The event's type, or a raw int for a value newer than this - package's :class:`EventType` table -- see its docstring.""" + """The event's type. + + Returns a raw int for a value newer than this package's + :class:`EventType` table -- see its docstring. + """ raw = _capi.libei.event_get_type(self) try: return EventType(raw) @@ -1009,11 +1059,14 @@ class Context(CObject): _wrappable = False def __init__(self, pointer: int, *, _adopt: bool = False) -> None: - # _adopt is accepted and forwarded for signature consistency with - # CObject, but with _wrappable = False, _get_or_create() never - # actually reaches this constructor -- Context (and Sender/ - # Receiver) are always built directly via cls(cls._new()) in - # create_for_fd()/create_for_socket(). + """Wrap a freshly created ``struct ei *`` and arm its log handler. + + _adopt is accepted and forwarded for signature consistency with + CObject, but with _wrappable = False, _get_or_create() never + actually reaches this constructor -- Context (and Sender/ + Receiver) are always built directly via cls(cls._new()) in + create_for_fd()/create_for_socket(). + """ super().__init__(pointer, _adopt=_adopt) self._name: str | None = None _capi.libei.log_set_handler(self, _log_handler) @@ -1081,7 +1134,8 @@ def set_fd(self: _ContextT, fd: IO[bytes] | int) -> _ContextT: """Use an already-connected socket as the transport. libei takes ownership of a raw int fd and closes it itself; a file - object is duplicated first, so the caller's own object stays valid.""" + object is duplicated first, so the caller's own object stays valid. + """ # ei_setup_backend_fd() takes ownership of the fd and will close it # itself. A raw int is assumed to already be one the caller is # handing off (matching what eis.Eis.add_client()/oeffis.eis_fd @@ -1099,7 +1153,8 @@ def set_socket(self: _ContextT, path: Path | None) -> _ContextT: """Connect to an EIS socket by path. ``None`` uses ``$LIBEI_SOCKET``; a relative path is resolved - against ``$XDG_RUNTIME_DIR``.""" + against ``$XDG_RUNTIME_DIR``. + """ encoded = os.fspath(path).encode("utf-8") if path else None err = _capi.libei.setup_backend_socket(self, encoded) if err < 0: @@ -1162,7 +1217,8 @@ def dispatch(self) -> None: """Read from the connection and queue any events that arrive. Call this before iterating :attr:`events`, which only drains what - is already queued.""" + is already queued. + """ _capi.libei.dispatch(self) diff --git a/src/libei/eis.py b/src/libei/eis.py index e3e74e1..eeb7397 100644 --- a/src/libei/eis.py +++ b/src/libei/eis.py @@ -55,6 +55,7 @@ class Error(Exception): """ def __init__(self, message: str, errno: int | None = None) -> None: + """Record the failure message and, where libeis reported one, errno.""" super().__init__(message) self.message = message self.errno = errno @@ -166,48 +167,75 @@ class _LogPriority(enum.IntEnum): @dataclasses.dataclass(frozen=True, slots=True) class KeyEvent: + """Key code and press state received on a KEYBOARD_KEY event. + + ``key`` is a Linux ``KEY_*`` code, as sent by the client's + ``ei.Device.keyboard_key``. + """ + key: int is_press: bool @dataclasses.dataclass(frozen=True, slots=True) class ButtonEvent: + """Button code and press state received on a BUTTON_BUTTON event. + + ``button`` is a Linux ``BTN_*`` code, as sent by the client's + ``ei.Device.button``. + """ + button: int is_press: bool @dataclasses.dataclass(frozen=True, slots=True) class PointerEvent: + """Relative motion deltas, in logical pixels, from a POINTER_MOTION event.""" + dx: float dy: float @dataclasses.dataclass(frozen=True, slots=True) class PointerAbsoluteEvent: + """Absolute position from a POINTER_MOTION_ABSOLUTE event. + + In the logical pixel space of the region the sending device covers. + """ + x: float y: float @dataclasses.dataclass(frozen=True, slots=True) class ScrollEvent: + """Smooth scroll deltas from a SCROLL_DELTA event.""" + dx: float dy: float @dataclasses.dataclass(frozen=True, slots=True) class ScrollDiscreteEvent: + """Detent scroll deltas (120 per detent) from a SCROLL_DISCRETE event.""" + dx: int dy: int @dataclasses.dataclass(frozen=True, slots=True) class ScrollStopEvent: + """Which axes stopped scrolling, from a SCROLL_STOP/SCROLL_CANCEL event.""" + stop_x: bool stop_y: bool @dataclasses.dataclass(frozen=True, slots=True) class TouchEvent: + """Touch id and position from a TOUCH_DOWN or TOUCH_MOTION event.""" + touchid: int x: float y: float @@ -215,17 +243,23 @@ class TouchEvent: @dataclasses.dataclass(frozen=True, slots=True) class TouchUpEvent: + """Touch id and cancellation flag from a TOUCH_UP event.""" + touchid: int is_cancel: bool @dataclasses.dataclass(frozen=True, slots=True) class TextUtf8Event: + """UTF-8 text carried by a TEXT_UTF8 event.""" + text: str @dataclasses.dataclass(frozen=True, slots=True) class TextKeysymEvent: + """Keysym and press state from a TEXT_KEYSYM event.""" + keysym: int is_press: bool @@ -576,8 +610,10 @@ def stop_emulating(self) -> Device: return self def frame(self, timestamp: int | None = None) -> Device: - """Commit the events queued since the last frame as one logical - hardware event. ``timestamp`` defaults to the context's current time.""" + """Commit the events queued since the last frame as one logical hardware event. + + ``timestamp`` defaults to the context's current time. + """ if timestamp is None: timestamp = _capi.libeis.now(_capi.libeis.device_get_context(self)) _capi.libeis.device_frame(self, timestamp) @@ -837,8 +873,11 @@ def __repr__(self) -> str: @property def event_type(self) -> EventType | int: - """The event's type, or a raw int for a value newer than this - package's :class:`EventType` table -- see its docstring.""" + """The event's type. + + Returns a raw int for a value newer than this package's + :class:`EventType` table -- see its docstring. + """ raw = _capi.libeis.event_get_type(self) try: return EventType(raw) @@ -1069,10 +1108,13 @@ class Eis(CObject): _wrappable = False def __init__(self, pointer: int, *, _adopt: bool = False) -> None: - # _adopt is accepted and forwarded for signature consistency with - # CObject, but with _wrappable = False, _get_or_create() never - # actually reaches this constructor -- Eis is always built directly - # via cls(cls._new()) in create_for_fd(). + """Wrap a freshly created ``struct eis *`` and arm its log handler. + + _adopt is accepted and forwarded for signature consistency with + CObject, but with _wrappable = False, _get_or_create() never + actually reaches this constructor -- Eis is always built directly + via cls(cls._new()) in create_for_fd(). + """ super().__init__(pointer, _adopt=_adopt) _capi.libeis.log_set_handler(self, _log_handler) _capi.libeis.log_set_priority(self, _LogPriority.DEBUG) @@ -1146,7 +1188,8 @@ def dispatch(self) -> None: """Read from the connection and queue any events that arrive. Call this before iterating :attr:`events`, which only drains what - is already queued.""" + is already queued. + """ _capi.libeis.dispatch(self) def add_client(self) -> int: @@ -1172,14 +1215,16 @@ def _new(cls) -> int: @classmethod def create_for_fd(cls, flags: Sequence[Flag] = ()) -> Eis: - """Create a server using the fd backend -- the one real compositors - use, since it keeps each client's fd private rather than exposing a - connectable socket path. Call :meth:`add_client` once per - connection you want to accept. + """Create a server using the fd backend. + + The one real compositors use, since it keeps each client's fd + private rather than exposing a connectable socket path. Call + :meth:`add_client` once per connection you want to accept. ``flags`` are applied here rather than left to the caller because :meth:`set_flag` has to run before the backend is set up, and this - method does both.""" + method does both. + """ server = cls(cls._new()) for flag in flags: server.set_flag(flag) @@ -1190,9 +1235,12 @@ def create_for_fd(cls, flags: Sequence[Flag] = ()) -> Eis: @classmethod def create_for_socket(cls, path: Path, flags: Sequence[Flag] = ()) -> Eis: - """Create a server listening on a Unix socket, as a compositor - would (this is the path a real ``ei_setup_backend_socket()`` client - connects to). See :meth:`create_for_fd` on ``flags``.""" + """Create a server listening on a Unix socket. + + As a compositor would (this is the path a real + ``ei_setup_backend_socket()`` client connects to). See + :meth:`create_for_fd` on ``flags``. + """ server = cls(cls._new()) for flag in flags: server.set_flag(flag) diff --git a/src/libei/oeffis.py b/src/libei/oeffis.py index 58cce7b..ddaee8e 100644 --- a/src/libei/oeffis.py +++ b/src/libei/oeffis.py @@ -1,5 +1,7 @@ -"""Pythonic wrapper around liboeffis -- negotiates an EIS connection through -the ``org.freedesktop.portal.RemoteDesktop`` XDG desktop portal. +"""Pythonic wrapper around liboeffis. + +Negotiates an EIS connection through the +``org.freedesktop.portal.RemoteDesktop`` XDG desktop portal. This is the path a sandboxed or otherwise non-privileged client uses to get an EI socket: it asks the portal, the user is shown a consent dialog, and on @@ -52,6 +54,7 @@ class DisconnectedError(Exception): """The portal session ended unexpectedly (error, or denied by the user).""" def __init__(self, message: str | None) -> None: + """Record why the session ended.""" super().__init__(message) self.message = message @@ -60,6 +63,7 @@ class SessionClosedError(DisconnectedError): """The portal explicitly closed the session (not necessarily an error).""" def __init__(self) -> None: + """Build the fixed "Session closed" message.""" super().__init__(message="Session closed") @@ -100,6 +104,7 @@ class Oeffis: """ def __init__(self) -> None: + """Create the underlying liboeffis context (no portal call yet).""" pointer = _capi.liboeffis.new(None) if not pointer: raise DisconnectedError("oeffis_new() returned NULL") diff --git a/src/libei/portal.py b/src/libei/portal.py index ffb8432..5863a03 100644 --- a/src/libei/portal.py +++ b/src/libei/portal.py @@ -1,5 +1,7 @@ -"""Negotiate an EIS connection by driving a portal directly over D-Bus, -rather than through :mod:`libei.oeffis`. +"""Negotiate an EIS connection by driving a portal directly over D-Bus. + +Not through :mod:`libei.oeffis` -- see that module instead for the simpler, +liboeffis-backed path. Two portals, two directions. :class:`RemoteDesktopSession` negotiates ``org.freedesktop.portal.RemoteDesktop`` to *inject* input; below it, @@ -69,6 +71,7 @@ from __future__ import annotations +import contextlib import enum import logging import os @@ -161,6 +164,7 @@ class PortalTimeoutError(PortalError): """ def __init__(self, step: str, timeout: float) -> None: + """Name which step timed out and after how long.""" super().__init__(f"{step} did not answer within {timeout:g}s") self.step = step self.timeout = timeout @@ -175,6 +179,7 @@ class PortalDeniedError(PortalError): """ def __init__(self, step: str, message: str | None = None) -> None: + """Name which step was refused and, where the portal gave one, why.""" super().__init__(message or f"{step} was not approved") self.step = step self.message = message @@ -584,6 +589,11 @@ def __init__( session_handle: str | None = None, busname: str = _BUS_NAME, ) -> None: + """Hold a negotiated session's handle, connection and EIS fd. + + Not for direct use -- built by :meth:`negotiate` once ``Start`` and + ``ConnectToEIS`` have both already succeeded. + """ self._connection = connection self._eis_fd: int | None = eis_fd self._session_handle = session_handle @@ -687,10 +697,9 @@ def __del__(self) -> None: return eis_fd = getattr(self, "_eis_fd", None) if eis_fd is not None: - try: + # an exception here is only printed to stderr anyway + with contextlib.suppress(OSError): os.close(eis_fd) - except OSError: - pass # an exception here is only printed to stderr anyway @classmethod def negotiate( @@ -1058,8 +1067,9 @@ def on_timeout() -> bool: class Activation(NamedTuple): - """One ``Activated`` signal's payload -- see - :meth:`InputCaptureSession.wait_for_activation`. + """One ``Activated`` signal's payload. + + See :meth:`InputCaptureSession.wait_for_activation`. """ activation_id: int @@ -1129,6 +1139,11 @@ def __init__( restore_token: str | None, busname: str = _BUS_NAME, ) -> None: + """Hold a negotiated capture session's handle, connection and EIS fd. + + Not for direct use -- built by :meth:`negotiate` once ``ConnectToEIS`` + has already succeeded. + """ self._connection = connection self._session_handle: str | None = session_handle self._eis_fd: int | None = eis_fd @@ -1427,10 +1442,8 @@ def __del__(self) -> None: return eis_fd = getattr(self, "_eis_fd", None) if eis_fd is not None: - try: + with contextlib.suppress(OSError): os.close(eis_fd) - except OSError: - pass @classmethod def negotiate( diff --git a/tests/test_ei_objects.py b/tests/test_ei_objects.py index 29e69bb..f174ed2 100644 --- a/tests/test_ei_objects.py +++ b/tests/test_ei_objects.py @@ -8,6 +8,7 @@ from __future__ import annotations +import contextlib import gc import os from ctypes import c_int @@ -313,10 +314,8 @@ def test_keymap_fd_dups_so_it_can_be_closed_independently( os.fstat(real_fd) # still open after closing the second dup too finally: for f in (f1, f2): - try: + with contextlib.suppress(OSError): f.close() - except OSError: - pass finally: os.close(real_fd) os.close(write_fd) diff --git a/tests/test_eis_objects.py b/tests/test_eis_objects.py index ed15e95..7b5dd7f 100644 --- a/tests/test_eis_objects.py +++ b/tests/test_eis_objects.py @@ -9,6 +9,7 @@ from __future__ import annotations +import contextlib import os import pytest @@ -243,10 +244,8 @@ def test_keymap_fd_dups_so_it_can_be_closed_independently( os.fstat(real_fd) finally: for f in (f1, f2): - try: + with contextlib.suppress(OSError): f.close() - except OSError: - pass finally: os.close(real_fd) os.close(write_fd) diff --git a/tests/test_inputcapture.py b/tests/test_inputcapture.py index 5c78048..9c88479 100644 --- a/tests/test_inputcapture.py +++ b/tests/test_inputcapture.py @@ -21,6 +21,7 @@ class docstring. from __future__ import annotations +import contextlib import os import sys from typing import Any @@ -591,10 +592,8 @@ def test_close_closes_an_unclaimed_eis_fd() -> None: with pytest.raises(OSError): os.fstat(read_fd) finally: - try: + with contextlib.suppress(OSError): os.close(read_fd) - except OSError: - pass os.close(write_fd) diff --git a/tests/test_integration_extras.py b/tests/test_integration_extras.py index 065fb7e..e82c133 100644 --- a/tests/test_integration_extras.py +++ b/tests/test_integration_extras.py @@ -1,8 +1,8 @@ -"""End-to-end tests for the accessors and capabilities added on top of the -core injection path, against the real libei/libeis. +"""End-to-end tests for the accessors and capabilities added on top of the core path. -``test_integration_socketpair.py`` proves the connect/negotiate/inject path -works; this file covers the parts that were only bound later -- text input, +Against the real libei/libeis. ``test_integration_socketpair.py`` proves the +connect/negotiate/inject path works; this file covers the parts that were +only bound later -- text input, touch cancellation, ping/pong round trips, region mapping ids and keymap transfer -- plus the two silent failures those made worth fixing: a keymap fd that arrives at EOF, and accessors that return zeros for the wrong event diff --git a/tests/test_oeffis.py b/tests/test_oeffis.py index 4948aa1..84b2411 100644 --- a/tests/test_oeffis.py +++ b/tests/test_oeffis.py @@ -12,6 +12,7 @@ from __future__ import annotations +import contextlib import gc import os @@ -126,10 +127,9 @@ def fake_get_event(pointer: int) -> int: with pytest.raises(OSError): os.fstat(read_fd) finally: - try: + # expected: __del__ should have already closed this + with contextlib.suppress(OSError): os.close(read_fd) - except OSError: - pass # expected: __del__ should have already closed this os.close(write_fd) diff --git a/tests/test_portal.py b/tests/test_portal.py index 6cdad70..e7dd865 100644 --- a/tests/test_portal.py +++ b/tests/test_portal.py @@ -19,6 +19,7 @@ from __future__ import annotations +import contextlib import os import sys import time @@ -92,10 +93,9 @@ def _close_fake_fds() -> Iterator[None]: yield while _OPEN_PIPES: for fd in _OPEN_PIPES.pop(): - try: + # already closed by the code under test, which is the point + with contextlib.suppress(OSError): os.close(fd) - except OSError: - pass # already closed by the code under test, which is the point class FakeMainLoop: @@ -562,10 +562,9 @@ def test_close_closes_an_unclaimed_eis_fd() -> None: with pytest.raises(OSError): os.fstat(read_fd) finally: - try: + # expected: close() should already have closed it + with contextlib.suppress(OSError): os.close(read_fd) - except OSError: - pass # expected: close() should already have closed it os.close(write_fd)