Compare commits

...

1 Commits

Author SHA1 Message Date
Franck Nijhof e205976ddc Fix template switch state restore calling super twice in optimistic mode 2026-06-14 11:14:48 +00:00
2 changed files with 15 additions and 6 deletions
+6 -5
View File
@@ -181,11 +181,12 @@ class StateSwitchEntity(TemplateEntity, AbstractTemplateSwitch):
async def async_added_to_hass(self) -> None:
"""Register callbacks."""
if CONF_STATE not in self._templates:
# restore state after startup
await super().async_added_to_hass()
if state := await self.async_get_last_state():
self._attr_is_on = state.state == STATE_ON
if (
CONF_STATE not in self._templates
and (state := await self.async_get_last_state()) is not None
and state.state not in (STATE_UNKNOWN, STATE_UNAVAILABLE)
):
self._attr_is_on = state.state == STATE_ON
await super().async_added_to_hass()
+9 -1
View File
@@ -9,6 +9,7 @@ from homeassistant.components import switch, template
from homeassistant.components.switch import DOMAIN as SWITCH_DOMAIN
from homeassistant.const import (
ATTR_ENTITY_ID,
EVENT_HOMEASSISTANT_START,
SERVICE_TURN_OFF,
SERVICE_TURN_ON,
STATE_OFF,
@@ -581,7 +582,7 @@ async def test_off_action_optimistic(
async def test_restore_state(
hass: HomeAssistant, style: ConfigurationStyle, test_state: str
) -> None:
"""Test state restoration."""
"""Test state restoration persists through startup for optimistic switches."""
mock_restore_cache(
hass,
(State(TEST_SWITCH.entity_id, test_state),),
@@ -596,6 +597,13 @@ async def test_restore_state(
assert state
assert state.state == test_state
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
state = hass.states.get(TEST_SWITCH.entity_id)
assert state
assert state.state == test_state
@pytest.mark.parametrize(
("count", "attribute_template"),