Skip to content

Commit

Permalink
add support for parsing values containing lists (#44)
Browse files Browse the repository at this point in the history
* add support for parsing values containing lists

* add test for values containing lists

* fix test style

* black formatting fixes

---------

Co-authored-by: rivo nurges <[email protected]>
  • Loading branch information
rixxxx and rivo nurges authored Feb 21, 2023
1 parent 6bcf9fd commit bb5be58
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
6 changes: 6 additions & 0 deletions mqtt_exporter/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
10 changes: 10 additions & 0 deletions tests/functional/test_parse_metrics.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

0 comments on commit bb5be58

Please sign in to comment.