Glances: Add error handling for invalid sensor data (#93542)

* Set sensor to Unavailable
when native_value is invalid

* Add unit tests for sensors
pull/80563/head
Dominik 2023-05-31 03:35:33 +02:00 committed by GitHub
parent ac8d8dccd2
commit f6d3b0618e
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 48 additions and 3 deletions

View File

@ -328,6 +328,18 @@ class GlancesSensor(CoordinatorEntity[GlancesDataUpdateCoordinator], SensorEntit
)
self._attr_unique_id = f"{coordinator.config_entry.entry_id}-{sensor_name_prefix}-{description.key}"
@property
def available(self) -> bool:
"""Set sensor unavailable when native value is invalid."""
if super().available:
return (
not self._numeric_state_expected
or isinstance(self.native_value, (int, float))
or isinstance(self.native_value, str)
and self.native_value.isnumeric()
)
return False
@property
def native_value(self) -> StateType:
"""Return the state of the resources."""

View File

@ -109,7 +109,25 @@ MOCK_DATA = {
"unit": "C",
"type": "temperature_core",
"key": "label",
}
},
{
"label": "err_temp",
"value": "ERR",
"warning": None,
"critical": None,
"unit": "C",
"type": "temperature_hdd",
"key": "label",
},
{
"label": "na_temp",
"value": "NA",
"warning": None,
"critical": None,
"unit": "C",
"type": "temperature_hdd",
"key": "label",
},
],
"system": {
"os_name": "Linux",
@ -127,7 +145,11 @@ HA_SENSOR_DATA: dict[str, Any] = {
"/ssl": {"disk_use": 30.7, "disk_use_percent": 6.7, "disk_free": 426.5},
"/media": {"disk_use": 30.7, "disk_use_percent": 6.7, "disk_free": 426.5},
},
"sensors": {"cpu_thermal 1": {"temperature_core": 59}},
"sensors": {
"cpu_thermal 1": {"temperature_core": 59},
"err_temp": {"temperature_hdd": "Unavailable"},
"na_temp": {"temperature_hdd": "Unavailable"},
},
"mem": {
"memory_use_percent": 27.6,
"memory_use": 1047.1,

View File

@ -21,9 +21,20 @@ async def test_sensor_states(hass: HomeAssistant) -> None:
if state := hass.states.get("sensor.0_0_0_0_ssl_disk_use"):
assert state.state == HA_SENSOR_DATA["fs"]["/ssl"]["disk_use"]
if state := hass.states.get("sensor.0_0_0_0_cpu_thermal_1"):
assert state.state == HA_SENSOR_DATA["sensors"]["cpu_thermal 1"]
if state := hass.states.get("sensor.0_0_0_0_err_temp"):
assert state.state == HA_SENSOR_DATA["sensors"]["err_temp"]
if state := hass.states.get("sensor.0_0_0_0_na_temp"):
assert state.state == HA_SENSOR_DATA["sensors"]["na_temp"]
if state := hass.states.get("sensor.0_0_0_0_memory_use_percent"):
assert state.state == HA_SENSOR_DATA["mem"]["memory_use_percent"]
if state := hass.states.get("sensor.0_0_0_0_docker_active"):
assert state.state == HA_SENSOR_DATA["docker"]["docker_active"]
if state := hass.states.get("sensor.0_0_0_0_docker_cpu_use"):
assert state.state == HA_SENSOR_DATA["docker"]["docker_cpu_use"]
if state := hass.states.get("sensor.0_0_0_0_docker_memory_use"):
assert state.state == HA_SENSOR_DATA["docker"]["docker_memory_use"]
@pytest.mark.parametrize(