-
Notifications
You must be signed in to change notification settings - Fork 51
Expand file tree
/
Copy pathtest_metric.py
More file actions
404 lines (338 loc) · 16.7 KB
/
test_metric.py
File metadata and controls
404 lines (338 loc) · 16.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
import os
import unittest
from datetime import datetime, timedelta
from unittest.mock import call, patch
from botocore.exceptions import ClientError as BotocoreClientError
from datadog.api.exceptions import ClientError
from datadog_lambda.api import KMS_ENCRYPTION_CONTEXT_KEY, decrypt_kms_api_key
from datadog_lambda.metric import (
MetricsHandler,
_select_metrics_handler,
flush_stats,
lambda_metric,
submit_batch_item_failures_metric,
)
from datadog_lambda.tags import dd_lambda_layer_tag
from datadog_lambda.thread_stats_writer import ThreadStatsWriter
class TestLambdaMetric(unittest.TestCase):
def setUp(self):
lambda_stats_patcher = patch("datadog_lambda.metric.lambda_stats")
self.mock_metric_lambda_stats = lambda_stats_patcher.start()
self.addCleanup(lambda_stats_patcher.stop)
stdout_metric_patcher = patch(
"datadog_lambda.metric.write_metric_point_to_stdout"
)
self.mock_write_metric_point_to_stdout = stdout_metric_patcher.start()
self.addCleanup(stdout_metric_patcher.stop)
def test_lambda_metric_tagged_with_dd_lambda_layer(self):
lambda_metric("test", 1)
lambda_metric("test", 1, 123, [])
lambda_metric("test", 1, tags=["tag1:test"])
self.mock_metric_lambda_stats.distribution.assert_has_calls(
[
call("test", 1, timestamp=None, tags=[dd_lambda_layer_tag]),
call("test", 1, timestamp=123, tags=[dd_lambda_layer_tag]),
call(
"test", 1, timestamp=None, tags=["tag1:test", dd_lambda_layer_tag]
),
]
)
# let's fake that the extension is present, this should override DD_FLUSH_TO_LOG
@patch("datadog_lambda.metric.should_use_extension", True)
def test_select_metrics_handler_extension_despite_flush_to_logs(self):
os.environ["DD_FLUSH_TO_LOG"] = "True"
self.assertEqual(MetricsHandler.EXTENSION, _select_metrics_handler())
del os.environ["DD_FLUSH_TO_LOG"]
@patch("datadog_lambda.metric.should_use_extension", False)
def test_select_metrics_handler_forwarder_when_flush_to_logs(self):
os.environ["DD_FLUSH_TO_LOG"] = "True"
self.assertEqual(MetricsHandler.FORWARDER, _select_metrics_handler())
del os.environ["DD_FLUSH_TO_LOG"]
@patch("datadog_lambda.metric.should_use_extension", False)
def test_select_metrics_handler_dd_api_fallback(self):
os.environ["DD_FLUSH_TO_LOG"] = "False"
self.assertEqual(MetricsHandler.DATADOG_API, _select_metrics_handler())
del os.environ["DD_FLUSH_TO_LOG"]
@patch("datadog_lambda.config.Config.fips_mode_enabled", True)
@patch("datadog_lambda.metric.should_use_extension", False)
def test_select_metrics_handler_has_no_fallback_in_fips_mode(self):
os.environ["DD_FLUSH_TO_LOG"] = "False"
self.assertEqual(MetricsHandler.NO_METRICS, _select_metrics_handler())
del os.environ["DD_FLUSH_TO_LOG"]
@patch("datadog_lambda.metric.metrics_handler", MetricsHandler.EXTENSION)
def test_lambda_metric_goes_to_extension_with_extension_handler(self):
lambda_metric("test", 1)
self.mock_metric_lambda_stats.distribution.assert_has_calls(
[call("test", 1, timestamp=None, tags=[dd_lambda_layer_tag])]
)
@patch("datadog_lambda.metric.metrics_handler", MetricsHandler.NO_METRICS)
def test_lambda_metric_has_nowhere_to_go_with_no_metrics_handler(self):
lambda_metric("test", 1)
self.mock_metric_lambda_stats.distribution.assert_not_called()
self.mock_write_metric_point_to_stdout.assert_not_called()
@patch("datadog_lambda.metric.metrics_handler", MetricsHandler.EXTENSION)
def test_lambda_metric_timestamp_with_extension(self):
delta = timedelta(minutes=1)
timestamp = int((datetime.now() - delta).timestamp())
lambda_metric("test_timestamp", 1, timestamp)
self.mock_metric_lambda_stats.distribution.assert_has_calls(
[call("test_timestamp", 1, timestamp=timestamp, tags=[dd_lambda_layer_tag])]
)
self.mock_write_metric_point_to_stdout.assert_not_called()
@patch("datadog_lambda.metric.metrics_handler", MetricsHandler.EXTENSION)
def test_lambda_metric_datetime_with_extension(self):
delta = timedelta(minutes=1)
timestamp = datetime.now() - delta
lambda_metric("test_datetime_timestamp", 0, timestamp)
self.mock_metric_lambda_stats.distribution.assert_has_calls(
[
call(
"test_datetime_timestamp",
0,
timestamp=int(timestamp.timestamp()),
tags=[dd_lambda_layer_tag],
)
]
)
self.mock_write_metric_point_to_stdout.assert_not_called()
@patch("datadog_lambda.metric.metrics_handler", MetricsHandler.EXTENSION)
def test_lambda_metric_float_with_extension(self):
delta = timedelta(minutes=1)
timestamp_float = (datetime.now() - delta).timestamp()
timestamp_int = int(timestamp_float)
lambda_metric("test_timestamp", 1, timestamp_float)
self.mock_metric_lambda_stats.distribution.assert_has_calls(
[
call(
"test_timestamp",
1,
timestamp=timestamp_int,
tags=[dd_lambda_layer_tag],
)
]
)
self.mock_write_metric_point_to_stdout.assert_not_called()
@patch("datadog_lambda.metric.metrics_handler", MetricsHandler.EXTENSION)
def test_lambda_metric_timestamp_junk_with_extension(self):
delta = timedelta(minutes=1)
timestamp = (datetime.now() - delta).isoformat()
lambda_metric("test_timestamp", 1, timestamp)
self.mock_metric_lambda_stats.distribution.assert_not_called()
self.mock_write_metric_point_to_stdout.assert_not_called()
@patch("datadog_lambda.metric.metrics_handler", MetricsHandler.EXTENSION)
def test_lambda_metric_invalid_timestamp_with_extension(self):
delta = timedelta(hours=5)
timestamp = int((datetime.now() - delta).timestamp())
lambda_metric("test_timestamp", 1, timestamp)
self.mock_metric_lambda_stats.distribution.assert_not_called()
self.mock_write_metric_point_to_stdout.assert_not_called()
@patch("datadog_lambda.metric.metrics_handler", MetricsHandler.FORWARDER)
def test_lambda_metric_flush_to_log(self):
lambda_metric("test", 1)
self.mock_metric_lambda_stats.distribution.assert_not_called()
self.mock_write_metric_point_to_stdout.assert_has_calls(
[call("test", 1, timestamp=None, tags=[dd_lambda_layer_tag])]
)
@patch("datadog_lambda.metric.logger.warning")
def test_lambda_metric_invalid_metric_name_none(self, mock_logger_warning):
lambda_metric(None, 1)
self.mock_metric_lambda_stats.distribution.assert_not_called()
self.mock_write_metric_point_to_stdout.assert_not_called()
mock_logger_warning.assert_called_once_with(
"Ignoring metric submission. Invalid metric name: %s", None
)
@patch("datadog_lambda.metric.logger.warning")
def test_lambda_metric_invalid_metric_name_not_string(self, mock_logger_warning):
lambda_metric(123, 1)
self.mock_metric_lambda_stats.distribution.assert_not_called()
self.mock_write_metric_point_to_stdout.assert_not_called()
mock_logger_warning.assert_called_once_with(
"Ignoring metric submission. Invalid metric name: %s", 123
)
@patch("datadog_lambda.metric.logger.warning")
def test_lambda_metric_non_numeric_value(self, mock_logger_warning):
lambda_metric("test.non_numeric", "oops")
self.mock_metric_lambda_stats.distribution.assert_not_called()
self.mock_write_metric_point_to_stdout.assert_not_called()
mock_logger_warning.assert_called_once_with(
"Ignoring metric submission for metric '%s' because the value is not numeric: %r",
"test.non_numeric",
"oops",
)
class TestFlushThreadStats(unittest.TestCase):
def setUp(self):
patcher = patch(
"datadog.threadstats.reporters.HttpReporter.flush_distributions"
)
self.mock_threadstats_flush_distributions = patcher.start()
self.addCleanup(patcher.stop)
def test_retry_on_remote_disconnected(self):
# Raise the RemoteDisconnected error
lambda_stats = ThreadStatsWriter(True)
self.mock_threadstats_flush_distributions.side_effect = ClientError(
"POST",
"https://api.datadoghq.com/api/v1/distribution_points",
"RemoteDisconnected('Remote end closed connection without response')",
)
lambda_stats.flush()
self.assertEqual(self.mock_threadstats_flush_distributions.call_count, 2)
def test_flush_stats_with_tags(self):
lambda_stats = ThreadStatsWriter(True)
original_constant_tags = lambda_stats.thread_stats.constant_tags.copy()
tags = ["tag1:value1", "tag2:value2"]
# Add a metric to be flushed
lambda_stats.distribution("test.metric", 1, tags=["metric:tag"])
with patch.object(
lambda_stats.thread_stats.reporter, "flush_distributions"
) as mock_flush_distributions:
lambda_stats.flush(tags)
mock_flush_distributions.assert_called_once()
# Verify that after flush, constant_tags is reset to original
self.assertEqual(
lambda_stats.thread_stats.constant_tags, original_constant_tags
)
def test_flush_temp_constant_tags(self):
lambda_stats = ThreadStatsWriter(flush_in_thread=True)
lambda_stats.thread_stats.constant_tags = ["initial:tag"]
original_constant_tags = lambda_stats.thread_stats.constant_tags.copy()
lambda_stats.distribution("test.metric", 1, tags=["metric:tag"])
flush_tags = ["flush:tag1", "flush:tag2"]
with patch.object(
lambda_stats.thread_stats.reporter, "flush_distributions"
) as mock_flush_distributions:
lambda_stats.flush(tags=flush_tags)
mock_flush_distributions.assert_called_once()
flushed_dists = mock_flush_distributions.call_args[0][0]
# Expected tags: original constant_tags + flush_tags + metric tags
expected_tags = original_constant_tags + flush_tags + ["metric:tag"]
# Verify the tags on the metric
self.assertEqual(len(flushed_dists), 1)
metric = flushed_dists[0]
self.assertEqual(sorted(metric["tags"]), sorted(expected_tags))
# Verify that constant_tags is reset after flush
self.assertEqual(
lambda_stats.thread_stats.constant_tags, original_constant_tags
)
# Repeat to ensure tags do not accumulate over multiple flushes
new_flush_tags = ["flush:tag3"]
lambda_stats.distribution("test.metric2", 2, tags=["metric2:tag"])
with patch.object(
lambda_stats.thread_stats.reporter, "flush_distributions"
) as mock_flush_distributions:
lambda_stats.flush(tags=new_flush_tags)
mock_flush_distributions.assert_called_once()
flushed_dists = mock_flush_distributions.call_args[0][0]
# Expected tags for the new metric
expected_tags = original_constant_tags + new_flush_tags + ["metric2:tag"]
self.assertEqual(len(flushed_dists), 1)
metric = flushed_dists[0]
self.assertEqual(sorted(metric["tags"]), sorted(expected_tags))
self.assertEqual(
lambda_stats.thread_stats.constant_tags, original_constant_tags
)
MOCK_FUNCTION_NAME = "myFunction"
# An API key encrypted with KMS and encoded as a base64 string
MOCK_ENCRYPTED_API_KEY_BASE64 = "MjIyMjIyMjIyMjIyMjIyMg=="
# The encrypted API key after it has been decoded from base64
MOCK_ENCRYPTED_API_KEY = "2222222222222222"
# The true value of the API key after decryption by KMS
EXPECTED_DECRYPTED_API_KEY = "1111111111111111"
class TestDecryptKMSApiKey(unittest.TestCase):
def test_key_encrypted_with_encryption_context(self):
os.environ["AWS_LAMBDA_FUNCTION_NAME"] = MOCK_FUNCTION_NAME
class MockKMSClient:
def decrypt(self, CiphertextBlob=None, EncryptionContext={}):
if (
EncryptionContext.get(KMS_ENCRYPTION_CONTEXT_KEY)
!= MOCK_FUNCTION_NAME
):
raise BotocoreClientError({}, "Decrypt")
if CiphertextBlob == MOCK_ENCRYPTED_API_KEY.encode("utf-8"):
return {
"Plaintext": EXPECTED_DECRYPTED_API_KEY.encode("utf-8"),
}
mock_kms_client = MockKMSClient()
decrypted_key = decrypt_kms_api_key(
mock_kms_client, MOCK_ENCRYPTED_API_KEY_BASE64
)
self.assertEqual(decrypted_key, EXPECTED_DECRYPTED_API_KEY)
del os.environ["AWS_LAMBDA_FUNCTION_NAME"]
def test_key_encrypted_without_encryption_context(self):
class MockKMSClient:
def decrypt(self, CiphertextBlob=None, EncryptionContext={}):
if EncryptionContext.get(KMS_ENCRYPTION_CONTEXT_KEY) != None:
raise BotocoreClientError({}, "Decrypt")
if CiphertextBlob == MOCK_ENCRYPTED_API_KEY.encode("utf-8"):
return {
"Plaintext": EXPECTED_DECRYPTED_API_KEY.encode("utf-8"),
}
mock_kms_client = MockKMSClient()
decrypted_key = decrypt_kms_api_key(
mock_kms_client, MOCK_ENCRYPTED_API_KEY_BASE64
)
self.assertEqual(decrypted_key, EXPECTED_DECRYPTED_API_KEY)
class TestBatchItemFailuresMetric(unittest.TestCase):
def setUp(self):
patcher = patch("datadog_lambda.metric.lambda_metric")
self.mock_lambda_metric = patcher.start()
self.addCleanup(patcher.stop)
patcher = patch("datadog_lambda.config.Config.enhanced_metrics_enabled", True)
self.mock_enhanced_metrics_enabled = patcher.start()
self.addCleanup(patcher.stop)
def test_submit_batch_item_failures_with_failures(self):
response = {
"batchItemFailures": [
{"itemIdentifier": "msg-1"},
{"itemIdentifier": "msg-2"},
{"itemIdentifier": "msg-3"},
]
}
context = unittest.mock.Mock()
with patch("datadog_lambda.metric.get_enhanced_metrics_tags") as mock_get_tags:
mock_get_tags.return_value = ["tag1:value1"]
submit_batch_item_failures_metric(response, context)
self.mock_lambda_metric.assert_called_once_with(
"aws.lambda.enhanced.batch_item_failures",
3,
timestamp=None,
tags=["tag1:value1"],
force_async=True,
)
def test_submit_batch_item_failures_with_no_failures(self):
response = {"batchItemFailures": []}
context = unittest.mock.Mock()
with patch("datadog_lambda.metric.get_enhanced_metrics_tags") as mock_get_tags:
mock_get_tags.return_value = ["tag1:value1"]
submit_batch_item_failures_metric(response, context)
self.mock_lambda_metric.assert_called_once_with(
"aws.lambda.enhanced.batch_item_failures",
0,
timestamp=None,
tags=["tag1:value1"],
force_async=True,
)
def test_submit_batch_item_failures_with_no_field(self):
response = {"statusCode": 200}
context = unittest.mock.Mock()
submit_batch_item_failures_metric(response, context)
self.mock_lambda_metric.assert_not_called()
def test_submit_batch_item_failures_with_none_response(self):
response = None
context = unittest.mock.Mock()
submit_batch_item_failures_metric(response, context)
self.mock_lambda_metric.assert_not_called()
def test_submit_batch_item_failures_with_non_list_value(self):
response = {"batchItemFailures": "invalid"}
context = unittest.mock.Mock()
submit_batch_item_failures_metric(response, context)
self.mock_lambda_metric.assert_not_called()
@patch("datadog_lambda.config.Config.enhanced_metrics_enabled", False)
def test_submit_batch_item_failures_enhanced_metrics_disabled(self):
response = {
"batchItemFailures": [
{"itemIdentifier": "msg-1"},
]
}
context = unittest.mock.Mock()
submit_batch_item_failures_metric(response, context)
self.mock_lambda_metric.assert_not_called()