From ff0d2e8b5d403f95b9c2ee96828f309453f314e4 Mon Sep 17 00:00:00 2001 From: strohganoff Date: Thu, 3 Dec 2026 21:54:00 -0700 Subject: [PATCH 1/4] Apply Ruff safe automatic fixes --- streamdeck/event_listener.py | 1 + streamdeck/manager.py | 1 + streamdeck/utils/helper_actions.py | 4 ++-- streamdeck/utils/logging.py | 2 +- streamdeck/websocket.py | 1 + tests/data/dummy_event_listener.py | 2 +- tests/event_handlers/test_action_event_handler_filtering.py | 3 ++- tests/event_handlers/test_action_registry.py | 2 -- tests/event_handlers/test_actions.py | 1 + tests/event_listener/test_event_listener.py | 2 +- tests/models/test_toml_settings.py | 2 +- tests/plugin_manager/test_plugin_manager.py | 2 +- tests/test_logging.py | 3 ++- tests/test_utils/fake_event_factories.py | 1 + 14 files changed, 16 insertions(+), 11 deletions(-) diff --git a/streamdeck/event_listener.py b/streamdeck/event_listener.py index 113566a..74261aa 100644 --- a/streamdeck/event_listener.py +++ b/streamdeck/event_listener.py @@ -24,6 +24,7 @@ from typing_extensions import sentinel + if sys.version_info < (3, 11): from exceptiongroup import ExceptionGroup diff --git a/streamdeck/manager.py b/streamdeck/manager.py index 1e85f57..05d6ed6 100644 --- a/streamdeck/manager.py +++ b/streamdeck/manager.py @@ -20,6 +20,7 @@ from streamdeck.utils.logging import configure_streamdeck_logger from streamdeck.websocket import WebSocketEventListener, WebSocketTransport + if sys.version_info < (3, 11): from exceptiongroup import ExceptionGroup diff --git a/streamdeck/utils/helper_actions.py b/streamdeck/utils/helper_actions.py index 729cb81..ff07165 100644 --- a/streamdeck/utils/helper_actions.py +++ b/streamdeck/utils/helper_actions.py @@ -17,7 +17,7 @@ def create_logging_action(action_uuid: str) -> Action: """Action that logs the event name of every occurring event.""" logging_action = Action(action_uuid) - action_component_name = action_uuid.split(".")[-1] + action_component_name = action_uuid.rsplit(".", maxsplit=1)[-1] logger = getLogger(action_component_name) def log_event(event_data: EventBase) -> None: @@ -34,7 +34,7 @@ def create_file_writing_action(action_uuid: str, file: TextIOWrapper) -> Action: """Action that saves the full json of every occurring event.""" file_writing_action = Action(action_uuid) - action_component_name = action_uuid.split(".")[-1] + action_component_name = action_uuid.rsplit(".", maxsplit=1)[-1] logger = getLogger(action_component_name) def write_event(event_data: EventBase) -> None: diff --git a/streamdeck/utils/logging.py b/streamdeck/utils/logging.py index 43c5eae..db536f5 100644 --- a/streamdeck/utils/logging.py +++ b/streamdeck/utils/logging.py @@ -51,7 +51,7 @@ def configure_local_logger( log_level (int, optional): The logging level. Defaults to logging.DEBUG. """ # The log file name is the last component of the plugin_uuid. - plugin_component_name = plugin_uuid.split(".")[-1] + plugin_component_name = plugin_uuid.rsplit(".", maxsplit=1)[-1] local_log_filepath = ( plugin_local_data_dir(plugin_uuid=plugin_uuid) / f"logs/{plugin_component_name}.log" diff --git a/streamdeck/websocket.py b/streamdeck/websocket.py index 13f86c6..c8d8ea2 100644 --- a/streamdeck/websocket.py +++ b/streamdeck/websocket.py @@ -15,6 +15,7 @@ WebSocketException, ) + if sys.version_info < (3, 11): from exceptiongroup import ExceptionGroup diff --git a/tests/data/dummy_event_listener.py b/tests/data/dummy_event_listener.py index a7d2d91..864d120 100644 --- a/tests/data/dummy_event_listener.py +++ b/tests/data/dummy_event_listener.py @@ -2,7 +2,7 @@ from typing import TYPE_CHECKING, Literal -from typing_extensions import override # noqa: UP035 +from typing_extensions import override from streamdeck.event_listener import EventListener from streamdeck.models.events import EventBase diff --git a/tests/event_handlers/test_action_event_handler_filtering.py b/tests/event_handlers/test_action_event_handler_filtering.py index f1ed681..7466d5b 100644 --- a/tests/event_handlers/test_action_event_handler_filtering.py +++ b/tests/event_handlers/test_action_event_handler_filtering.py @@ -4,10 +4,10 @@ from unittest.mock import create_autospec import pytest + from streamdeck.event_handlers.actions import Action, GlobalAction from streamdeck.event_handlers.registry import HandlersRegistry from streamdeck.models.events.common import ActionInstanceEventMixin - from tests.test_utils.fake_event_factories import ( ApplicationDidLaunchEventFactory, DeviceDidConnectFactory, @@ -19,6 +19,7 @@ from unittest.mock import Mock from polyfactory.factories.pydantic_factory import ModelFactory + from streamdeck.models import events diff --git a/tests/event_handlers/test_action_registry.py b/tests/event_handlers/test_action_registry.py index 35e2ad6..02540b3 100644 --- a/tests/event_handlers/test_action_registry.py +++ b/tests/event_handlers/test_action_registry.py @@ -2,10 +2,8 @@ from typing import TYPE_CHECKING -import pytest from streamdeck.event_handlers.actions import Action from streamdeck.event_handlers.registry import ALL_EVENTS, HandlersRegistry - from tests.test_utils.fake_event_factories import ( DialDownEventFactory, DialUpEventFactory, diff --git a/tests/event_handlers/test_actions.py b/tests/event_handlers/test_actions.py index 7407a3e..b9e1d3c 100644 --- a/tests/event_handlers/test_actions.py +++ b/tests/event_handlers/test_actions.py @@ -3,6 +3,7 @@ from typing import TYPE_CHECKING, Any, cast import pytest + from streamdeck.event_handlers.actions import Action, ActionBase, GlobalAction from streamdeck.models.events import DEFAULT_EVENT_NAMES diff --git a/tests/event_listener/test_event_listener.py b/tests/event_listener/test_event_listener.py index 5de0572..2eded0f 100644 --- a/tests/event_listener/test_event_listener.py +++ b/tests/event_listener/test_event_listener.py @@ -170,7 +170,7 @@ async def scenario() -> None: manager = EventListenerManager() manager.add_listener(FailingStopListener([])) manager.add_listener(FailingStopListener([])) - manager._event_queue.put_nowait(cast(str, 123)) + manager._event_queue.put_nowait(cast("str", 123)) with pytest.raises(TypeError, match="Unexpected event queue item"): async for _ in manager.event_stream(): diff --git a/tests/models/test_toml_settings.py b/tests/models/test_toml_settings.py index 53651ca..9b12514 100644 --- a/tests/models/test_toml_settings.py +++ b/tests/models/test_toml_settings.py @@ -90,8 +90,8 @@ def test_cli_listener_modules_replace_toml_before_import(tmp_path, flag): def test_repeated_listener_aliases_combine_in_one_override(tmp_path): - from tests.data.dummy_event_listener import DummyEventListener from streamdeck.websocket import WebSocketEventListener + from tests.data.dummy_event_listener import DummyEventListener write_config( tmp_path, diff --git a/tests/plugin_manager/test_plugin_manager.py b/tests/plugin_manager/test_plugin_manager.py index 0b956ff..105b1da 100644 --- a/tests/plugin_manager/test_plugin_manager.py +++ b/tests/plugin_manager/test_plugin_manager.py @@ -8,12 +8,12 @@ from streamdeck.event_handlers.actions import Action from streamdeck.manager import EventAdapter, PluginManager -from streamdeck.websocket import WebSocketEventListener from streamdeck.models.events import ( #, event_adapter DEFAULT_EVENT_MODELS, DEFAULT_EVENT_NAMES, EventBase, ) +from streamdeck.websocket import WebSocketEventListener @pytest.fixture diff --git a/tests/test_logging.py b/tests/test_logging.py index d9b3d3a..1c3101e 100644 --- a/tests/test_logging.py +++ b/tests/test_logging.py @@ -8,6 +8,7 @@ import platformdirs import pytest + from streamdeck.utils.logging import configure_local_logger, configure_streamdeck_logger @@ -66,7 +67,7 @@ def test_local_logger(fake_plugin_local_log_dir: Path) -> None: logger.info(LOG_STATEMENT) - plugin_component_name = FAKE_PLUGIN_UUID.split(".")[-1] + plugin_component_name = FAKE_PLUGIN_UUID.rsplit(".", maxsplit=1)[-1] log_file = ( fake_plugin_local_log_dir diff --git a/tests/test_utils/fake_event_factories.py b/tests/test_utils/fake_event_factories.py index 62816e6..b0c6dd0 100644 --- a/tests/test_utils/fake_event_factories.py +++ b/tests/test_utils/fake_event_factories.py @@ -1,5 +1,6 @@ from polyfactory import Use from polyfactory.factories.pydantic_factory import ModelFactory + from streamdeck.models import events from streamdeck.models.events.settings import SingleActionSettingsPayload from streamdeck.models.events.visibility import SingleActionVisibilityPayload From 7e2829ce646081e6a8901f0f41de160ff7a32c1c Mon Sep 17 00:00:00 2001 From: strohganoff Date: Thu, 3 Dec 2026 22:29:01 -0700 Subject: [PATCH 2/4] Resolve straightforward Ruff violations and configure exemptions Resolve N806, F841, RUF005, PT018, PTH123, and SIM105 with targeted edits. Temporarily ignore ERA001 globally and exempt INP001 for test resources under tests/data/. --- pyproject.toml | 5 +++ streamdeck/utils/_version.py | 7 ++-- tests/event_listener/test_event_listener.py | 8 ++--- tests/test_launch_settings.py | 6 ++-- tests/test_logging.py | 36 ++++++++++----------- 5 files changed, 34 insertions(+), 28 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 189dddd..851a308 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -181,6 +181,7 @@ packaging = [ "ANN204", # Allow special methods, including __init__, without return annotations. "B024", # Allow ABC subclasses without abstract methods or properties. "E501", # Do not enforce line length in the linter; the formatter uses line-length. + "ERA001", # Temporarily allow commented-out code; revisit after cleanup. "ISC001", # Avoid conflicts with Ruff formatting of single-line string concatenation. "TD002", # Do not require an author in TODO comments. "TD003", # Do not require an issue link in TODO comments. @@ -208,6 +209,10 @@ packaging = [ "FBT002", # Allow boolean default values for positional test parameters. ] + "tests/data/*" = [ + "INP001", # Allow test resource directories without __init__.py. + ] + [tool.ruff.lint.mccabe] max-complexity = 25 diff --git a/streamdeck/utils/_version.py b/streamdeck/utils/_version.py index 2662b55..69d84b2 100644 --- a/streamdeck/utils/_version.py +++ b/streamdeck/utils/_version.py @@ -13,6 +13,7 @@ import json import logging import os +from pathlib import Path # NOTE: A single variable is set using this function below. @@ -43,12 +44,12 @@ def get_version() -> str: return "0.0.1" try: - with open(event_path) as f: + with Path(event_path).open() as f: event_data = json.load(f) - except FileNotFoundError as e: + except FileNotFoundError: logging.exception("Error reading event data from file.") return "0.0.1" - except json.JSONDecodeError as e: + except json.JSONDecodeError: logging.exception("Error parsing event data as JSON.") return "0.0.1" diff --git a/tests/event_listener/test_event_listener.py b/tests/event_listener/test_event_listener.py index 2eded0f..dd5b78f 100644 --- a/tests/event_listener/test_event_listener.py +++ b/tests/event_listener/test_event_listener.py @@ -1,6 +1,7 @@ from __future__ import annotations import asyncio +from contextlib import suppress from typing import TYPE_CHECKING, ClassVar, cast import pytest @@ -51,7 +52,8 @@ async def scenario() -> None: break await manager.stop() assert set(events) == {"a", "b", "c", "d"} - assert first.stopped and second.stopped + assert first.stopped + assert second.stopped asyncio.run(scenario()) @@ -215,10 +217,8 @@ async def scenario() -> None: raise AssertionError("A normally completed listener must not end the stream.") await manager.stop() pending.cancel() - try: + with suppress(asyncio.CancelledError, StopAsyncIteration): await pending - except (asyncio.CancelledError, StopAsyncIteration): - pass await stream.aclose() assert listener.stopped diff --git a/tests/test_launch_settings.py b/tests/test_launch_settings.py index ac0d4c9..2542de8 100644 --- a/tests/test_launch_settings.py +++ b/tests/test_launch_settings.py @@ -29,8 +29,8 @@ def host_args(port_flag="-port"): @pytest.mark.parametrize("listener_flag", ["--event-listener", "--event-listener-modules"]) def test_host_flags_and_development_options(tmp_path, port_flag, debug_flag, listener_flag): launch = LaunchArguments( - _cli_parse_args=host_args(port_flag) - + [ + _cli_parse_args=[ + *host_args(port_flag), "--plugin-dir", str(tmp_path), debug_flag, @@ -138,7 +138,7 @@ def test_plugin_directory_rejects_a_file(tmp_path): path = tmp_path / "file.txt" path.write_text("not a directory") with pytest.raises(ValidationError) as exc: - LaunchArguments(_cli_parse_args=host_args() + ["--plugin-dir", str(path)]) + LaunchArguments(_cli_parse_args=[*host_args(), "--plugin-dir", str(path)]) assert "Path does not point to a directory" in str(exc.value) diff --git a/tests/test_logging.py b/tests/test_logging.py index 1c3101e..675571e 100644 --- a/tests/test_logging.py +++ b/tests/test_logging.py @@ -58,21 +58,21 @@ def test_local_logger(fake_plugin_local_log_dir: Path) -> None: Args: fake_plugin_local_log_dir (Path): The fake local log directory path provided by the fixture. """ - FAKE_LOGGER_NAME = "TEST-PLUGIN-FILE" - FAKE_PLUGIN_UUID = "com.test.spotifier" - LOG_STATEMENT = "Test log." + fake_logger_name = "TEST-PLUGIN-FILE" + fake_plugin_uuid = "com.test.spotifier" + log_statement = "Test log." - configure_local_logger(name=FAKE_LOGGER_NAME, plugin_uuid=FAKE_PLUGIN_UUID) - logger = logging.getLogger(FAKE_LOGGER_NAME) + configure_local_logger(name=fake_logger_name, plugin_uuid=fake_plugin_uuid) + logger = logging.getLogger(fake_logger_name) - logger.info(LOG_STATEMENT) + logger.info(log_statement) - plugin_component_name = FAKE_PLUGIN_UUID.rsplit(".", maxsplit=1)[-1] + plugin_component_name = fake_plugin_uuid.rsplit(".", maxsplit=1)[-1] log_file = ( fake_plugin_local_log_dir / "com.elgato.StreamDeck/Plugins" - / f"{FAKE_PLUGIN_UUID}.sdPlugin" + / f"{fake_plugin_uuid}.sdPlugin" / f"logs/{plugin_component_name}.log" ) @@ -82,7 +82,7 @@ def test_local_logger(fake_plugin_local_log_dir: Path) -> None: actual_log_file_output = f.read() # We don't want to make too many assumptions here about the format of the log output. assert "INFO" in actual_log_file_output - assert LOG_STATEMENT in actual_log_file_output + assert log_statement in actual_log_file_output # Probably don't need to assert that the logger's name is in the log. # assert fake_name in actual_log_file_output @@ -95,22 +95,22 @@ def test_streamdeck_logger(fake_streamdeck_log_dir: Path) -> None: Args: fake_streamdeck_log_dir (Path): The fake Stream Deck log directory path provided by the fixture. """ - FAKE_LOGGER_NAME = "my_test_name" - FAKE_PLUGIN_UUID = "com.test.plugin" - LOG_STATEMENT = "Testing 123..." + fake_logger_name = "my_test_name" + fake_plugin_uuid = "com.test.plugin" + log_statement = "Testing 123..." - configure_streamdeck_logger(name=FAKE_LOGGER_NAME, plugin_uuid=FAKE_PLUGIN_UUID) - logger = logging.getLogger(FAKE_LOGGER_NAME) + configure_streamdeck_logger(name=fake_logger_name, plugin_uuid=fake_plugin_uuid) + logger = logging.getLogger(fake_logger_name) - logger.info(LOG_STATEMENT) + logger.info(log_statement) - log_file = fake_streamdeck_log_dir / "ElgatoStreamDeck" / f"{FAKE_PLUGIN_UUID}.log" + log_file = fake_streamdeck_log_dir / "ElgatoStreamDeck" / f"{fake_plugin_uuid}.log" assert log_file.exists() with log_file.open("r") as f: actual_log_file_output = f.read() # We don't want to make too many assumptions here about the format of the log output. assert "INFO" in actual_log_file_output - assert LOG_STATEMENT in actual_log_file_output + assert log_statement in actual_log_file_output # Probably don't need to assert that the logger's name is in the log. - assert FAKE_LOGGER_NAME in actual_log_file_output + assert fake_logger_name in actual_log_file_output From d7cd65ae002fe1e07a966f87c47dc6faf8f378de Mon Sep 17 00:00:00 2001 From: strohganoff Date: Thu, 3 Dec 2026 22:32:43 -0700 Subject: [PATCH 3/4] Add missing test parameter type annotations Annotate pytest fixtures and parametrized inputs in test_toml_settings.py and test_launch_settings.py, resolving all 53 ANN001 violations without changing test behavior or lint settings. --- tests/models/test_toml_settings.py | 37 ++++++++++++--------- tests/test_launch_settings.py | 53 ++++++++++++++++++++++-------- 2 files changed, 61 insertions(+), 29 deletions(-) diff --git a/tests/models/test_toml_settings.py b/tests/models/test_toml_settings.py index 9b12514..72a580d 100644 --- a/tests/models/test_toml_settings.py +++ b/tests/models/test_toml_settings.py @@ -10,22 +10,22 @@ @pytest.fixture(autouse=True) -def plugin_working_directory(tmp_path, monkeypatch): +def plugin_working_directory(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): monkeypatch.chdir(tmp_path) monkeypatch.setattr(sys, "argv", ["streamdeck"]) -def with_cli_actions(actions): +def with_cli_actions(actions: list[str]): return StreamDeckToolConfig(_cli_parse_args=["--action-scripts", json.dumps(actions)]) -def write_config(tmp_path, text): +def write_config(tmp_path: Path, text: str): path = tmp_path / "pyproject.toml" path.write_text(text) return path -def test_discovery_and_load_isolation(tmp_path): +def test_discovery_and_load_isolation(tmp_path: Path): from tests.data.dummy_event_listener import DummyEvent, DummyEventListener from tests.data.test_action1 import test_action1 @@ -41,7 +41,10 @@ def test_discovery_and_load_isolation(tmp_path): assert test_action1 in config.actions -def test_cli_and_toml_sources_and_no_implicit_inputs(tmp_path, monkeypatch): +def test_cli_and_toml_sources_and_no_implicit_inputs( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +): monkeypatch.chdir(tmp_path) write_config(tmp_path, "[tool.streamdeck]\naction_scripts = []\n") monkeypatch.setenv("ACTION_SCRIPTS", '["does.not.exist"]') @@ -64,7 +67,7 @@ def test_cli_and_toml_sources_and_no_implicit_inputs(tmp_path, monkeypatch): ] -def test_cli_override_before_import(tmp_path): +def test_cli_override_before_import(tmp_path: Path): from tests.data.test_action1 import test_action1 write_config(tmp_path, '[tool.streamdeck]\naction_scripts=["does.not.exist"]\n') @@ -74,7 +77,7 @@ def test_cli_override_before_import(tmp_path): @pytest.mark.parametrize("flag", ["--event-listener", "--event-listener-modules"]) -def test_cli_listener_modules_replace_toml_before_import(tmp_path, flag): +def test_cli_listener_modules_replace_toml_before_import(tmp_path: Path, flag: str): from tests.data.dummy_event_listener import DummyEvent, DummyEventListener write_config( @@ -89,7 +92,7 @@ def test_cli_listener_modules_replace_toml_before_import(tmp_path, flag): StreamDeckToolConfig() -def test_repeated_listener_aliases_combine_in_one_override(tmp_path): +def test_repeated_listener_aliases_combine_in_one_override(tmp_path: Path): from streamdeck.websocket import WebSocketEventListener from tests.data.dummy_event_listener import DummyEventListener @@ -112,7 +115,7 @@ def test_repeated_listener_aliases_combine_in_one_override(tmp_path): assert config.event_listeners == [DummyEventListener, WebSocketEventListener] -def test_cli_listener_override_retains_toml_actions(tmp_path): +def test_cli_listener_override_retains_toml_actions(tmp_path: Path): from tests.data.test_action1 import test_action1 write_config(tmp_path, '[tool.streamdeck]\naction_scripts=["tests.data.test_action1"]\n') @@ -125,7 +128,7 @@ def test_cli_listener_override_retains_toml_actions(tmp_path): assert config.actions == [test_action1] -def test_filtered_cli_accepts_repeated_actions_and_ignores_host_args(tmp_path): +def test_filtered_cli_accepts_repeated_actions_and_ignores_host_args(tmp_path: Path): from tests.data.test_action1 import test_action1 from tests.data.test_action2 import test_action2, test_global_action1 @@ -148,7 +151,11 @@ def test_filtered_cli_accepts_repeated_actions_and_ignores_host_args(tmp_path): @pytest.mark.parametrize("flag", ["--help", "-h"]) -def test_filtered_cli_help_exposes_only_module_options(tmp_path, capsys, flag): +def test_filtered_cli_help_exposes_only_module_options( + tmp_path: Path, + capsys: pytest.CaptureFixture[str], + flag: str, +): write_config(tmp_path, "[tool.streamdeck]\naction_scripts=[]\n") with pytest.raises(SystemExit) as exc: StreamDeckToolConfig(_cli_parse_args=[flag]) @@ -160,7 +167,7 @@ def test_filtered_cli_help_exposes_only_module_options(tmp_path, capsys, flag): assert "--debug" not in help_text -def test_missing_section_with_cli_values(tmp_path): +def test_missing_section_with_cli_values(tmp_path: Path): write_config(tmp_path, '[project]\nname="example"\n') with pytest.raises(ValidationError): StreamDeckToolConfig() @@ -173,14 +180,14 @@ def test_missing_file_uses_cli_or_reports_missing_fields(): assert len(with_cli_actions(["tests.data.test_action1"]).actions) == 1 -def test_failed_cli_load_does_not_affect_next_load(tmp_path): +def test_failed_cli_load_does_not_affect_next_load(tmp_path: Path): write_config(tmp_path, "[tool.streamdeck]\naction_scripts=[]\n") with pytest.raises(ValidationError): with_cli_actions(["does.not.exist"]) assert StreamDeckToolConfig().actions == [] -def test_only_working_directory_toml_is_used(tmp_path, monkeypatch): +def test_only_working_directory_toml_is_used(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): write_config(tmp_path, "[tool.streamdeck]\naction_scripts=[]\n") child = tmp_path / "child" child.mkdir() @@ -190,7 +197,7 @@ def test_only_working_directory_toml_is_used(tmp_path, monkeypatch): @pytest.mark.parametrize("value", ["42", '"module"', '["does.not.exist"]']) -def test_invalid_module_values(tmp_path, value): +def test_invalid_module_values(tmp_path: Path, value: str): write_config(tmp_path, "[tool.streamdeck]\naction_scripts=" + value) with pytest.raises(ValidationError): StreamDeckToolConfig() diff --git a/tests/test_launch_settings.py b/tests/test_launch_settings.py index 2542de8..fd148cd 100644 --- a/tests/test_launch_settings.py +++ b/tests/test_launch_settings.py @@ -2,6 +2,7 @@ import json import subprocess import sys +from pathlib import Path from unittest.mock import AsyncMock, Mock, call import pytest @@ -11,7 +12,7 @@ from streamdeck.models.launch import LaunchArguments -def host_args(port_flag="-port"): +def host_args(port_flag: str = "-port"): return [ port_flag, "12345", @@ -27,7 +28,12 @@ def host_args(port_flag="-port"): @pytest.mark.parametrize("port_flag", ["-port", "-p"]) @pytest.mark.parametrize("debug_flag", ["--debug", "-d"]) @pytest.mark.parametrize("listener_flag", ["--event-listener", "--event-listener-modules"]) -def test_host_flags_and_development_options(tmp_path, port_flag, debug_flag, listener_flag): +def test_host_flags_and_development_options( + tmp_path: Path, + port_flag: str, + debug_flag: str, + listener_flag: str, +): launch = LaunchArguments( _cli_parse_args=[ *host_args(port_flag), @@ -55,7 +61,7 @@ def test_host_flags_and_development_options(tmp_path, port_flag, debug_flag, lis assert launch.event_listener_modules == ["example.listener_a", "example.listener_b"] -def test_defaults_are_resolved_at_parse_time(tmp_path, monkeypatch): +def test_defaults_are_resolved_at_parse_time(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): monkeypatch.chdir(tmp_path) monkeypatch.setenv("PORT", "9999") monkeypatch.setenv("ACTION_SCRIPTS", '["does.not.exist"]') @@ -69,7 +75,10 @@ def test_defaults_are_resolved_at_parse_time(tmp_path, monkeypatch): assert launch.debug_port is None -def test_launch_sources_exclude_constructor_dotenv_and_secrets(tmp_path, monkeypatch): +def test_launch_sources_exclude_constructor_dotenv_and_secrets( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +): monkeypatch.chdir(tmp_path) (tmp_path / ".env").write_text('debug=9999\naction_scripts=["does.not.exist"]\n') secrets = tmp_path / "secrets" @@ -100,7 +109,7 @@ def test_launch_sources_exclude_constructor_dotenv_and_secrets(tmp_path, monkeyp {"plugin": {"uuid": {}}}, ], ) -def test_registration_info_requires_nested_string_uuid(info): +def test_registration_info_requires_nested_string_uuid(info: dict[str, object]): args = host_args() args[-1] = json.dumps(info) with pytest.raises(ValidationError) as exc: @@ -125,7 +134,7 @@ def test_registration_info_extracts_only_used_fields(): @pytest.mark.parametrize("module", ["streamdeck", "streamdeck.utils.helper_actions"]) -def test_cli_help_and_helper_import_in_fresh_process(module): +def test_cli_help_and_helper_import_in_fresh_process(module: str): args = ["-m", module, "--help"] if module == "streamdeck" else ["-c", f"import {module}"] result = subprocess.run([sys.executable, *args], capture_output=True, text=True, timeout=15) assert result.returncode == 0, result.stdout + result.stderr @@ -134,7 +143,7 @@ def test_cli_help_and_helper_import_in_fresh_process(module): assert "--help" in result.stdout -def test_plugin_directory_rejects_a_file(tmp_path): +def test_plugin_directory_rejects_a_file(tmp_path: Path): path = tmp_path / "file.txt" path.write_text("not a directory") with pytest.raises(ValidationError) as exc: @@ -143,7 +152,13 @@ def test_plugin_directory_rejects_a_file(tmp_path): @pytest.mark.parametrize("change", ["missing", "port", "json", "identity", "unknown", "directory"]) -def test_invalid_launch_exits_before_startup(tmp_path, capsys, caplog, monkeypatch, change): +def test_invalid_launch_exits_before_startup( + tmp_path: Path, + capsys: pytest.CaptureFixture[str], + caplog: pytest.LogCaptureFixture, + monkeypatch: pytest.MonkeyPatch, + change: str, +): from streamdeck.__main__ import main args = host_args() @@ -169,7 +184,7 @@ def test_invalid_launch_exits_before_startup(tmp_path, capsys, caplog, monkeypat assert "Invalid launch arguments:" in caplog.text -def test_help_does_not_require_host_arguments(capsys): +def test_help_does_not_require_host_arguments(capsys: pytest.CaptureFixture[str]): with pytest.raises(SystemExit) as exc: LaunchArguments(_cli_parse_args=["--help"]) assert exc.value.code == 0 @@ -179,7 +194,10 @@ def test_help_does_not_require_host_arguments(capsys): assert "--event-listener" in help_text -def test_cli_precedence_does_not_import_invalid_toml_action(tmp_path, monkeypatch): +def test_cli_precedence_does_not_import_invalid_toml_action( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +): monkeypatch.chdir(tmp_path) (tmp_path / "pyproject.toml").write_text( '[tool.streamdeck]\naction_scripts=["does.not.exist"]\n' @@ -192,7 +210,7 @@ def test_cli_precedence_does_not_import_invalid_toml_action(tmp_path, monkeypatc StreamDeckToolConfig(_cli_parse_args=[]) -def test_omitted_cli_actions_preserve_toml(tmp_path, monkeypatch): +def test_omitted_cli_actions_preserve_toml(tmp_path: Path, monkeypatch: pytest.MonkeyPatch): monkeypatch.chdir(tmp_path) (tmp_path / "pyproject.toml").write_text( '[tool.streamdeck]\naction_scripts=["tests.data.test_action1"]\n' @@ -203,7 +221,7 @@ def test_omitted_cli_actions_preserve_toml(tmp_path, monkeypatch): @pytest.mark.parametrize("explicit_args", [False, True]) def test_launcher_imports_from_plugin_directory_and_registers_listeners_first( - tmp_path, monkeypatch, explicit_args + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, explicit_args: bool ): import streamdeck.__main__ as entry @@ -262,7 +280,11 @@ def test_launcher_imports_from_plugin_directory_and_registers_listeners_first( @pytest.mark.parametrize("phase", ["settings", "listener", "action", "run"]) -def test_main_logs_startup_and_runtime_failures(monkeypatch, caplog, phase): +def test_main_logs_startup_and_runtime_failures( + monkeypatch: pytest.MonkeyPatch, + caplog: pytest.LogCaptureFixture, + phase: str, +): import streamdeck.__main__ as entry error = RuntimeError(f"{phase} failed") @@ -293,7 +315,10 @@ def test_main_logs_startup_and_runtime_failures(monkeypatch, caplog, phase): assert "Plugin startup or execution failed" in caplog.text -def test_run_plugin_uses_supplied_settings_without_reading_process_args(tmp_path, monkeypatch): +def test_run_plugin_uses_supplied_settings_without_reading_process_args( + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +): import streamdeck.__main__ as entry monkeypatch.chdir(tmp_path) From 41987a588632ce42065f9889f17b05f01b1fb2c3 Mon Sep 17 00:00:00 2001 From: strohganoff Date: Thu, 3 Dec 2026 23:23:03 -0700 Subject: [PATCH 4/4] Resolve selected deferred Ruff diagnostics Allow intentional exception messages and TODOs, test-local imports and literal comparisons, and the qualified SDK types module. Preserve intentional debugger calls, asynchronous iteration, controlled subprocess invocation, and concise CLI validation errors with targeted exemptions. Replace two Any parameter annotations with JsonValue and Callable, and specify subprocess check=False. --- pyproject.toml | 10 ++++++++++ streamdeck/__main__.py | 8 ++++---- streamdeck/command_sender.py | 6 +++--- tests/event_handlers/test_actions.py | 4 +++- tests/test_launch_settings.py | 8 +++++++- tests/test_websocket.py | 5 +++-- 6 files changed, 30 insertions(+), 11 deletions(-) diff --git a/pyproject.toml b/pyproject.toml index 851a308..87ecc9a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -181,10 +181,14 @@ packaging = [ "ANN204", # Allow special methods, including __init__, without return annotations. "B024", # Allow ABC subclasses without abstract methods or properties. "E501", # Do not enforce line length in the linter; the formatter uses line-length. + "EM101", # Allow inline exception messages. + "EM102", # Allow formatted inline exception messages. "ERA001", # Temporarily allow commented-out code; revisit after cleanup. + "FIX002", # Allow TODO comments for tracking future improvements. "ISC001", # Avoid conflicts with Ruff formatting of single-line string concatenation. "TD002", # Do not require an author in TODO comments. "TD003", # Do not require an issue link in TODO comments. + "TRY003", # Allow descriptive messages when raising standard exceptions. ] # Report these rules, but leave their fixes to manual review. @@ -207,6 +211,12 @@ packaging = [ "ANN202", # Allow private test helpers without return annotations. "FBT001", # Allow boolean-typed positional parameters in test functions. "FBT002", # Allow boolean default values for positional test parameters. + "PLC0415", # Allow deferred imports in tests. + "PLR2004", # Allow explicit expected values in test comparisons. + ] + + "streamdeck/types.py" = [ + "A005", # Preserve the SDK's qualified type-alias module. ] "tests/data/*" = [ diff --git a/streamdeck/__main__.py b/streamdeck/__main__.py index 1e57153..45a919f 100644 --- a/streamdeck/__main__.py +++ b/streamdeck/__main__.py @@ -34,7 +34,7 @@ async def async_main(argv: list[str] | None = None) -> None: try: launch = CliApp.run(LaunchArguments, cli_args=args) except (ValidationError, SettingsError) as exc: - logger.error("Invalid launch arguments: %s", exc) + logger.error("Invalid launch arguments: %s", exc) # noqa: TRY400 raise SystemExit(2) from exc try: @@ -58,11 +58,11 @@ async def async_main(argv: list[str] | None = None) -> None: def setup_debug_mode(debug_port: int) -> None: """Setup the debug mode for the plugin and wait for the debugger to attach.""" - import debugpy + import debugpy # noqa: PLC0415, T100 - debugpy.listen(debug_port) + debugpy.listen(debug_port) # noqa: T100 logger.info("Starting in debug mode. Waiting for debugger to attach on port %d...", debug_port) - debugpy.wait_for_client() + debugpy.wait_for_client() # noqa: T100 logger.info("Debugger attached.") diff --git a/streamdeck/command_sender.py b/streamdeck/command_sender.py index 4f68a97..71de2c5 100644 --- a/streamdeck/command_sender.py +++ b/streamdeck/command_sender.py @@ -7,7 +7,7 @@ if TYPE_CHECKING: - from typing import Any, Literal + from typing import Literal from pydantic import JsonValue @@ -31,7 +31,7 @@ def __init__(self, request_broker: RequestBroker, plugin_registration_uuid: str) self._request_broker = request_broker self._plugin_registration_uuid = plugin_registration_uuid - async def _send_event(self, event: EventNameStr, **kwargs: Any) -> None: + async def _send_event(self, event: EventNameStr, **kwargs: JsonValue) -> None: await self._request_broker.send_event({ "event": event, **kwargs, @@ -314,7 +314,7 @@ async def switch_to_profile( page (int): Page to show when switching to the profile; indexed from 0. """ # TODO: Should validation happen that ensures the specified profile is declared in manifest.yaml? - payload: dict[str, str | int | None] = {} + payload: dict[str, JsonValue] = {} if profile is not None: payload = { diff --git a/tests/event_handlers/test_actions.py b/tests/event_handlers/test_actions.py index b9e1d3c..4dde703 100644 --- a/tests/event_handlers/test_actions.py +++ b/tests/event_handlers/test_actions.py @@ -9,6 +9,8 @@ if TYPE_CHECKING: + from collections.abc import Callable + from streamdeck.models.events import EventBase @@ -43,7 +45,7 @@ def handler(event_data: EventBase) -> None: lambda event_data=None: None, ], ) -def test_action_rejects_invalid_handler_signature(action: ActionBase, handler: Any) -> None: +def test_action_rejects_invalid_handler_signature(action: ActionBase, handler: Callable[..., None]) -> None: """Reject handlers that do not start with a required positional event parameter.""" with pytest.raises(TypeError, match="Invalid event handler signature"): action.on("keyDown")(handler) diff --git a/tests/test_launch_settings.py b/tests/test_launch_settings.py index fd148cd..1318f3f 100644 --- a/tests/test_launch_settings.py +++ b/tests/test_launch_settings.py @@ -136,7 +136,13 @@ def test_registration_info_extracts_only_used_fields(): @pytest.mark.parametrize("module", ["streamdeck", "streamdeck.utils.helper_actions"]) def test_cli_help_and_helper_import_in_fresh_process(module: str): args = ["-m", module, "--help"] if module == "streamdeck" else ["-c", f"import {module}"] - result = subprocess.run([sys.executable, *args], capture_output=True, text=True, timeout=15) + result = subprocess.run( # noqa: S603 + [sys.executable, *args], + check=False, + capture_output=True, + text=True, + timeout=15, + ) assert result.returncode == 0, result.stdout + result.stderr if module == "streamdeck": assert "usage:" in result.stdout.lower() diff --git a/tests/test_websocket.py b/tests/test_websocket.py index 7551864..081f0fa 100644 --- a/tests/test_websocket.py +++ b/tests/test_websocket.py @@ -64,9 +64,10 @@ async def scenario() -> None: connection.recv = AsyncMock(side_effect=["text", b"binary", ConnectionClosed(None, None)]) client._connection = connection received: list[str | bytes] = [] - with pytest.raises(StopStreaming): + # Preserve messages received before the listener signals shutdown. + with pytest.raises(StopStreaming): # noqa: PT012 async for message in WebSocketEventListener(client).listen(): - received.append(message) + received.append(message) # noqa: PERF401 assert received == ["text", b"binary"] asyncio.run(scenario())