-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathhandlers_test.py
More file actions
2631 lines (2113 loc) · 86.2 KB
/
handlers_test.py
File metadata and controls
2631 lines (2113 loc) · 86.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
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
"""Tests for HTTP endpoint handlers."""
from __future__ import annotations
from typing import TYPE_CHECKING, Any
from unittest.mock import Mock
import pytest
from aws_durable_execution_sdk_python.lambda_service import (
ErrorObject,
Operation,
OperationStatus,
OperationType,
)
from aws_durable_execution_sdk_python_testing.exceptions import (
AwsApiException,
IllegalArgumentException,
IllegalStateException,
InvalidParameterValueException,
ResourceNotFoundException,
)
if TYPE_CHECKING:
from aws_durable_execution_sdk_python_testing.executor import Executor
from aws_durable_execution_sdk_python_testing.model import (
CheckpointDurableExecutionResponse,
Event,
ExecutionStartedDetails,
GetDurableExecutionHistoryResponse,
GetDurableExecutionResponse,
GetDurableExecutionStateResponse,
ListDurableExecutionsByFunctionResponse,
ListDurableExecutionsResponse,
SendDurableExecutionCallbackFailureRequest,
SendDurableExecutionCallbackFailureResponse,
SendDurableExecutionCallbackHeartbeatRequest,
SendDurableExecutionCallbackHeartbeatResponse,
SendDurableExecutionCallbackSuccessRequest,
SendDurableExecutionCallbackSuccessResponse,
StartDurableExecutionInput,
StartDurableExecutionOutput,
StopDurableExecutionResponse,
)
from aws_durable_execution_sdk_python_testing.model import (
Execution as ExecutionSummary,
)
from aws_durable_execution_sdk_python_testing.web import handlers
from aws_durable_execution_sdk_python_testing.web.handlers import (
CheckpointDurableExecutionHandler,
EndpointHandler,
GetDurableExecutionHandler,
GetDurableExecutionHistoryHandler,
GetDurableExecutionStateHandler,
HealthHandler,
ListDurableExecutionsByFunctionHandler,
ListDurableExecutionsHandler,
MetricsHandler,
SendDurableExecutionCallbackFailureHandler,
SendDurableExecutionCallbackHeartbeatHandler,
SendDurableExecutionCallbackSuccessHandler,
StartExecutionHandler,
StopDurableExecutionHandler,
)
from aws_durable_execution_sdk_python_testing.web.models import (
HTTPRequest,
HTTPResponse,
)
from aws_durable_execution_sdk_python_testing.web.routes import (
CallbackFailureRoute,
CallbackHeartbeatRoute,
CallbackSuccessRoute,
GetDurableExecutionRoute,
ListDurableExecutionsRoute,
Route,
Router,
StartExecutionRoute,
)
class MockableEndpointHandler(EndpointHandler):
"""Test-specific handler that exposes private methods for testing."""
def handle(self, parsed_route: Route, request: HTTPRequest) -> HTTPResponse:
"""Handle request - test implementation."""
return self._success_response({"test": "data"})
# Public methods that expose private functionality for testing
def parse_json_body(self, request: HTTPRequest) -> dict[str, Any]:
"""Public wrapper for _parse_json_body."""
return self._parse_json_body(request)
def json_response(
self,
status_code: int,
data: dict[str, Any],
additional_headers: dict[str, str] | None = None,
) -> HTTPResponse:
"""Public wrapper for _json_response."""
return self._json_response(status_code, data, additional_headers)
def success_response(
self, data: dict[str, Any], additional_headers: dict[str, str] | None = None
) -> HTTPResponse:
"""Public wrapper for _success_response."""
return self._success_response(data, additional_headers)
def created_response(
self, data: dict[str, Any], additional_headers: dict[str, str] | None = None
) -> HTTPResponse:
"""Public wrapper for _created_response."""
return self._created_response(data, additional_headers)
def no_content_response(
self, additional_headers: dict[str, str] | None = None
) -> HTTPResponse:
"""Public wrapper for _no_content_response."""
return self._no_content_response(additional_headers)
def parse_query_param(self, request: HTTPRequest, param_name: str) -> str | None:
"""Public wrapper for _parse_query_param."""
return self._parse_query_param(request, param_name)
def parse_query_param_list(
self, request: HTTPRequest, param_name: str
) -> list[str]:
"""Public wrapper for _parse_query_param_list."""
return self._parse_query_param_list(request, param_name)
def validate_required_fields(
self, data: dict[str, Any], required_fields: list[str]
) -> None:
"""Public wrapper for _validate_required_fields."""
return self._validate_required_fields(data, required_fields)
def test_endpoint_handler_initialization():
"""Test EndpointHandler initialization."""
executor = Mock()
handler = MockableEndpointHandler(executor)
assert handler.executor == executor
def test_endpoint_handler_parse_json_body_valid():
"""Test parse_json_body with valid JSON."""
executor = Mock()
handler = MockableEndpointHandler(executor)
request = HTTPRequest(
method="POST",
path=Route.from_string("/test"),
headers={"Content-Type": "application/json"},
query_params={},
body={"key": "value"},
)
result = handler.parse_json_body(request)
assert result == {"key": "value"}
def test_endpoint_handler_parse_json_body_empty():
"""Test parse_json_body with empty body."""
executor = Mock()
handler = MockableEndpointHandler(executor)
request = HTTPRequest(
method="POST",
path=Route.from_string("/test"),
headers={"Content-Type": "application/json"},
query_params={},
body={},
)
with pytest.raises(
InvalidParameterValueException, match="Request body is required"
):
handler.parse_json_body(request)
def test_endpoint_handler_parse_json_body_invalid():
"""Test parse_json_body with invalid JSON - now this test is not applicable since body is already a dict."""
executor = Mock()
handler = MockableEndpointHandler(executor)
# Since body is now a dict, this test case doesn't apply anymore
# The validation happens during HTTPRequest.from_bytes() deserialization
request = HTTPRequest(
method="POST",
path=Route.from_string("/test"),
headers={"Content-Type": "application/json"},
query_params={},
body={"valid": "json"}, # Body is always valid dict now
)
# This should work fine now since body is already parsed
result = handler.parse_json_body(request)
assert result == {"valid": "json"}
def test_endpoint_handler_json_response():
"""Test json_response method."""
executor = Mock()
handler = MockableEndpointHandler(executor)
response = handler.json_response(200, {"test": "data"})
assert response.status_code == 200
assert response.headers["Content-Type"] == "application/json"
assert response.body == {"test": "data"}
# Verify serialization to bytes works
body_bytes = response.body_to_bytes()
assert b'"test":"data"' in body_bytes
def test_endpoint_handler_success_response():
"""Test success_response method."""
executor = Mock()
handler = MockableEndpointHandler(executor)
response = handler.success_response({"test": "data"})
assert response.status_code == 200
assert response.headers["Content-Type"] == "application/json"
def test_endpoint_handler_created_response():
"""Test created_response method."""
executor = Mock()
handler = MockableEndpointHandler(executor)
response = handler.created_response({"test": "data"})
assert response.status_code == 201
assert response.headers["Content-Type"] == "application/json"
def test_endpoint_handler_no_content_response():
"""Test no_content_response method."""
executor = Mock()
handler = MockableEndpointHandler(executor)
response = handler.no_content_response()
assert response.status_code == 204
assert response.body == {}
def test_endpoint_handler_error_response():
"""Test error response creation using HTTPResponse.create_error_from_exception."""
# Test that we can create error responses using the new method
exception = InvalidParameterValueException("Bad request")
response = HTTPResponse.create_error_from_exception(exception)
assert response.status_code == 400
assert response.headers["Content-Type"] == "application/json"
# The new format doesn't wrap in an "error" object
# InvalidParameterValueException uses lowercase "message" per Smithy definition
expected_body = {
"Type": "InvalidParameterValueException",
"message": "Bad request",
}
assert response.body == expected_body
# Verify serialization to bytes works
body_bytes = response.body_to_bytes()
assert b'"message":"Bad request"' in body_bytes
assert b'"Type":"InvalidParameterValueException"' in body_bytes
def test_endpoint_handler_parse_query_param():
"""Test parse_query_param method."""
executor = Mock()
handler = MockableEndpointHandler(executor)
request = HTTPRequest(
method="GET",
path=Route.from_string("/test"),
headers={},
query_params={"param1": ["value1"], "param2": ["value2a", "value2b"]},
body={},
)
assert handler.parse_query_param(request, "param1") == "value1"
assert handler.parse_query_param(request, "param2") == "value2a" # First value
assert handler.parse_query_param(request, "nonexistent") is None
def test_endpoint_handler_parse_query_param_list():
"""Test parse_query_param_list method."""
executor = Mock()
handler = MockableEndpointHandler(executor)
request = HTTPRequest(
method="GET",
path=Route.from_string("/test"),
headers={},
query_params={"param1": ["value1"], "param2": ["value2a", "value2b"]},
body={},
)
assert handler.parse_query_param_list(request, "param1") == ["value1"]
assert handler.parse_query_param_list(request, "param2") == ["value2a", "value2b"]
assert handler.parse_query_param_list(request, "nonexistent") == []
def test_endpoint_handler_validate_required_fields_valid():
"""Test validate_required_fields with valid data."""
executor = Mock()
handler = MockableEndpointHandler(executor)
data = {"field1": "value1", "field2": "value2", "field3": "value3"}
required_fields = ["field1", "field2"]
# Should not raise an exception
handler.validate_required_fields(data, required_fields)
def test_endpoint_handler_validate_required_fields_missing():
"""Test validate_required_fields with missing fields."""
executor = Mock()
handler = MockableEndpointHandler(executor)
data = {"field1": "value1"}
required_fields = ["field1", "field2", "field3"]
with pytest.raises(
InvalidParameterValueException, match="Missing required fields: field2, field3"
):
handler.validate_required_fields(data, required_fields)
def test_start_execution_handler_success():
"""Test StartExecutionHandler with successful execution start."""
executor = Mock()
handler = StartExecutionHandler(executor)
# Mock successful executor response
mock_output = StartDurableExecutionOutput(execution_arn="test-execution-arn")
executor.start_execution.return_value = mock_output
# Create request with valid input data
request_data = {
"AccountId": "123456789012",
"FunctionName": "test-function",
"FunctionQualifier": "$LATEST",
"ExecutionName": "test-execution",
"ExecutionTimeoutSeconds": 300,
"ExecutionRetentionPeriodDays": 7,
"Input": '{"test": "data"}',
}
request = HTTPRequest(
method="POST",
path=StartExecutionRoute.from_string("/start-durable-execution"),
headers={"Content-Type": "application/json"},
query_params={},
body=request_data,
)
route = StartExecutionRoute.from_string("/start-durable-execution")
response = handler.handle(route, request)
# Verify response
assert response.status_code == 201
assert response.headers["Content-Type"] == "application/json"
assert response.body == {"ExecutionArn": "test-execution-arn"}
# Verify executor was called with correct input
executor.start_execution.assert_called_once()
call_args = executor.start_execution.call_args[0][0]
assert isinstance(call_args, StartDurableExecutionInput)
assert call_args.account_id == "123456789012"
assert call_args.function_name == "test-function"
assert call_args.execution_name == "test-execution"
def test_start_execution_handler_empty_body():
"""Test StartExecutionHandler with empty request body."""
executor = Mock()
handler = StartExecutionHandler(executor)
request = HTTPRequest(
method="POST",
path=StartExecutionRoute.from_string("/start-durable-execution"),
headers={"Content-Type": "application/json"},
query_params={},
body={},
)
route = StartExecutionRoute.from_string("/start-durable-execution")
response = handler.handle(route, request)
# Should return 400 Bad Request for empty body with AWS-compliant format
assert response.status_code == 400
assert response.body["Type"] == "InvalidParameterValueException"
assert "Request body is required" in response.body["message"]
def test_start_execution_handler_missing_required_fields():
"""Test StartExecutionHandler with missing required fields."""
executor = Mock()
handler = StartExecutionHandler(executor)
# Request missing required fields
request_data = {
"AccountId": "123456789012",
"FunctionName": "test-function",
# Missing other required fields
}
request = HTTPRequest(
method="POST",
path=StartExecutionRoute.from_string("/start-durable-execution"),
headers={"Content-Type": "application/json"},
query_params={},
body=request_data,
)
route = StartExecutionRoute.from_string("/start-durable-execution")
response = handler.handle(route, request)
# Should return 400 Bad Request for missing fields with AWS-compliant format
assert response.status_code == 400
assert response.body["Type"] == "InvalidParameterValueException"
assert "FunctionQualifier" in response.body["message"]
def test_start_execution_handler_invalid_parameter_error():
"""Test StartExecutionHandler with IllegalArgumentException from executor."""
executor = Mock()
handler = StartExecutionHandler(executor)
# Mock executor to raise IllegalArgumentException
executor.start_execution.side_effect = IllegalArgumentException(
"Invalid timeout value"
)
request_data = {
"AccountId": "123456789012",
"FunctionName": "test-function",
"FunctionQualifier": "$LATEST",
"ExecutionName": "test-execution",
"ExecutionTimeoutSeconds": -1, # Invalid value
"ExecutionRetentionPeriodDays": 7,
}
request = HTTPRequest(
method="POST",
path=StartExecutionRoute.from_string("/start-durable-execution"),
headers={"Content-Type": "application/json"},
query_params={},
body=request_data,
)
route = StartExecutionRoute.from_string("/start-durable-execution")
response = handler.handle(route, request)
# Should return 400 Bad Request with AWS-compliant format
assert response.status_code == 400
assert response.body["Type"] == "InvalidParameterValueException"
assert response.body["message"] == "Invalid timeout value"
def test_start_execution_handler_execution_already_exists():
"""Test StartExecutionHandler with execution already exists error."""
executor = Mock()
handler = StartExecutionHandler(executor)
# Mock executor to raise IllegalStateException (execution already exists)
executor.start_execution.side_effect = IllegalStateException(
"Execution with name 'test-execution' already exists"
)
request_data = {
"AccountId": "123456789012",
"FunctionName": "test-function",
"FunctionQualifier": "$LATEST",
"ExecutionName": "test-execution",
"ExecutionTimeoutSeconds": 300,
"ExecutionRetentionPeriodDays": 7,
}
request = HTTPRequest(
method="POST",
path=StartExecutionRoute.from_string("/start-durable-execution"),
headers={"Content-Type": "application/json"},
query_params={},
body=request_data,
)
route = StartExecutionRoute.from_string("/start-durable-execution")
response = handler.handle(route, request)
# Should return 409 Conflict with AWS-compliant format (ExecutionAlreadyStartedException has no Type field)
assert response.status_code == 409
assert "already exists" in response.body["message"]
assert (
response.body["DurableExecutionArn"]
== "arn:aws:lambda:us-east-1:123456789012:function:test"
)
assert (
"Type" not in response.body
) # ExecutionAlreadyStartedException doesn't have Type field
def test_start_execution_handler_unexpected_error():
"""Test StartExecutionHandler with unexpected error from executor."""
executor = Mock()
handler = StartExecutionHandler(executor)
# Mock executor to raise unexpected error
executor.start_execution.side_effect = RuntimeError("Unexpected database error")
request_data = {
"AccountId": "123456789012",
"FunctionName": "test-function",
"FunctionQualifier": "$LATEST",
"ExecutionName": "test-execution",
"ExecutionTimeoutSeconds": 300,
"ExecutionRetentionPeriodDays": 7,
}
request = HTTPRequest(
method="POST",
path=StartExecutionRoute.from_string("/start-durable-execution"),
headers={"Content-Type": "application/json"},
query_params={},
body=request_data,
)
route = StartExecutionRoute.from_string("/start-durable-execution")
response = handler.handle(route, request)
# Should return 500 Internal Server Error with AWS-compliant format
assert response.status_code == 500
assert response.body["Type"] == "ServiceException"
assert response.body["Message"] == "Unexpected database error"
def test_start_execution_handler_with_optional_fields():
"""Test StartExecutionHandler with optional fields included."""
executor = Mock()
handler = StartExecutionHandler(executor)
# Mock successful executor response
mock_output = StartDurableExecutionOutput(execution_arn="test-execution-arn")
executor.start_execution.return_value = mock_output
# Create request with optional fields
request_data = {
"AccountId": "123456789012",
"FunctionName": "test-function",
"FunctionQualifier": "$LATEST",
"ExecutionName": "test-execution",
"ExecutionTimeoutSeconds": 300,
"ExecutionRetentionPeriodDays": 7,
"InvocationId": "test-invocation-id",
"TraceFields": {"traceId": "test-trace"},
"TenantId": "test-tenant",
"Input": '{"test": "data"}',
}
request = HTTPRequest(
method="POST",
path=StartExecutionRoute.from_string("/start-durable-execution"),
headers={"Content-Type": "application/json"},
query_params={},
body=request_data,
)
route = StartExecutionRoute.from_string("/start-durable-execution")
response = handler.handle(route, request)
# Verify response
assert response.status_code == 201
assert response.body == {"ExecutionArn": "test-execution-arn"}
# Verify executor was called with correct input including optional fields
executor.start_execution.assert_called_once()
call_args = executor.start_execution.call_args[0][0]
assert isinstance(call_args, StartDurableExecutionInput)
assert call_args.invocation_id == "test-invocation-id"
assert call_args.trace_fields == {"traceId": "test-trace"}
assert call_args.tenant_id == "test-tenant"
assert call_args.input == '{"test": "data"}'
def test_get_durable_execution_handler_success():
"""Test GetDurableExecutionHandler with successful execution retrieval."""
executor = Mock()
handler = GetDurableExecutionHandler(executor)
# Mock the executor response
mock_response = GetDurableExecutionResponse(
durable_execution_arn="test-arn",
durable_execution_name="test-execution",
function_arn="arn:aws:lambda:us-east-1:123456789012:function:test-function",
status="SUCCEEDED",
start_timestamp="2023-01-01T00:00:00Z",
input_payload="test-input",
result="test-result",
error=None,
end_timestamp="2023-01-01T00:01:00Z",
version="1.0",
)
executor.get_execution_details.return_value = mock_response
# Create strongly-typed route
base_route = Route.from_string("/2025-12-01/durable-executions/test-arn")
typed_route = GetDurableExecutionRoute.from_route(base_route)
request = HTTPRequest(
method="GET",
path=typed_route,
headers={},
query_params={},
body={},
)
response = handler.handle(typed_route, request)
# Verify response
assert response.status_code == 200
expected_body = {
"DurableExecutionArn": "test-arn",
"DurableExecutionName": "test-execution",
"FunctionArn": "arn:aws:lambda:us-east-1:123456789012:function:test-function",
"Status": "SUCCEEDED",
"StartTimestamp": "2023-01-01T00:00:00Z",
"InputPayload": "test-input",
"Result": "test-result",
"EndTimestamp": "2023-01-01T00:01:00Z",
"Version": "1.0",
}
assert response.body == expected_body
# Verify executor was called with correct ARN
executor.get_execution_details.assert_called_once_with("test-arn")
def test_get_durable_execution_handler_resource_not_found():
"""Test GetDurableExecutionHandler with ResourceNotFoundException."""
executor = Mock()
handler = GetDurableExecutionHandler(executor)
# Mock executor to raise ResourceNotFoundException
executor.get_execution_details.side_effect = ResourceNotFoundException(
"Execution not-found-arn not found"
)
# Create strongly-typed route
base_route = Route.from_string("/2025-12-01/durable-executions/not-found-arn")
typed_route = GetDurableExecutionRoute.from_route(base_route)
request = HTTPRequest(
method="GET",
path=typed_route,
headers={},
query_params={},
body={},
)
response = handler.handle(typed_route, request)
# Verify error response with AWS-compliant format
assert response.status_code == 404
assert response.body["Type"] == "ResourceNotFoundException"
assert response.body["Message"] == "Execution not-found-arn not found"
# Verify executor was called
executor.get_execution_details.assert_called_once_with("not-found-arn")
def test_get_durable_execution_handler_invalid_parameter():
"""Test GetDurableExecutionHandler with IllegalArgumentException."""
executor = Mock()
handler = GetDurableExecutionHandler(executor)
# Mock executor to raise IllegalArgumentException
executor.get_execution_details.side_effect = IllegalArgumentException(
"Invalid execution ARN format"
)
# Create strongly-typed route
base_route = Route.from_string("/2025-12-01/durable-executions/invalid-arn")
typed_route = GetDurableExecutionRoute.from_route(base_route)
request = HTTPRequest(
method="GET",
path=typed_route,
headers={},
query_params={},
body={},
)
response = handler.handle(typed_route, request)
# Verify error response with AWS-compliant format
assert response.status_code == 400
assert response.body["Type"] == "InvalidParameterValueException"
assert response.body["message"] == "Invalid execution ARN format"
# Verify executor was called
executor.get_execution_details.assert_called_once_with("invalid-arn")
def test_get_durable_execution_handler_unexpected_error():
"""Test GetDurableExecutionHandler with unexpected error."""
executor = Mock()
handler = GetDurableExecutionHandler(executor)
# Mock executor to raise unexpected error
executor.get_execution_details.side_effect = RuntimeError("Unexpected error")
# Create strongly-typed route
base_route = Route.from_string("/2025-12-01/durable-executions/test-arn")
typed_route = GetDurableExecutionRoute.from_route(base_route)
request = HTTPRequest(
method="GET",
path=typed_route,
headers={},
query_params={},
body={},
)
response = handler.handle(typed_route, request)
# Verify error response with AWS-compliant format
assert response.status_code == 500
assert response.body["Type"] == "ServiceException"
assert response.body["Message"] == "Unexpected error"
# Verify executor was called
executor.get_execution_details.assert_called_once_with("test-arn")
def test_checkpoint_durable_execution_handler_success():
"""Test CheckpointDurableExecutionHandler with successful checkpoint processing."""
executor = Mock()
handler = CheckpointDurableExecutionHandler(executor)
# Mock the executor response
mock_response = CheckpointDurableExecutionResponse(
checkpoint_token="new-token-123", # noqa: S106
new_execution_state=None,
)
executor.checkpoint_execution.return_value = mock_response
# Create request with proper checkpoint data
request_body = {
"CheckpointToken": "current-token-123",
"Updates": [
{"Id": "op-1", "Type": "STEP", "Action": "SUCCEED", "SubType": "Step"}
],
"ClientToken": "client-token-123",
}
# Create strongly-typed route using Router
router = Router()
typed_route = router.find_route(
"/2025-12-01/durable-executions/test-arn/checkpoint", "POST"
)
request = HTTPRequest(
method="POST",
path=typed_route,
headers={"Content-Type": "application/json"},
query_params={},
body=request_body,
)
response = handler.handle(typed_route, request)
# Verify response
assert response.status_code == 200
assert response.body == {
"CheckpointToken": "new-token-123",
}
# Verify executor was called with correct parameters
executor.checkpoint_execution.assert_called_once()
call_args = executor.checkpoint_execution.call_args
assert call_args[0][0] == "test-arn" # execution_arn
assert call_args[0][1] == "current-token-123" # checkpoint_token
assert call_args[0][3] == "client-token-123" # client_token
# Verify the updates parameter
updates = call_args[0][2]
assert len(updates) == 1
assert updates[0].operation_id == "op-1"
def test_checkpoint_durable_execution_handler_invalid_request():
"""Test CheckpointDurableExecutionHandler with invalid request body."""
executor = Mock()
handler = CheckpointDurableExecutionHandler(executor)
# Create strongly-typed route using Router
router = Router()
typed_route = router.find_route(
"/2025-12-01/durable-executions/test-arn/checkpoint", "POST"
)
request = HTTPRequest(
method="POST",
path=typed_route,
headers={},
query_params={},
body={},
)
response = handler.handle(typed_route, request)
# Verify AWS-compliant error format
assert response.status_code == 400
assert response.body["Type"] == "InvalidParameterValueException"
assert "Request body is required" in response.body["message"]
def test_checkpoint_durable_execution_handler_invalid_checkpoint_exception():
"""Test CheckpointDurableExecutionHandler with IllegalStateException mapping to ServiceException."""
executor = Mock()
handler = CheckpointDurableExecutionHandler(executor)
# Mock executor to raise IllegalStateException
executor.checkpoint_execution.side_effect = IllegalStateException(
"Invalid checkpoint token"
)
request_body = {
"CheckpointToken": "invalid-token",
}
# Create strongly-typed route using Router
router = Router()
typed_route = router.find_route(
"/2025-12-01/durable-executions/test-arn/checkpoint", "POST"
)
request = HTTPRequest(
method="POST",
path=typed_route,
headers={"Content-Type": "application/json"},
query_params={},
body=request_body,
)
response = handler.handle(typed_route, request)
# Verify IllegalStateException maps to ServiceException in AWS-compliant format
assert response.status_code == 500
assert response.body["Type"] == "ServiceException"
assert response.body["Message"] == "Invalid checkpoint token"
def test_stop_durable_execution_handler_success():
"""Test StopDurableExecutionHandler with successful execution stop."""
executor = Mock()
handler = StopDurableExecutionHandler(executor)
# Mock the executor response
mock_response = StopDurableExecutionResponse(stop_timestamp="2023-01-01T00:01:00Z")
executor.stop_execution.return_value = mock_response
# Create request with proper stop data
request_body = {
"DurableExecutionArn": "test-arn",
"Error": {
"ErrorMessage": "User requested stop",
"ErrorType": "UserStop",
},
}
# Create strongly-typed route using Router
router = Router()
typed_route = router.find_route(
"/2025-12-01/durable-executions/test-arn/stop", "POST"
)
request = HTTPRequest(
method="POST",
path=typed_route,
headers={"Content-Type": "application/json"},
query_params={},
body=request_body,
)
response = handler.handle(typed_route, request)
# Verify response
assert response.status_code == 200
assert response.body == {"StopTimestamp": "2023-01-01T00:01:00Z"}
# Verify executor was called with correct parameters
executor.stop_execution.assert_called_once()
call_args = executor.stop_execution.call_args
assert call_args[0][0] == "test-arn" # execution_arn
def test_stop_durable_execution_handler_execution_already_stopped():
"""Test StopDurableExecutionHandler with execution already stopped error."""
executor = Mock()
handler = StopDurableExecutionHandler(executor)
# Mock executor to raise IllegalStateException
executor.stop_execution.side_effect = IllegalStateException(
"Execution test-arn is already completed"
)
request_body = {
"DurableExecutionArn": "test-arn",
}
# Create strongly-typed route using Router
router = Router()
typed_route = router.find_route(
"/2025-12-01/durable-executions/test-arn/stop", "POST"
)
request = HTTPRequest(
method="POST",
path=typed_route,
headers={"Content-Type": "application/json"},
query_params={},
body=request_body,
)
response = handler.handle(typed_route, request)
# Verify IllegalStateException maps to ServiceException in AWS-compliant format
assert response.status_code == 500
assert response.body["Type"] == "ServiceException"
assert response.body["Message"] == "Execution test-arn is already completed"
def test_stop_durable_execution_handler_resource_not_found():
"""Test StopDurableExecutionHandler with ResourceNotFoundException."""
executor = Mock()
handler = StopDurableExecutionHandler(executor)
# Mock executor to raise ResourceNotFoundException
executor.stop_execution.side_effect = ResourceNotFoundException(
"Execution not-found-arn not found"
)
request_body = {
"DurableExecutionArn": "not-found-arn",
}
# Create strongly-typed route using Router
router = Router()
typed_route = router.find_route(
"/2025-12-01/durable-executions/not-found-arn/stop", "POST"
)
request = HTTPRequest(
method="POST",
path=typed_route,
headers={"Content-Type": "application/json"},
query_params={},
body=request_body,
)
response = handler.handle(typed_route, request)
# Verify error response with AWS-compliant format
assert response.status_code == 404
assert response.body["Type"] == "ResourceNotFoundException"
assert response.body["Message"] == "Execution not-found-arn not found"
def test_get_durable_execution_state_handler_success():
"""Test GetDurableExecutionStateHandler with successful state retrieval."""
executor = Mock()
handler = GetDurableExecutionStateHandler(executor)
# Mock the executor response with operations
mock_operations = [
Operation(
operation_id="op-1",
operation_type=OperationType.STEP,
status=OperationStatus.SUCCEEDED,
name="test-step",
)
]