From 3b3ab2c19ccefbb07635c4a78fcae66378c44058 Mon Sep 17 00:00:00 2001 From: rianadon Date: Thu, 16 Dec 2021 13:01:32 -0800 Subject: [PATCH] Handle None values in weather entity forecast (#61467) --- homeassistant/components/weather/__init__.py | 22 ++++++++++--------- tests/components/weather/test_init.py | 23 ++++++++++++++++++++ 2 files changed, 35 insertions(+), 10 deletions(-) diff --git a/homeassistant/components/weather/__init__.py b/homeassistant/components/weather/__init__.py index b9fa7e2ae39..0a562a40f64 100644 --- a/homeassistant/components/weather/__init__.py +++ b/homeassistant/components/weather/__init__.py @@ -262,29 +262,31 @@ class WeatherEntity(Entity): self.temperature_unit, self.precision, ) - if ATTR_FORECAST_PRESSURE in forecast_entry: + if ( + native_pressure := forecast_entry.get(ATTR_FORECAST_PRESSURE) + ) is not None: if (unit := self.pressure_unit) is not None: pressure = round( - self.hass.config.units.pressure( - forecast_entry[ATTR_FORECAST_PRESSURE], unit - ), + self.hass.config.units.pressure(native_pressure, unit), ROUNDING_PRECISION, ) forecast_entry[ATTR_FORECAST_PRESSURE] = pressure - if ATTR_FORECAST_WIND_SPEED in forecast_entry: + if ( + native_wind_speed := forecast_entry.get(ATTR_FORECAST_WIND_SPEED) + ) is not None: if (unit := self.wind_speed_unit) is not None: wind_speed = round( - self.hass.config.units.wind_speed( - forecast_entry[ATTR_FORECAST_WIND_SPEED], unit - ), + self.hass.config.units.wind_speed(native_wind_speed, unit), ROUNDING_PRECISION, ) forecast_entry[ATTR_FORECAST_WIND_SPEED] = wind_speed - if ATTR_FORECAST_PRECIPITATION in forecast_entry: + if ( + native_precip := forecast_entry.get(ATTR_FORECAST_PRECIPITATION) + ) is not None: if (unit := self.precipitation_unit) is not None: precipitation = round( self.hass.config.units.accumulated_precipitation( - forecast_entry[ATTR_FORECAST_PRECIPITATION], unit + native_precip, unit ), ROUNDING_PRECISION, ) diff --git a/tests/components/weather/test_init.py b/tests/components/weather/test_init.py index 4125e94749a..9849a6abe18 100644 --- a/tests/components/weather/test_init.py +++ b/tests/components/weather/test_init.py @@ -168,3 +168,26 @@ async def test_precipitation_conversion( native_value, native_unit, unit_system.accumulated_precipitation_unit ) assert float(forecast[ATTR_FORECAST_PRECIPITATION]) == approx(expected, rel=1e-2) + + +async def test_none_forecast( + hass, + enable_custom_integrations, +): + """Test that conversion with None values succeeds.""" + entity0 = await create_entity( + hass, + pressure=None, + pressure_unit=PRESSURE_INHG, + wind_speed=None, + wind_speed_unit=SPEED_METERS_PER_SECOND, + precipitation=None, + precipitation_unit=LENGTH_MILLIMETERS, + ) + + state = hass.states.get(entity0.entity_id) + forecast = state.attributes[ATTR_FORECAST][0] + + assert forecast[ATTR_FORECAST_PRESSURE] is None + assert forecast[ATTR_FORECAST_WIND_SPEED] is None + assert forecast[ATTR_FORECAST_PRECIPITATION] is None