From ce98324da34d44527b211c77e75420d8d92037a2 Mon Sep 17 00:00:00 2001 From: MatthewFlamm <39341281+MatthewFlamm@users.noreply.github.com> Date: Wed, 17 May 2023 16:00:13 -0400 Subject: [PATCH] Fix NWS error with no observation (#92997) Co-authored-by: epenet <6771947+epenet@users.noreply.github.com> --- homeassistant/components/nws/sensor.py | 7 +++++-- tests/components/nws/test_sensor.py | 7 +++++-- 2 files changed, 10 insertions(+), 4 deletions(-) diff --git a/homeassistant/components/nws/sensor.py b/homeassistant/components/nws/sensor.py index 61f823de8e6..79a4294449b 100644 --- a/homeassistant/components/nws/sensor.py +++ b/homeassistant/components/nws/sensor.py @@ -195,9 +195,12 @@ class NWSSensor(CoordinatorEntity[NwsDataUpdateCoordinator], SensorEntity): @property def native_value(self) -> float | None: """Return the state.""" - value = self._nws.observation.get(self.entity_description.key) - if value is None: + if ( + not (observation := self._nws.observation) + or (value := observation.get(self.entity_description.key)) is None + ): return None + # Set alias to unit property -> prevent unnecessary hasattr calls unit_of_measurement = self.native_unit_of_measurement if unit_of_measurement == UnitOfSpeed.MILES_PER_HOUR: diff --git a/tests/components/nws/test_sensor.py b/tests/components/nws/test_sensor.py index 5edae630263..5e36c9c0717 100644 --- a/tests/components/nws/test_sensor.py +++ b/tests/components/nws/test_sensor.py @@ -70,10 +70,13 @@ async def test_imperial_metric( assert state.attributes.get(ATTR_ATTRIBUTION) == ATTRIBUTION -async def test_none_values(hass: HomeAssistant, mock_simple_nws, no_weather) -> None: +@pytest.mark.parametrize("values", [NONE_OBSERVATION, None]) +async def test_none_values( + hass: HomeAssistant, mock_simple_nws, no_weather, values +) -> None: """Test with no values.""" instance = mock_simple_nws.return_value - instance.observation = NONE_OBSERVATION + instance.observation = values registry = er.async_get(hass)