Handle attributes set to None in prometheus (#104247)

Better handle attributes set to None
This commit is contained in:
Anton Tolchanov 2023-11-20 18:53:25 +00:00 committed by GitHub
parent 58a73f7723
commit 80f8e76fa3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 25 additions and 4 deletions

View File

@ -19,6 +19,7 @@ from homeassistant.components.climate import (
from homeassistant.components.cover import ATTR_POSITION, ATTR_TILT_POSITION
from homeassistant.components.http import HomeAssistantView
from homeassistant.components.humidifier import ATTR_AVAILABLE_MODES, ATTR_HUMIDITY
from homeassistant.components.light import ATTR_BRIGHTNESS
from homeassistant.components.sensor import SensorDeviceClass
from homeassistant.const import (
ATTR_BATTERY_LEVEL,
@ -323,14 +324,14 @@ class PrometheusMetrics:
}
def _battery(self, state):
if "battery_level" in state.attributes:
if (battery_level := state.attributes.get(ATTR_BATTERY_LEVEL)) is not None:
metric = self._metric(
"battery_level_percent",
self.prometheus_cli.Gauge,
"Battery level as a percentage of its capacity",
)
try:
value = float(state.attributes[ATTR_BATTERY_LEVEL])
value = float(battery_level)
metric.labels(**self._labels(state)).set(value)
except ValueError:
pass
@ -440,8 +441,9 @@ class PrometheusMetrics:
)
try:
if "brightness" in state.attributes and state.state == STATE_ON:
value = state.attributes["brightness"] / 255.0
brightness = state.attributes.get(ATTR_BRIGHTNESS)
if state.state == STATE_ON and brightness is not None:
value = brightness / 255.0
else:
value = self.state_as_number(state)
value = value * 100

View File

@ -491,6 +491,12 @@ async def test_light(client, light_entities) -> None:
'friendly_name="PC"} 70.58823529411765' in body
)
assert (
'light_brightness_percent{domain="light",'
'entity="light.hallway",'
'friendly_name="Hallway"} 100.0' in body
)
@pytest.mark.parametrize("namespace", [""])
async def test_lock(client, lock_entities) -> None:
@ -1557,6 +1563,19 @@ async def light_fixture(
data["light_4"] = light_4
data["light_4_attributes"] = light_4_attributes
light_5 = entity_registry.async_get_or_create(
domain=light.DOMAIN,
platform="test",
unique_id="light_5",
suggested_object_id="hallway",
original_name="Hallway",
)
# Light is on, but brightness is unset; expect metrics to report
# brightness of 100%.
light_5_attributes = {light.ATTR_BRIGHTNESS: None}
set_state_with_entry(hass, light_5, STATE_ON, light_5_attributes)
data["light_5"] = light_5
data["light_5_attributes"] = light_5_attributes
await hass.async_block_till_done()
return data