From 8ab6a505a4267fca4dd5411e4754bdb5ce705e80 Mon Sep 17 00:00:00 2001 From: Kevin Stillhammer Date: Mon, 8 Jul 2024 13:15:17 +0200 Subject: [PATCH] Write data to state after Broadlink entity added (#121493) * Write data to ha after entity added * Properly mock api return values Some values like _attr_is_on were mapped to MagicMocks which led to them evaluating to True. Actually calling the update state method when adding the entities made that improper mocking come to the surface. * Call _update_state instead of _recv_data --- homeassistant/components/broadlink/entity.py | 2 ++ tests/components/broadlink/__init__.py | 25 ++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/homeassistant/components/broadlink/entity.py b/homeassistant/components/broadlink/entity.py index ffd0b46e0bf..6c956d8c80a 100644 --- a/homeassistant/components/broadlink/entity.py +++ b/homeassistant/components/broadlink/entity.py @@ -20,6 +20,8 @@ class BroadlinkEntity(Entity): async def async_added_to_hass(self): """Call when the entity is added to hass.""" self.async_on_remove(self._coordinator.async_add_listener(self._recv_data)) + if self._coordinator.data: + self._update_state(self._coordinator.data) async def async_update(self): """Update the state of the entity.""" diff --git a/tests/components/broadlink/__init__.py b/tests/components/broadlink/__init__.py index c9245fb16fa..1c87de8d9e2 100644 --- a/tests/components/broadlink/__init__.py +++ b/tests/components/broadlink/__init__.py @@ -168,6 +168,31 @@ class BroadlinkDevice: } +class BroadlinkMP1BG1Device(BroadlinkDevice): + """Mock device for MP1 and BG1 with special mocking of api return values.""" + + def get_mock_api(self): + """Return a mock device (API) with support for check_power calls.""" + mock_api = super().get_mock_api() + mock_api.check_power.return_value = {"s1": 0, "s2": 0, "s3": 0, "s4": 0} + return mock_api + + +class BroadlinkSP4BDevice(BroadlinkDevice): + """Mock device for SP4b with special mocking of api return values.""" + + def get_mock_api(self): + """Return a mock device (API) with support for get_state calls.""" + mock_api = super().get_mock_api() + mock_api.get_state.return_value = {"pwr": 0} + return mock_api + + def get_device(name): """Get a device by name.""" + dev_type = BROADLINK_DEVICES[name][5] + if dev_type in {0x4EB5}: + return BroadlinkMP1BG1Device(name, *BROADLINK_DEVICES[name]) + if dev_type in {0x5115}: + return BroadlinkSP4BDevice(name, *BROADLINK_DEVICES[name]) return BroadlinkDevice(name, *BROADLINK_DEVICES[name])