From 40591c373b7312470564e7858a078a32c4895c11 Mon Sep 17 00:00:00 2001 From: Hamed Karbasi Date: Thu, 29 Feb 2024 00:20:56 +0330 Subject: [PATCH] fix empty results by returning dataframe with a null value (#3) --- app/helper/prometheus.py | 9 +++++++++ tests/test_main.py | 19 ++++++++++++------- 2 files changed, 21 insertions(+), 7 deletions(-) diff --git a/app/helper/prometheus.py b/app/helper/prometheus.py index 7411e6c..2407e7f 100644 --- a/app/helper/prometheus.py +++ b/app/helper/prometheus.py @@ -6,6 +6,7 @@ from requests import RequestException from .logger import logger import pandas as pd +import time class Prometheus: @@ -30,4 +31,12 @@ def get_current_value(self, query) -> pd.DataFrame: "non 200 response status code on query {}".format(query), stack_info=True, ) + # handle empty results as a dummy metric with current time and none value. + if len(result) == 0: + return MetricSnapshotDataFrame( + data={ + "metric": {"__name__": "dummy_metric"}, + "value": [time.time(), None], + } + ) return MetricSnapshotDataFrame(result) diff --git a/tests/test_main.py b/tests/test_main.py index c523a9c..5c3d677 100644 --- a/tests/test_main.py +++ b/tests/test_main.py @@ -1,20 +1,25 @@ from unittest.mock import patch, Mock from app.main import main + @patch( "app.helper.prometheus.PrometheusConnect.check_prometheus_connection", Mock(return_value=True), ) @patch( "app.helper.prometheus.PrometheusConnect.custom_query", + # It uses two outputs for the prometheus: an ordinary and an empty result. Mock( - return_value=[ - { - "metric": {"__name__": "dummy_metric"}, - "value": [1708184035.052, "0.29875"], - } - ] + side_effect=[ + [ + { + "metric": {"__name__": "dummy_metric"}, + "value": [1708184035.052, "0.29875"], + } + ], + [], + ], ), ) def test_main(): - main(config_path="tests/config.yaml", output_path="tests/output.json") \ No newline at end of file + main(config_path="tests/config.yaml", output_path="tests/output.json")