Handle None values in weather entity forecast (#61467)

This commit is contained in:
rianadon 2021-12-16 13:01:32 -08:00 committed by GitHub
parent cabd6375d1
commit 3b3ab2c19c
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 35 additions and 10 deletions

View file

@ -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,
)

View file

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