|
1 | 1 | import pytest
|
| 2 | +import warnings |
2 | 3 |
|
3 | 4 | from aws_lambda_powertools.metrics.functions import (
|
4 | 5 | extract_cloudwatch_metric_resolution_value,
|
|
9 | 10 | MetricUnitError,
|
10 | 11 | )
|
11 | 12 | from aws_lambda_powertools.metrics.provider.cloudwatch_emf.metric_properties import MetricResolution, MetricUnit
|
| 13 | +from aws_lambda_powertools.metrics import Metrics |
| 14 | +from aws_lambda_powertools.warnings import PowertoolsUserWarning |
| 15 | + |
| 16 | +@pytest.fixture |
| 17 | +def warning_catcher(monkeypatch): |
| 18 | + caught_warnings = [] |
| 19 | + |
| 20 | + def custom_warn(message, category=None, stacklevel=1, source=None): |
| 21 | + caught_warnings.append(PowertoolsUserWarning(message)) |
| 22 | + |
| 23 | + monkeypatch.setattr(warnings, 'warn', custom_warn) |
| 24 | + return caught_warnings |
12 | 25 |
|
13 | 26 |
|
14 | 27 | def test_extract_invalid_cloudwatch_metric_resolution_value():
|
@@ -61,3 +74,31 @@ def test_extract_valid_cloudwatch_metric_unit_value():
|
61 | 74 |
|
62 | 75 | # THEN value must be extracted
|
63 | 76 | assert extracted_unit_value == unit
|
| 77 | + |
| 78 | + |
| 79 | +def test_add_dimension_overwrite_warning(warning_catcher): |
| 80 | + """ |
| 81 | + Adds a dimension and then tries to add another with the same name |
| 82 | + but a different value. Verifies if the dimension is updated with |
| 83 | + the new value and warning is issued when an existing dimension |
| 84 | + is overwritten. |
| 85 | + """ |
| 86 | + metrics = Metrics(namespace="TestNamespace") |
| 87 | + |
| 88 | + # GIVEN default dimension |
| 89 | + dimension_name = "test-dimension" |
| 90 | + value1 = "test-value-1" |
| 91 | + value2 = "test-value-2" |
| 92 | + |
| 93 | + # WHEN adding the same dimension twice with different values |
| 94 | + metrics.add_dimension(dimension_name, value1) |
| 95 | + metrics.add_dimension(dimension_name, value2) |
| 96 | + |
| 97 | + # THEN the dimension should be updated with the new value |
| 98 | + assert metrics._dimensions[dimension_name] == value2 |
| 99 | + |
| 100 | + # AND a warning should be issued with the exact message |
| 101 | + expected_warning = f"Dimension '{dimension_name}' has already been added. The previous value will be overwritten." |
| 102 | + assert any(str(w) == expected_warning for w in warning_catcher) |
| 103 | + |
| 104 | + |
0 commit comments