From d885bf886ac302e353e15b730cb3696b52a90773 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Sun, 21 Jan 2024 01:04:13 -1000 Subject: [PATCH] Ensure button platform does not restore unavailable state (#108316) --- homeassistant/components/button/__init__.py | 3 ++- tests/components/button/test_init.py | 22 ++++++++++++++++++++- 2 files changed, 23 insertions(+), 2 deletions(-) diff --git a/homeassistant/components/button/__init__.py b/homeassistant/components/button/__init__.py index 3ecc27f8573..0acc5b63339 100644 --- a/homeassistant/components/button/__init__.py +++ b/homeassistant/components/button/__init__.py @@ -9,6 +9,7 @@ from typing import TYPE_CHECKING, final import voluptuous as vol from homeassistant.config_entries import ConfigEntry +from homeassistant.const import STATE_UNAVAILABLE from homeassistant.core import HomeAssistant from homeassistant.helpers.config_validation import ( # noqa: F401 PLATFORM_SCHEMA, @@ -141,7 +142,7 @@ class ButtonEntity(RestoreEntity, cached_properties=CACHED_PROPERTIES_WITH_ATTR_ """Call when the button is added to hass.""" await super().async_internal_added_to_hass() state = await self.async_get_last_state() - if state is not None and state.state is not None: + if state is not None and state.state not in (STATE_UNAVAILABLE, None): self.__set_state(state.state) def press(self) -> None: diff --git a/tests/components/button/test_init.py b/tests/components/button/test_init.py index 2457a796d45..acf7bd39e10 100644 --- a/tests/components/button/test_init.py +++ b/tests/components/button/test_init.py @@ -14,7 +14,12 @@ from homeassistant.components.button import ( ButtonEntityDescription, ) from homeassistant.config_entries import ConfigEntry, ConfigFlow -from homeassistant.const import ATTR_ENTITY_ID, CONF_PLATFORM, STATE_UNKNOWN +from homeassistant.const import ( + ATTR_ENTITY_ID, + CONF_PLATFORM, + STATE_UNAVAILABLE, + STATE_UNKNOWN, +) from homeassistant.core import HomeAssistant, State from homeassistant.helpers.entity_platform import AddEntitiesCallback from homeassistant.setup import async_setup_component @@ -106,6 +111,21 @@ async def test_restore_state( assert hass.states.get("button.button_1").state == "2021-01-01T23:59:59+00:00" +async def test_restore_state_does_not_restore_unavailable( + hass: HomeAssistant, enable_custom_integrations: None +) -> None: + """Test we restore state integration except for unavailable.""" + mock_restore_cache(hass, (State("button.button_1", STATE_UNAVAILABLE),)) + + platform = getattr(hass.components, f"test.{DOMAIN}") + platform.init() + + assert await async_setup_component(hass, DOMAIN, {DOMAIN: {CONF_PLATFORM: "test"}}) + await hass.async_block_till_done() + + assert hass.states.get("button.button_1").state == STATE_UNKNOWN + + class MockFlow(ConfigFlow): """Test flow."""