Skip to content

Commit 9c15b5b

Browse files
Adding test for wrong type
1 parent c651b6f commit 9c15b5b

File tree

2 files changed

+32
-2
lines changed

2 files changed

+32
-2
lines changed

aws_lambda_powertools/metrics/functions.py

+7-1
Original file line numberDiff line numberDiff line change
@@ -125,4 +125,10 @@ def convert_timestamp_to_emf_format(timestamp: int | datetime) -> int:
125125
if isinstance(timestamp, int):
126126
return timestamp
127127

128-
return int(round(timestamp.timestamp() * 1000))
128+
try:
129+
return int(round(timestamp.timestamp() * 1000))
130+
except AttributeError:
131+
# If this point is reached, it indicates timestamp is not a datetime object
132+
# Returning zero represents the initial date of epoch time,
133+
# which will be skipped by Amazon CloudWatch.
134+
return 0

tests/functional/metrics/test_metrics_cloudwatch_emf.py

+25-1
Original file line numberDiff line numberDiff line change
@@ -1266,7 +1266,7 @@ def lambda_handler(evt, ctx):
12661266
assert invocation["_aws"]["Timestamp"] == metric_timestamp
12671267

12681268

1269-
def test_metric_with_wrong_custom_timestamp(namespace, metric):
1269+
def test_metric_custom_timestamp_more_than_14days_ago(namespace, metric):
12701270
# GIVEN Metrics instance is initialized
12711271
my_metrics = Metrics(namespace=namespace)
12721272

@@ -1288,3 +1288,27 @@ def lambda_handler(evt, ctx):
12881288
"This metric doesn't meet the requirements and will be skipped by Amazon CloudWatch. "
12891289
"Ensure the timestamp is within 14 days past or 2 hours future."
12901290
)
1291+
1292+
1293+
def test_metric_custom_timestamp_with_wrong_type(namespace, metric):
1294+
# GIVEN Metrics instance is initialized
1295+
my_metrics = Metrics(namespace=namespace)
1296+
1297+
# Setting timestamp outside of contraints with 20 days before
1298+
metric_timestamp = "timestamp_as_string"
1299+
1300+
# WHEN we set a wrong timestamp before to flush the metric
1301+
@my_metrics.log_metrics
1302+
def lambda_handler(evt, ctx):
1303+
my_metrics.add_metric(**metric)
1304+
my_metrics.set_timestamp(metric_timestamp)
1305+
1306+
# THEN should raise a warning
1307+
with warnings.catch_warnings(record=True) as w:
1308+
warnings.simplefilter("default")
1309+
lambda_handler({}, {})
1310+
assert len(w) == 1
1311+
assert str(w[-1].message) == (
1312+
"This metric doesn't meet the requirements and will be skipped by Amazon CloudWatch. "
1313+
"Ensure the timestamp is within 14 days past or 2 hours future."
1314+
)

0 commit comments

Comments
 (0)