Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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]
Expand Down
8 changes: 4 additions & 4 deletions streamdeck/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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.")


Expand Down
6 changes: 3 additions & 3 deletions streamdeck/command_sender.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@


if TYPE_CHECKING:
from typing import Any, Literal
from typing import Literal

from pydantic import JsonValue

Expand All @@ -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,
Expand Down Expand Up @@ -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 = {
Expand Down
1 change: 1 addition & 0 deletions streamdeck/event_listener.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@

from typing_extensions import sentinel


if sys.version_info < (3, 11):
from exceptiongroup import ExceptionGroup

Expand Down
1 change: 1 addition & 0 deletions streamdeck/manager.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
7 changes: 4 additions & 3 deletions streamdeck/utils/_version.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
import json
import logging
import os
from pathlib import Path


# NOTE: A single variable is set using this function below.
Expand Down Expand Up @@ -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"

Expand Down
4 changes: 2 additions & 2 deletions streamdeck/utils/helper_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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:
Expand Down
2 changes: 1 addition & 1 deletion streamdeck/utils/logging.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"
Expand Down
1 change: 1 addition & 0 deletions streamdeck/websocket.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
WebSocketException,
)


if sys.version_info < (3, 11):
from exceptiongroup import ExceptionGroup

Expand Down
2 changes: 1 addition & 1 deletion tests/data/dummy_event_listener.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
3 changes: 2 additions & 1 deletion tests/event_handlers/test_action_event_handler_filtering.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -19,6 +19,7 @@
from unittest.mock import Mock

from polyfactory.factories.pydantic_factory import ModelFactory

from streamdeck.models import events


Expand Down
2 changes: 0 additions & 2 deletions tests/event_handlers/test_action_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
5 changes: 4 additions & 1 deletion tests/event_handlers/test_actions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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


Expand Down Expand Up @@ -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)
Expand Down
10 changes: 5 additions & 5 deletions tests/event_listener/test_event_listener.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from __future__ import annotations

import asyncio
from contextlib import suppress
from typing import TYPE_CHECKING, ClassVar, cast

import pytest
Expand Down Expand Up @@ -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())

Expand Down Expand Up @@ -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():
Expand Down Expand Up @@ -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

Expand Down
39 changes: 23 additions & 16 deletions tests/models/test_toml_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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"]')
Expand All @@ -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')
Expand All @@ -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(
Expand All @@ -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,
Expand All @@ -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')
Expand All @@ -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

Expand All @@ -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])
Expand All @@ -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()
Expand All @@ -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()
Expand All @@ -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()
Loading
Loading