Adapt wake_on_lan to in-place entity ID change (#184893)

This commit is contained in:
Erik Montnemery
2026-10-08 14:55:50 +02:00
committed by GitHub
parent 5be5044d5d
commit cedfdf4297
2 changed files with 39 additions and 14 deletions
+14 -8
View File
@@ -18,7 +18,7 @@ from homeassistant.const import (
CONF_MAC,
CONF_NAME,
)
from homeassistant.core import HomeAssistant
from homeassistant.core import HomeAssistant, callback
from homeassistant.helpers import config_validation as cv, device_registry as dr
from homeassistant.helpers.entity_platform import AddEntitiesCallback
from homeassistant.helpers.script import Script
@@ -125,16 +125,22 @@ class WolSwitch(SwitchEntity):
self._state = True
self.schedule_update_ha_state()
@callback
@override
def async_entity_id_changed(self, old_entity_id: str) -> None:
"""Opt in to in-place entity_id changes.
Can be removed when backwards compatibility is disabled for core
integrations, i.e. once all core integrations have been migrated
to in-place entity ID change.
"""
super().async_entity_id_changed(old_entity_id)
@override
async def async_will_remove_from_hass(self) -> None:
"""Clean up script when removing from Home Assistant."""
if self._off_script is None:
return
if self.registry_entry and self.registry_entry.entity_id != self.entity_id:
# Entity ID change, do not unload the script as it will be reused.
await self._off_script.async_stop()
return
await self._off_script.async_unload()
if self._off_script is not None:
await self._off_script.async_unload()
@override
def turn_off(self, **kwargs: Any) -> None:
+25 -6
View File
@@ -333,13 +333,32 @@ async def test_changed_entity_id(
await hass.async_block_till_done()
assert len(calls) == 1
entity = hass.data[switch.DOMAIN].get_entity("switch.wake_on_lan")
assert isinstance(entity, WolSwitch)
assert entity._off_script is not None
# Change entity_id while loaded
entry = entity_registry.async_get("switch.wake_on_lan")
assert entry is not None
entity_registry.async_update_entity(
entry.entity_id, new_entity_id="switch.custom_wol"
)
await hass.async_block_till_done()
with (
patch.object(
entity._off_script,
"async_stop",
wraps=entity._off_script.async_stop,
) as stop_mock,
patch.object(
entity._off_script,
"async_unload",
wraps=entity._off_script.async_unload,
) as unload_mock,
):
entity_registry.async_update_entity(
"switch.wake_on_lan", new_entity_id="switch.custom_wol"
)
await hass.async_block_till_done()
# The entity is not removed, so the off script is neither stopped nor unloaded
stop_mock.assert_not_called()
unload_mock.assert_not_called()
assert hass.states.get("switch.wake_on_lan") is None
# Turn off should still work after entity_id change
with patch("homeassistant.components.wake_on_lan.switch.sp.call", return_value=1):