Fix Switcher review comments (#143607)

This commit is contained in:
Shay Levy 2025-04-24 22:54:25 +03:00 committed by GitHub
parent a61aff8432
commit 575db4665d
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
5 changed files with 41 additions and 54 deletions

View File

@ -21,8 +21,8 @@ _LOGGER = logging.getLogger(__name__)
CONFIG_SCHEMA: Final = vol.Schema( CONFIG_SCHEMA: Final = vol.Schema(
{ {
vol.Required(CONF_USERNAME, default=""): str, vol.Required(CONF_USERNAME): str,
vol.Required(CONF_TOKEN, default=""): str, vol.Required(CONF_TOKEN): str,
} }
) )
@ -32,9 +32,12 @@ class SwitcherFlowHandler(ConfigFlow, domain=DOMAIN):
VERSION = 1 VERSION = 1
username: str | None = None def __init__(self) -> None:
token: str | None = None """Init the config flow."""
discovered_devices: dict[str, SwitcherBase] = {} super().__init__()
self.discovered_devices: dict[str, SwitcherBase] = {}
self.username: str | None = None
self.token: str | None = None
async def async_step_user( async def async_step_user(
self, user_input: dict[str, Any] | None = None self, user_input: dict[str, Any] | None = None

View File

@ -59,6 +59,16 @@ class SwitcherBaseLightEntity(SwitcherEntity, LightEntity):
control_result: bool | None = None control_result: bool | None = None
_light_id: int _light_id: int
def __init__(
self,
coordinator: SwitcherDataUpdateCoordinator,
light_id: int,
) -> None:
"""Initialize the entity."""
super().__init__(coordinator)
self._light_id = light_id
self.control_result: bool | None = None
@callback @callback
def _handle_coordinator_update(self) -> None: def _handle_coordinator_update(self) -> None:
"""When device updates, clear control result that overrides state.""" """When device updates, clear control result that overrides state."""
@ -98,9 +108,7 @@ class SwitcherSingleLightEntity(SwitcherBaseLightEntity):
light_id: int, light_id: int,
) -> None: ) -> None:
"""Initialize the entity.""" """Initialize the entity."""
super().__init__(coordinator) super().__init__(coordinator, light_id)
self._light_id = light_id
self.control_result: bool | None = None
# Entity class attributes # Entity class attributes
self._attr_unique_id = f"{coordinator.device_id}-{coordinator.mac_address}" self._attr_unique_id = f"{coordinator.device_id}-{coordinator.mac_address}"
@ -117,9 +125,7 @@ class SwitcherMultiLightEntity(SwitcherBaseLightEntity):
light_id: int, light_id: int,
) -> None: ) -> None:
"""Initialize the entity.""" """Initialize the entity."""
super().__init__(coordinator) super().__init__(coordinator, light_id)
self._light_id = light_id
self.control_result: bool | None = None
# Entity class attributes # Entity class attributes
self._attr_translation_placeholders = {"light_id": str(light_id + 1)} self._attr_translation_placeholders = {"light_id": str(light_id + 1)}

View File

@ -6,8 +6,13 @@ from datetime import timedelta
import logging import logging
from typing import Any, cast from typing import Any, cast
from aioswitcher.api import Command, ShutterChildLock from aioswitcher.api import Command
from aioswitcher.device import DeviceCategory, DeviceState, SwitcherShutter from aioswitcher.device import (
DeviceCategory,
DeviceState,
ShutterChildLock,
SwitcherShutter,
)
import voluptuous as vol import voluptuous as vol
from homeassistant.components.switch import SwitchDeviceClass, SwitchEntity from homeassistant.components.switch import SwitchDeviceClass, SwitchEntity
@ -83,11 +88,11 @@ async def async_setup_entry(
number_of_covers = len(cast(SwitcherShutter, coordinator.data).position) number_of_covers = len(cast(SwitcherShutter, coordinator.data).position)
if number_of_covers == 1: if number_of_covers == 1:
entities.append( entities.append(
SwitchereShutterChildLockSingleSwitchEntity(coordinator, 0) SwitcherShutterChildLockSingleSwitchEntity(coordinator, 0)
) )
else: else:
entities.extend( entities.extend(
SwitchereShutterChildLockMultiSwitchEntity(coordinator, i) SwitcherShutterChildLockMultiSwitchEntity(coordinator, i)
for i in range(number_of_covers) for i in range(number_of_covers)
) )
async_add_entities(entities) async_add_entities(entities)
@ -176,7 +181,7 @@ class SwitcherWaterHeaterSwitchEntity(SwitcherBaseSwitchEntity):
self.async_write_ha_state() self.async_write_ha_state()
class SwitchereShutterChildLockBaseSwitchEntity(SwitcherEntity, SwitchEntity): class SwitcherShutterChildLockBaseSwitchEntity(SwitcherEntity, SwitchEntity):
"""Representation of a Switcher shutter base switch entity.""" """Representation of a Switcher shutter base switch entity."""
_attr_device_class = SwitchDeviceClass.SWITCH _attr_device_class = SwitchDeviceClass.SWITCH
@ -221,8 +226,8 @@ class SwitchereShutterChildLockBaseSwitchEntity(SwitcherEntity, SwitchEntity):
self.async_write_ha_state() self.async_write_ha_state()
class SwitchereShutterChildLockSingleSwitchEntity( class SwitcherShutterChildLockSingleSwitchEntity(
SwitchereShutterChildLockBaseSwitchEntity SwitcherShutterChildLockBaseSwitchEntity
): ):
"""Representation of a Switcher runner child lock single switch entity.""" """Representation of a Switcher runner child lock single switch entity."""
@ -242,8 +247,8 @@ class SwitchereShutterChildLockSingleSwitchEntity(
) )
class SwitchereShutterChildLockMultiSwitchEntity( class SwitcherShutterChildLockMultiSwitchEntity(
SwitchereShutterChildLockBaseSwitchEntity SwitcherShutterChildLockBaseSwitchEntity
): ):
"""Representation of a Switcher runner child lock multiple switch entity.""" """Representation of a Switcher runner child lock multiple switch entity."""

View File

@ -2,6 +2,7 @@
from datetime import timedelta from datetime import timedelta
from freezegun.api import FrozenDateTimeFactory
import pytest import pytest
from homeassistant.components.switcher_kis.const import DOMAIN, MAX_UPDATE_INTERVAL_SEC from homeassistant.components.switcher_kis.const import DOMAIN, MAX_UPDATE_INTERVAL_SEC
@ -20,7 +21,10 @@ from tests.typing import WebSocketGenerator
async def test_update_fail( async def test_update_fail(
hass: HomeAssistant, mock_bridge, caplog: pytest.LogCaptureFixture hass: HomeAssistant,
mock_bridge,
caplog: pytest.LogCaptureFixture,
freezer: FrozenDateTimeFactory,
) -> None: ) -> None:
"""Test entities state unavailable when updates fail..""" """Test entities state unavailable when updates fail.."""
entry = await init_integration(hass) entry = await init_integration(hass)
@ -32,9 +36,8 @@ async def test_update_fail(
assert mock_bridge.is_running is True assert mock_bridge.is_running is True
assert len(entry.runtime_data) == 2 assert len(entry.runtime_data) == 2
async_fire_time_changed( freezer.tick(timedelta(seconds=MAX_UPDATE_INTERVAL_SEC + 1))
hass, dt_util.utcnow() + timedelta(seconds=MAX_UPDATE_INTERVAL_SEC + 1) async_fire_time_changed(hass)
)
await hass.async_block_till_done() await hass.async_block_till_done()
for device in DUMMY_SWITCHER_DEVICES: for device in DUMMY_SWITCHER_DEVICES:

View File

@ -3,7 +3,6 @@
import pytest import pytest
from homeassistant.core import HomeAssistant from homeassistant.core import HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.util import slugify from homeassistant.util import slugify
from . import init_integration from . import init_integration
@ -55,35 +54,6 @@ async def test_sensor_platform(hass: HomeAssistant, mock_bridge) -> None:
assert state.state == str(getattr(device, field)) assert state.state == str(getattr(device, field))
async def test_sensor_disabled(
hass: HomeAssistant, entity_registry: er.EntityRegistry, mock_bridge
) -> None:
"""Test sensor disabled by default."""
await init_integration(hass)
assert mock_bridge
mock_bridge.mock_callbacks([DUMMY_WATER_HEATER_DEVICE])
await hass.async_block_till_done()
device = DUMMY_WATER_HEATER_DEVICE
unique_id = f"{device.device_id}-{device.mac_address}-auto_off_set"
entity_id = f"sensor.{slugify(device.name)}_auto_shutdown"
entry = entity_registry.async_get(entity_id)
assert entry
assert entry.unique_id == unique_id
assert entry.disabled is True
assert entry.disabled_by is er.RegistryEntryDisabler.INTEGRATION
# Test enabling entity
updated_entry = entity_registry.async_update_entity(
entry.entity_id, disabled_by=None
)
assert updated_entry != entry
assert updated_entry.disabled is False
@pytest.mark.parametrize("mock_bridge", [[DUMMY_WATER_HEATER_DEVICE]], indirect=True) @pytest.mark.parametrize("mock_bridge", [[DUMMY_WATER_HEATER_DEVICE]], indirect=True)
async def test_sensor_update( async def test_sensor_update(
hass: HomeAssistant, mock_bridge, monkeypatch: pytest.MonkeyPatch hass: HomeAssistant, mock_bridge, monkeypatch: pytest.MonkeyPatch