Fix input_number invalid state restore handling (#74213)

Co-authored-by: J. Nick Koston <nick@koston.org>
This commit is contained in:
Franck Nijhof 2022-06-30 07:06:35 +02:00 committed by GitHub
parent f721b9e3df
commit 555e9c6762
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 28 additions and 2 deletions

View File

@ -1,6 +1,7 @@
"""Support to set a numeric value from a slider or text box."""
from __future__ import annotations
from contextlib import suppress
import logging
import voluptuous as vol
@ -281,8 +282,10 @@ class InputNumber(RestoreEntity):
if self._current_value is not None:
return
state = await self.async_get_last_state()
value = state and float(state.state)
value: float | None = None
if state := await self.async_get_last_state():
with suppress(ValueError):
value = float(state.state)
# Check against None because value can be 0
if value is not None and self._minimum <= value <= self._maximum:

View File

@ -255,6 +255,29 @@ async def test_restore_state(hass):
assert float(state.state) == 10
async def test_restore_invalid_state(hass):
"""Ensure an invalid restore state is handled."""
mock_restore_cache(
hass, (State("input_number.b1", "="), State("input_number.b2", "200"))
)
hass.state = CoreState.starting
await async_setup_component(
hass,
DOMAIN,
{DOMAIN: {"b1": {"min": 2, "max": 100}, "b2": {"min": 10, "max": 100}}},
)
state = hass.states.get("input_number.b1")
assert state
assert float(state.state) == 2
state = hass.states.get("input_number.b2")
assert state
assert float(state.state) == 10
async def test_initial_state_overrules_restore_state(hass):
"""Ensure states are restored on startup."""
mock_restore_cache(