From e4c0d0618c586ffb6eb5d8c9f2c8437f57eacebc Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ma=C3=ABl=20Mandis?= Date: Fri, 2 Dec 2022 23:00:25 +0100 Subject: [PATCH] CloudWatch: Add custom label param to get_metric_data (#5728) --- moto/cloudwatch/models.py | 8 ++- .../test_cloudwatch/test_cloudwatch_boto3.py | 71 +++++++++++++++++++ 2 files changed, 78 insertions(+), 1 deletion(-) diff --git a/moto/cloudwatch/models.py b/moto/cloudwatch/models.py index d5eb1440f..c65fe70c1 100644 --- a/moto/cloudwatch/models.py +++ b/moto/cloudwatch/models.py @@ -603,7 +603,13 @@ class CloudWatchBackend(BaseBackend): if scan_by == "TimestampDescending" and len(timestamps) > 0: timestamps.reverse() result_vals.reverse() - label = query["metric_stat._metric._metric_name"] + " " + stat + + label = ( + query["label"] + if "label" in query + else query["metric_stat._metric._metric_name"] + " " + stat + ) + results.append( { "id": query["id"], diff --git a/tests/test_cloudwatch/test_cloudwatch_boto3.py b/tests/test_cloudwatch/test_cloudwatch_boto3.py index bac1180a7..f5c8489e1 100644 --- a/tests/test_cloudwatch/test_cloudwatch_boto3.py +++ b/tests/test_cloudwatch/test_cloudwatch_boto3.py @@ -1513,3 +1513,74 @@ def test_put_metric_alarm_error_evaluate_low_sample_count_percentile(): "Option unknown is not supported. " "Supported options for parameter EvaluateLowSampleCountPercentile are evaluate and ignore." ) + + +@mock_cloudwatch +def test_get_metric_data_with_custom_label(): + utc_now = datetime.now(tz=pytz.utc) + cloudwatch = boto3.client("cloudwatch", "eu-west-1") + namespace = "my_namespace/" + + label = "MyCustomLabel" + + # put metric data + cloudwatch.put_metric_data( + Namespace=namespace, + MetricData=[ + { + "MetricName": "metric1", + "Value": 50, + "Timestamp": utc_now, + }, + { + "MetricName": "metric1", + "Value": -50, + "Timestamp": utc_now, + }, + ], + ) + # get_metric_data + response = cloudwatch.get_metric_data( + MetricDataQueries=[ + { + "Id": "result_without_custom_label", + "MetricStat": { + "Metric": { + "Namespace": namespace, + "MetricName": "metric1", + }, + "Period": 60, + "Stat": "SampleCount", + }, + }, + { + "Id": "result_with_custom_label", + "Label": label, + "MetricStat": { + "Metric": { + "Namespace": namespace, + "MetricName": "metric1", + }, + "Period": 60, + "Stat": "SampleCount", + }, + }, + ], + StartTime=utc_now - timedelta(seconds=60), + EndTime=utc_now + timedelta(seconds=60), + ) + + expected_values = { + "result_without_custom_label": "metric1 SampleCount", + "result_with_custom_label": label, + } + + for id_, expected_value in expected_values.items(): + metric_result_data = list( + filter( + lambda result_data: result_data["Id"] == id_, + response["MetricDataResults"], + ) + ) + len(metric_result_data).should.equal(1) + metric_result_data[0]["Label"].should.equal(expected_value)