Skip to content

Commit dd6d208

Browse files
authored
Merge pull request #943 from sdangol/improv/metrics-runtime-validations
feat(metrics): Added runtime validation for the metric name
2 parents 22aa2cd + 31bfd9c commit dd6d208

File tree

2 files changed

+19
-0
lines changed

2 files changed

+19
-0
lines changed

libraries/src/AWS.Lambda.Powertools.Metrics/Metrics.cs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -182,6 +182,10 @@ void IMetrics.AddMetric(string key, double value, MetricUnit unit, MetricResolut
182182
throw new ArgumentNullException(
183183
nameof(key),
184184
"'AddMetric' method requires a valid metrics key. 'Null' or empty values are not allowed.");
185+
if (key.Length > 255)
186+
throw new ArgumentOutOfRangeException(
187+
nameof(key),
188+
"'AddMetric' method requires a valid metrics key. Key exceeds the allowed length constraint.");
185189

186190
if (value < 0)
187191
{

libraries/tests/AWS.Lambda.Powertools.Metrics.Tests/MetricsTests.cs

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -155,6 +155,21 @@ public void When_AddMetric_With_InvalidKey_Should_ThrowArgumentNullException(str
155155
exception.Message);
156156
}
157157

158+
[Fact]
159+
public void When_AddMetric_With_TooLongKey_Should_ThrowArgumentOutOfRangeException()
160+
{
161+
// Arrange
162+
Substitute.For<IMetrics>();
163+
var powertoolsConfigMock = Substitute.For<IPowertoolsConfigurations>();
164+
IMetrics metrics = new Metrics(powertoolsConfigMock);
165+
166+
// Act & Assert
167+
var exception = Assert.Throws<ArgumentOutOfRangeException>(() => metrics.AddMetric("Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.", 1.0));
168+
Assert.Equal("key", exception.ParamName);
169+
Assert.Contains("'AddMetric' method requires a valid metrics key. Key exceeds the allowed length constraint.",
170+
exception.Message);
171+
}
172+
158173
[Fact]
159174
public void When_SetDefaultDimensions_With_InvalidKeyOrValue_Should_ThrowArgumentNullException()
160175
{

0 commit comments

Comments
 (0)