Ensure button platform does not restore unavailable state (#108316)

This commit is contained in:
J. Nick Koston 2024-01-21 01:04:13 -10:00 committed by GitHub
parent fa485513d5
commit d885bf886a
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 23 additions and 2 deletions

View file

@ -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:

View file

@ -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."""