Skip to content

Commit

Permalink
Configure ruff linter (#81)
Browse files Browse the repository at this point in the history
* Configure ruff linter
* Apply linter fixes
* Fix linter errors in tests
  • Loading branch information
mvn23 authored Sep 17, 2024
1 parent 273ce8c commit 1246612
Show file tree
Hide file tree
Showing 15 changed files with 54 additions and 31 deletions.
2 changes: 1 addition & 1 deletion pyotgw/commandprocessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
from __future__ import annotations

import asyncio
from asyncio.queues import QueueFull
import logging
import re
from asyncio.queues import QueueFull
from typing import TYPE_CHECKING

from . import vars as v
Expand Down
4 changes: 2 additions & 2 deletions pyotgw/connection.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@
from __future__ import annotations

import asyncio
import logging
from collections.abc import Awaitable, Callable
from dataclasses import dataclass
from functools import partial
import logging
from typing import TYPE_CHECKING, Literal

import serial
Expand Down Expand Up @@ -181,7 +181,7 @@ async def _attempt_connect(self) -> tuple[asyncio.Transport, asyncio.Protocol]:
)
self._error = err

except asyncio.TimeoutError as err:
except TimeoutError as err:
if not isinstance(err, type(self._error)):
_LOGGER.error(
"The serial device on %s is not responding. "
Expand Down
3 changes: 1 addition & 2 deletions pyotgw/messageprocessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,7 @@
import re
from typing import TYPE_CHECKING

from . import messages as m
from . import vars as v
from . import messages as m, vars as v
from .types import (
OpenThermCommand,
OpenThermDataSource,
Expand Down
2 changes: 1 addition & 1 deletion pyotgw/protocol.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
from __future__ import annotations

import asyncio
from collections.abc import Awaitable, Callable
import logging
import re
from collections.abc import Awaitable, Callable
from typing import TYPE_CHECKING

from .commandprocessor import CommandProcessor
Expand Down
11 changes: 7 additions & 4 deletions pyotgw/pyotgw.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
from __future__ import annotations

import asyncio
import logging
from collections.abc import Awaitable, Callable
from datetime import datetime
import logging
from typing import TYPE_CHECKING, Final, Literal

from . import vars as v
Expand Down Expand Up @@ -207,7 +207,7 @@ async def set_outside_temp(

async def set_clock(
self,
date: datetime = datetime.now(),
date: datetime | None = None,
timeout: asyncio.Timeout = v.OTGW_DEFAULT_TIMEOUT,
) -> str | None:
"""
Expand All @@ -221,6 +221,8 @@ async def set_clock(
This method is a coroutine
"""
cmd = OpenThermCommand.SET_CLOCK
if date is None:
date = datetime.now()
value = f"{date.strftime('%H:%M')}/{date.isoweekday()}"
return await self._wait_for_cmd(cmd, value, timeout)

Expand Down Expand Up @@ -343,7 +345,8 @@ async def get_report(
report_type: OpenThermReport,
timeout: asyncio.Timeout = v.OTGW_DEFAULT_TIMEOUT,
) -> dict[OpenThermDataSource, dict] | None:
"""Get the report, update status dict accordingly. Return updated status dict."""
"""Get the report, update status dict accordingly.
Return updated status dict."""
ret = await self._wait_for_cmd(OpenThermCommand.REPORT, report_type, timeout)
if (
ret is None
Expand Down Expand Up @@ -865,7 +868,7 @@ async def _wait_for_cmd(
self._protocol.command_processor.issue_cmd(cmd, value),
timeout,
)
except asyncio.TimeoutError:
except TimeoutError:
_LOGGER.error("Timed out waiting for command: %s, value: %s.", cmd, value)
return
except (RuntimeError, SyntaxError, ValueError) as exc:
Expand Down
2 changes: 1 addition & 1 deletion pyotgw/status.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@
from __future__ import annotations

import asyncio
import logging
from collections.abc import Awaitable, Callable
from copy import deepcopy
import logging

from . import vars as v
from .types import OpenThermDataSource
Expand Down
10 changes: 10 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,16 @@
[tool.pytest.ini_options]
asyncio_default_fixture_loop_scope = "function"

[tool.ruff.lint]
select = [
"E", # pycodestyle
"F", # Pyflakes
"UP", # pyupgrade
"B", # flake8-bugbear
"SIM", # flake8-simplify
"I", # isort
]

[tool.ruff.lint.isort]
force-sort-within-sections = true
known-first-party = [
Expand Down
2 changes: 1 addition & 1 deletion tests/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@

from types import SimpleNamespace

import pyotgw.vars as v
from pyotgw.types import OpenThermDataSource, OpenThermMessageID, OpenThermMessageType
import pyotgw.vars as v

_report_responses_51 = {
v.OTGW_REPORT_ABOUT: "A=OpenTherm Gateway 5.1",
Expand Down
17 changes: 11 additions & 6 deletions tests/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,13 +32,23 @@ async def _wait():


def respond_to_reports(
cmds: list[OpenThermReport] = [], responses: list[str] = []
cmds: list[OpenThermReport] | None = None, responses: list[str] | None = None
) -> Callable[[OpenThermCommand, str, float | None], str]:
"""
Respond to PR= commands with test values.
Override response values by specifying cmds and responses in order.
"""

if len(cmds) != len(responses):
raise ValueError(
"There should be an equal amount of provided cmds and responses"
)

if cmds is None:
cmds = []
if responses is None:
responses = []

default_responses = {
OpenThermReport.ABOUT: "A=OpenTherm Gateway 5.8",
OpenThermReport.BUILD: "B=17:52 12-03-2023",
Expand All @@ -58,11 +68,6 @@ def respond_to_reports(
OpenThermReport.DHW: "W=1",
}

if len(cmds) != len(responses):
raise ValueError(
"There should be an equal amount of provided cmds and responses"
)

for cmd, response in zip(cmds, responses):
if cmd not in default_responses:
raise ValueError(f"Command {cmd} not found in default responses.")
Expand Down
9 changes: 6 additions & 3 deletions tests/test_commandprocessor.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,7 +149,8 @@ async def test_issue_cmd(caplog, pygw_proto):
(
"pyotgw.commandprocessor",
logging.WARNING,
f"Command {OpenThermCommand.CONTROL_SETPOINT_2} failed with InvalidCommand, retrying...",
f"Command {OpenThermCommand.CONTROL_SETPOINT_2} failed with InvalidCommand,"
" retrying...",
),
]
caplog.clear()
Expand Down Expand Up @@ -185,12 +186,14 @@ async def test_issue_cmd(caplog, pygw_proto):
(
"pyotgw.commandprocessor",
logging.WARNING,
f"Command {OpenThermCommand.CONTROL_HEATING_2} failed with Error 03, retrying...",
f"Command {OpenThermCommand.CONTROL_HEATING_2} failed with Error 03,"
" retrying...",
),
(
"pyotgw.commandprocessor",
logging.WARNING,
f"Command {OpenThermCommand.CONTROL_HEATING_2} failed with {OpenThermCommand.CONTROL_HEATING_2}: BV, retrying...",
f"Command {OpenThermCommand.CONTROL_HEATING_2} failed with"
f" {OpenThermCommand.CONTROL_HEATING_2}: BV, retrying...",
),
]

Expand Down
2 changes: 1 addition & 1 deletion tests/test_messages.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
"""Tests for pyotgw/messages.py"""

import pyotgw.messages as m
from pyotgw.messageprocessor import MessageProcessor
import pyotgw.messages as m


def test_message_registry():
Expand Down
5 changes: 3 additions & 2 deletions tests/test_poll_task.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
"""Tests for pyotgw/poll_tasks.py"""

from unittest.mock import AsyncMock, call

import pytest
from unittest.mock import call, AsyncMock

from pyotgw.poll_task import OpenThermPollTask
from pyotgw.pyotgw import OpenThermGateway, GPIO_POLL_TASK_NAME
from pyotgw.pyotgw import GPIO_POLL_TASK_NAME, OpenThermGateway
from pyotgw.types import OpenThermDataSource, OpenThermReport
import pyotgw.vars as v

Expand Down
8 changes: 4 additions & 4 deletions tests/test_pyotgw.py
Original file line number Diff line number Diff line change
@@ -1,21 +1,21 @@
"""Tests for pyotgw/pyotgw.py"""

import asyncio
import logging
from datetime import datetime
import logging
from unittest.mock import AsyncMock, MagicMock, call, patch

import pytest
import serial

import pyotgw.vars as v
from pyotgw.pyotgw import GPIO_POLL_TASK_NAME
from pyotgw.types import (
OpenThermCommand,
OpenThermDataSource,
OpenThermGatewayOpMode,
OpenThermReport,
)
import pyotgw.vars as v
from tests.data import pygw_reports, pygw_status
from tests.helpers import called_x_times, respond_to_reports

Expand Down Expand Up @@ -402,8 +402,8 @@ def get_response_42(cmd, val):
"""Get response from dict or raise ValueError"""
try:
return pygw_reports.report_responses_42[val]
except KeyError:
raise ValueError
except KeyError as e:
raise ValueError from e

with patch.object(
pygw,
Expand Down
6 changes: 4 additions & 2 deletions tests/test_reports.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@

import pytest

import pyotgw.vars as v
from pyotgw.reports import _CONVERSIONS, convert_report_response_to_status_update
from pyotgw.types import (
OpenThermDataSource,
Expand All @@ -20,6 +19,7 @@
OpenThermThermostatDetection,
OpenThermVoltageReferenceLevel,
)
import pyotgw.vars as v

REPORT_TEST_PARAMETERS = ("report", "response", "expected_dict")

Expand All @@ -44,7 +44,9 @@
"D=R",
{
OpenThermDataSource.GATEWAY: {
v.OTGW_TEMP_SENSOR: OpenThermTemperatureSensorFunction.RETURN_WATER_TEMPERATURE
v.OTGW_TEMP_SENSOR: (
OpenThermTemperatureSensorFunction.RETURN_WATER_TEMPERATURE
)
}
},
),
Expand Down
2 changes: 1 addition & 1 deletion tests/test_status.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@

import pytest

import pyotgw.vars as v
from pyotgw.types import OpenThermDataSource
import pyotgw.vars as v
from tests.helpers import called_once


Expand Down

0 comments on commit 1246612

Please sign in to comment.