From bb5be58a99a1aba2e2986dfee7d359b3eaf44593 Mon Sep 17 00:00:00 2001 From: rivo nurges Date: Tue, 21 Feb 2023 11:33:44 +0200 Subject: [PATCH] add support for parsing values containing lists (#44) * add support for parsing values containing lists * add test for values containing lists * fix test style * black formatting fixes --------- Co-authored-by: rivo nurges --- mqtt_exporter/main.py | 6 ++++++ tests/functional/test_parse_metrics.py | 10 ++++++++++ 2 files changed, 16 insertions(+) diff --git a/mqtt_exporter/main.py b/mqtt_exporter/main.py index ae2ae71..71b3ad9 100644 --- a/mqtt_exporter/main.py +++ b/mqtt_exporter/main.py @@ -116,6 +116,12 @@ def _parse_metrics(data, topic, client_id, prefix=""): Note when `data` contains nested metrics this function will be called recursivley. """ for metric, value in data.items(): + # when value is a list recursivley call _parse_metrics to handle these messages + if isinstance(value, list): + LOG.debug("parsing list %s: %s", metric, value) + _parse_metrics(dict(enumerate(value)), topic, client_id, f"{prefix}{metric}_") + continue + # when value is a dict recursivley call _parse_metrics to handle these messages if isinstance(value, dict): LOG.debug("parsing dict %s: %s", metric, value) diff --git a/tests/functional/test_parse_metrics.py b/tests/functional/test_parse_metrics.py index 34ff44d..0cf50d0 100644 --- a/tests/functional/test_parse_metrics.py +++ b/tests/functional/test_parse_metrics.py @@ -36,3 +36,13 @@ def test_metrics_escaping(): assert "mqtt_test_value_a" in main.prom_metrics assert "mqtt_test_value_b" in main.prom_metrics assert "mqtt_test_value_c" in main.prom_metrics + + +def test_parse_metrics__value_is_list(): + """Verify if list recursion works properly.""" + main.prom_metrics = {} + parsed_topic = "test_topic" + parsed_payload = {"test_value": [1, 2]} + main._parse_metrics(parsed_payload, parsed_topic, "dummy_client_id") + assert "mqtt_test_value_0" in main.prom_metrics + assert "mqtt_test_value_1" in main.prom_metrics