Skip to content

Commit

Permalink
feat/fix: Add Ruff and Pre-commit Configuration, Resolve Undefined Na…
Browse files Browse the repository at this point in the history
…me (#158)

Enables automatic code quality checks for new PRs in blebox_uniapi uring mainly ruff and pre-commit.
  • Loading branch information
Pastucha authored Mar 8, 2024
1 parent faf4db2 commit 15b755c
Show file tree
Hide file tree
Showing 16 changed files with 53 additions and 28 deletions.
11 changes: 7 additions & 4 deletions .github/workflows/ci-test.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,3 @@
# This workflow will install Python dependencies, run tests
# For more information see: https://docs.github.com/en/actions/automating-builds-and-tests/building-and-testing-python

name: Python application

on:
Expand All @@ -14,14 +11,20 @@ permissions:

jobs:
build:

runs-on: ubuntu-latest
strategy:
matrix:
python-version: ["3.9", "3.10"]

steps:
- uses: actions/checkout@v3
- uses: actions/checkout@v4
- uses: chartboost/ruff-action@v1
with:
args: 'check'
- uses: chartboost/ruff-action@v1
with:
args: 'format'
- name: Set up Python ${{matrix.python-version}}
uses: actions/setup-python@v3
with:
Expand Down
16 changes: 16 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
repos:
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v3.3.0
hooks:
- id: check-yaml
- id: end-of-file-fixer
- id: trailing-whitespace
- repo: https://github.com/astral-sh/ruff-pre-commit
# Ruff version.
rev: v0.3.0
hooks:
# Run the linter.
- id: ruff
args: [ --fix ]
# Run the formatter.
- id: ruff-format
5 changes: 4 additions & 1 deletion blebox_uniapi/binary_sensor.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
from typing import Union
from typing import Union, TYPE_CHECKING

from .feature import Feature

if TYPE_CHECKING:
from .box import Box


class BinarySensor(Feature):
"""Class representing sensor with bool state."""
Expand Down
9 changes: 4 additions & 5 deletions blebox_uniapi/box.py
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,6 @@ def __init__(
def create_features(
self, config: dict, info: dict, extended_state: Optional[dict]
) -> dict:

features = {}
for field, klass in {
"covers": Cover,
Expand Down Expand Up @@ -260,9 +259,9 @@ def _update_last_data(self, new_data: Optional[dict]) -> None:
# Note that SwitchboxD is just an example. It is possible that APIs of other
# box types also exhibit this kind of behavior.
if (
isinstance(self._last_data, dict) and
isinstance(new_data, dict) and
self._last_data.keys() != new_data.keys()
isinstance(self._last_data, dict)
and isinstance(new_data, dict)
and self._last_data.keys() != new_data.keys()
):
# ... In such a case we need to merge both states instead of overwriting
# the old one as-is.
Expand Down Expand Up @@ -398,7 +397,7 @@ def check_int(self, value: int, field: str, max_value: int, min_value: int) -> i
if value is None:
raise BadFieldMissing(self.name, field)

if not type(value) is int:
if not isinstance(value, int):
raise BadFieldNotANumber(self.name, field, value)

return self.check_int_range(value, field, max_value, min_value)
Expand Down
14 changes: 7 additions & 7 deletions blebox_uniapi/climate.py
Original file line number Diff line number Diff line change
Expand Up @@ -151,15 +151,15 @@ def after_update(self) -> None:

@staticmethod
def get_temp_sensor_id(safety_sensor_id: int, sensor_list) -> Optional[int]:
"""Return ID of first sensor which is not safety sensor."""
li_sensor_id = list()
for sensor in sensor_list:
id = sensor.get("id")
if id is not None and id != safety_sensor_id:
li_sensor_id.append(sensor["id"])
"""Return ID of the first sensor which is not a safety sensor."""
li_sensor_id = [
sensor.get("id")
for sensor in sensor_list
if sensor.get("id") is not None and sensor.get("id") != safety_sensor_id
]
li_sensor_id.sort()

if len(li_sensor_id) == False:
if not li_sensor_id:
return None

return li_sensor_id[0]
2 changes: 0 additions & 2 deletions blebox_uniapi/cover.py
Original file line number Diff line number Diff line change
Expand Up @@ -174,7 +174,6 @@ def __init__(
subclass: Type[GateT],
extended_state: dict,
) -> None:

self._control_type = None
if extended_state not in [None, {}]:
self._control_type = extended_state.get("shutter", {}).get(
Expand All @@ -190,7 +189,6 @@ def __init__(
def many_from_config(
cls, product, box_type_config, extended_state
) -> list["Feature"]:

return [cls(product, *args, extended_state) for args in box_type_config]

@property
Expand Down
2 changes: 2 additions & 0 deletions blebox_uniapi/error.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,9 +32,11 @@ class ClientError(Error):
class HttpError(ClientError):
pass


class UnauthorizedRequest(ClientError):
pass


# API errors


Expand Down
7 changes: 5 additions & 2 deletions blebox_uniapi/light.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,6 @@ def __init__(
def many_from_config(
cls, product, box_type_config, extended_state
) -> list["Light"]:

if isinstance(extended_state, dict) and extended_state is not None:
desired_color = extended_state.get("rgbw", {}).get("desiredColor")
color_mode = extended_state.get("rgbw", {}).get("colorMode")
Expand All @@ -165,7 +164,11 @@ def many_from_config(
if extended_state is not None and color_mode is not None:
if BleboxColorMode(color_mode).name == "RGBW":
if len(desired_color) == 10:
mask = lambda x: f"{x}--"

def generate_mask(x):
return f"{x}--"

mask = generate_mask
else:
mask = None
return [cls(product, alias=alias + "_RGBW", mask=mask, **const_kwargs)]
Expand Down
2 changes: 1 addition & 1 deletion blebox_uniapi/session.py
Original file line number Diff line number Diff line change
Expand Up @@ -36,7 +36,7 @@ def __init__(

auth = None

if any(data != None for data in [self._username, self._password]):
if any(data is not None for data in [self._username, self._password]):
auth = aiohttp.BasicAuth(login=self._username, password=self._password)

if not self._session:
Expand Down
2 changes: 1 addition & 1 deletion requirements_dev.txt
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
pytest>=7,<8
pytest-asyncio>=0.14.0
deepmerge==0.1.1
flake8==3.8.4
flake8==3.8.4
3 changes: 2 additions & 1 deletion requirements_tests.txt
Original file line number Diff line number Diff line change
Expand Up @@ -30,4 +30,5 @@ tomli==2.0.1
urllib3==1.26.12
yarg==0.1.9
yarl==1.8.1

ruff==0.3.0
pre-commit==3.6.2
1 change: 0 additions & 1 deletion tests/test_box_types.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@


class TestBoxTypes:

box_types = tuple(BOX_TYPE_CONF.keys())
simple_conf_set = {5: {"tag": "first_entry"}, 10: {"tag": "second_entry"}}

Expand Down
1 change: 1 addition & 0 deletions tests/test_climate.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""BleBox climate entities tests."""

import json

from blebox_uniapi.box_types import get_latest_api_level
Expand Down
1 change: 1 addition & 0 deletions tests/test_cover.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
"""BleBox cover entities tests."""

import json

import pytest
Expand Down
3 changes: 1 addition & 2 deletions tests/test_light.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
"""BleBox light entities tests."""

import json

from .conftest import CommonEntity, DefaultBoxTest, future_date, jmerge

from blebox_uniapi.box_types import get_latest_api_level
from blebox_uniapi.error import BadOnValueError, UnsupportedBoxVersion
from blebox_uniapi.light import Light

# TODO: remove
Expand Down Expand Up @@ -1027,7 +1027,6 @@ async def turn_on():
assert max(entity.rgb_color) == 255

async def test_sensible_on_value_for_color_mode_1(self, aioclient_mock):

self.DEVICE_EXTENDED_INFO = self.DEVICE_EXTENDED_INFO_COLORMODE_1
self.DEVICE_EXTENDED_INFO = jmerge(
self.DEVICE_EXTENDED_INFO, self.patch_state("00000000", "00000000")
Expand Down
2 changes: 1 addition & 1 deletion tests/test_light_unit.py
Original file line number Diff line number Diff line change
Expand Up @@ -103,7 +103,7 @@ def test_dimmer_box_normalise_elements_of_rgb(dimmer_box: Light, io_params):
assert dimmer_box.normalise_elements_of_rgb(io_params[0]) == io_params[1]


def test_dimmer_box_normalise_elements_of_rgb(dimmer_box: Light):
def test_dimmer_box_normalise_elements_of_rgb_invalid_values(dimmer_box: Light):
with pytest.raises(ValueError):
dimmer_box.normalise_elements_of_rgb([-10])

Expand Down

0 comments on commit 15b755c

Please sign in to comment.