Fix availability for GIOS index sensors (#113021)

* Fix availability for index sensors

* Improve test_availability()

---------

Co-authored-by: Maciej Bieniek <478555+bieniu@users.noreply.github.com>
This commit is contained in:
Maciej Bieniek 2024-03-12 17:41:16 +01:00 committed by GitHub
parent cd4e8707ea
commit f01095fb66
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 38 additions and 34 deletions

View File

@ -230,11 +230,11 @@ class GiosSensor(CoordinatorEntity[GiosDataUpdateCoordinator], SensorEntity):
@property @property
def available(self) -> bool: def available(self) -> bool:
"""Return if entity is available.""" """Return if entity is available."""
available = super().available
sensor_data = getattr(self.coordinator.data, self.entity_description.key) sensor_data = getattr(self.coordinator.data, self.entity_description.key)
available = super().available and bool(sensor_data)
# Sometimes the API returns sensor data without indexes # Sometimes the API returns sensor data without indexes
if self.entity_description.subkey: if self.entity_description.subkey and available:
return available and bool(sensor_data.index) return available and bool(sensor_data.index)
return available and bool(sensor_data) return available

View File

@ -1,5 +1,6 @@
"""Test sensor of GIOS integration.""" """Test sensor of GIOS integration."""
from copy import deepcopy
from datetime import timedelta from datetime import timedelta
import json import json
from unittest.mock import patch from unittest.mock import patch
@ -289,10 +290,12 @@ async def test_availability(hass: HomeAssistant) -> None:
assert state assert state
assert state.state == STATE_UNAVAILABLE assert state.state == STATE_UNAVAILABLE
incomplete_sensors = deepcopy(sensors)
incomplete_sensors["pm2.5"] = {}
future = utcnow() + timedelta(minutes=120) future = utcnow() + timedelta(minutes=120)
with patch( with patch(
"homeassistant.components.gios.Gios._get_all_sensors", "homeassistant.components.gios.Gios._get_all_sensors",
return_value=sensors, return_value=incomplete_sensors,
), patch( ), patch(
"homeassistant.components.gios.Gios._get_indexes", "homeassistant.components.gios.Gios._get_indexes",
return_value={}, return_value={},
@ -300,9 +303,10 @@ async def test_availability(hass: HomeAssistant) -> None:
async_fire_time_changed(hass, future) async_fire_time_changed(hass, future)
await hass.async_block_till_done() await hass.async_block_till_done()
# There is no PM2.5 data so the state should be unavailable
state = hass.states.get("sensor.home_pm2_5") state = hass.states.get("sensor.home_pm2_5")
assert state assert state
assert state.state == "4" assert state.state == STATE_UNAVAILABLE
# Indexes are empty so the state should be unavailable # Indexes are empty so the state should be unavailable
state = hass.states.get("sensor.home_air_quality_index") state = hass.states.get("sensor.home_air_quality_index")