diff --git a/homeassistant/components/bosch_shc/entity.py b/homeassistant/components/bosch_shc/entity.py index 7e99ce8e2073..73a991a226b1 100644 --- a/homeassistant/components/bosch_shc/entity.py +++ b/homeassistant/components/bosch_shc/entity.py @@ -1,5 +1,6 @@ """Bosch Smart Home Controller base entity.""" +from functools import partial from typing import override from boschshcpy import SHCDevice @@ -47,12 +48,7 @@ class SHCBaseEntity(Entity): self.schedule_update_ha_state() self._device.subscribe_callback(self.unique_id, on_state_changed) - - @override - async def async_will_remove_from_hass(self) -> None: - """Unsubscribe from SHC events.""" - await super().async_will_remove_from_hass() - self._device.unsubscribe_callback(self.unique_id) + self.async_on_remove(partial(self._device.unsubscribe_callback, self.unique_id)) @property def device_id(self) -> str: @@ -96,13 +92,7 @@ class SHCEntity(SHCBaseEntity): for service in self._device.device_services: service.subscribe_callback(self.unique_id, on_state_changed) - - @override - async def async_will_remove_from_hass(self) -> None: - """Unsubscribe from SHC events.""" - await super().async_will_remove_from_hass() - for service in self._device.device_services: - service.unsubscribe_callback(self.unique_id) + self.async_on_remove(partial(service.unsubscribe_callback, self.unique_id)) @property @override diff --git a/homeassistant/components/bosch_shc/event.py b/homeassistant/components/bosch_shc/event.py index 421039c05a83..f9da56700d0c 100644 --- a/homeassistant/components/bosch_shc/event.py +++ b/homeassistant/components/bosch_shc/event.py @@ -1,5 +1,6 @@ """Platform for event integration.""" +from functools import partial from typing import TYPE_CHECKING, Any, override from boschshcpy import SHCMotionDetector, SHCMotionDetector2, SHCSmokeDetector @@ -93,15 +94,12 @@ class MotionDetectorEvent(SHCEntity, EventEntity): for service in self._device.device_services: if service.id == "LatestMotion": service.register_event(self._device.id, self._event_callback) + # register_event() has no public unsubscribe counterpart. + self.async_on_remove(partial(self._unregister_event, service)) - @override - async def async_will_remove_from_hass(self) -> None: - """Unregister the LatestMotion event callback.""" - await super().async_will_remove_from_hass() - # register_event() has no public unsubscribe counterpart. - for service in self._device.device_services: - if service.id == "LatestMotion": - service._event_callbacks.pop(self._device.id, None) # noqa: SLF001 + def _unregister_event(self, service: Any) -> None: + """Remove this entity's callback from the service.""" + service._event_callbacks.pop(self._device.id, None) # noqa: SLF001 def _event_callback(self) -> None: """Handle a LatestMotion update from the SHC polling thread.""" @@ -162,15 +160,12 @@ class SmokeDetectorEvent(SHCEntity, EventEntity): for service in self._device.device_services: if service.id == "Alarm": service.register_event(self._device.id, self._event_callback) + # register_event() has no public unsubscribe counterpart. + self.async_on_remove(partial(self._unregister_event, service)) - @override - async def async_will_remove_from_hass(self) -> None: - """Unregister the Alarm event callback.""" - await super().async_will_remove_from_hass() - # register_event() has no public unsubscribe counterpart. - for service in self._device.device_services: - if service.id == "Alarm": - service._event_callbacks.pop(self._device.id, None) # noqa: SLF001 + def _unregister_event(self, service: Any) -> None: + """Remove this entity's callback from the service.""" + service._event_callbacks.pop(self._device.id, None) # noqa: SLF001 def _event_callback(self) -> None: """Handle an Alarm update from the SHC polling thread.""" diff --git a/tests/components/bosch_shc/test_entity.py b/tests/components/bosch_shc/test_entity.py index 376f82f41be0..5a38a4bbd18b 100644 --- a/tests/components/bosch_shc/test_entity.py +++ b/tests/components/bosch_shc/test_entity.py @@ -121,3 +121,25 @@ async def test_callbacks_after_entity_id_change( motion_device.subscribe_callback.assert_called_once() motion_device.unsubscribe_callback.assert_called_once_with(key) service.unsubscribe_callback.assert_called_once_with(key) + + +@pytest.mark.parametrize( + "device_buckets", + [{"motion_detectors": [battery_only_device()]}], + indirect=True, +) +async def test_callbacks_unsubscribed_after_failed_entity_add( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, + motion_device: MagicMock, +) -> None: + """Callbacks are unsubscribed when adding the entity is aborted.""" + await setup_integration(hass, mock_config_entry) + key = motion_device.subscribe_callback.call_args.args[0] + motion_device.unsubscribe_callback.assert_not_called() + + entity = next(iter(hass.data["entity_components"]["binary_sensor"].entities)) + # HA calls this instead of async_will_remove_from_hass if adding fails. + entity.add_to_platform_abort() + + motion_device.unsubscribe_callback.assert_called_once_with(key) diff --git a/tests/components/bosch_shc/test_event.py b/tests/components/bosch_shc/test_event.py index 2e25f5205419..44a05424914f 100644 --- a/tests/components/bosch_shc/test_event.py +++ b/tests/components/bosch_shc/test_event.py @@ -140,6 +140,28 @@ async def test_motion_detector_unregisters_callback_on_unload( assert device.id not in latest_motion_service._event_callbacks +@pytest.mark.parametrize( + "device_buckets", + [{"motion_detectors": [motion_detector_device()]}], + indirect=True, +) +async def test_motion_detector_unregisters_callback_on_failed_add( + hass: HomeAssistant, + mock_session: MagicMock, + mock_config_entry: MockConfigEntry, +) -> None: + """An aborted add removes the LatestMotion callback registration.""" + await setup_integration(hass, mock_config_entry) + device = mock_session.device_helper.motion_detectors[0] + latest_motion_service = device.device_services[0] + assert device.id in latest_motion_service._event_callbacks + + entity = next(iter(hass.data["entity_components"]["event"].entities)) + entity.add_to_platform_abort() + + assert device.id not in latest_motion_service._event_callbacks + + @pytest.mark.parametrize( "device_buckets", [{"motion_detectors2": [motion_detector2_device()]}],