From bbbdf8e6a2543f66c3842d1b45917423110bfad0 Mon Sep 17 00:00:00 2001 From: Pere Diaz Bou Date: Tue, 14 Dec 2021 09:25:49 +0100 Subject: [PATCH] monitoring/grafana: doctest util regex Signed-off-by: Pere Diaz Bou --- .../grafana/dashboards/tests/__init__.py | 5 ++-- monitoring/grafana/dashboards/tests/util.py | 23 +++++++++++++++++++ monitoring/grafana/dashboards/tox.ini | 1 + 3 files changed, 27 insertions(+), 2 deletions(-) diff --git a/monitoring/grafana/dashboards/tests/__init__.py b/monitoring/grafana/dashboards/tests/__init__.py index d758afabf526a..45147e5c32490 100644 --- a/monitoring/grafana/dashboards/tests/__init__.py +++ b/monitoring/grafana/dashboards/tests/__init__.py @@ -7,6 +7,8 @@ from typing import Any, List import yaml +from .util import replace_grafana_expr_variables + @dataclass class InputSeries: @@ -171,8 +173,7 @@ class PromqlTest: for variable, value in self.variables.items(): expr = self.promql_expr_test.expr - regex = fr'\${variable}(?=\W)' - new_expr = re.sub(regex, fr'{str(value)}', expr) + new_expr = replace_grafana_expr_variables(expr, variable, value) self.set_expression(new_expr) test_as_dict = asdict(self.test_file) diff --git a/monitoring/grafana/dashboards/tests/util.py b/monitoring/grafana/dashboards/tests/util.py index 4f09e9edd3b0f..7b6391a34ab67 100644 --- a/monitoring/grafana/dashboards/tests/util.py +++ b/monitoring/grafana/dashboards/tests/util.py @@ -1,4 +1,5 @@ import json +import re from pathlib import Path from typing import Any, Dict, Tuple, Union @@ -66,3 +67,25 @@ def add_dashboard_variables(data: Dict[str, Any], dashboard_data: Dict[str, Any] for variable in dashboard_data['templating']['list']: if 'name' in variable: data['variables'][variable['name']] = 'UNSET VARIABLE' + + +def replace_grafana_expr_variables(expr: str, variable: str, value: Any) -> str: + """ Replace grafana variables in expression with a value + + It should match the whole word, 'osd' musn't match with the 'osd' prefix in 'osd_hosts' + >>> replace_grafana_expr_variables('metric{name~="$osd_hosts|$other|$osd"}', \ + 'osd', 'replacement') + 'metric{name~="$osd_hosts|$other|replacement"}' + + >>> replace_grafana_expr_variables('metric{name~="$osd_hosts|$other|$osd"}', \ + 'other', 'replacement') + 'metric{name~="$osd_hosts|replacement|$osd"}' + + It replaces words with dollar prefix + >>> replace_grafana_expr_variables('metric{name~="no_dollar|$other|$osd"}', \ + 'no_dollar', 'replacement') + 'metric{name~="no_dollar|$other|$osd"}' + """ + regex = fr'\${variable}(?=\W)' + new_expr = re.sub(regex, fr'{str(value)}', expr) + return new_expr diff --git a/monitoring/grafana/dashboards/tox.ini b/monitoring/grafana/dashboards/tox.ini index 382952c5b1bee..c489a7897113f 100644 --- a/monitoring/grafana/dashboards/tox.ini +++ b/monitoring/grafana/dashboards/tox.ini @@ -41,4 +41,5 @@ deps = depends = grafonnet-check setenv = commands = + python -m doctest tests/util.py behave tests/features -- 2.39.5