From f71d49230df53ae917227b0f091043ffb12fe680 Mon Sep 17 00:00:00 2001 From: Renat Nurgaliyev Date: Tue, 4 Jan 2022 17:34:05 +0100 Subject: [PATCH] Add counter entities support to Prometheus component (#62410) --- .../components/prometheus/__init__.py | 9 +++++++ tests/components/prometheus/test_init.py | 27 ++++++++++++++++++- 2 files changed, 35 insertions(+), 1 deletion(-) diff --git a/homeassistant/components/prometheus/__init__.py b/homeassistant/components/prometheus/__init__.py index f130aee9f29..9c3d3abffa5 100644 --- a/homeassistant/components/prometheus/__init__.py +++ b/homeassistant/components/prometheus/__init__.py @@ -515,6 +515,15 @@ class PrometheusMetrics: metric.labels(**self._labels(state)).inc() + def _handle_counter(self, state): + metric = self._metric( + "counter_value", + self.prometheus_cli.Gauge, + "Value of counter entities", + ) + + metric.labels(**self._labels(state)).set(self.state_as_number(state)) + class PrometheusView(HomeAssistantView): """Handle Prometheus requests.""" diff --git a/tests/components/prometheus/test_init.py b/tests/components/prometheus/test_init.py index 7ad945d2d22..0a4e528a179 100644 --- a/tests/components/prometheus/test_init.py +++ b/tests/components/prometheus/test_init.py @@ -7,7 +7,7 @@ import unittest.mock as mock import prometheus_client import pytest -from homeassistant.components import climate, humidifier, lock, sensor +from homeassistant.components import climate, counter, humidifier, lock, sensor from homeassistant.components.demo.binary_sensor import DemoBinarySensor from homeassistant.components.demo.light import DemoLight from homeassistant.components.demo.number import DemoNumber @@ -662,6 +662,31 @@ async def test_lock(hass, hass_client): ) +async def test_counter(hass, hass_client): + """Test prometheus metrics for counter.""" + assert await async_setup_component( + hass, + "conversation", + {}, + ) + + client = await setup_prometheus_client(hass, hass_client, "") + + await async_setup_component( + hass, counter.DOMAIN, {"counter": {"counter": {"initial": "2"}}} + ) + + await hass.async_block_till_done() + + body = await generate_latest_metrics(client) + + assert ( + 'counter_value{domain="counter",' + 'entity="counter.counter",' + 'friendly_name="None"} 2.0' in body + ) + + @pytest.fixture(name="mock_client") def mock_client_fixture(): """Mock the prometheus client."""