File: test_stepfunctions.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 (1485 lines) | stat: -rw-r--r-- 51,647 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
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
import json
import os
import re
from datetime import datetime
from unittest import SkipTest, mock
from uuid import uuid4

import boto3
import pytest
from botocore.exceptions import ClientError, ParamValidationError
from dateutil.tz import tzutc

from moto import mock_aws
from moto.core import DEFAULT_ACCOUNT_ID as ACCOUNT_ID
from tests.test_stepfunctions.parser import sfn_role_policy

region = "us-east-1"
simple_definition = (
    '{"Comment": "An example of the Amazon States Language using a choice state.",'
    '"StartAt": "DefaultState",'
    '"States": '
    '{"DefaultState": {"Type": "Fail","Error": "DefaultStateError","Cause": "No Matches!"}}}'
)
account_id = None


@mock_aws
def test_state_machine_creation_succeeds():
    client = boto3.client("stepfunctions", region_name=region)
    name = "example_step_function"
    response = client.create_state_machine(
        name=name, definition=str(simple_definition), roleArn=_get_default_role()
    )
    assert response["ResponseMetadata"]["HTTPStatusCode"] == 200
    assert isinstance(response["creationDate"], datetime)
    assert response["stateMachineArn"] == (
        "arn:aws:states:" + region + ":" + ACCOUNT_ID + ":stateMachine:" + name
    )


@mock_aws
def test_state_machine_with_cmk():
    client = boto3.client("stepfunctions", region_name=region)
    kms_key_id = boto3.client("kms", region_name=region).create_key()["KeyMetadata"][
        "KeyId"
    ]
    name = "example_step_function_cmk"
    encryption_config = {
        "kmsDataKeyReusePeriodSeconds": 60,
        "kmsKeyId": kms_key_id,
        "type": "CUSTOMER_MANAGED_CMK",
    }

    state_machine_arn = client.create_state_machine(
        name=name,
        definition=str(simple_definition),
        roleArn=_get_default_role(),
        encryptionConfiguration=encryption_config,
    )["stateMachineArn"]

    desc = client.describe_state_machine(stateMachineArn=state_machine_arn)
    assert desc["encryptionConfiguration"] == encryption_config


@mock_aws
def test_state_machine_creation_fails_with_invalid_names():
    client = boto3.client("stepfunctions", region_name=region)
    invalid_names = [
        "with space",
        "with<bracket",
        "with>bracket",
        "with{bracket",
        "with}bracket",
        "with[bracket",
        "with]bracket",
        "with?wildcard",
        "with*wildcard",
        'special"char',
        "special#char",
        "special%char",
        "special\\char",
        "special^char",
        "special|char",
        "special~char",
        "special`char",
        "special$char",
        "special&char",
        "special,char",
        "special;char",
        "special:char",
        "special/char",
        "uni\u0000code",
        "uni\u0001code",
        "uni\u0002code",
        "uni\u0003code",
        "uni\u0004code",
        "uni\u0005code",
        "uni\u0006code",
        "uni\u0007code",
        "uni\u0008code",
        "uni\u0009code",
        "uni\u000acode",
        "uni\u000bcode",
        "uni\u000ccode",
        "uni\u000dcode",
        "uni\u000ecode",
        "uni\u000fcode",
        "uni\u0010code",
        "uni\u0011code",
        "uni\u0012code",
        "uni\u0013code",
        "uni\u0014code",
        "uni\u0015code",
        "uni\u0016code",
        "uni\u0017code",
        "uni\u0018code",
        "uni\u0019code",
        "uni\u001acode",
        "uni\u001bcode",
        "uni\u001ccode",
        "uni\u001dcode",
        "uni\u001ecode",
        "uni\u001fcode",
        "uni\u007fcode",
        "uni\u0080code",
        "uni\u0081code",
        "uni\u0082code",
        "uni\u0083code",
        "uni\u0084code",
        "uni\u0085code",
        "uni\u0086code",
        "uni\u0087code",
        "uni\u0088code",
        "uni\u0089code",
        "uni\u008acode",
        "uni\u008bcode",
        "uni\u008ccode",
        "uni\u008dcode",
        "uni\u008ecode",
        "uni\u008fcode",
        "uni\u0090code",
        "uni\u0091code",
        "uni\u0092code",
        "uni\u0093code",
        "uni\u0094code",
        "uni\u0095code",
        "uni\u0096code",
        "uni\u0097code",
        "uni\u0098code",
        "uni\u0099code",
        "uni\u009acode",
        "uni\u009bcode",
        "uni\u009ccode",
        "uni\u009dcode",
        "uni\u009ecode",
        "uni\u009fcode",
    ]
    #

    for invalid_name in invalid_names:
        with pytest.raises(ClientError):
            client.create_state_machine(
                name=invalid_name,
                definition=str(simple_definition),
                roleArn=_get_default_role(),
            )


@mock_aws
def test_state_machine_creation_requires_valid_role_arn():
    client = boto3.client("stepfunctions", region_name=region)
    name = "example_step_function"
    #
    with pytest.raises(ClientError):
        client.create_state_machine(
            name=name,
            definition=str(simple_definition),
            roleArn="arn:aws:iam::1234:role/unknown_role",
        )


@mock_aws
def test_update_state_machine():
    client = boto3.client("stepfunctions", region_name=region)

    resp = client.create_state_machine(
        name="test", definition=str(simple_definition), roleArn=_get_default_role()
    )
    state_machine_arn = resp["stateMachineArn"]

    updated_role = _get_default_role() + "-updated"
    updated_definition = str(simple_definition).replace(
        "DefaultState", "DefaultStateUpdated"
    )
    kms_key_id = boto3.client("kms", region_name=region).create_key()["KeyMetadata"][
        "KeyId"
    ]
    encryption_config = {
        "kmsDataKeyReusePeriodSeconds": 60,
        "kmsKeyId": kms_key_id,
        "type": "CUSTOMER_MANAGED_CMK",
    }
    updated_logging_config = {
        "level": "ALL",
        "destinations": [
            {
                "cloudWatchLogsLogGroup": {
                    "logGroupArn": "arn:aws:logs:us-east-1:123456789012:log-group:my-log-group"
                }
            }
        ],
    }
    updated_tracing_config = {"enabled": True}
    resp = client.update_state_machine(
        stateMachineArn=state_machine_arn,
        definition=updated_definition,
        roleArn=updated_role,
        encryptionConfiguration=encryption_config,
        loggingConfiguration=updated_logging_config,
        tracingConfiguration=updated_tracing_config,
    )
    assert resp["ResponseMetadata"]["HTTPStatusCode"] == 200
    assert isinstance(resp["updateDate"], datetime)

    desc = client.describe_state_machine(stateMachineArn=state_machine_arn)
    assert desc["definition"] == updated_definition
    assert desc["roleArn"] == updated_role
    assert desc["encryptionConfiguration"] == encryption_config
    assert desc["loggingConfiguration"] == updated_logging_config
    assert desc["tracingConfiguration"] == updated_tracing_config


@mock_aws
def test_state_machine_list_returns_empty_list_by_default():
    client = boto3.client("stepfunctions", region_name=region)
    #
    sm_list = client.list_state_machines()
    assert sm_list["stateMachines"] == []


@mock_aws
def test_state_machine_list_returns_created_state_machines():
    client = boto3.client("stepfunctions", region_name=region)
    #
    machine1 = client.create_state_machine(
        name="name1",
        definition=str(simple_definition),
        roleArn=_get_default_role(),
        tags=[{"key": "tag_key", "value": "tag_value"}],
    )
    machine2 = client.create_state_machine(
        name="name2", definition=str(simple_definition), roleArn=_get_default_role()
    )
    sm_list = client.list_state_machines()
    #
    assert sm_list["ResponseMetadata"]["HTTPStatusCode"] == 200
    assert len(sm_list["stateMachines"]) == 2
    assert isinstance(sm_list["stateMachines"][0]["creationDate"], datetime)
    assert sm_list["stateMachines"][0]["creationDate"] == machine1["creationDate"]
    assert sm_list["stateMachines"][0]["name"] == "name1"
    assert sm_list["stateMachines"][0]["stateMachineArn"] == machine1["stateMachineArn"]
    assert isinstance(sm_list["stateMachines"][1]["creationDate"], datetime)
    assert sm_list["stateMachines"][1]["creationDate"] == machine2["creationDate"]
    assert sm_list["stateMachines"][1]["name"] == "name2"
    assert sm_list["stateMachines"][1]["stateMachineArn"] == machine2["stateMachineArn"]


@mock_aws
def test_state_machine_list_pagination():
    client = boto3.client("stepfunctions", region_name=region)
    for i in range(25):
        machine_name = f"StateMachine-{i}"
        client.create_state_machine(
            name=machine_name,
            definition=str(simple_definition),
            roleArn=_get_default_role(),
        )

    resp = client.list_state_machines()
    assert "nextToken" not in resp
    assert len(resp["stateMachines"]) == 25

    paginator = client.get_paginator("list_state_machines")
    page_iterator = paginator.paginate(maxResults=5)
    page_list = list(page_iterator)
    for page in page_list:
        assert len(page["stateMachines"]) == 5
    assert "24" in page_list[-1]["stateMachines"][-1]["name"]


@mock_aws
def test_state_machine_creation_is_idempotent_by_name():
    client = boto3.client("stepfunctions", region_name=region)
    #
    client.create_state_machine(
        name="name", definition=str(simple_definition), roleArn=_get_default_role()
    )
    sm_list = client.list_state_machines()
    assert len(sm_list["stateMachines"]) == 1
    #
    client.create_state_machine(
        name="name", definition=str(simple_definition), roleArn=_get_default_role()
    )
    sm_list = client.list_state_machines()
    assert len(sm_list["stateMachines"]) == 1
    #
    client.create_state_machine(
        name="diff_name", definition=str(simple_definition), roleArn=_get_default_role()
    )
    sm_list = client.list_state_machines()
    assert len(sm_list["stateMachines"]) == 2


@mock_aws
def test_state_machine_creation_can_be_described():
    client = boto3.client("stepfunctions", region_name=region)
    #
    sm = client.create_state_machine(
        name="name", definition=str(simple_definition), roleArn=_get_default_role()
    )
    desc = client.describe_state_machine(stateMachineArn=sm["stateMachineArn"])
    assert desc["ResponseMetadata"]["HTTPStatusCode"] == 200
    assert desc["creationDate"] == sm["creationDate"]
    assert desc["definition"] == str(simple_definition)
    assert desc["name"] == "name"
    assert desc["roleArn"] == _get_default_role()
    assert desc["stateMachineArn"] == sm["stateMachineArn"]
    assert desc["status"] == "ACTIVE"
    assert desc["type"] == "STANDARD"
    assert desc["encryptionConfiguration"] == {"type": "AWS_OWNED_KEY"}
    assert desc["loggingConfiguration"] == {"level": "OFF"}
    assert desc["tracingConfiguration"] == {"enabled": False}


@mock_aws
def test_state_machine_throws_error_when_describing_unknown_machine():
    client = boto3.client("stepfunctions", region_name=region)
    #
    with pytest.raises(ClientError):
        unknown_state_machine = (
            f"arn:aws:states:{region}:{ACCOUNT_ID}:stateMachine:unknown"
        )
        client.describe_state_machine(stateMachineArn=unknown_state_machine)


@mock_aws
def test_state_machine_throws_error_when_describing_bad_arn():
    client = boto3.client("stepfunctions", region_name=region)
    #
    with pytest.raises(ClientError):
        client.describe_state_machine(stateMachineArn="bad")


@mock_aws
def test_state_machine_throws_error_when_describing_machine_in_different_account():
    client = boto3.client("stepfunctions", region_name=region)
    #
    with pytest.raises(ClientError):
        unknown_state_machine = (
            "arn:aws:states:" + region + ":000000000000:stateMachine:unknown"
        )
        client.describe_state_machine(stateMachineArn=unknown_state_machine)


@mock_aws
def test_state_machine_can_be_deleted():
    client = boto3.client("stepfunctions", region_name=region)
    sm = client.create_state_machine(
        name="name", definition=str(simple_definition), roleArn=_get_default_role()
    )
    #
    response = client.delete_state_machine(stateMachineArn=sm["stateMachineArn"])
    assert response["ResponseMetadata"]["HTTPStatusCode"] == 200
    #
    sm_list = client.list_state_machines()
    assert len(sm_list["stateMachines"]) == 0


@mock_aws
def test_state_machine_can_deleted_nonexisting_machine():
    client = boto3.client("stepfunctions", region_name=region)
    #
    unknown_state_machine = (
        "arn:aws:states:" + region + ":" + ACCOUNT_ID + ":stateMachine:unknown"
    )
    response = client.delete_state_machine(stateMachineArn=unknown_state_machine)
    assert response["ResponseMetadata"]["HTTPStatusCode"] == 200
    #
    sm_list = client.list_state_machines()
    assert len(sm_list["stateMachines"]) == 0


@mock_aws
def test_state_machine_tagging():
    client = boto3.client("stepfunctions", region_name=region)
    # Test tags are added on resource creation
    tags = [
        {"key": "tag_key1", "value": "tag_value1"},
        {"key": "tag_key2", "value": "tag_value2"},
    ]
    machine = client.create_state_machine(
        name="test-with-tags",
        definition=str(simple_definition),
        roleArn=_get_default_role(),
        tags=tags,
    )
    resp = client.list_tags_for_resource(resourceArn=machine["stateMachineArn"])
    assert resp["tags"] == tags

    # Test tags are added after creation with tag_resource
    machine = client.create_state_machine(
        name="test", definition=str(simple_definition), roleArn=_get_default_role()
    )
    client.tag_resource(resourceArn=machine["stateMachineArn"], tags=tags)
    resp = client.list_tags_for_resource(resourceArn=machine["stateMachineArn"])
    assert resp["tags"] == tags

    tags_update = [
        {"key": "tag_key1", "value": "tag_value1_new"},
        {"key": "tag_key3", "value": "tag_value3"},
    ]
    client.tag_resource(resourceArn=machine["stateMachineArn"], tags=tags_update)
    resp = client.list_tags_for_resource(resourceArn=machine["stateMachineArn"])
    tags_expected = [
        tags_update[0],
        tags[1],
        tags_update[1],
    ]
    assert resp["tags"] == tags_expected


@mock_aws
def test_state_machine_untagging():
    client = boto3.client("stepfunctions", region_name=region)
    tags = [
        {"key": "tag_key1", "value": "tag_value1"},
        {"key": "tag_key2", "value": "tag_value2"},
        {"key": "tag_key3", "value": "tag_value3"},
    ]
    machine = client.create_state_machine(
        name="test",
        definition=str(simple_definition),
        roleArn=_get_default_role(),
        tags=tags,
    )
    resp = client.list_tags_for_resource(resourceArn=machine["stateMachineArn"])
    assert resp["tags"] == tags
    tags_to_delete = ["tag_key1", "tag_key2"]
    client.untag_resource(
        resourceArn=machine["stateMachineArn"], tagKeys=tags_to_delete
    )
    resp = client.list_tags_for_resource(resourceArn=machine["stateMachineArn"])
    expected_tags = [tag for tag in tags if tag["key"] not in tags_to_delete]
    assert resp["tags"] == expected_tags


@mock_aws
def test_state_machine_list_tags_for_created_machine():
    client = boto3.client("stepfunctions", region_name=region)
    #
    machine = client.create_state_machine(
        name="name1",
        definition=str(simple_definition),
        roleArn=_get_default_role(),
        tags=[{"key": "tag_key", "value": "tag_value"}],
    )
    response = client.list_tags_for_resource(resourceArn=machine["stateMachineArn"])
    tags = response["tags"]
    assert len(tags) == 1
    assert tags[0] == {"key": "tag_key", "value": "tag_value"}


@mock_aws
def test_state_machine_list_tags_for_machine_without_tags():
    client = boto3.client("stepfunctions", region_name=region)
    #
    machine = client.create_state_machine(
        name="name1", definition=str(simple_definition), roleArn=_get_default_role()
    )
    response = client.list_tags_for_resource(resourceArn=machine["stateMachineArn"])
    tags = response["tags"]
    assert len(tags) == 0


@mock_aws
def test_state_machine_list_tags_for_nonexisting_machine():
    client = boto3.client("stepfunctions", region_name=region)
    #
    non_existing_state_machine = (
        f"arn:aws:states:{region}:{ACCOUNT_ID}:stateMachine:unknown"
    )
    response = client.list_tags_for_resource(resourceArn=non_existing_state_machine)
    tags = response["tags"]
    assert len(tags) == 0


@mock_aws
def test_state_machine_start_execution():
    client = boto3.client("stepfunctions", region_name=region)
    #
    sm = client.create_state_machine(
        name="name", definition=str(simple_definition), roleArn=_get_default_role()
    )
    execution = client.start_execution(stateMachineArn=sm["stateMachineArn"])
    #
    assert execution["ResponseMetadata"]["HTTPStatusCode"] == 200
    uuid_regex = "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}"
    expected_exec_name = (
        f"arn:aws:states:{region}:{ACCOUNT_ID}:execution:name:{uuid_regex}"
    )
    assert re.match(expected_exec_name, execution["executionArn"])
    assert isinstance(execution["startDate"], datetime)


@mock_aws
def test_state_machine_start_execution_bad_arn_raises_exception():
    client = boto3.client("stepfunctions", region_name=region)
    #
    with pytest.raises(ClientError):
        client.start_execution(stateMachineArn="bad")


@mock_aws
def test_state_machine_start_execution_with_custom_name():
    client = boto3.client("stepfunctions", region_name=region)
    #
    sm = client.create_state_machine(
        name="name", definition=str(simple_definition), roleArn=_get_default_role()
    )
    execution = client.start_execution(
        stateMachineArn=sm["stateMachineArn"], name="execution_name"
    )
    #
    assert execution["ResponseMetadata"]["HTTPStatusCode"] == 200
    expected_exec_name = (
        f"arn:aws:states:{region}:{ACCOUNT_ID}:execution:name:execution_name"
    )
    assert execution["executionArn"] == expected_exec_name
    assert isinstance(execution["startDate"], datetime)


@mock_aws
def test_state_machine_start_execution_fails_on_duplicate_execution_name_with_different_input():
    client = boto3.client("stepfunctions", region_name=region)
    #
    sm = client.create_state_machine(
        name="name", definition=str(simple_definition), roleArn=_get_default_role()
    )
    execution_one = client.start_execution(
        stateMachineArn=sm["stateMachineArn"],
        name="execution_name",
        input='{"a": "b", "c": "d"}',
    )
    #
    with pytest.raises(ClientError) as ex:
        _ = client.start_execution(
            stateMachineArn=sm["stateMachineArn"],
            name="execution_name",
            # Input is different (even though the decoded json is equivalent)
            input='{"c": "d", "a": "b"}',
        )
    assert ex.value.response["Error"]["Message"] == (
        "Execution Already Exists: '" + execution_one["executionArn"] + "'"
    )


@mock_aws
def test_state_machine_start_execution_is_idempotent_by_name_and_input():
    client = boto3.client("stepfunctions", region_name=region)
    #
    sm = client.create_state_machine(
        name="name", definition=str(simple_definition), roleArn=_get_default_role()
    )
    execution_input = '{"a": "b", "c": "d"}'
    execution_one = client.start_execution(
        stateMachineArn=sm["stateMachineArn"],
        name="execution_name",
        input=execution_input,
    )
    #
    execution_two = client.start_execution(
        stateMachineArn=sm["stateMachineArn"],
        name="execution_name",
        input=execution_input,
    )
    assert execution_one["executionArn"] == execution_two["executionArn"]

    # Check idempotency
    list_execs = client.list_executions(stateMachineArn=sm["stateMachineArn"])
    assert len(list_execs["executions"]) == 1


@mock_aws
def test_state_machine_start_execution_with_custom_input():
    client = boto3.client("stepfunctions", region_name=region)
    #
    sm = client.create_state_machine(
        name="name", definition=str(simple_definition), roleArn=_get_default_role()
    )
    execution_input = json.dumps({"input_key": "input_value"})
    execution = client.start_execution(
        stateMachineArn=sm["stateMachineArn"], input=execution_input
    )
    #
    assert execution["ResponseMetadata"]["HTTPStatusCode"] == 200
    uuid_regex = "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}"
    expected_exec_name = (
        f"arn:aws:states:{region}:{ACCOUNT_ID}:execution:name:{uuid_regex}"
    )
    assert re.match(expected_exec_name, execution["executionArn"])
    assert isinstance(execution["startDate"], datetime)


@mock_aws
def test_state_machine_start_execution_with_invalid_input():
    client = boto3.client("stepfunctions", region_name=region)
    #
    sm = client.create_state_machine(
        name="name", definition=str(simple_definition), roleArn=_get_default_role()
    )
    with pytest.raises(ClientError):
        client.start_execution(stateMachineArn=sm["stateMachineArn"], input="")
    with pytest.raises(ClientError):
        client.start_execution(stateMachineArn=sm["stateMachineArn"], input="{")


@mock_aws
def test_state_machine_list_executions():
    client = boto3.client("stepfunctions", region_name=region)
    #
    sm = client.create_state_machine(
        name="name", definition=str(simple_definition), roleArn=_get_default_role()
    )
    execution = client.start_execution(stateMachineArn=sm["stateMachineArn"])
    execution_arn = execution["executionArn"]
    execution_name = execution_arn[execution_arn.rindex(":") + 1 :]
    executions = client.list_executions(stateMachineArn=sm["stateMachineArn"])
    #
    assert executions["ResponseMetadata"]["HTTPStatusCode"] == 200
    assert len(executions["executions"]) == 1
    assert executions["executions"][0]["executionArn"] == execution_arn
    assert executions["executions"][0]["name"] == execution_name
    assert executions["executions"][0]["startDate"] == execution["startDate"]
    assert executions["executions"][0]["stateMachineArn"] == sm["stateMachineArn"]
    assert executions["executions"][0]["status"] == "RUNNING"
    assert "stopDate" not in executions["executions"][0]


@mock_aws
def test_state_machine_list_executions_with_filter():
    client = boto3.client("stepfunctions", region_name=region)
    sm = client.create_state_machine(
        name="name", definition=str(simple_definition), roleArn=_get_default_role()
    )
    for i in range(20):
        execution = client.start_execution(stateMachineArn=sm["stateMachineArn"])
        if not i % 4:
            client.stop_execution(executionArn=execution["executionArn"])

    resp = client.list_executions(stateMachineArn=sm["stateMachineArn"])
    assert len(resp["executions"]) == 20

    resp = client.list_executions(
        stateMachineArn=sm["stateMachineArn"], statusFilter="ABORTED"
    )
    assert len(resp["executions"]) == 5
    assert all(e["status"] == "ABORTED" for e in resp["executions"]) is True


@mock_aws
def test_state_machine_list_executions_with_pagination():
    client = boto3.client("stepfunctions", region_name=region)
    sm = client.create_state_machine(
        name="name", definition=str(simple_definition), roleArn=_get_default_role()
    )
    for _ in range(100):
        client.start_execution(stateMachineArn=sm["stateMachineArn"])

    resp = client.list_executions(stateMachineArn=sm["stateMachineArn"])
    assert "nextToken" not in resp
    assert len(resp["executions"]) == 100

    paginator = client.get_paginator("list_executions")
    page_iterator = paginator.paginate(
        stateMachineArn=sm["stateMachineArn"], maxResults=25
    )
    for page in page_iterator:
        assert len(page["executions"]) == 25

    with pytest.raises(ClientError) as ex:
        resp = client.list_executions(
            stateMachineArn=sm["stateMachineArn"], maxResults=10
        )
        client.list_executions(
            stateMachineArn=sm["stateMachineArn"],
            maxResults=10,
            statusFilter="ABORTED",
            nextToken=resp["nextToken"],
        )
    assert ex.value.response["Error"]["Code"] == "InvalidToken"
    assert "Input inconsistent with page token" in ex.value.response["Error"]["Message"]

    with pytest.raises(ClientError) as ex:
        client.list_executions(
            stateMachineArn=sm["stateMachineArn"], nextToken="invalid"
        )
    assert ex.value.response["Error"]["Code"] == "InvalidToken"


@mock_aws
def test_state_machine_list_executions_when_none_exist():
    client = boto3.client("stepfunctions", region_name=region)
    #
    sm = client.create_state_machine(
        name="name", definition=str(simple_definition), roleArn=_get_default_role()
    )
    executions = client.list_executions(stateMachineArn=sm["stateMachineArn"])
    #
    assert executions["ResponseMetadata"]["HTTPStatusCode"] == 200
    assert len(executions["executions"]) == 0


@mock_aws
def test_state_machine_describe_execution_with_no_input():
    client = boto3.client("stepfunctions", region_name=region)
    #
    sm = client.create_state_machine(
        name="name", definition=str(simple_definition), roleArn=_get_default_role()
    )
    execution = client.start_execution(stateMachineArn=sm["stateMachineArn"])
    description = client.describe_execution(executionArn=execution["executionArn"])
    #
    assert description["ResponseMetadata"]["HTTPStatusCode"] == 200
    assert description["executionArn"] == execution["executionArn"]
    assert description["input"] == "{}"
    assert re.match("[-0-9a-z]+", description["name"])
    assert description["startDate"] == execution["startDate"]
    assert description["stateMachineArn"] == sm["stateMachineArn"]
    assert description["status"] == "RUNNING"
    assert "stopDate" not in description


@mock_aws
def test_state_machine_describe_execution_with_custom_input():
    client = boto3.client("stepfunctions", region_name=region)
    #
    execution_input = json.dumps({"input_key": "input_val"})
    sm = client.create_state_machine(
        name="name", definition=str(simple_definition), roleArn=_get_default_role()
    )
    execution = client.start_execution(
        stateMachineArn=sm["stateMachineArn"], input=execution_input
    )
    description = client.describe_execution(executionArn=execution["executionArn"])
    #
    assert description["ResponseMetadata"]["HTTPStatusCode"] == 200
    assert description["executionArn"] == execution["executionArn"]
    assert description["input"] == execution_input
    assert re.match("[-a-z0-9]+", description["name"])
    assert description["startDate"] == execution["startDate"]
    assert description["stateMachineArn"] == sm["stateMachineArn"]
    assert description["status"] == "RUNNING"
    assert "stopDate" not in description


@mock_aws
def test_execution_throws_error_when_describing_unknown_execution():
    client = boto3.client("stepfunctions", region_name=region)
    #
    with pytest.raises(ClientError):
        unknown_execution = f"arn:aws:states:{region}:{ACCOUNT_ID}:execution:unknown"
        client.describe_execution(executionArn=unknown_execution)


@mock_aws
def test_state_machine_can_be_described_by_execution():
    client = boto3.client("stepfunctions", region_name=region)
    #
    sm = client.create_state_machine(
        name="name", definition=str(simple_definition), roleArn=_get_default_role()
    )
    execution = client.start_execution(stateMachineArn=sm["stateMachineArn"])
    desc = client.describe_state_machine_for_execution(
        executionArn=execution["executionArn"]
    )
    assert desc["ResponseMetadata"]["HTTPStatusCode"] == 200
    assert desc["definition"] == str(simple_definition)
    assert desc["name"] == "name"
    assert desc["roleArn"] == _get_default_role()
    assert desc["stateMachineArn"] == sm["stateMachineArn"]


@mock_aws
def test_state_machine_throws_error_when_describing_unknown_execution():
    client = boto3.client("stepfunctions", region_name=region)
    #
    with pytest.raises(ClientError):
        unknown_execution = f"arn:aws:states:{region}:{ACCOUNT_ID}:execution:unknown"
        client.describe_state_machine_for_execution(executionArn=unknown_execution)


@mock_aws
def test_state_machine_stop_execution():
    client = boto3.client("stepfunctions", region_name=region)
    #
    sm_arn = client.create_state_machine(
        name="name", definition=str(simple_definition), roleArn=_get_default_role()
    )["stateMachineArn"]
    start = client.start_execution(stateMachineArn=sm_arn)
    stop = client.stop_execution(executionArn=start["executionArn"])
    #
    assert stop["ResponseMetadata"]["HTTPStatusCode"] == 200
    assert isinstance(stop["stopDate"], datetime)

    description = client.describe_execution(executionArn=start["executionArn"])
    assert description["status"] == "ABORTED"
    assert isinstance(description["stopDate"], datetime)

    execution = client.list_executions(stateMachineArn=sm_arn)["executions"][0]
    assert isinstance(execution["stopDate"], datetime)


@mock_aws
def test_state_machine_stop_raises_error_when_unknown_execution():
    client = boto3.client("stepfunctions", region_name=region)
    client.create_state_machine(
        name="test-state-machine",
        definition=str(simple_definition),
        roleArn=_get_default_role(),
    )
    with pytest.raises(ClientError) as ex:
        unknown_execution = (
            f"arn:aws:states:{region}:{ACCOUNT_ID}:execution:test-state-machine:unknown"
        )
        client.stop_execution(executionArn=unknown_execution)
    assert ex.value.response["Error"]["Code"] == "ExecutionDoesNotExist"
    assert "Execution Does Not Exist:" in ex.value.response["Error"]["Message"]


@mock_aws
def test_state_machine_get_execution_history_throws_error_with_unknown_execution():
    client = boto3.client("stepfunctions", region_name=region)
    client.create_state_machine(
        name="test-state-machine",
        definition=str(simple_definition),
        roleArn=_get_default_role(),
    )
    with pytest.raises(ClientError) as ex:
        unknown_execution = (
            f"arn:aws:states:{region}:{ACCOUNT_ID}:execution:test-state-machine:unknown"
        )
        client.get_execution_history(executionArn=unknown_execution)
    assert ex.value.response["Error"]["Code"] == "ExecutionDoesNotExist"
    assert "Execution Does Not Exist:" in ex.value.response["Error"]["Message"]


@mock_aws
def test_state_machine_get_execution_history_contains_expected_success_events_when_started():
    expected_events = [
        {
            "timestamp": datetime(2020, 1, 1, 0, 0, 0, tzinfo=tzutc()),
            "type": "ExecutionStarted",
            "id": 1,
            "previousEventId": 0,
            "executionStartedEventDetails": {
                "input": "{}",
                "inputDetails": {"truncated": False},
                "roleArn": _get_default_role(),
            },
        },
        {
            "timestamp": datetime(2020, 1, 1, 0, 0, 10, tzinfo=tzutc()),
            "type": "PassStateEntered",
            "id": 2,
            "previousEventId": 0,
            "stateEnteredEventDetails": {
                "name": "A State",
                "input": "{}",
                "inputDetails": {"truncated": False},
            },
        },
        {
            "timestamp": datetime(2020, 1, 1, 0, 0, 10, tzinfo=tzutc()),
            "type": "PassStateExited",
            "id": 3,
            "previousEventId": 2,
            "stateExitedEventDetails": {
                "name": "A State",
                "output": "An output",
                "outputDetails": {"truncated": False},
            },
        },
        {
            "timestamp": datetime(2020, 1, 1, 0, 0, 20, tzinfo=tzutc()),
            "type": "ExecutionSucceeded",
            "id": 4,
            "previousEventId": 3,
            "executionSucceededEventDetails": {
                "output": "An output",
                "outputDetails": {"truncated": False},
            },
        },
    ]

    client = boto3.client("stepfunctions", region_name=region)
    sm = client.create_state_machine(
        name="test-state-machine",
        definition=simple_definition,
        roleArn=_get_default_role(),
    )
    execution = client.start_execution(stateMachineArn=sm["stateMachineArn"])
    execution_history = client.get_execution_history(
        executionArn=execution["executionArn"]
    )
    assert len(execution_history["events"]) == 4
    assert execution_history["events"] == expected_events


@mock.patch.dict("os.environ", {"MOTO_ENABLE_ISO_REGIONS": "true"})
@pytest.mark.parametrize(
    "test_region", ["us-west-2", "cn-northwest-1", "us-isob-east-1"]
)
@mock_aws
def test_stepfunction_regions(test_region):
    client = boto3.client("stepfunctions", region_name=test_region)
    resp = client.list_state_machines()
    assert resp["ResponseMetadata"]["HTTPStatusCode"] == 200

    response = client.create_state_machine(
        name="name", definition=str(simple_definition), roleArn=_get_default_role()
    )
    if test_region == "us-west-2":
        assert (
            response["stateMachineArn"]
            == f"arn:aws:states:{test_region}:{ACCOUNT_ID}:stateMachine:name"
        )
    if test_region == "cn-northwest-1":
        assert (
            response["stateMachineArn"]
            == f"arn:aws-cn:states:{test_region}:{ACCOUNT_ID}:stateMachine:name"
        )
    if test_region == "us-isob-east-1":
        assert (
            response["stateMachineArn"]
            == f"arn:aws-iso-b:states:{test_region}:{ACCOUNT_ID}:stateMachine:name"
        )


@mock_aws
@mock.patch.dict(os.environ, {"SF_EXECUTION_HISTORY_TYPE": "FAILURE"})
def test_state_machine_get_execution_history_contains_expected_failure_events_when_started():
    if os.environ.get("TEST_SERVER_MODE", "false").lower() == "true":
        raise SkipTest("Cant pass environment variable in server mode")
    expected_events = [
        {
            "timestamp": datetime(2020, 1, 1, 0, 0, 0, tzinfo=tzutc()),
            "type": "ExecutionStarted",
            "id": 1,
            "previousEventId": 0,
            "executionStartedEventDetails": {
                "input": "{}",
                "inputDetails": {"truncated": False},
                "roleArn": _get_default_role(),
            },
        },
        {
            "timestamp": datetime(2020, 1, 1, 0, 0, 10, tzinfo=tzutc()),
            "type": "FailStateEntered",
            "id": 2,
            "previousEventId": 0,
            "stateEnteredEventDetails": {
                "name": "A State",
                "input": "{}",
                "inputDetails": {"truncated": False},
            },
        },
        {
            "timestamp": datetime(2020, 1, 1, 0, 0, 10, tzinfo=tzutc()),
            "type": "ExecutionFailed",
            "id": 3,
            "previousEventId": 2,
            "executionFailedEventDetails": {
                "error": "AnError",
                "cause": "An error occurred!",
            },
        },
    ]

    client = boto3.client("stepfunctions", region_name=region)
    sm = client.create_state_machine(
        name="test-state-machine",
        definition=simple_definition,
        roleArn=_get_default_role(),
    )
    execution = client.start_execution(stateMachineArn=sm["stateMachineArn"])
    execution_history = client.get_execution_history(
        executionArn=execution["executionArn"]
    )
    assert len(execution_history["events"]) == 3
    assert execution_history["events"] == expected_events

    exc = client.describe_execution(executionArn=execution["executionArn"])
    assert exc["status"] == "FAILED"

    exc = client.list_executions(stateMachineArn=sm["stateMachineArn"])["executions"][0]
    assert exc["status"] == "FAILED"


@mock_aws
def test_state_machine_name_limits():
    # Setup
    client = boto3.client("stepfunctions", region_name=region)
    long_name = "t" * 81

    # Execute
    with pytest.raises(ClientError) as exc:
        client.create_state_machine(
            name=long_name,
            definition=simple_definition,
            roleArn=_get_default_role(),
        )

    # Verify
    assert exc.value.response["Error"]["Code"] == "ValidationException"
    assert exc.value.response["Error"]["Message"] == (
        f"1 validation error detected: Value '{long_name}' at 'name' "
        "failed to satisfy constraint: "
        "Member must have length less than or equal to 80"
    )


@mock_aws
def test_state_machine_execution_name_limits():
    # Setup
    client = boto3.client("stepfunctions", region_name=region)
    machine_name = "test_name"
    long_name = "t" * 81
    resp = client.create_state_machine(
        name=machine_name,
        definition=simple_definition,
        roleArn=_get_default_role(),
    )

    # Execute
    with pytest.raises(ClientError) as exc:
        client.start_execution(name=long_name, stateMachineArn=resp["stateMachineArn"])

    # Verify
    assert exc.value.response["Error"]["Code"] == "ValidationException"
    assert exc.value.response["Error"]["Message"] == (
        f"1 validation error detected: Value '{long_name}' at 'name' "
        "failed to satisfy constraint: "
        "Member must have length less than or equal to 80"
    )


@mock_aws
def test_version_is_only_available_when_published():
    iam = boto3.client("iam", region_name="us-east-1")
    role_name = f"sfn_role_{str(uuid4())[0:6]}"
    sfn_role = iam.create_role(
        RoleName=role_name,
        AssumeRolePolicyDocument=json.dumps(sfn_role_policy),
        Path="/",
    )["Role"]["Arn"]

    client = boto3.client("stepfunctions", region_name="us-east-1")

    name1 = f"sfn_name_{str(uuid4())[0:6]}"
    response = client.create_state_machine(
        name=name1, definition=simple_definition, roleArn=sfn_role
    )
    assert "stateMachineVersionArn" not in response
    arn1 = response["stateMachineArn"]

    resp = client.update_state_machine(
        stateMachineArn=arn1, publish=True, tracingConfiguration={"enabled": True}
    )
    assert resp["stateMachineVersionArn"] == f"{arn1}:1"

    resp = client.update_state_machine(
        stateMachineArn=arn1, tracingConfiguration={"enabled": False}
    )
    assert "stateMachineVersionArn" not in resp

    name2 = f"sfn_name_{str(uuid4())[0:6]}"
    response = client.create_state_machine(
        name=name2, definition=simple_definition, roleArn=sfn_role, publish=True
    )
    arn2 = response["stateMachineArn"]
    assert response["stateMachineVersionArn"] == f"{arn2}:1"

    resp = client.update_state_machine(
        stateMachineArn=arn2, publish=True, tracingConfiguration={"enabled": True}
    )
    assert resp["stateMachineVersionArn"] == f"{arn2}:2"


def _get_default_role():
    return "arn:aws:iam::" + ACCOUNT_ID + ":role/unknown_sf_role"


@mock_aws
def test_create_activity():
    client = boto3.client("stepfunctions", region_name=region)
    response = client.create_activity(
        name="test-activity",
        tags=[{"key": "activity-name", "value": "test-activity"}],
        encryptionConfiguration={
            "kmsKeyId": "test-id",
            "kmsDataKeyReusePeriodSeconds": 123,
            "type": "CUSTOMER_MANAGED_KMS_KEY",
        },
    )

    assert "creationDate" in response
    assert "activityArn" in response


@mock_aws
def test_create_activity_with_invalid_name():
    client = boto3.client("stepfunctions", region_name=region)

    invalid_names = [
        "with space",
        "with<bracket",
        "with>bracket",
        "with{bracket",
        "with}bracket",
        "with[bracket",
        "with]bracket",
        "with?wildcard",
        "with*wildcard",
        'special"char',
        "special#char",
        "special%char",
        "special\\char",
        "special^char",
        "special|char",
        "special~char",
        "special`char",
        "special$char",
        "special&char",
        "special,char",
        "special;char",
        "special:char",
        "special/char",
        "uni\u0000code",
        "uni\u0001code",
        "uni\u0002code",
        "uni\u0003code",
        "uni\u0004code",
        "uni\u0005code",
        "uni\u0006code",
        "uni\u0007code",
        "uni\u0008code",
        "uni\u0009code",
        "uni\u000acode",
        "uni\u000bcode",
        "uni\u000ccode",
        "uni\u000dcode",
        "uni\u000ecode",
        "uni\u000fcode",
        "uni\u0010code",
        "uni\u0011code",
        "uni\u0012code",
        "uni\u0013code",
        "uni\u0014code",
        "uni\u0015code",
        "uni\u0016code",
        "uni\u0017code",
        "uni\u0018code",
        "uni\u0019code",
        "uni\u001acode",
        "uni\u001bcode",
        "uni\u001ccode",
        "uni\u001dcode",
        "uni\u001ecode",
        "uni\u001fcode",
        "uni\u007fcode",
        "uni\u0080code",
        "uni\u0081code",
        "uni\u0082code",
        "uni\u0083code",
        "uni\u0084code",
        "uni\u0085code",
        "uni\u0086code",
        "uni\u0087code",
        "uni\u0088code",
        "uni\u0089code",
        "uni\u008acode",
        "uni\u008bcode",
        "uni\u008ccode",
        "uni\u008dcode",
        "uni\u008ecode",
        "uni\u008fcode",
        "uni\u0090code",
        "uni\u0091code",
        "uni\u0092code",
        "uni\u0093code",
        "uni\u0094code",
        "uni\u0095code",
        "uni\u0096code",
        "uni\u0097code",
        "uni\u0098code",
        "uni\u0099code",
        "uni\u009acode",
        "uni\u009bcode",
        "uni\u009ccode",
        "uni\u009dcode",
        "uni\u009ecode",
        "uni\u009fcode",
    ]

    for invalid_name in invalid_names:
        with pytest.raises(ClientError) as exc:
            client.create_activity(
                name=invalid_name,
                tags=[{"key": "activity-name", "value": "test-activity"}],
            )

        assert exc.value.response["Error"]["Code"] == "InvalidName"

    # Validate name too long error.
    with pytest.raises(ClientError) as exc:
        client.create_activity(
            name="test" * 25,  # 100 characters long.
            tags=[{"key": "activity-name", "value": "test-activity"}],
        )

    assert exc.value.response["Error"]["Code"] == "ValidationException"
    assert (
        "Member must have length less than or equal to 80"
        in exc.value.response["Error"]["Message"]
    )


@mock_aws
def test_create_activity_with_invalid_encryption_configuration():
    client = boto3.client("stepfunctions", region_name=region)

    # Missing `type` in encryptionConfiguration
    with pytest.raises(ParamValidationError) as exc:
        client.create_activity(
            name="test-activity",
            tags=[{"key": "activity-name", "value": "test-activity"}],
            encryptionConfiguration={
                "kmsKeyId": "test-id",
                "kmsDataKeyReusePeriodSeconds": 123,
            },
        )

    # `kmsKeyId` missing when `type` is `CUSTOMER_MANAGED_KMS_KEY`
    with pytest.raises(ClientError) as exc:
        client.create_activity(
            name="test-activity",
            tags=[{"key": "activity-name", "value": "test-activity"}],
            encryptionConfiguration={
                "kmsDataKeyReusePeriodSeconds": 123,
                "type": "CUSTOMER_MANAGED_KMS_KEY",
            },
        )
    assert exc.value.response["Error"]["Code"] == "InvalidEncryptionConfiguration"


@mock_aws
def test_create_activity_with_duplicate_name():
    client = boto3.client("stepfunctions", region_name=region)
    client.create_activity(
        name="test-activity",
        tags=[{"key": "activity-name", "value": "test-activity"}],
        encryptionConfiguration={
            "kmsKeyId": "test-id",
            "kmsDataKeyReusePeriodSeconds": 123,
            "type": "CUSTOMER_MANAGED_KMS_KEY",
        },
    )

    # Validate error if user tries to create activity with the existing name
    with pytest.raises(ClientError) as exc:
        client.create_activity(
            name="test-activity",
            tags=[{"key": "activity-name", "value": "test-activity"}],
            encryptionConfiguration={
                "kmsKeyId": "test-id",
                "kmsDataKeyReusePeriodSeconds": 123,
                "type": "CUSTOMER_MANAGED_KMS_KEY",
            },
        )

    assert exc.value.response["Error"]["Code"] == "ActivityAlreadyExists"


@mock_aws
def test_describe_activity():
    client = boto3.client("stepfunctions", region_name=region)
    activity = client.create_activity(
        name="test-activity",
        tags=[{"key": "activity-name", "value": "test-activity"}],
        encryptionConfiguration={
            "kmsKeyId": "test-id",
            "kmsDataKeyReusePeriodSeconds": 123,
            "type": "CUSTOMER_MANAGED_KMS_KEY",
        },
    )

    response = client.describe_activity(activityArn=activity["activityArn"])
    assert response["name"] == "test-activity"
    assert response["activityArn"] == activity["activityArn"]
    assert response["creationDate"] == activity["creationDate"]
    assert response["encryptionConfiguration"]["kmsKeyId"] == "test-id"
    assert response["encryptionConfiguration"]["kmsDataKeyReusePeriodSeconds"] == 123
    assert response["encryptionConfiguration"]["type"] == "CUSTOMER_MANAGED_KMS_KEY"


@mock_aws
def test_delete_activity():
    client = boto3.client("stepfunctions", region_name=region)
    activity = client.create_activity(
        name="test-activity",
        tags=[{"key": "activity-name", "value": "test-activity"}],
        encryptionConfiguration={
            "kmsKeyId": "test-id",
            "kmsDataKeyReusePeriodSeconds": 123,
            "type": "CUSTOMER_MANAGED_KMS_KEY",
        },
    )

    response = client.describe_activity(activityArn=activity["activityArn"])
    assert response["name"] == "test-activity"

    client.delete_activity(activityArn=activity["activityArn"])

    # Make sure activity is deleted.
    with pytest.raises(ClientError) as exc:
        client.describe_activity(activityArn=activity["activityArn"])

    assert exc.value.response["Error"]["Code"] == "ActivityDoesNotExist"


@mock_aws
def test_list_activities_returns_empty_list_by_default():
    client = boto3.client("stepfunctions", region_name=region)
    #
    activities = client.list_activities()
    assert activities["activities"] == []


@mock_aws
def test_list_activities_returns_created_activities():
    client = boto3.client("stepfunctions", region_name=region)
    activity1 = client.create_activity(
        name="test-activity-1",
        tags=[{"key": "activity-name", "value": "test-activity"}],
    )
    activity2 = client.create_activity(
        name="test-activity-2",
        tags=[{"key": "activity-name", "value": "test-activity"}],
    )
    activities = client.list_activities()

    assert activities["ResponseMetadata"]["HTTPStatusCode"] == 200
    assert len(activities["activities"]) == 2
    assert isinstance(activities["activities"][0]["creationDate"], datetime)
    assert activities["activities"][0]["creationDate"] == activity1["creationDate"]
    assert activities["activities"][0]["name"] == "test-activity-1"
    assert activities["activities"][0]["activityArn"] == activity1["activityArn"]
    assert isinstance(activities["activities"][1]["creationDate"], datetime)
    assert activities["activities"][1]["creationDate"] == activity2["creationDate"]
    assert activities["activities"][1]["name"] == "test-activity-2"
    assert activities["activities"][1]["activityArn"] == activity2["activityArn"]


@mock_aws
def test_list_activities_pagination():
    client = boto3.client("stepfunctions", region_name=region)
    for i in range(25):
        activity_name = f"test-activity-{i}"
        client.create_activity(
            name=activity_name,
            tags=[{"key": "activity-name", "value": f"test-activity-{i}"}],
        )

    resp = client.list_activities()
    assert "nextToken" not in resp
    assert len(resp["activities"]) == 25

    paginator = client.get_paginator("list_activities")
    page_iterator = paginator.paginate(maxResults=5)
    page_list = list(page_iterator)
    for page in page_list:
        assert len(page["activities"]) == 5
    assert "24" in page_list[-1]["activities"][-1]["name"]


@mock_aws
def test_activity_tagging():
    client = boto3.client("stepfunctions", region_name=region)
    # Test tags are added on resource creation
    tags = [
        {"key": "tag_key1", "value": "tag_value1"},
        {"key": "tag_key2", "value": "tag_value2"},
    ]
    activity = client.create_activity(
        name="test-with-tags",
        tags=tags,
    )
    resp = client.list_tags_for_resource(resourceArn=activity["activityArn"])
    assert resp["tags"] == tags

    # Test tags are added after creation with tag_resource
    activity = client.create_activity(
        name="test-activity",
    )
    client.tag_resource(resourceArn=activity["activityArn"], tags=tags)
    resp = client.list_tags_for_resource(resourceArn=activity["activityArn"])
    assert resp["tags"] == tags

    tags_update = [
        {"key": "tag_key1", "value": "tag_value1_new"},
        {"key": "tag_key3", "value": "tag_value3"},
    ]
    client.tag_resource(resourceArn=activity["activityArn"], tags=tags_update)
    resp = client.list_tags_for_resource(resourceArn=activity["activityArn"])
    tags_expected = [
        tags_update[0],
        tags[1],
        tags_update[1],
    ]
    assert resp["tags"] == tags_expected


@mock_aws
def test_activity_untagging():
    client = boto3.client("stepfunctions", region_name=region)
    tags = [
        {"key": "tag_key1", "value": "tag_value1"},
        {"key": "tag_key2", "value": "tag_value2"},
        {"key": "tag_key3", "value": "tag_value3"},
    ]
    activity = client.create_activity(
        name="test-activity",
        tags=tags,
    )
    resp = client.list_tags_for_resource(resourceArn=activity["activityArn"])
    assert resp["tags"] == tags
    tags_to_delete = ["tag_key1", "tag_key2"]
    client.untag_resource(resourceArn=activity["activityArn"], tagKeys=tags_to_delete)
    resp = client.list_tags_for_resource(resourceArn=activity["activityArn"])
    expected_tags = [tag for tag in tags if tag["key"] not in tags_to_delete]
    assert resp["tags"] == expected_tags


@mock_aws
def test_activity_list_tags_for_created_activity():
    client = boto3.client("stepfunctions", region_name=region)
    #
    activity = client.create_activity(
        name="test-activity",
        tags=[{"key": "tag_key", "value": "tag_value"}],
    )
    response = client.list_tags_for_resource(resourceArn=activity["activityArn"])
    tags = response["tags"]
    assert len(tags) == 1
    assert tags[0] == {"key": "tag_key", "value": "tag_value"}


@mock_aws
def test_activity_list_tags_for_activity_without_tags():
    client = boto3.client("stepfunctions", region_name=region)
    #
    activity = client.create_activity(name="test-activity")
    response = client.list_tags_for_resource(resourceArn=activity["activityArn"])
    tags = response["tags"]
    assert len(tags) == 0


@mock_aws
def test_activity_list_tags_for_nonexisting_activity():
    client = boto3.client("stepfunctions", region_name=region)
    #
    non_existing_activity = f"arn:aws:states:{region}:{ACCOUNT_ID}:activity:unknown"
    response = client.list_tags_for_resource(resourceArn=non_existing_activity)
    tags = response["tags"]
    assert len(tags) == 0