-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathtest_ecstats.py
More file actions
557 lines (460 loc) · 20.7 KB
/
test_ecstats.py
File metadata and controls
557 lines (460 loc) · 20.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
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
import pytest
import datetime
import configparser
import boto3
from unittest.mock import Mock, patch
import os
import sys
import tempfile
import openpyxl
# Import the module under test
import ecstats
def create_paginator_side_effect(clusters=None, reserved_instances=None):
"""Shared helper to create paginator side effect with custom data."""
if clusters is None:
clusters = []
if reserved_instances is None:
reserved_instances = []
def get_paginator_side_effect(paginator_name):
mock_paginator = Mock()
if paginator_name == "describe_cache_clusters":
mock_paginator.paginate.return_value = [{"CacheClusters": clusters}]
elif paginator_name == "describe_reserved_cache_nodes":
mock_paginator.paginate.return_value = [
{"ReservedCacheNodes": reserved_instances}
]
return mock_paginator
return get_paginator_side_effect
class TestMetricDefinitions:
"""Test metric definition functions."""
def test_get_max_metrics_hourly(self):
"""Test hourly metrics definition."""
metrics = ecstats.get_max_metrics_hourly()
assert isinstance(metrics, list)
assert len(metrics) > 0
# Check structure of metrics
for metric in metrics:
assert len(metric) == 3
metric_name, aggregation, period = metric
assert isinstance(metric_name, str)
assert aggregation == "Maximum"
assert period == ecstats.SECONDS_IN_HOUR
def test_get_max_metrics_weekly(self):
"""Test weekly metrics definition."""
metrics = ecstats.get_max_metrics_weekly()
assert isinstance(metrics, list)
assert len(metrics) > 0
# Check structure of metrics
for metric in metrics:
assert len(metric) == 3
metric_name, aggregation, period = metric
assert isinstance(metric_name, str)
assert aggregation == "Maximum"
assert (
period == ecstats.SECONDS_IN_DAY * ecstats.METRIC_COLLECTION_PERIOD_DAYS
)
class TestUtilityFunctions:
"""Test utility functions."""
def test_calc_expiry_time(self):
"""Test expiry time calculation."""
# Test future date
future_date = datetime.datetime.utcnow() + datetime.timedelta(days=30)
future_date = future_date.replace(tzinfo=datetime.timezone.utc)
days_until_expiry = ecstats.calc_expiry_time(future_date)
assert 29 <= days_until_expiry <= 30 # Allow for small timing differences
# Test past date
past_date = datetime.datetime.utcnow() - datetime.timedelta(days=10)
past_date = past_date.replace(tzinfo=datetime.timezone.utc)
days_until_expiry = ecstats.calc_expiry_time(past_date)
assert days_until_expiry < 0
class TestClusterInfo:
"""Test cluster information retrieval."""
@patch("boto3.Session")
def test_get_clusters_info_basic_structure(self, mock_session):
"""Test basic structure of get_clusters_info return value."""
# Mock the session and clients
mock_session_instance = Mock()
mock_session.return_value = mock_session_instance
mock_elasticache_client = Mock()
mock_session_instance.client.return_value = mock_elasticache_client
# Use helper to create paginator side effect
clusters = [
{
"CacheClusterId": "test-cluster-001",
"CacheClusterStatus": "available",
"Engine": "redis",
"CacheNodeType": "cache.t3.micro",
"CacheNodes": [{"CacheNodeId": "0001"}],
}
]
mock_elasticache_client.get_paginator.side_effect = (
create_paginator_side_effect(clusters)
)
# Mock describe_snapshots
mock_elasticache_client.describe_snapshots.return_value = {"Snapshots": []}
result = ecstats.get_clusters_info(mock_session_instance)
assert "elc_running_instances" in result
assert "elc_reserved_instances" in result
assert "snapshots" in result
assert isinstance(result["elc_running_instances"], dict)
assert isinstance(result["elc_reserved_instances"], dict)
assert isinstance(result["snapshots"], dict)
@patch("boto3.Session")
def test_get_clusters_info_redis_engine_only(self, mock_session):
"""Test that Redis engine clusters are correctly included."""
mock_session_instance = Mock()
mock_session.return_value = mock_session_instance
mock_elasticache_client = Mock()
mock_session_instance.client.return_value = mock_elasticache_client
clusters = [
{
"CacheClusterId": "redis-cluster-001",
"CacheClusterStatus": "available",
"Engine": "redis",
"CacheNodeType": "cache.r6g.large",
"CacheNodes": [
{"CacheNodeId": "0001"},
{"CacheNodeId": "0002"},
],
},
{
"CacheClusterId": "redis-cluster-002",
"CacheClusterStatus": "available",
"Engine": "redis",
"CacheNodeType": "cache.t3.medium",
"CacheNodes": [{"CacheNodeId": "0001"}],
},
]
mock_elasticache_client.get_paginator.side_effect = (
create_paginator_side_effect(clusters)
)
mock_elasticache_client.describe_snapshots.return_value = {"Snapshots": []}
result = ecstats.get_clusters_info(mock_session_instance)
assert len(result["elc_running_instances"]) == 2
assert "redis-cluster-001" in result["elc_running_instances"]
assert "redis-cluster-002" in result["elc_running_instances"]
# Verify Redis engine is preserved
for cluster_id, cluster_info in result["elc_running_instances"].items():
assert cluster_info["Engine"] == "redis"
@patch("boto3.Session")
def test_get_clusters_info_valkey_engine_only(self, mock_session):
"""Test that Valkey engine clusters are correctly included."""
mock_session_instance = Mock()
mock_session.return_value = mock_session_instance
mock_elasticache_client = Mock()
mock_session_instance.client.return_value = mock_elasticache_client
clusters = [
{
"CacheClusterId": "valkey-cluster-001",
"CacheClusterStatus": "available",
"Engine": "valkey",
"CacheNodeType": "cache.r7g.xlarge",
"CacheNodes": [{"CacheNodeId": "0001"}],
},
{
"CacheClusterId": "valkey-cluster-002",
"CacheClusterStatus": "available",
"Engine": "valkey",
"CacheNodeType": "cache.m6g.large",
"CacheNodes": [
{"CacheNodeId": "0001"},
{"CacheNodeId": "0002"},
{"CacheNodeId": "0003"},
],
},
]
mock_elasticache_client.get_paginator.side_effect = (
create_paginator_side_effect(clusters)
)
mock_elasticache_client.describe_snapshots.return_value = {"Snapshots": []}
result = ecstats.get_clusters_info(mock_session_instance)
assert len(result["elc_running_instances"]) == 2
assert "valkey-cluster-001" in result["elc_running_instances"]
assert "valkey-cluster-002" in result["elc_running_instances"]
# Verify Valkey engine is preserved
for cluster_info in result["elc_running_instances"].values():
assert cluster_info["Engine"] == "valkey"
@patch("boto3.Session")
def test_get_clusters_info_filters_redis_valkey_only(self, mock_session):
"""Test that only Redis and Valkey engines are included, other engines filtered out."""
mock_session_instance = Mock()
mock_session.return_value = mock_session_instance
mock_elasticache_client = Mock()
mock_session_instance.client.return_value = mock_elasticache_client
clusters = [
{
"CacheClusterId": "redis-cluster",
"CacheClusterStatus": "available",
"Engine": "redis",
"CacheNodeType": "cache.r6g.large",
"CacheNodes": [{"CacheNodeId": "0001"}],
},
{
"CacheClusterId": "valkey-cluster",
"CacheClusterStatus": "available",
"Engine": "valkey",
"CacheNodeType": "cache.m6g.medium",
"CacheNodes": [{"CacheNodeId": "0001"}],
},
{
"CacheClusterId": "memcached-cluster",
"CacheClusterStatus": "available",
"Engine": "memcached",
"CacheNodeType": "cache.t3.micro",
"CacheNodes": [{"CacheNodeId": "0001"}],
},
]
mock_elasticache_client.get_paginator.side_effect = (
create_paginator_side_effect(clusters)
)
mock_elasticache_client.describe_snapshots.return_value = {"Snapshots": []}
result = ecstats.get_clusters_info(mock_session_instance)
# Verify only Redis and Valkey clusters are included
assert len(result["elc_running_instances"]) == 2
assert "redis-cluster" in result["elc_running_instances"]
assert "valkey-cluster" in result["elc_running_instances"]
assert "memcached-cluster" not in result["elc_running_instances"]
# Verify engines are correctly preserved
assert result["elc_running_instances"]["redis-cluster"]["Engine"] == "redis"
assert result["elc_running_instances"]["valkey-cluster"]["Engine"] == "valkey"
@patch("boto3.Session")
def test_get_clusters_info_status_filtering(self, mock_session):
"""Test that only 'available' status clusters are included."""
mock_session_instance = Mock()
mock_session.return_value = mock_session_instance
mock_elasticache_client = Mock()
mock_session_instance.client.return_value = mock_elasticache_client
clusters = [
{
"CacheClusterId": "available-redis",
"CacheClusterStatus": "available",
"Engine": "redis",
"CacheNodeType": "cache.t3.micro",
"CacheNodes": [{"CacheNodeId": "0001"}],
},
{
"CacheClusterId": "creating-redis",
"CacheClusterStatus": "creating",
"Engine": "redis",
"CacheNodeType": "cache.t3.micro",
"CacheNodes": [{"CacheNodeId": "0001"}],
},
{
"CacheClusterId": "deleting-valkey",
"CacheClusterStatus": "deleting",
"Engine": "valkey",
"CacheNodeType": "cache.t3.micro",
"CacheNodes": [{"CacheNodeId": "0001"}],
},
{
"CacheClusterId": "available-valkey",
"CacheClusterStatus": "available",
"Engine": "valkey",
"CacheNodeType": "cache.t3.micro",
"CacheNodes": [{"CacheNodeId": "0001"}],
},
]
mock_elasticache_client.get_paginator.side_effect = (
create_paginator_side_effect(clusters)
)
mock_elasticache_client.describe_snapshots.return_value = {"Snapshots": []}
result = ecstats.get_clusters_info(mock_session_instance)
# Only available clusters should be included
assert len(result["elc_running_instances"]) == 2
assert "available-redis" in result["elc_running_instances"]
assert "available-valkey" in result["elc_running_instances"]
assert "creating-redis" not in result["elc_running_instances"]
assert "deleting-valkey" not in result["elc_running_instances"]
@patch("boto3.Session")
def test_get_clusters_info_with_reserved_instances(self, mock_session):
"""Test processing of reserved instances for Redis and Valkey."""
mock_session_instance = Mock()
mock_session.return_value = mock_session_instance
mock_elasticache_client = Mock()
mock_session_instance.client.return_value = mock_elasticache_client
reserved_instances = [
{
"CacheNodeType": "cache.r6g.large",
"State": "active",
"ProductDescription": "redis",
"CacheNodeCount": 3,
"StartTime": datetime.datetime.now() - datetime.timedelta(days=30),
"Duration": 31536000, # 1 year in seconds
},
{
"CacheNodeType": "cache.m6g.xlarge",
"State": "active",
"ProductDescription": "valkey",
"CacheNodeCount": 2,
"StartTime": datetime.datetime.now() - datetime.timedelta(days=60),
"Duration": 94608000, # 3 years in seconds
},
{
"CacheNodeType": "cache.t3.micro",
"State": "retired",
"ProductDescription": "redis",
"CacheNodeCount": 1,
"StartTime": datetime.datetime.now() - datetime.timedelta(days=400),
"Duration": 31536000,
},
{
"CacheNodeType": "cache.r5.large",
"State": "active",
"ProductDescription": "memcached",
"CacheNodeCount": 2,
"StartTime": datetime.datetime.now() - datetime.timedelta(days=30),
"Duration": 31536000,
},
]
mock_elasticache_client.get_paginator.side_effect = (
create_paginator_side_effect(
clusters=[], reserved_instances=reserved_instances
)
)
mock_elasticache_client.describe_snapshots.return_value = {"Snapshots": []}
result = ecstats.get_clusters_info(mock_session_instance)
# Should only include active Redis and Valkey reserved instances
assert len(result["elc_reserved_instances"]) == 2
assert "cache.r6g.large" in result["elc_reserved_instances"]
assert "cache.m6g.xlarge" in result["elc_reserved_instances"]
assert "cache.t3.micro" not in result["elc_reserved_instances"] # retired
assert "cache.r5.large" not in result["elc_reserved_instances"] # memcached
# Verify reserved instance details
redis_ri = result["elc_reserved_instances"]["cache.r6g.large"]
valkey_ri = result["elc_reserved_instances"]["cache.m6g.xlarge"]
assert redis_ri["count"] == 3
assert valkey_ri["count"] == 2
assert isinstance(redis_ri["expiry_time"], int)
assert isinstance(valkey_ri["expiry_time"], int)
class TestMetricRetrieval:
"""Test metric retrieval functions."""
@patch("datetime.date")
def test_get_metric(self, mock_date):
"""Test get_metric function."""
# Mock date.today()
mock_today = datetime.date(2023, 1, 8)
mock_date.today.return_value = mock_today
mock_cloudwatch = Mock()
mock_cloudwatch.get_metric_statistics.return_value = {
"Datapoints": [{"Maximum": 100.0}, {"Maximum": 150.0}, {"Maximum": 120.0}]
}
result = ecstats.get_metric(
mock_cloudwatch, "test-cluster", "0001", "CurrItems", "Maximum", 3600
)
assert result == [100.0, 150.0, 120.0]
# Verify the CloudWatch call
mock_cloudwatch.get_metric_statistics.assert_called_once()
call_args = mock_cloudwatch.get_metric_statistics.call_args
assert call_args[1]["Namespace"] == "AWS/ElastiCache"
assert call_args[1]["MetricName"] == "CurrItems"
assert call_args[1]["Statistics"] == ["Maximum"]
def test_get_metric_curr(self):
"""Test get_metric_curr function."""
mock_cloudwatch = Mock()
mock_cloudwatch.get_metric_data.return_value = {
"MetricDataResults": [{"Values": [1.0]}]
}
result = ecstats.get_metric_curr(
mock_cloudwatch, "test-cluster", "0001", "IsMaster"
)
assert result == 1.0
# Test empty response
mock_cloudwatch.get_metric_data.return_value = {
"MetricDataResults": [{"Values": []}]
}
result = ecstats.get_metric_curr(
mock_cloudwatch, "test-cluster", "0001", "IsMaster"
)
assert result == -1
class TestWorkbookOperations:
"""Test Excel workbook operations."""
def test_create_workbook(self):
"""Test workbook creation."""
with tempfile.TemporaryDirectory() as temp_dir:
wb = ecstats.create_workbook(temp_dir, "test-section", "us-west-1")
assert isinstance(wb, openpyxl.Workbook)
assert len(wb.sheetnames) == 2
assert ecstats.RUNNING_INSTANCES_WORKSHEET_NAME in wb.sheetnames
assert ecstats.RESERVED_INSTANCES_WORKSHEET_NAME in wb.sheetnames
# Check running instances worksheet headers
ws = wb[ecstats.RUNNING_INSTANCES_WORKSHEET_NAME]
headers = [cell.value for cell in ws[1]]
expected_base_headers = [
"Source",
"ClusterId",
"NodeId",
"NodeRole",
"NodeType",
"Region",
"SnapshotRetentionLimit",
]
for header in expected_base_headers:
assert header in headers
# Should have metrics from both weekly and hourly
assert "Engine" in headers
assert "QPF" in headers
class TestIntegration:
"""Integration tests."""
def test_end_to_end_workflow_mock(self):
"""Test end-to-end workflow with comprehensive mocking."""
with tempfile.TemporaryDirectory() as temp_dir:
config_file = os.path.join(temp_dir, "test_config.ini")
# Create test config
config = configparser.ConfigParser()
config.add_section("production")
config.set("production", "aws_access_key_id", "test-key")
config.set("production", "aws_secret_access_key", "test-secret")
config.set("production", "region_name", "us-west-1")
with open(config_file, "w") as f:
config.write(f)
# Mock all AWS interactions
with patch("boto3.Session") as mock_session, patch(
"sys.argv", ["ecstats.py", "-c", config_file, "-d", temp_dir]
):
# Setup mock session and clients
mock_session_instance = Mock()
mock_session.return_value = mock_session_instance
mock_elasticache_client = Mock()
mock_cloudwatch_client = Mock()
def client_side_effect(service_name):
if service_name == "elasticache":
return mock_elasticache_client
elif service_name == "cloudwatch":
return mock_cloudwatch_client
return Mock()
mock_session_instance.client.side_effect = client_side_effect
# Mock ElastiCache responses using helper
clusters = [
{
"CacheClusterId": "test-cluster-001",
"CacheClusterStatus": "available",
"Engine": "redis",
"CacheNodeType": "cache.t3.micro",
"PreferredAvailabilityZone": "us-west-1a",
"CacheNodes": [{"CacheNodeId": "0001"}],
}
]
mock_elasticache_client.get_paginator.side_effect = (
create_paginator_side_effect(clusters)
)
mock_elasticache_client.describe_snapshots.return_value = {
"Snapshots": []
}
# Mock CloudWatch responses
mock_cloudwatch_client.get_metric_statistics.return_value = {
"Datapoints": [{"Maximum": 100.0}]
}
mock_cloudwatch_client.get_metric_data.return_value = {
"MetricDataResults": [{"Values": [1.0]}]
}
# Run main function
ecstats.main()
# Verify output file was created
expected_output = os.path.join(temp_dir, "production-us-west-1.xlsx")
assert os.path.exists(expected_output)
# Verify the Excel file structure
wb = openpyxl.load_workbook(expected_output)
assert ecstats.RUNNING_INSTANCES_WORKSHEET_NAME in wb.sheetnames
assert ecstats.RESERVED_INSTANCES_WORKSHEET_NAME in wb.sheetnames
if __name__ == "__main__":
pytest.main([__file__])