Skip to content

Commit 16592b4

Browse files
committed
Beautify code with Ruff
1 parent c81514d commit 16592b4

File tree

6 files changed

+54
-69
lines changed

6 files changed

+54
-69
lines changed

custom_components/car_wash/__init__.py

+2-1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
1-
"""The Car Wash binary sensor.
1+
"""
2+
The Car Wash binary sensor.
23
34
For more details about this platform, please refer to the documentation at
45
https://github.com/Limych/ha-car_wash/

custom_components/car_wash/binary_sensor.py

+27-25
Original file line numberDiff line numberDiff line change
@@ -1,18 +1,17 @@
11
# Copyright (c) 2019-2021, Andrey "Limych" Khrolenok <andrey@khrolenok.ru>
22
# Creative Commons BY-NC-SA 4.0 International Public License
33
# (see LICENSE.md or https://creativecommons.org/licenses/by-nc-sa/4.0/)
4-
"""The Car Wash binary sensor.
4+
"""
5+
The Car Wash binary sensor.
56
67
For more details about this platform, please refer to the documentation at
78
https://github.com/Limych/ha-car_wash/
89
"""
910

10-
from collections.abc import Callable
11-
from datetime import datetime
1211
import logging
12+
from datetime import datetime
1313

1414
import voluptuous as vol
15-
1615
from homeassistant.components.binary_sensor import BinarySensorEntity
1716
from homeassistant.components.weather import (
1817
ATTR_FORECAST_CONDITION,
@@ -21,10 +20,12 @@
2120
ATTR_FORECAST_TEMP_LOW,
2221
ATTR_FORECAST_TIME,
2322
ATTR_WEATHER_TEMPERATURE,
24-
DOMAIN as WEATHER_DOMAIN,
2523
SERVICE_GET_FORECASTS,
2624
WeatherEntityFeature,
2725
)
26+
from homeassistant.components.weather import (
27+
DOMAIN as WEATHER_DOMAIN,
28+
)
2829
from homeassistant.const import (
2930
ATTR_SUPPORTED_FEATURES,
3031
CONF_ENTITY_ID,
@@ -34,11 +35,12 @@
3435
EVENT_HOMEASSISTANT_START,
3536
UnitOfTemperature,
3637
)
37-
from homeassistant.core import Event, EventStateChangedData, HomeAssistant, callback
38+
from homeassistant.core import Event, HomeAssistant, callback
3839
from homeassistant.exceptions import HomeAssistantError
3940
from homeassistant.helpers import config_validation as cv
41+
from homeassistant.helpers.entity_platform import AddEntitiesCallback
4042
from homeassistant.helpers.event import async_track_state_change_event
41-
from homeassistant.helpers.typing import ConfigType
43+
from homeassistant.helpers.typing import ConfigType, DiscoveryInfoType
4244
from homeassistant.util import dt as dt_util
4345
from homeassistant.util.unit_conversion import TemperatureConverter
4446

@@ -67,11 +69,11 @@
6769

6870
# pylint: disable=unused-argument
6971
async def async_setup_platform(
70-
hass: HomeAssistant,
72+
hass: HomeAssistant, # noqa: ARG001
7173
config: ConfigType,
72-
async_add_entities: Callable,
73-
discovery_info=None,
74-
):
74+
async_add_entities: AddEntitiesCallback,
75+
discovery_info: DiscoveryInfoType = None, # noqa: ARG001
76+
) -> None:
7577
"""Set up the Car Wash sensor."""
7678
# Print startup message
7779
_LOGGER.info(STARTUP_MESSAGE)
@@ -97,7 +99,7 @@ def __init__(
9799
friendly_name: str,
98100
weather_entity: str,
99101
days: int,
100-
):
102+
) -> None:
101103
"""Initialize the sensor."""
102104
self._weather_entity = weather_entity
103105
self._days = days
@@ -124,19 +126,19 @@ async def async_added_to_hass(self) -> None:
124126

125127
# pylint: disable=unused-argument
126128
@callback
127-
def sensor_state_listener(event: Event[EventStateChangedData]) -> None:
129+
def sensor_state_listener(event: Event) -> None: # noqa: ARG001
128130
"""Handle device state changes."""
129-
self.async_schedule_update_ha_state(True)
131+
self.async_schedule_update_ha_state(force_refresh=True)
130132

131133
# pylint: disable=unused-argument
132134
@callback
133-
def sensor_startup(event) -> None:
135+
def sensor_startup(event: Event) -> None: # noqa: ARG001
134136
"""Update template on startup."""
135137
async_track_state_change_event(
136138
self.hass, [self._weather_entity], sensor_state_listener
137139
)
138140

139-
self.async_schedule_update_ha_state(True)
141+
self.async_schedule_update_ha_state(force_refresh=True)
140142

141143
self.hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, sensor_startup)
142144

@@ -150,13 +152,12 @@ def _temp2c(temperature: float | None, temperature_unit: str) -> float | None:
150152
return temperature
151153

152154
# pylint: disable=too-many-branches,too-many-statements
153-
async def async_update(self):
155+
async def async_update(self) -> None: # noqa: PLR0912, PLR0915
154156
"""Update the sensor state."""
155157
wstate = self.hass.states.get(self._weather_entity)
156158
if wstate is None:
157-
raise HomeAssistantError(
158-
f"Unable to find an entity called {self._weather_entity}"
159-
)
159+
msg = f"Unable to find an entity called {self._weather_entity}"
160+
raise HomeAssistantError(msg)
160161

161162
tmpu = self.hass.config.units.temperature_unit
162163
temp = wstate.attributes.get(ATTR_WEATHER_TEMPERATURE)
@@ -170,7 +171,8 @@ async def async_update(self):
170171
elif (wfeatures & WeatherEntityFeature.FORECAST_HOURLY) != 0:
171172
forecast_type = "hourly"
172173
else:
173-
raise HomeAssistantError("Weather entity doesn't support any forecast")
174+
msg = "Weather entity doesn't support any forecast"
175+
raise HomeAssistantError(msg)
174176

175177
try:
176178
forecast = await self.hass.services.async_call(
@@ -185,9 +187,8 @@ async def async_update(self):
185187
)
186188
except HomeAssistantError as ex:
187189
self._attr_is_on = None
188-
raise HomeAssistantError(
189-
"Can't get forecast data! Are you sure it's the weather provider?"
190-
) from ex
190+
msg = "Can't get forecast data! Are you sure it's the weather provider?"
191+
raise HomeAssistantError(msg) from ex
191192

192193
_LOGGER.debug("Current temperature %s, condition '%s'", temp, cond)
193194

@@ -201,7 +202,8 @@ async def async_update(self):
201202
today = dt_util.start_of_local_day()
202203
cur_date = today.strftime("%F")
203204
stop_date = datetime.fromtimestamp(
204-
today.timestamp() + 86400 * (self._days + 1)
205+
today.timestamp() + 86400 * (self._days + 1),
206+
tz=dt_util.DEFAULT_TIME_ZONE,
205207
).strftime("%F")
206208

207209
_LOGGER.debug("Inspect weather forecast from now till %s", stop_date)

custom_components/car_wash/const.py

+3-1
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,13 @@
11
# Copyright (c) 2019-2021, Andrey "Limych" Khrolenok <andrey@khrolenok.ru>
22
# Creative Commons BY-NC-SA 4.0 International Public License
33
# (see LICENSE.md or https://creativecommons.org/licenses/by-nc-sa/4.0/)
4-
"""The Car Wash binary sensor.
4+
"""
5+
The Car Wash binary sensor.
56
67
For more details about this platform, please refer to the documentation at
78
https://github.com/Limych/ha-car_wash/
89
"""
10+
911
from typing import Final
1012

1113
from homeassistant.components.weather import (

custom_components/car_wash/manifest.json

+3-1
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,8 @@
1111
"documentation": "https://github.com/Limych/ha-car_wash",
1212
"iot_class": "calculated",
1313
"issue_tracker": "https://github.com/Limych/ha-car_wash/issues",
14-
"requirements": [],
14+
"requirements": [
15+
"pip>=21.3.1"
16+
],
1517
"version": "1.5.8-alpha"
1618
}

tests/conftest.py

-23
Original file line numberDiff line numberDiff line change
@@ -42,26 +42,3 @@ def _skip_notifications_fixture() -> None:
4242
patch("homeassistant.components.persistent_notification.async_dismiss"),
4343
):
4444
yield
45-
46-
47-
# This fixture, when used, will result in calls to async_get_data to return None. To
48-
# have the call return a value, we would add the `return_value=<VALUE_TO_RETURN>`
49-
# parameter to the patch call.
50-
@pytest.fixture(name="bypass_get_data")
51-
def _bypass_get_data_fixture() -> None:
52-
"""Skip calls to get data from API."""
53-
with patch.object(
54-
IntegrationBlueprintApiClient, "async_get_data", side_effect=Mock()
55-
):
56-
yield
57-
58-
59-
# In this fixture, we are forcing calls to async_get_data to raise an Exception. This
60-
# is useful for exception handling.
61-
@pytest.fixture(name="error_on_get_data")
62-
def _error_get_data_fixture() -> None:
63-
"""Simulate error when retrieving data from API."""
64-
with patch.object(
65-
IntegrationBlueprintApiClient, "async_get_data", side_effect=Exception
66-
):
67-
yield

tests/test_binary_sensor.py

+19-18
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,6 @@
55
from unittest.mock import MagicMock, patch
66

77
import pytest
8-
from pytest import raises
9-
from pytest_homeassistant_custom_component.common import async_mock_service
10-
11-
from custom_components.car_wash.binary_sensor import (
12-
CarWashBinarySensor,
13-
async_setup_platform,
14-
)
15-
from custom_components.car_wash.const import CONF_WEATHER, DOMAIN, ICON
168
from homeassistant.components.weather import (
179
ATTR_CONDITION_RAINY,
1810
ATTR_CONDITION_SUNNY,
@@ -22,10 +14,12 @@
2214
ATTR_FORECAST_TEMP_LOW,
2315
ATTR_FORECAST_TIME,
2416
ATTR_WEATHER_TEMPERATURE,
25-
DOMAIN as WEATHER_DOMAIN,
2617
SERVICE_GET_FORECASTS,
2718
WeatherEntityFeature,
2819
)
20+
from homeassistant.components.weather import (
21+
DOMAIN as WEATHER_DOMAIN,
22+
)
2923
from homeassistant.const import (
3024
ATTR_SUPPORTED_FEATURES,
3125
CONF_PLATFORM,
@@ -35,6 +29,13 @@
3529
from homeassistant.core import HomeAssistant, ServiceRegistry, SupportsResponse
3630
from homeassistant.exceptions import HomeAssistantError
3731
from homeassistant.util import dt as dt_util
32+
from pytest_homeassistant_custom_component.common import async_mock_service
33+
34+
from custom_components.car_wash.binary_sensor import (
35+
CarWashBinarySensor,
36+
async_setup_platform,
37+
)
38+
from custom_components.car_wash.const import CONF_WEATHER, DOMAIN, ICON
3839

3940
MOCK_ENTITY: Final = DOMAIN + ".test"
4041
MOCK_UNIQUE_ID: Final = "test_id"
@@ -49,7 +50,7 @@
4950
}
5051

5152

52-
@pytest.fixture()
53+
@pytest.fixture
5354
def default_sensor(hass: HomeAssistant):
5455
"""Create an AverageSensor with default values."""
5556
entity = CarWashBinarySensor(
@@ -60,7 +61,7 @@ def default_sensor(hass: HomeAssistant):
6061

6162

6263
@pytest.mark.parametrize(
63-
"uid, expected_uid",
64+
("uid", "expected_uid"),
6465
[
6566
(None, None),
6667
("__legacy__", DOMAIN + "-" + MOCK_WEATHER_ENTITY_NAME),
@@ -90,7 +91,7 @@ async def test_async_setup_platform(hass: HomeAssistant):
9091

9192
# pylint: disable=protected-access
9293
@pytest.mark.parametrize(
93-
"temp1, temp2",
94+
("temp1", "temp2"),
9495
[(0, -17.78), (10, -12.22), (20, -6.67), (30, -1.11), (40, 4.44), (50, 10)],
9596
)
9697
async def test__temp2c(temp1, temp2):
@@ -109,7 +110,7 @@ async def test_async_update_fail(hass: HomeAssistant):
109110
MOCK_UNIQUE_ID, MOCK_NAME, WEATHER_DOMAIN + ".nonexistent", MOCK_DAYS
110111
)
111112
entity.hass = hass
112-
with raises(HomeAssistantError):
113+
with pytest.raises(HomeAssistantError):
113114
await entity.async_update()
114115

115116

@@ -122,7 +123,7 @@ async def test_async_update_forecast_fail(hass: HomeAssistant, default_sensor):
122123
supports_response=SupportsResponse.OPTIONAL,
123124
)
124125

125-
with raises(HomeAssistantError, match="Unable to find an entity"):
126+
with pytest.raises(HomeAssistantError, match="Unable to find an entity"):
126127
await default_sensor.async_update()
127128

128129
hass.states.async_set(
@@ -133,7 +134,7 @@ async def test_async_update_forecast_fail(hass: HomeAssistant, default_sensor):
133134
},
134135
)
135136

136-
with raises(HomeAssistantError, match="doesn't support any forecast"):
137+
with pytest.raises(HomeAssistantError, match="doesn't support any forecast"):
137138
await default_sensor.async_update()
138139

139140
hass.states.async_set(
@@ -145,7 +146,7 @@ async def test_async_update_forecast_fail(hass: HomeAssistant, default_sensor):
145146
},
146147
)
147148

148-
with raises(TypeError):
149+
with pytest.raises(TypeError):
149150
await default_sensor.async_update()
150151

151152

@@ -155,12 +156,12 @@ async def test_async_update(hass: HomeAssistant, default_sensor):
155156

156157
hass.states.async_set(MOCK_WEATHER_ENTITY, None)
157158

158-
with raises(HomeAssistantError):
159+
with pytest.raises(HomeAssistantError):
159160
await default_sensor.async_update()
160161

161162
hass.states.async_set(MOCK_WEATHER_ENTITY, "State")
162163

163-
with raises(HomeAssistantError):
164+
with pytest.raises(HomeAssistantError):
164165
await default_sensor.async_update()
165166

166167
hass.states.async_set(

0 commit comments

Comments
 (0)