diff --git a/pyproject.toml b/pyproject.toml index 189dddd..87ecc9a 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -181,9 +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. @@ -206,6 +211,16 @@ 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/*" = [ + "INP001", # Allow test resource directories without __init__.py. ] [tool.ruff.lint.mccabe] 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/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/_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/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..4dde703 100644 --- a/tests/event_handlers/test_actions.py +++ b/tests/event_handlers/test_actions.py @@ -3,11 +3,14 @@ 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 if TYPE_CHECKING: + from collections.abc import Callable + from streamdeck.models.events import EventBase @@ -42,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/event_listener/test_event_listener.py b/tests/event_listener/test_event_listener.py index 5de0572..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()) @@ -170,7 +172,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(): @@ -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/models/test_toml_settings.py b/tests/models/test_toml_settings.py index 53651ca..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,9 +92,9 @@ def test_cli_listener_modules_replace_toml_before_import(tmp_path, flag): StreamDeckToolConfig() -def test_repeated_listener_aliases_combine_in_one_override(tmp_path): - from tests.data.dummy_event_listener import DummyEventListener +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 write_config( tmp_path, @@ -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/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_launch_settings.py b/tests/test_launch_settings.py index ac0d4c9..1318f3f 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,10 +28,15 @@ 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) - + [ + _cli_parse_args=[ + *host_args(port_flag), "--plugin-dir", str(tmp_path), debug_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,25 +134,37 @@ 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) + 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() 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: - 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) @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 +190,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 +200,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 +216,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 +227,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 +286,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 +321,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) diff --git a/tests/test_logging.py b/tests/test_logging.py index d9b3d3a..675571e 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 @@ -57,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.split(".")[-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" ) @@ -81,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 @@ -94,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 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 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())