File: test_eks.py

package info (click to toggle)
python-moto 5.1.18-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 116,520 kB
  • sloc: python: 636,725; javascript: 181; makefile: 39; sh: 3
file content (1472 lines) | stat: -rw-r--r-- 54,020 bytes parent folder | download
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
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
import datetime
from copy import deepcopy
from unittest import SkipTest, mock
from unittest.mock import PropertyMock

import boto3
import pytest
from botocore.exceptions import ClientError
from dateutil.tz import tzutc
from freezegun import freeze_time

from moto import mock_aws, settings
from moto.core import DEFAULT_ACCOUNT_ID as ACCOUNT_ID
from moto.eks.exceptions import (
    InvalidParameterException,
    InvalidRequestException,
    ResourceInUseException,
    ResourceNotFoundException,
)
from moto.eks.models import (
    CLUSTER_EXISTS_MSG,
    CLUSTER_IN_USE_MSG,
    CLUSTER_NOT_FOUND_MSG,
    CLUSTER_NOT_READY_MSG,
    FARGATE_PROFILE_EXISTS_MSG,
    FARGATE_PROFILE_NEEDS_SELECTOR_MSG,
    FARGATE_PROFILE_NOT_FOUND_MSG,
    FARGATE_PROFILE_SELECTOR_NEEDS_NAMESPACE,
    FARGATE_PROFILE_TOO_MANY_LABELS,
    LAUNCH_TEMPLATE_WITH_DISK_SIZE_MSG,
    LAUNCH_TEMPLATE_WITH_REMOTE_ACCESS_MSG,
    NODEGROUP_EXISTS_MSG,
    NODEGROUP_NOT_FOUND_MSG,
)
from moto.eks.responses import DEFAULT_MAX_RESULTS
from moto.moto_api._internal import mock_random

from .test_eks_constants import (
    DEFAULT_NAMESPACE,
    DISK_SIZE,
    INSTANCE_TYPES,
    LAUNCH_TEMPLATE,
    MAX_FARGATE_LABELS,
    PARTITIONS,
    POD_EXECUTION_ROLE_ARN,
    REGION,
    REMOTE_ACCESS,
    SERVICE,
    BatchCountSize,
    ClusterAttributes,
    ClusterInputs,
    ErrorAttributes,
    FargateProfileAttributes,
    FargateProfileInputs,
    NodegroupAttributes,
    NodegroupInputs,
    PageCount,
    PossibleTestResults,
    RegExTemplates,
    ResponseAttributes,
)
from .test_eks_utils import (
    attributes_to_test,
    generate_clusters,
    generate_dict,
    generate_fargate_profiles,
    generate_nodegroups,
    is_valid_uri,
    random_names,
    region_matches_partition,
)


@pytest.fixture(scope="function", name="ClusterBuilder")
def fixture_ClusterBuilder():
    class ClusterTestDataFactory:
        def __init__(self, client, count, minimal):
            # Generate 'count' number of random Cluster objects.
            self.cluster_names = generate_clusters(client, count, minimal)

            # Get the name of the first generated Cluster.
            first_name = self.cluster_names[0]

            # Collect the output of describe_cluster() for the first Cluster.
            self.cluster_describe_output = client.describe_cluster(name=first_name)[
                ResponseAttributes.CLUSTER
            ]

            # Pick a random Cluster name from the list and a name guaranteed not to be on the list.
            (self.existing_cluster_name, self.nonexistent_cluster_name) = random_names(
                self.cluster_names
            )

            # Generate a list of the Cluster attributes to be tested when validating results.
            self.attributes_to_test = attributes_to_test(
                ClusterInputs, self.existing_cluster_name
            )

    def _execute(count=1, minimal=True):
        client = boto3.client(SERVICE, region_name=REGION)
        return client, ClusterTestDataFactory(client, count, minimal)

    yield _execute


@pytest.fixture(scope="function", name="FargateProfileBuilder")
def fixture_FargateProfileBuilder(ClusterBuilder):
    class FargateProfileTestDataFactory:
        def __init__(self, client, cluster, count, minimal):
            self.cluster_name = cluster.existing_cluster_name

            # Generate 'count' number of random FargateProfile objects.
            self.fargate_profile_names = generate_fargate_profiles(
                client, self.cluster_name, count, minimal
            )

            # Get the name of the first generated profile.
            first_name = self.fargate_profile_names[0]

            # Collect the output of describe_fargate_profiles() for the first profile.
            self.fargate_describe_output = client.describe_fargate_profile(
                clusterName=self.cluster_name, fargateProfileName=first_name
            )[ResponseAttributes.FARGATE_PROFILE]

            # Pick a random profile name from the list and a name guaranteed not to be on the list.
            (
                self.existing_fargate_profile_name,
                self.nonexistent_fargate_profile_name,
            ) = random_names(self.fargate_profile_names)
            _, self.nonexistent_cluster_name = random_names(self.cluster_name)

            # Generate a list of the Fargate Profile attributes to be tested when validating results.
            self.attributes_to_test = attributes_to_test(
                FargateProfileInputs, self.existing_fargate_profile_name
            )

    def _execute(count=1, minimal=True):
        client, cluster = ClusterBuilder()
        return client, FargateProfileTestDataFactory(client, cluster, count, minimal)

    return _execute


@pytest.fixture(scope="function", name="NodegroupBuilder")
def fixture_NodegroupBuilder(ClusterBuilder):
    class NodegroupTestDataFactory:
        def __init__(self, client, cluster, count, minimal):
            self.cluster_name = cluster.existing_cluster_name

            # Generate 'count' number of random Nodegroup objects.
            self.nodegroup_names = generate_nodegroups(
                client, self.cluster_name, count, minimal
            )

            # Get the name of the first generated Nodegroup.
            first_name = self.nodegroup_names[0]

            # Collect the output of describe_nodegroup() for the first Nodegroup.
            self.nodegroup_describe_output = client.describe_nodegroup(
                clusterName=self.cluster_name, nodegroupName=first_name
            )[ResponseAttributes.NODEGROUP]

            # Pick a random Nodegroup name from the list and a name guaranteed not to be on the list.
            (
                self.existing_nodegroup_name,
                self.nonexistent_nodegroup_name,
            ) = random_names(self.nodegroup_names)
            _, self.nonexistent_cluster_name = random_names(self.cluster_name)

            # Generate a list of the Nodegroup attributes to be tested when validating results.
            self.attributes_to_test = attributes_to_test(
                NodegroupInputs, self.existing_nodegroup_name
            )

    def _execute(count=1, minimal=True):
        client, cluster = ClusterBuilder()
        return client, NodegroupTestDataFactory(client, cluster, count, minimal)

    return _execute


###
# This specific test does not use the fixture since
# it is intended to verify that there are no clusters
# in the list at initialization, which means the mock
# decorator must be used manually in this one case.
###


@mock_aws
def test_list_clusters_returns_empty_by_default():
    client = boto3.client(SERVICE, region_name=REGION)

    result = client.list_clusters()[ResponseAttributes.CLUSTERS]

    assert result == []


@mock_aws
def test_list_tags_returns_empty_by_default(ClusterBuilder):
    client, generated_test_data = ClusterBuilder(BatchCountSize.SINGLE)
    cluster_arn = generated_test_data.cluster_describe_output[ClusterAttributes.ARN]
    result = client.list_tags_for_resource(resourceArn=cluster_arn)
    assert len(result["tags"]) == 0


@mock_aws
def test_list_tags_returns_all(ClusterBuilder):
    client, generated_test_data = ClusterBuilder(BatchCountSize.SINGLE)
    cluster_arn = generated_test_data.cluster_describe_output[ClusterAttributes.ARN]
    client.tag_resource(resourceArn=cluster_arn, tags={"key1": "val1", "key2": "val2"})
    result = client.list_tags_for_resource(resourceArn=cluster_arn)
    assert len(result["tags"]) == 2
    assert result["tags"] == {"key1": "val1", "key2": "val2"}


@mock_aws
def test_list_tags_returns_all_after_delete(ClusterBuilder):
    client, generated_test_data = ClusterBuilder(BatchCountSize.SINGLE)
    cluster_arn = generated_test_data.cluster_describe_output[ClusterAttributes.ARN]
    client.tag_resource(resourceArn=cluster_arn, tags={"key1": "val1", "key2": "val2"})
    client.untag_resource(resourceArn=cluster_arn, tagKeys=["key1"])
    result = client.list_tags_for_resource(resourceArn=cluster_arn)
    assert len(result["tags"]) == 1
    assert result["tags"] == {"key2": "val2"}


@mock_aws
def test_list_clusters_returns_sorted_cluster_names(ClusterBuilder):
    client, generated_test_data = ClusterBuilder(BatchCountSize.SMALL)
    expected_result = sorted(generated_test_data.cluster_names)

    result = client.list_clusters()[ResponseAttributes.CLUSTERS]

    assert_result_matches_expected_list(result, expected_result, BatchCountSize.SMALL)


@mock_aws
def test_list_clusters_returns_default_max_results(ClusterBuilder):
    client, generated_test_data = ClusterBuilder(BatchCountSize.LARGE)
    expected_len = DEFAULT_MAX_RESULTS
    expected_result = (sorted(generated_test_data.cluster_names))[:expected_len]

    result = client.list_clusters()[ResponseAttributes.CLUSTERS]

    assert_result_matches_expected_list(result, expected_result, expected_len)


@mock_aws
def test_list_clusters_returns_custom_max_results(ClusterBuilder):
    client, generated_test_data = ClusterBuilder(BatchCountSize.MEDIUM)
    expected_len = PageCount.LARGE
    expected_result = (sorted(generated_test_data.cluster_names))[:expected_len]

    result = client.list_clusters(maxResults=expected_len)[ResponseAttributes.CLUSTERS]

    assert_result_matches_expected_list(result, expected_result, expected_len)


@mock_aws
def test_list_clusters_returns_second_page_results(ClusterBuilder):
    client, generated_test_data = ClusterBuilder(BatchCountSize.MEDIUM)
    page1_len = PageCount.LARGE
    expected_len = BatchCountSize.MEDIUM - page1_len
    expected_result = (sorted(generated_test_data.cluster_names))[page1_len:]
    token = client.list_clusters(maxResults=page1_len)[ResponseAttributes.NEXT_TOKEN]

    result = client.list_clusters(nextToken=token)[ResponseAttributes.CLUSTERS]

    assert_result_matches_expected_list(result, expected_result, expected_len)


@mock_aws
def test_list_clusters_returns_custom_second_page_results(ClusterBuilder):
    client, generated_test_data = ClusterBuilder(BatchCountSize.MEDIUM)
    page1_len = PageCount.LARGE
    expected_len = PageCount.SMALL
    expected_result = (sorted(generated_test_data.cluster_names))[
        page1_len : page1_len + expected_len
    ]
    token = client.list_clusters(maxResults=page1_len)[ResponseAttributes.NEXT_TOKEN]

    result = client.list_clusters(maxResults=expected_len, nextToken=token)[
        ResponseAttributes.CLUSTERS
    ]

    assert_result_matches_expected_list(result, expected_result, expected_len)


@mock_aws
def test_create_cluster_throws_exception_when_cluster_exists(ClusterBuilder):
    client, generated_test_data = ClusterBuilder(BatchCountSize.SMALL)
    expected_exception = ResourceInUseException
    expected_msg = CLUSTER_EXISTS_MSG.format(
        clusterName=generated_test_data.existing_cluster_name
    )

    with pytest.raises(ClientError) as raised_exception:
        client.create_cluster(
            name=generated_test_data.existing_cluster_name,
            **dict(ClusterInputs.REQUIRED),
        )
    count_clusters_after_test = len(client.list_clusters()[ResponseAttributes.CLUSTERS])

    assert count_clusters_after_test == BatchCountSize.SMALL
    assert_expected_exception(raised_exception, expected_exception, expected_msg)


@mock_aws
def test_create_cluster_generates_valid_cluster_arn(ClusterBuilder):
    _, generated_test_data = ClusterBuilder()
    expected_arn_values = [
        PARTITIONS,
        REGION,
        ACCOUNT_ID,
        generated_test_data.cluster_names,
    ]

    all_arn_values_should_be_valid(
        expected_arn_values=expected_arn_values,
        pattern=RegExTemplates.CLUSTER_ARN,
        arn_under_test=generated_test_data.cluster_describe_output[
            ClusterAttributes.ARN
        ],
    )


@mock_aws
def test_create_cluster_generates_valid_cluster_created_timestamp(ClusterBuilder):
    cluster_create_time = datetime.datetime(2013, 11, 27, 1, 42, tzinfo=tzutc())
    with freeze_time(cluster_create_time):
        _, generated_test_data = ClusterBuilder()
    result_time = generated_test_data.cluster_describe_output[
        ClusterAttributes.CREATED_AT
    ]
    if not settings.TEST_SERVER_MODE:
        assert result_time == cluster_create_time


@mock_aws
def test_create_cluster_generates_valid_cluster_endpoint(ClusterBuilder):
    _, generated_test_data = ClusterBuilder()

    result_endpoint = generated_test_data.cluster_describe_output[
        ClusterAttributes.ENDPOINT
    ]

    assert is_valid_uri(result_endpoint) is True
    assert REGION in result_endpoint


@mock_aws
def test_create_cluster_generates_valid_oidc_identity(ClusterBuilder):
    _, generated_test_data = ClusterBuilder()

    result_issuer = generated_test_data.cluster_describe_output[
        ClusterAttributes.IDENTITY
    ][ClusterAttributes.OIDC][ClusterAttributes.ISSUER]

    assert is_valid_uri(result_issuer) is True
    assert REGION in result_issuer


@mock_aws
def test_create_cluster_saves_provided_parameters(ClusterBuilder):
    _, generated_test_data = ClusterBuilder(minimal=False)

    for key, expected_value in generated_test_data.attributes_to_test:
        assert generated_test_data.cluster_describe_output[key] == expected_value


@mock_aws
def test_describe_cluster_throws_exception_when_cluster_not_found(ClusterBuilder):
    client, generated_test_data = ClusterBuilder(BatchCountSize.SMALL)
    expected_exception = ResourceNotFoundException
    expected_msg = CLUSTER_NOT_FOUND_MSG.format(
        clusterName=generated_test_data.nonexistent_cluster_name
    )

    with pytest.raises(ClientError) as raised_exception:
        client.describe_cluster(name=generated_test_data.nonexistent_cluster_name)

    assert_expected_exception(raised_exception, expected_exception, expected_msg)


@mock_aws
def test_delete_cluster_returns_deleted_cluster(ClusterBuilder):
    client, generated_test_data = ClusterBuilder(BatchCountSize.SMALL, False)

    result = client.delete_cluster(name=generated_test_data.existing_cluster_name)[
        ResponseAttributes.CLUSTER
    ]

    for key, expected_value in generated_test_data.attributes_to_test:
        assert result[key] == expected_value


@mock_aws
def test_delete_cluster_removes_deleted_cluster(ClusterBuilder):
    client, generated_test_data = ClusterBuilder(BatchCountSize.SMALL, False)

    client.delete_cluster(name=generated_test_data.existing_cluster_name)
    result_cluster_list = client.list_clusters()[ResponseAttributes.CLUSTERS]

    assert len(result_cluster_list) == BatchCountSize.SMALL - 1
    assert generated_test_data.existing_cluster_name not in result_cluster_list


@mock_aws
def test_delete_cluster_throws_exception_when_cluster_not_found(ClusterBuilder):
    client, generated_test_data = ClusterBuilder(BatchCountSize.SMALL)
    expected_exception = ResourceNotFoundException
    expected_msg = CLUSTER_NOT_FOUND_MSG.format(
        clusterName=generated_test_data.nonexistent_cluster_name
    )

    with pytest.raises(ClientError) as raised_exception:
        client.delete_cluster(name=generated_test_data.nonexistent_cluster_name)
    count_clusters_after_test = len(client.list_clusters()[ResponseAttributes.CLUSTERS])

    assert count_clusters_after_test == BatchCountSize.SMALL
    assert_expected_exception(raised_exception, expected_exception, expected_msg)


@mock_aws
def test_list_nodegroups_returns_empty_by_default(ClusterBuilder):
    client, generated_test_data = ClusterBuilder()

    result = client.list_nodegroups(
        clusterName=generated_test_data.existing_cluster_name
    )[ResponseAttributes.NODEGROUPS]

    assert result == []


@mock_aws
def test_list_nodegroups_returns_sorted_nodegroup_names(NodegroupBuilder):
    client, generated_test_data = NodegroupBuilder(BatchCountSize.SMALL)
    expected_result = sorted(generated_test_data.nodegroup_names)

    result = client.list_nodegroups(clusterName=generated_test_data.cluster_name)[
        ResponseAttributes.NODEGROUPS
    ]

    assert_result_matches_expected_list(result, expected_result, BatchCountSize.SMALL)


@mock_aws
def test_list_nodegroups_returns_default_max_results(NodegroupBuilder):
    client, generated_test_data = NodegroupBuilder(BatchCountSize.LARGE)
    expected_len = DEFAULT_MAX_RESULTS
    expected_result = (sorted(generated_test_data.nodegroup_names))[:expected_len]

    result = client.list_nodegroups(clusterName=generated_test_data.cluster_name)[
        ResponseAttributes.NODEGROUPS
    ]

    assert_result_matches_expected_list(result, expected_result, expected_len)


@mock_aws
def test_list_nodegroups_returns_custom_max_results(NodegroupBuilder):
    client, generated_test_data = NodegroupBuilder(BatchCountSize.LARGE)
    expected_len = BatchCountSize.LARGE
    expected_result = (sorted(generated_test_data.nodegroup_names))[:expected_len]

    result = client.list_nodegroups(
        clusterName=generated_test_data.cluster_name, maxResults=expected_len
    )[ResponseAttributes.NODEGROUPS]

    assert_result_matches_expected_list(result, expected_result, expected_len)


@mock_aws
def test_list_nodegroups_returns_second_page_results(NodegroupBuilder):
    client, generated_test_data = NodegroupBuilder(BatchCountSize.MEDIUM)
    page1_len = PageCount.LARGE
    expected_len = BatchCountSize.MEDIUM - page1_len
    expected_result = (sorted(generated_test_data.nodegroup_names))[page1_len:]
    token = client.list_nodegroups(
        clusterName=generated_test_data.cluster_name, maxResults=page1_len
    )[ResponseAttributes.NEXT_TOKEN]

    result = client.list_nodegroups(
        clusterName=generated_test_data.cluster_name, nextToken=token
    )[ResponseAttributes.NODEGROUPS]

    assert_result_matches_expected_list(result, expected_result, expected_len)


@mock_aws
def test_list_nodegroups_returns_custom_second_page_results(NodegroupBuilder):
    client, generated_test_data = NodegroupBuilder(BatchCountSize.MEDIUM)
    page1_len = PageCount.LARGE
    expected_len = PageCount.SMALL
    expected_result = (sorted(generated_test_data.nodegroup_names))[
        page1_len : page1_len + expected_len
    ]
    token = client.list_nodegroups(
        clusterName=generated_test_data.cluster_name, maxResults=page1_len
    )[ResponseAttributes.NEXT_TOKEN]

    result = client.list_nodegroups(
        clusterName=generated_test_data.cluster_name,
        maxResults=expected_len,
        nextToken=token,
    )[ResponseAttributes.NODEGROUPS]

    assert_result_matches_expected_list(result, expected_result, expected_len)


@mock_aws
def test_create_nodegroup_throws_exception_when_cluster_not_found():
    client = boto3.client(SERVICE, region_name=REGION)
    non_existent_cluster_name = mock_random.get_random_string()
    expected_exception = ResourceNotFoundException
    expected_msg = CLUSTER_NOT_FOUND_MSG.format(clusterName=non_existent_cluster_name)

    with pytest.raises(ClientError) as raised_exception:
        client.create_nodegroup(
            clusterName=non_existent_cluster_name,
            nodegroupName=mock_random.get_random_string(),
            **dict(NodegroupInputs.REQUIRED),
        )

    assert_expected_exception(raised_exception, expected_exception, expected_msg)


@mock_aws
def test_create_nodegroup_throws_exception_when_nodegroup_already_exists(
    NodegroupBuilder,
):
    client, generated_test_data = NodegroupBuilder(BatchCountSize.SMALL)
    expected_exception = ResourceInUseException
    expected_msg = NODEGROUP_EXISTS_MSG.format(
        clusterName=generated_test_data.cluster_name,
        nodegroupName=generated_test_data.existing_nodegroup_name,
    )

    with pytest.raises(ClientError) as raised_exception:
        client.create_nodegroup(
            clusterName=generated_test_data.cluster_name,
            nodegroupName=generated_test_data.existing_nodegroup_name,
            **dict(NodegroupInputs.REQUIRED),
        )
    count_nodegroups_after_test = len(
        client.list_nodegroups(clusterName=generated_test_data.cluster_name)[
            ResponseAttributes.NODEGROUPS
        ]
    )

    assert count_nodegroups_after_test == BatchCountSize.SMALL
    assert_expected_exception(raised_exception, expected_exception, expected_msg)


@mock_aws
def test_create_nodegroup_throws_exception_when_cluster_not_active(NodegroupBuilder):
    if settings.TEST_SERVER_MODE:
        raise SkipTest("Cant patch Cluster attributes in server mode.")
    client, generated_test_data = NodegroupBuilder(BatchCountSize.SMALL)
    expected_exception = InvalidRequestException
    expected_msg = CLUSTER_NOT_READY_MSG.format(
        clusterName=generated_test_data.cluster_name
    )

    with mock.patch(
        "moto.eks.models.Cluster.is_active",
        new_callable=PropertyMock,
        return_value=False,
    ):
        with pytest.raises(ClientError) as raised_exception:
            client.create_nodegroup(
                clusterName=generated_test_data.cluster_name,
                nodegroupName=mock_random.get_random_string(),
                **dict(NodegroupInputs.REQUIRED),
            )
    count_nodegroups_after_test = len(
        client.list_nodegroups(clusterName=generated_test_data.cluster_name)[
            ResponseAttributes.NODEGROUPS
        ]
    )

    assert count_nodegroups_after_test == BatchCountSize.SMALL
    assert_expected_exception(raised_exception, expected_exception, expected_msg)


@mock_aws
def test_create_nodegroup_generates_valid_nodegroup_arn(NodegroupBuilder):
    _, generated_test_data = NodegroupBuilder()
    expected_arn_values = [
        PARTITIONS,
        REGION,
        ACCOUNT_ID,
        generated_test_data.cluster_name,
        generated_test_data.nodegroup_names,
        None,
    ]

    all_arn_values_should_be_valid(
        expected_arn_values=expected_arn_values,
        pattern=RegExTemplates.NODEGROUP_ARN,
        arn_under_test=generated_test_data.nodegroup_describe_output[
            NodegroupAttributes.ARN
        ],
    )


@mock_aws
def test_create_nodegroup_generates_valid_nodegroup_created_timestamp(NodegroupBuilder):
    ng_create_time = datetime.datetime(2013, 11, 27, 1, 42, tzinfo=tzutc())
    with freeze_time(ng_create_time):
        _, generated_test_data = NodegroupBuilder()

    result_time = generated_test_data.nodegroup_describe_output[
        NodegroupAttributes.CREATED_AT
    ]
    if not settings.TEST_SERVER_MODE:
        assert result_time == ng_create_time


@mock_aws
def test_create_nodegroup_generates_valid_nodegroup_modified_timestamp(
    NodegroupBuilder,
):
    ng_mod_time = datetime.datetime(2013, 11, 27, 1, 42, tzinfo=tzutc())
    with freeze_time(ng_mod_time):
        _, generated_test_data = NodegroupBuilder()
    result_time = generated_test_data.nodegroup_describe_output[
        NodegroupAttributes.MODIFIED_AT
    ]
    if not settings.TEST_SERVER_MODE:
        assert result_time == ng_mod_time


@mock_aws
def test_create_nodegroup_generates_valid_autoscaling_group_name(NodegroupBuilder):
    _, generated_test_data = NodegroupBuilder()
    result_resources = generated_test_data.nodegroup_describe_output[
        NodegroupAttributes.RESOURCES
    ]

    result_asg_name = result_resources[NodegroupAttributes.AUTOSCALING_GROUPS][0][
        NodegroupAttributes.NAME
    ]

    assert RegExTemplates.NODEGROUP_ASG_NAME_PATTERN.match(result_asg_name)


@mock_aws
def test_create_nodegroup_generates_valid_security_group_name(NodegroupBuilder):
    _, generated_test_data = NodegroupBuilder()
    result_resources = generated_test_data.nodegroup_describe_output[
        NodegroupAttributes.RESOURCES
    ]

    result_security_group = result_resources[NodegroupAttributes.REMOTE_ACCESS_SG]

    assert RegExTemplates.NODEGROUP_SECURITY_GROUP_NAME_PATTERN.match(
        result_security_group
    )


@mock_aws
def test_create_nodegroup_saves_provided_parameters(NodegroupBuilder):
    _, generated_test_data = NodegroupBuilder(minimal=False)

    for key, expected_value in generated_test_data.attributes_to_test:
        assert generated_test_data.nodegroup_describe_output[key] == expected_value


@mock_aws
def test_describe_nodegroup_throws_exception_when_cluster_not_found(NodegroupBuilder):
    client, generated_test_data = NodegroupBuilder()
    expected_exception = ResourceNotFoundException
    expected_msg = CLUSTER_NOT_FOUND_MSG.format(
        clusterName=generated_test_data.nonexistent_cluster_name
    )

    with pytest.raises(ClientError) as raised_exception:
        client.describe_nodegroup(
            clusterName=generated_test_data.nonexistent_cluster_name,
            nodegroupName=generated_test_data.existing_nodegroup_name,
        )

    assert_expected_exception(raised_exception, expected_exception, expected_msg)


@mock_aws
def test_describe_nodegroup_throws_exception_when_nodegroup_not_found(NodegroupBuilder):
    client, generated_test_data = NodegroupBuilder()
    expected_exception = ResourceNotFoundException
    expected_msg = NODEGROUP_NOT_FOUND_MSG.format(
        nodegroupName=generated_test_data.nonexistent_nodegroup_name
    )

    with pytest.raises(ClientError) as raised_exception:
        client.describe_nodegroup(
            clusterName=generated_test_data.cluster_name,
            nodegroupName=generated_test_data.nonexistent_nodegroup_name,
        )

    assert_expected_exception(raised_exception, expected_exception, expected_msg)


@mock_aws
def test_delete_cluster_throws_exception_when_nodegroups_exist(NodegroupBuilder):
    client, generated_test_data = NodegroupBuilder()
    expected_exception = ResourceInUseException
    expected_msg = CLUSTER_IN_USE_MSG

    with pytest.raises(ClientError) as raised_exception:
        client.delete_cluster(name=generated_test_data.cluster_name)
    count_clusters_after_test = len(client.list_clusters()[ResponseAttributes.CLUSTERS])

    assert count_clusters_after_test == BatchCountSize.SINGLE
    assert_expected_exception(raised_exception, expected_exception, expected_msg)


@mock_aws
def test_delete_nodegroup_removes_deleted_nodegroup(NodegroupBuilder):
    client, generated_test_data = NodegroupBuilder(BatchCountSize.SMALL)

    client.delete_nodegroup(
        clusterName=generated_test_data.cluster_name,
        nodegroupName=generated_test_data.existing_nodegroup_name,
    )
    result = client.list_nodegroups(clusterName=generated_test_data.cluster_name)[
        ResponseAttributes.NODEGROUPS
    ]

    assert len(result) == BatchCountSize.SMALL - 1
    assert generated_test_data.existing_nodegroup_name not in result


@mock_aws
def test_delete_nodegroup_returns_deleted_nodegroup(NodegroupBuilder):
    client, generated_test_data = NodegroupBuilder(BatchCountSize.SMALL, False)

    result = client.delete_nodegroup(
        clusterName=generated_test_data.cluster_name,
        nodegroupName=generated_test_data.existing_nodegroup_name,
    )[ResponseAttributes.NODEGROUP]

    for key, expected_value in generated_test_data.attributes_to_test:
        assert result[key] == expected_value


@mock_aws
def test_delete_nodegroup_throws_exception_when_cluster_not_found(NodegroupBuilder):
    client, generated_test_data = NodegroupBuilder()
    expected_exception = ResourceNotFoundException
    expected_msg = CLUSTER_NOT_FOUND_MSG.format(
        clusterName=generated_test_data.nonexistent_cluster_name
    )

    with pytest.raises(ClientError) as raised_exception:
        client.delete_nodegroup(
            clusterName=generated_test_data.nonexistent_cluster_name,
            nodegroupName=generated_test_data.existing_nodegroup_name,
        )

    assert_expected_exception(raised_exception, expected_exception, expected_msg)


@mock_aws
def test_delete_nodegroup_throws_exception_when_nodegroup_not_found(NodegroupBuilder):
    client, generated_test_data = NodegroupBuilder()
    expected_exception = ResourceNotFoundException
    expected_msg = NODEGROUP_NOT_FOUND_MSG.format(
        nodegroupName=generated_test_data.nonexistent_nodegroup_name
    )

    with pytest.raises(ClientError) as raised_exception:
        client.delete_nodegroup(
            clusterName=generated_test_data.cluster_name,
            nodegroupName=generated_test_data.nonexistent_nodegroup_name,
        )

    assert_expected_exception(raised_exception, expected_exception, expected_msg)


# If launch_template is specified, you can not specify instanceTypes, diskSize, or remoteAccess.
test_cases = [
    # Happy Paths
    (LAUNCH_TEMPLATE, None, None, None, PossibleTestResults.SUCCESS),
    (None, INSTANCE_TYPES, DISK_SIZE, REMOTE_ACCESS, PossibleTestResults.SUCCESS),
    (None, None, DISK_SIZE, REMOTE_ACCESS, PossibleTestResults.SUCCESS),
    (None, INSTANCE_TYPES, None, REMOTE_ACCESS, PossibleTestResults.SUCCESS),
    (None, INSTANCE_TYPES, DISK_SIZE, None, PossibleTestResults.SUCCESS),
    (None, INSTANCE_TYPES, None, None, PossibleTestResults.SUCCESS),
    (None, None, DISK_SIZE, None, PossibleTestResults.SUCCESS),
    (None, None, None, REMOTE_ACCESS, PossibleTestResults.SUCCESS),
    (None, None, None, None, PossibleTestResults.SUCCESS),
    # Unhappy Paths
    (LAUNCH_TEMPLATE, INSTANCE_TYPES, None, None, PossibleTestResults.FAILURE),
    (LAUNCH_TEMPLATE, None, DISK_SIZE, None, PossibleTestResults.FAILURE),
    (LAUNCH_TEMPLATE, None, None, REMOTE_ACCESS, PossibleTestResults.FAILURE),
    (LAUNCH_TEMPLATE, INSTANCE_TYPES, DISK_SIZE, None, PossibleTestResults.FAILURE),
    (LAUNCH_TEMPLATE, INSTANCE_TYPES, None, REMOTE_ACCESS, PossibleTestResults.FAILURE),
    (LAUNCH_TEMPLATE, None, DISK_SIZE, REMOTE_ACCESS, PossibleTestResults.FAILURE),
    (
        LAUNCH_TEMPLATE,
        INSTANCE_TYPES,
        DISK_SIZE,
        REMOTE_ACCESS,
        PossibleTestResults.FAILURE,
    ),
]


@pytest.mark.parametrize(
    "launch_template, instance_types, disk_size, remote_access, expected_result",
    test_cases,
)
@mock_aws
def test_create_nodegroup_handles_launch_template_combinations(
    ClusterBuilder,
    launch_template,
    instance_types,
    disk_size,
    remote_access,
    expected_result,
):
    client, generated_test_data = ClusterBuilder()
    nodegroup_name = mock_random.get_random_string()
    expected_exception = InvalidParameterException
    expected_msg = None

    test_inputs = dict(
        deepcopy(
            # Required Constants
            NodegroupInputs.REQUIRED
            # Required Variables
            + [
                (
                    ClusterAttributes.CLUSTER_NAME,
                    generated_test_data.existing_cluster_name,
                ),
                (NodegroupAttributes.NODEGROUP_NAME, nodegroup_name),
            ]
            # Test Case Values
            + [
                _
                for _ in [launch_template, instance_types, disk_size, remote_access]
                if _
            ]
        )
    )

    if expected_result == PossibleTestResults.SUCCESS:
        result = client.create_nodegroup(**test_inputs)[ResponseAttributes.NODEGROUP]

        for key, expected_value in test_inputs.items():
            assert result[key] == expected_value
    else:
        if launch_template and disk_size:
            expected_msg = LAUNCH_TEMPLATE_WITH_DISK_SIZE_MSG
        elif launch_template and remote_access:
            expected_msg = LAUNCH_TEMPLATE_WITH_REMOTE_ACCESS_MSG
        # Docs say this combination throws an exception but testing shows that
        # instanceTypes overrides the launchTemplate instance values instead.
        # Leaving here for easier correction if/when that gets fixed.
        elif launch_template and instance_types:
            pass

    if expected_msg:
        with pytest.raises(ClientError) as raised_exception:
            client.create_nodegroup(**test_inputs)
        assert_expected_exception(raised_exception, expected_exception, expected_msg)


@mock_aws
def test_list_fargate_profile_returns_empty_by_default(ClusterBuilder):
    client, generated_test_data = ClusterBuilder()

    result = client.list_fargate_profiles(
        clusterName=generated_test_data.existing_cluster_name
    )[ResponseAttributes.FARGATE_PROFILE_NAMES]

    assert result == []


@mock_aws
def test_list_fargate_profile_returns_sorted_fargate_profile_names(
    FargateProfileBuilder,
):
    client, generated_test_data = FargateProfileBuilder(BatchCountSize.SMALL)
    expected_result = sorted(generated_test_data.fargate_profile_names)

    result = client.list_fargate_profiles(clusterName=generated_test_data.cluster_name)[
        ResponseAttributes.FARGATE_PROFILE_NAMES
    ]

    assert_result_matches_expected_list(result, expected_result, BatchCountSize.SMALL)


@mock_aws
def test_list_fargate_profile_returns_default_max_results(FargateProfileBuilder):
    client, generated_test_data = FargateProfileBuilder(BatchCountSize.LARGE)
    expected_len = DEFAULT_MAX_RESULTS
    expected_result = (sorted(generated_test_data.fargate_profile_names))[:expected_len]

    result = client.list_fargate_profiles(clusterName=generated_test_data.cluster_name)[
        ResponseAttributes.FARGATE_PROFILE_NAMES
    ]

    assert_result_matches_expected_list(result, expected_result, expected_len)


@mock_aws
def test_list_fargate_profile_returns_custom_max_results(FargateProfileBuilder):
    client, generated_test_data = FargateProfileBuilder(BatchCountSize.LARGE)
    expected_len = BatchCountSize.LARGE
    expected_result = (sorted(generated_test_data.fargate_profile_names))[:expected_len]

    result = client.list_fargate_profiles(
        clusterName=generated_test_data.cluster_name, maxResults=expected_len
    )[ResponseAttributes.FARGATE_PROFILE_NAMES]

    assert_result_matches_expected_list(result, expected_result, expected_len)


@mock_aws
def test_list_fargate_profile_returns_second_page_results(FargateProfileBuilder):
    client, generated_test_data = FargateProfileBuilder(BatchCountSize.MEDIUM)
    page1_len = PageCount.LARGE
    expected_len = BatchCountSize.MEDIUM - page1_len
    expected_result = (sorted(generated_test_data.fargate_profile_names))[page1_len:]
    token = client.list_fargate_profiles(
        clusterName=generated_test_data.cluster_name, maxResults=page1_len
    )[ResponseAttributes.NEXT_TOKEN]

    result = client.list_fargate_profiles(
        clusterName=generated_test_data.cluster_name, nextToken=token
    )[ResponseAttributes.FARGATE_PROFILE_NAMES]

    assert_result_matches_expected_list(result, expected_result, expected_len)


@mock_aws
def test_list_fargate_profile_returns_custom_second_page_results(FargateProfileBuilder):
    client, generated_test_data = FargateProfileBuilder(BatchCountSize.MEDIUM)
    page1_len = PageCount.LARGE
    expected_len = PageCount.SMALL
    expected_result = (sorted(generated_test_data.fargate_profile_names))[
        page1_len : page1_len + expected_len
    ]
    token = client.list_fargate_profiles(
        clusterName=generated_test_data.cluster_name, maxResults=page1_len
    )[ResponseAttributes.NEXT_TOKEN]

    result = client.list_fargate_profiles(
        clusterName=generated_test_data.cluster_name,
        maxResults=expected_len,
        nextToken=token,
    )[ResponseAttributes.FARGATE_PROFILE_NAMES]

    assert_result_matches_expected_list(result, expected_result, expected_len)


@mock_aws
def test_create_fargate_profile_throws_exception_when_cluster_not_found():
    client = boto3.client(SERVICE, region_name=REGION)
    non_existent_cluster_name = mock_random.get_random_string()
    expected_exception = ResourceNotFoundException
    expected_msg = CLUSTER_NOT_FOUND_MSG.format(clusterName=non_existent_cluster_name)

    with pytest.raises(ClientError) as raised_exception:
        client.create_fargate_profile(
            clusterName=non_existent_cluster_name,
            fargateProfileName=mock_random.get_random_string(),
            **dict(FargateProfileInputs.REQUIRED),
        )

    assert_expected_exception(raised_exception, expected_exception, expected_msg)


@mock_aws
def test_create_fargate_profile_throws_exception_when_fargate_profile_already_exists(
    FargateProfileBuilder,
):
    client, generated_test_data = FargateProfileBuilder(BatchCountSize.SMALL)
    expected_exception = ResourceInUseException
    expected_msg = FARGATE_PROFILE_EXISTS_MSG

    with pytest.raises(ClientError) as raised_exception:
        client.create_fargate_profile(
            clusterName=generated_test_data.cluster_name,
            fargateProfileName=generated_test_data.existing_fargate_profile_name,
            **dict(FargateProfileInputs.REQUIRED),
        )
    count_profiles_after_test = len(
        client.list_fargate_profiles(clusterName=generated_test_data.cluster_name)[
            ResponseAttributes.FARGATE_PROFILE_NAMES
        ]
    )

    assert count_profiles_after_test == BatchCountSize.SMALL
    assert_expected_exception(raised_exception, expected_exception, expected_msg)


@mock_aws
def test_create_fargate_profile_throws_exception_when_cluster_not_active(
    FargateProfileBuilder,
):
    if settings.TEST_SERVER_MODE:
        raise SkipTest("Cant patch Cluster attributes in server mode.")
    client, generated_test_data = FargateProfileBuilder(BatchCountSize.SMALL)
    expected_exception = InvalidRequestException
    expected_msg = CLUSTER_NOT_READY_MSG.format(
        clusterName=generated_test_data.cluster_name
    )

    with mock.patch(
        "moto.eks.models.Cluster.is_active",
        new_callable=PropertyMock,
        return_value=False,
    ):
        with pytest.raises(ClientError) as raised_exception:
            client.create_fargate_profile(
                clusterName=generated_test_data.cluster_name,
                fargateProfileName=mock_random.get_random_string(),
                **dict(FargateProfileInputs.REQUIRED),
            )
    count_fargate_profiles_after_test = len(
        client.list_fargate_profiles(clusterName=generated_test_data.cluster_name)[
            ResponseAttributes.FARGATE_PROFILE_NAMES
        ]
    )

    assert count_fargate_profiles_after_test == BatchCountSize.SMALL
    assert_expected_exception(raised_exception, expected_exception, expected_msg)


@mock_aws
def test_create_fargate_profile_generates_valid_profile_arn(FargateProfileBuilder):
    _, generated_test_data = FargateProfileBuilder()
    expected_arn_values = [
        PARTITIONS,
        REGION,
        ACCOUNT_ID,
        generated_test_data.cluster_name,
        generated_test_data.fargate_profile_names,
        None,
    ]

    all_arn_values_should_be_valid(
        expected_arn_values=expected_arn_values,
        pattern=RegExTemplates.FARGATE_PROFILE_ARN,
        arn_under_test=generated_test_data.fargate_describe_output[
            FargateProfileAttributes.ARN
        ],
    )


@mock_aws
def test_create_fargate_profile_generates_valid_created_timestamp(
    FargateProfileBuilder,
):
    fp_create_time = datetime.datetime(2013, 11, 27, 1, 42, tzinfo=tzutc())
    with freeze_time(fp_create_time):
        _, generated_test_data = FargateProfileBuilder()
    result_time = generated_test_data.fargate_describe_output[
        FargateProfileAttributes.CREATED_AT
    ]
    if not settings.TEST_SERVER_MODE:
        assert result_time == fp_create_time


@mock_aws
def test_create_fargate_profile_saves_provided_parameters(FargateProfileBuilder):
    _, generated_test_data = FargateProfileBuilder(minimal=False)

    for key, expected_value in generated_test_data.attributes_to_test:
        assert generated_test_data.fargate_describe_output[key] == expected_value


@mock_aws
def test_describe_fargate_profile_throws_exception_when_cluster_not_found(
    FargateProfileBuilder,
):
    client, generated_test_data = FargateProfileBuilder()
    expected_exception = ResourceNotFoundException
    expected_msg = CLUSTER_NOT_FOUND_MSG.format(
        clusterName=generated_test_data.nonexistent_cluster_name
    )

    with pytest.raises(ClientError) as raised_exception:
        client.describe_fargate_profile(
            clusterName=generated_test_data.nonexistent_cluster_name,
            fargateProfileName=generated_test_data.existing_fargate_profile_name,
        )

    assert_expected_exception(raised_exception, expected_exception, expected_msg)


@mock_aws
def test_describe_fargate_profile_throws_exception_when_profile_not_found(
    FargateProfileBuilder,
):
    client, generated_test_data = FargateProfileBuilder()
    expected_exception = ResourceNotFoundException
    expected_msg = FARGATE_PROFILE_NOT_FOUND_MSG.format(
        fargateProfileName=generated_test_data.nonexistent_fargate_profile_name
    )

    with pytest.raises(ClientError) as raised_exception:
        client.describe_fargate_profile(
            clusterName=generated_test_data.cluster_name,
            fargateProfileName=generated_test_data.nonexistent_fargate_profile_name,
        )

    assert_expected_exception(raised_exception, expected_exception, expected_msg)


@mock_aws
def test_delete_fargate_profile_removes_deleted_fargate_profile(FargateProfileBuilder):
    client, generated_test_data = FargateProfileBuilder(BatchCountSize.SMALL)

    client.delete_fargate_profile(
        clusterName=generated_test_data.cluster_name,
        fargateProfileName=generated_test_data.existing_fargate_profile_name,
    )
    result = client.list_fargate_profiles(clusterName=generated_test_data.cluster_name)[
        ResponseAttributes.FARGATE_PROFILE_NAMES
    ]

    assert len(result) == BatchCountSize.SMALL - 1
    assert generated_test_data.existing_fargate_profile_name not in result


@mock_aws
def test_delete_fargate_profile_returns_deleted_fargate_profile(FargateProfileBuilder):
    client, generated_test_data = FargateProfileBuilder(BatchCountSize.SMALL, False)

    result = client.delete_fargate_profile(
        clusterName=generated_test_data.cluster_name,
        fargateProfileName=generated_test_data.existing_fargate_profile_name,
    )[ResponseAttributes.FARGATE_PROFILE]

    for key, expected_value in generated_test_data.attributes_to_test:
        assert result[key] == expected_value


@mock_aws
def test_delete_fargate_profile_throws_exception_when_cluster_not_found(
    FargateProfileBuilder,
):
    client, generated_test_data = FargateProfileBuilder()
    expected_exception = ResourceNotFoundException
    expected_msg = CLUSTER_NOT_FOUND_MSG.format(
        clusterName=generated_test_data.nonexistent_cluster_name
    )

    with pytest.raises(ClientError) as raised_exception:
        client.delete_fargate_profile(
            clusterName=generated_test_data.nonexistent_cluster_name,
            fargateProfileName=generated_test_data.existing_fargate_profile_name,
        )

    assert_expected_exception(raised_exception, expected_exception, expected_msg)


@mock_aws
def test_delete_fargate_profile_throws_exception_when_fargate_profile_not_found(
    FargateProfileBuilder,
):
    client, generated_test_data = FargateProfileBuilder()
    expected_exception = ResourceNotFoundException
    expected_msg = FARGATE_PROFILE_NOT_FOUND_MSG.format(
        fargateProfileName=generated_test_data.nonexistent_fargate_profile_name
    )

    with pytest.raises(ClientError) as raised_exception:
        client.delete_fargate_profile(
            clusterName=generated_test_data.cluster_name,
            fargateProfileName=generated_test_data.nonexistent_fargate_profile_name,
        )

    assert_expected_exception(raised_exception, expected_exception, expected_msg)


@mock_aws
def test_create_fargate_throws_exception_when_no_selectors_provided(ClusterBuilder):
    client, generated_test_data = ClusterBuilder()
    cluster_name = generated_test_data.existing_cluster_name
    fargate_profile_name = mock_random.get_random_string()
    expected_exception = InvalidParameterException
    expected_msg = FARGATE_PROFILE_NEEDS_SELECTOR_MSG

    test_inputs = dict(
        deepcopy(
            # Required Constants
            [POD_EXECUTION_ROLE_ARN]
            # Required Variables
            + [
                (ClusterAttributes.CLUSTER_NAME, cluster_name),
                (FargateProfileAttributes.FARGATE_PROFILE_NAME, fargate_profile_name),
            ]
        )
    )

    with pytest.raises(ClientError) as raised_exception:
        client.create_fargate_profile(**test_inputs)
    assert_expected_exception(raised_exception, expected_exception, expected_msg)


# The following Selector test cases have all been verified against the AWS API using cURL.
selector_formatting_test_cases = [
    # Format is ([Selector(s), expected_message, expected_result])
    # Happy Paths
    # Selector with a Namespace and no Labels
    (
        [{FargateProfileAttributes.NAMESPACE: DEFAULT_NAMESPACE}],
        None,
        PossibleTestResults.SUCCESS,
    ),
    # Selector with a Namespace and an empty collection of Labels
    (
        [
            {
                FargateProfileAttributes.NAMESPACE: DEFAULT_NAMESPACE,
                FargateProfileAttributes.LABELS: generate_dict("label", 0),
            }
        ],
        None,
        PossibleTestResults.SUCCESS,
    ),
    # Selector with a Namespace and one valid Label
    (
        [
            {
                FargateProfileAttributes.NAMESPACE: DEFAULT_NAMESPACE,
                FargateProfileAttributes.LABELS: generate_dict("label", 1),
            }
        ],
        None,
        PossibleTestResults.SUCCESS,
    ),
    # Selector with a Namespace and the maximum number of Labels
    (
        [
            {
                FargateProfileAttributes.NAMESPACE: DEFAULT_NAMESPACE,
                FargateProfileAttributes.LABELS: generate_dict(
                    "label", MAX_FARGATE_LABELS
                ),
            }
        ],
        None,
        PossibleTestResults.SUCCESS,
    ),
    # Two valid Selectors
    (
        [
            {FargateProfileAttributes.NAMESPACE: DEFAULT_NAMESPACE},
            {FargateProfileAttributes.NAMESPACE: DEFAULT_NAMESPACE},
        ],
        None,
        PossibleTestResults.SUCCESS,
    ),
    # Unhappy Cases
    # No Selectors provided
    ([], FARGATE_PROFILE_NEEDS_SELECTOR_MSG, PossibleTestResults.FAILURE),
    # Empty Selector / Selector without a Namespace or Labels
    ([{}], FARGATE_PROFILE_SELECTOR_NEEDS_NAMESPACE, PossibleTestResults.FAILURE),
    # Selector with labels but no Namespace
    (
        [{FargateProfileAttributes.LABELS: generate_dict("label", 1)}],
        FARGATE_PROFILE_SELECTOR_NEEDS_NAMESPACE,
        PossibleTestResults.FAILURE,
    ),
    # Selector with Namespace but too many Labels
    (
        [
            {
                FargateProfileAttributes.NAMESPACE: DEFAULT_NAMESPACE,
                FargateProfileAttributes.LABELS: generate_dict(
                    "label", MAX_FARGATE_LABELS + 1
                ),
            }
        ],
        FARGATE_PROFILE_TOO_MANY_LABELS,
        PossibleTestResults.FAILURE,
    ),
    # Valid Selector followed by Empty Selector
    (
        [{FargateProfileAttributes.NAMESPACE: DEFAULT_NAMESPACE}, {}],
        FARGATE_PROFILE_SELECTOR_NEEDS_NAMESPACE,
        PossibleTestResults.FAILURE,
    ),
    # Empty Selector followed by Valid Selector
    (
        [{}, {FargateProfileAttributes.NAMESPACE: DEFAULT_NAMESPACE}],
        FARGATE_PROFILE_SELECTOR_NEEDS_NAMESPACE,
        PossibleTestResults.FAILURE,
    ),
    # Empty Selector followed by Empty Selector
    ([{}, {}], FARGATE_PROFILE_SELECTOR_NEEDS_NAMESPACE, PossibleTestResults.FAILURE),
    # Valid Selector followed by Selector with Namespace but too many Labels
    (
        [
            {FargateProfileAttributes.NAMESPACE: DEFAULT_NAMESPACE},
            {
                FargateProfileAttributes.NAMESPACE: DEFAULT_NAMESPACE,
                FargateProfileAttributes.LABELS: generate_dict(
                    "label", MAX_FARGATE_LABELS + 1
                ),
            },
        ],
        FARGATE_PROFILE_TOO_MANY_LABELS,
        PossibleTestResults.FAILURE,
    ),
]


@pytest.mark.parametrize(
    "selectors, expected_message, expected_result", selector_formatting_test_cases
)
@mock_aws
def test_create_fargate_selectors(
    ClusterBuilder, selectors, expected_message, expected_result
):
    client, generated_test_data = ClusterBuilder()
    cluster_name = generated_test_data.existing_cluster_name
    fargate_profile_name = mock_random.get_random_string()
    expected_exception = InvalidParameterException

    test_inputs = dict(
        deepcopy(
            # Required Constants
            [POD_EXECUTION_ROLE_ARN]
            # Required Variables
            + [
                (ClusterAttributes.CLUSTER_NAME, cluster_name),
                (FargateProfileAttributes.FARGATE_PROFILE_NAME, fargate_profile_name),
            ]
            # Test Case Values
            + [(FargateProfileAttributes.SELECTORS, selectors)]
        )
    )

    if expected_result == PossibleTestResults.SUCCESS:
        result = client.create_fargate_profile(**test_inputs)[
            ResponseAttributes.FARGATE_PROFILE
        ]
        for key, expected_value in test_inputs.items():
            assert result[key] == expected_value
    else:
        with pytest.raises(ClientError) as raised_exception:
            client.create_fargate_profile(**test_inputs)
        assert_expected_exception(
            raised_exception, expected_exception, expected_message
        )


def all_arn_values_should_be_valid(expected_arn_values, pattern, arn_under_test):
    """
    Applies regex `pattern` to `arn_under_test` and asserts
    that each group matches the provided expected value.
    A list entry of None in the 'expected_arn_values' will
    assert that the value exists but not match a specific value.
    """
    findall = pattern.findall(arn_under_test)[0]
    expected_values = deepcopy(expected_arn_values)
    # findall() returns a list of matches from right to left so it must be reversed
    # in order to match the logical order of the 'expected_arn_values' list.
    for value in reversed(findall):
        expected_value = expected_values.pop()
        if expected_value:
            assert value in expected_value
        else:
            assert value is not None
    assert region_matches_partition(findall[1], findall[0]) is True


def assert_expected_exception(raised_exception, expected_exception, expected_msg):
    error = raised_exception.value.response[ErrorAttributes.ERROR]
    assert error[ErrorAttributes.CODE] == expected_exception.TYPE
    assert error[ErrorAttributes.MESSAGE] == expected_msg


def assert_result_matches_expected_list(result, expected_result, expected_len):
    assert result == expected_result
    assert len(result) == expected_len


def assert_valid_selectors(ClusterBuilder, expected_msg, expected_result, selectors):
    client, generated_test_data = ClusterBuilder()
    cluster_name = generated_test_data.existing_cluster_name
    fargate_profile_name = mock_random.get_random_string()
    expected_exception = InvalidParameterException

    test_inputs = dict(
        deepcopy(
            # Required Constants
            [POD_EXECUTION_ROLE_ARN]
            # Required Variables
            + [
                (ClusterAttributes.CLUSTER_NAME, cluster_name),
                (FargateProfileAttributes.FARGATE_PROFILE_NAME, fargate_profile_name),
            ]
            # Test Case Values
            + [(FargateProfileAttributes.SELECTORS, selectors)]
        )
    )

    if expected_result == PossibleTestResults.SUCCESS:
        result = client.create_fargate_profile(**test_inputs)[
            ResponseAttributes.FARGATE_PROFILE
        ]
        for key, expected_value in test_inputs.items():
            assert result[key] == expected_value
    else:
        with pytest.raises(ClientError) as raised_exception:
            client.create_fargate_profile(**test_inputs)
        assert_expected_exception(raised_exception, expected_exception, expected_msg)


@mock_aws
def test_update_cluster_config(ClusterBuilder):
    client, generated_cluster = ClusterBuilder(BatchCountSize.SINGLE)
    cluster_name = generated_cluster.existing_cluster_name

    new_vpc_config = {
        "subnetIds": ["test-new-subnet"],
        "endpointPublicAccess": False,
    }

    new_logging = {"clusterLogging": [{"types": ["api", "audit"], "enabled": True}]}

    client_request_token = "test-new-client-request-token"

    new_kubernetes_network_config = {"serviceIpv4Cidr": "0.0.0.0"}
    new_remote_network_config = {
        "remoteNodeNetworks": [
            {"cidrs": ["test-new-cidrs"]},
        ],
    }

    client.update_cluster_config(
        name=cluster_name,
        resourcesVpcConfig=new_vpc_config,
        logging=new_logging,
        clientRequestToken=client_request_token,
        kubernetesNetworkConfig=new_kubernetes_network_config,
        remoteNetworkConfig=new_remote_network_config,
    )

    updated = client.describe_cluster(name=cluster_name)[ResponseAttributes.CLUSTER]
    assert updated[ClusterAttributes.RESOURCES_VPC_CONFIG] == new_vpc_config
    assert updated[ClusterAttributes.LOGGING] == new_logging
    assert (
        updated[ClusterAttributes.KUBERNETES_NETWORK_CONFIG]
        == new_kubernetes_network_config
    )
    assert updated[ClusterAttributes.REMOTE_NETWORK_CONFIG] == new_remote_network_config
    assert updated[ClusterAttributes.CLIENT_REQUEST_TOKEN] == client_request_token


@mock_aws
def test_update_cluster_config_not_found(ClusterBuilder):
    client, generated_cluster = ClusterBuilder(BatchCountSize.SINGLE)

    expected_exception = ResourceNotFoundException
    expected_msg = CLUSTER_NOT_FOUND_MSG.format(
        clusterName=generated_cluster.nonexistent_cluster_name
    )
    with pytest.raises(ClientError) as raised_exception:
        client.update_cluster_config(name=generated_cluster.nonexistent_cluster_name)

    assert_expected_exception(raised_exception, expected_exception, expected_msg)