mirror of
https://github.com/floci-io/floci.git
synced 2026-12-01 01:12:48 -05:00
feat(sfn): support mocked service integrations (SFN_MOCK_CONFIG) (#2452)
* feat(sfn): support mocked service integrations (SFN_MOCK_CONFIG) StartExecution accepts a state machine ARN with a test case suffix in the Step Functions Local format. The test case comes from the mock configuration file named by SFN_MOCK_CONFIG. A mocked Task state returns the configured Return payload or fails with the configured Throw error instead of calling the integrated service. The mocked error and cause reach Retry and Catch unchanged. States not named in the test case still call their real integration, so mocked and real calls combine in one execution. Behavior was verified against Step Functions Local 2.0.0. Closes #2283 * fix(sfn): never retry or catch States.Runtime even when named explicitly * fix(sfn): keep a bare trailing '#' unstripped on StartSyncExecution
This commit is contained in:
1 parent
a68bfc4e68
commit
b6418dbfee
13 files changed
+1245
-32
No files matched your search
+253
@@ -0,0 +1,253 @@
|
||||
package io.github.hectorvent.floci.services.stepfunctions;
|
||||
|
||||
import com.fasterxml.jackson.databind.JsonNode;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.config.EmulatorConfig;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbJsonHandler;
|
||||
import io.github.hectorvent.floci.services.dynamodb.DynamoDbService;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaExecutorService;
|
||||
import io.github.hectorvent.floci.services.lambda.LambdaFunctionStore;
|
||||
import io.github.hectorvent.floci.services.s3.S3Service;
|
||||
import io.github.hectorvent.floci.services.sqs.SqsJsonHandler;
|
||||
import io.github.hectorvent.floci.services.stepfunctions.model.Execution;
|
||||
import io.github.hectorvent.floci.services.stepfunctions.model.HistoryEvent;
|
||||
import io.github.hectorvent.floci.services.stepfunctions.model.MockedResponseStep;
|
||||
import io.github.hectorvent.floci.services.stepfunctions.model.MockedTestCase;
|
||||
import io.github.hectorvent.floci.services.stepfunctions.model.StateMachine;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.vertx.mutiny.core.Vertx;
|
||||
import jakarta.enterprise.inject.Instance;
|
||||
import jakarta.inject.Inject;
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.mockito.Mockito.mock;
|
||||
import static org.mockito.Mockito.verifyNoInteractions;
|
||||
|
||||
@QuarkusTest
|
||||
class AslExecutorMockedResponsesTest {
|
||||
|
||||
private static final String REGION = "us-east-2";
|
||||
private static final String ACCOUNT = "000000000000";
|
||||
private static final String UNSUPPORTED_RESOURCE = "arn:aws:states:::apigateway:invoke";
|
||||
|
||||
private final ObjectMapper objectMapper = new ObjectMapper();
|
||||
private LambdaExecutorService lambdaExecutor;
|
||||
private AslExecutor executor;
|
||||
|
||||
@Inject
|
||||
Vertx vertx;
|
||||
|
||||
@BeforeEach
|
||||
void setUp() {
|
||||
lambdaExecutor = mock(LambdaExecutorService.class);
|
||||
|
||||
executor = new AslExecutor(
|
||||
lambdaExecutor,
|
||||
mock(LambdaFunctionStore.class),
|
||||
mock(DynamoDbService.class),
|
||||
mock(DynamoDbJsonHandler.class),
|
||||
mock(SqsJsonHandler.class),
|
||||
mock(io.github.hectorvent.floci.services.cloudformation.CloudFormationQueryHandler.class),
|
||||
mock(io.github.hectorvent.floci.services.ec2.Ec2Service.class),
|
||||
mock(S3Service.class),
|
||||
mock(io.github.hectorvent.floci.services.ecs.EcsService.class),
|
||||
mock(io.github.hectorvent.floci.services.ecs.EcsJsonHandler.class),
|
||||
objectMapper,
|
||||
new JsonataEvaluator(objectMapper),
|
||||
mock(Instance.class), mock(EmulatorConfig.class), vertx);
|
||||
}
|
||||
|
||||
@Test
|
||||
void mockedReturnReplacesUnsupportedResource() throws Exception {
|
||||
var mocks = testCase(Map.of("Call API", List.of(
|
||||
returnStep(0, 0, "{\"StatusCode\": 200, \"ResponseBody\": {\"id\": 1}}"))));
|
||||
|
||||
var execution = run("""
|
||||
{
|
||||
"StartAt": "Call API",
|
||||
"States": {
|
||||
"Call API": {
|
||||
"Type": "Task",
|
||||
"Resource": "%s",
|
||||
"End": true
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(UNSUPPORTED_RESOURCE), mocks);
|
||||
|
||||
assertEquals("SUCCEEDED", execution.getStatus());
|
||||
var output = objectMapper.readTree(execution.getOutput());
|
||||
assertEquals(200, output.path("StatusCode").asInt());
|
||||
assertEquals(1, output.path("ResponseBody").path("id").asInt());
|
||||
verifyNoInteractions(lambdaExecutor);
|
||||
}
|
||||
|
||||
@Test
|
||||
void mockedThrowKeepsErrorAndCauseThroughCatch() throws Exception {
|
||||
var mocks = testCase(Map.of("Call API", List.of(
|
||||
throwStep(0, 0, "ApiGateway.422", "Unprocessable"))));
|
||||
|
||||
var execution = run("""
|
||||
{
|
||||
"StartAt": "Call API",
|
||||
"States": {
|
||||
"Call API": {
|
||||
"Type": "Task",
|
||||
"Resource": "%s",
|
||||
"End": true,
|
||||
"Catch": [{
|
||||
"ErrorEquals": ["ApiGateway.422"],
|
||||
"Next": "HandleError"
|
||||
}]
|
||||
},
|
||||
"HandleError": {
|
||||
"Type": "Pass",
|
||||
"End": true
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(UNSUPPORTED_RESOURCE), mocks);
|
||||
|
||||
assertEquals("SUCCEEDED", execution.getStatus());
|
||||
var output = objectMapper.readTree(execution.getOutput());
|
||||
assertEquals("ApiGateway.422", output.path("Error").asText());
|
||||
assertEquals("Unprocessable", output.path("Cause").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
void attemptKeyedMocksDriveRetry() throws Exception {
|
||||
var mocks = testCase(Map.of("Call API", List.of(
|
||||
throwStep(0, 0, "ApiGateway.429", "Too many requests"),
|
||||
returnStep(1, 2, "{\"retried\": true}"))));
|
||||
|
||||
var execution = run("""
|
||||
{
|
||||
"StartAt": "Call API",
|
||||
"States": {
|
||||
"Call API": {
|
||||
"Type": "Task",
|
||||
"Resource": "%s",
|
||||
"End": true,
|
||||
"Retry": [{
|
||||
"ErrorEquals": ["ApiGateway.429"],
|
||||
"IntervalSeconds": 1,
|
||||
"BackoffRate": 1.0,
|
||||
"MaxAttempts": 2
|
||||
}]
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(UNSUPPORTED_RESOURCE), mocks);
|
||||
|
||||
assertEquals("SUCCEEDED", execution.getStatus());
|
||||
assertTrue(objectMapper.readTree(execution.getOutput()).path("retried").asBoolean());
|
||||
}
|
||||
|
||||
@Test
|
||||
void missingAttemptEntryFailsExecution() throws Exception {
|
||||
var mocks = testCase(Map.of("Call API", List.of(
|
||||
throwStep(0, 0, "ApiGateway.429", "Too many requests"))));
|
||||
|
||||
var execution = run("""
|
||||
{
|
||||
"StartAt": "Call API",
|
||||
"States": {
|
||||
"Call API": {
|
||||
"Type": "Task",
|
||||
"Resource": "%s",
|
||||
"End": true,
|
||||
"Retry": [{
|
||||
"ErrorEquals": ["ApiGateway.429"],
|
||||
"IntervalSeconds": 1,
|
||||
"BackoffRate": 1.0,
|
||||
"MaxAttempts": 2
|
||||
}]
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(UNSUPPORTED_RESOURCE), mocks);
|
||||
|
||||
assertEquals("FAILED", execution.getStatus());
|
||||
assertEquals("States.Runtime", execution.getError());
|
||||
assertTrue(execution.getCause().contains("attempt 1"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void statesRuntimeIsNotRetriedOrCaughtEvenWhenNamedExplicitly() throws Exception {
|
||||
var mocks = testCase(Map.of("Call API", List.of(
|
||||
throwStep(0, 0, "ApiGateway.429", "Too many requests"))));
|
||||
|
||||
var execution = run("""
|
||||
{
|
||||
"StartAt": "Call API",
|
||||
"States": {
|
||||
"Call API": {
|
||||
"Type": "Task",
|
||||
"Resource": "%s",
|
||||
"End": true,
|
||||
"Retry": [
|
||||
{
|
||||
"ErrorEquals": ["ApiGateway.429"],
|
||||
"IntervalSeconds": 1,
|
||||
"BackoffRate": 1.0,
|
||||
"MaxAttempts": 2
|
||||
},
|
||||
{
|
||||
"ErrorEquals": ["States.Runtime"],
|
||||
"MaxAttempts": 3
|
||||
}
|
||||
],
|
||||
"Catch": [{
|
||||
"ErrorEquals": ["States.Runtime"],
|
||||
"Next": "ShouldNotCatch"
|
||||
}]
|
||||
},
|
||||
"ShouldNotCatch": {"Type": "Pass", "End": true}
|
||||
}
|
||||
}
|
||||
""".formatted(UNSUPPORTED_RESOURCE), mocks);
|
||||
|
||||
assertEquals("FAILED", execution.getStatus());
|
||||
assertEquals("States.Runtime", execution.getError());
|
||||
assertTrue(execution.getCause().contains("attempt 1"));
|
||||
}
|
||||
|
||||
private MockedTestCase testCase(Map<String, List<MockedResponseStep>> stateResponses) {
|
||||
return new MockedTestCase("mock-test", "Case", stateResponses);
|
||||
}
|
||||
|
||||
private MockedResponseStep returnStep(int from, int to, String json) throws Exception {
|
||||
return new MockedResponseStep(from, to, objectMapper.readTree(json), null, null);
|
||||
}
|
||||
|
||||
private MockedResponseStep throwStep(int from, int to, String error, String cause) {
|
||||
return new MockedResponseStep(from, to, null, error, cause);
|
||||
}
|
||||
|
||||
private Execution run(String definition, MockedTestCase mocks) {
|
||||
var stateMachine = new StateMachine();
|
||||
stateMachine.setName("mock-test");
|
||||
stateMachine.setStateMachineArn("arn:aws:states:%s:%s:stateMachine:mock-test".formatted(REGION, ACCOUNT));
|
||||
stateMachine.setRoleArn("arn:aws:iam::%s:role/test-role".formatted(ACCOUNT));
|
||||
stateMachine.setDefinition(definition);
|
||||
|
||||
var execution = new Execution();
|
||||
execution.setName("mock-test-execution");
|
||||
execution.setExecutionArn(
|
||||
"arn:aws:states:%s:%s:execution:mock-test:mock-test-execution".formatted(REGION, ACCOUNT));
|
||||
execution.setStateMachineArn(stateMachine.getStateMachineArn());
|
||||
execution.setInput("{}");
|
||||
|
||||
var history = new ArrayList<HistoryEvent>();
|
||||
executor.executeSync(stateMachine, execution, history, mocks, (updated, events) -> {
|
||||
});
|
||||
return execution;
|
||||
}
|
||||
}
|
||||
+175
@@ -0,0 +1,175 @@
|
||||
package io.github.hectorvent.floci.services.stepfunctions;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.core.common.AwsException;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.io.TempDir;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.nio.file.Files;
|
||||
import java.nio.file.Path;
|
||||
import java.util.Optional;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertNull;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
|
||||
class SfnMockLoaderTest {
|
||||
|
||||
private static final String CONFIG = """
|
||||
{
|
||||
"StateMachines": {
|
||||
"Test": {
|
||||
"TestCases": {
|
||||
"Case": { "Call API": "ThrowThenOk" }
|
||||
}
|
||||
}
|
||||
},
|
||||
"MockedResponses": {
|
||||
"ThrowThenOk": {
|
||||
"0": { "Throw": { "Error": "ApiGateway.422", "Cause": "Unprocessable" } },
|
||||
"1-2": { "Return": { "StatusCode": 200 } }
|
||||
}
|
||||
}
|
||||
}
|
||||
""";
|
||||
|
||||
@TempDir
|
||||
Path tempDir;
|
||||
|
||||
private SfnMockLoader loader(String content) throws IOException {
|
||||
var file = tempDir.resolve("mock-config.json");
|
||||
Files.writeString(file, content);
|
||||
return new SfnMockLoader(Optional.of(file.toString()), new ObjectMapper());
|
||||
}
|
||||
|
||||
@Test
|
||||
void parsesReturnAndThrowStepsWithAttemptRanges() throws IOException {
|
||||
var testCase = loader(CONFIG).requireTestCase("Test", "Case");
|
||||
|
||||
assertEquals("Case", testCase.testCaseName());
|
||||
var steps = testCase.stateResponses().get("Call API");
|
||||
assertEquals(2, steps.size());
|
||||
|
||||
var throwStep = steps.get(0);
|
||||
assertTrue(throwStep.isThrow());
|
||||
assertTrue(throwStep.covers(0));
|
||||
assertFalse(throwStep.covers(1));
|
||||
assertEquals("ApiGateway.422", throwStep.errorName());
|
||||
assertEquals("Unprocessable", throwStep.errorCause());
|
||||
|
||||
var returnStep = steps.get(1);
|
||||
assertFalse(returnStep.isThrow());
|
||||
assertTrue(returnStep.covers(1));
|
||||
assertTrue(returnStep.covers(2));
|
||||
assertFalse(returnStep.covers(3));
|
||||
assertEquals(200, returnStep.returnResult().path("StatusCode").asInt());
|
||||
assertNull(returnStep.errorName());
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsUnknownStateMachine() throws IOException {
|
||||
var loader = loader(CONFIG);
|
||||
var e = assertThrows(AwsException.class, () -> loader.requireTestCase("Other", "Case"));
|
||||
assertTrue(e.getMessage().contains("Other"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsUnknownTestCase() throws IOException {
|
||||
var loader = loader(CONFIG);
|
||||
var e = assertThrows(AwsException.class, () -> loader.requireTestCase("Test", "Missing"));
|
||||
assertTrue(e.getMessage().contains("Missing"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsMissingMockedResponsesEntry() throws IOException {
|
||||
var loader = loader("""
|
||||
{
|
||||
"StateMachines": {
|
||||
"Test": { "TestCases": { "Case": { "Call API": "Nope" } } }
|
||||
},
|
||||
"MockedResponses": {}
|
||||
}
|
||||
""");
|
||||
var e = assertThrows(AwsException.class, () -> loader.requireTestCase("Test", "Case"));
|
||||
assertTrue(e.getMessage().contains("Nope"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsInvalidAttemptKey() throws IOException {
|
||||
var loader = loader("""
|
||||
{
|
||||
"StateMachines": {
|
||||
"Test": { "TestCases": { "Case": { "Call API": "Bad" } } }
|
||||
},
|
||||
"MockedResponses": {
|
||||
"Bad": { "first": { "Return": {} } }
|
||||
}
|
||||
}
|
||||
""");
|
||||
var e = assertThrows(AwsException.class, () -> loader.requireTestCase("Test", "Case"));
|
||||
assertTrue(e.getMessage().contains("first"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsStepWithBothReturnAndThrow() throws IOException {
|
||||
var loader = loader("""
|
||||
{
|
||||
"StateMachines": {
|
||||
"Test": { "TestCases": { "Case": { "Call API": "Both" } } }
|
||||
},
|
||||
"MockedResponses": {
|
||||
"Both": { "0": { "Return": {}, "Throw": { "Error": "X" } } }
|
||||
}
|
||||
}
|
||||
""");
|
||||
var e = assertThrows(AwsException.class, () -> loader.requireTestCase("Test", "Case"));
|
||||
assertTrue(e.getMessage().contains("exactly one of Return or Throw"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void rejectsThrowWithoutError() throws IOException {
|
||||
var loader = loader("""
|
||||
{
|
||||
"StateMachines": {
|
||||
"Test": { "TestCases": { "Case": { "Call API": "NoError" } } }
|
||||
},
|
||||
"MockedResponses": {
|
||||
"NoError": { "0": { "Throw": { "Cause": "no name" } } }
|
||||
}
|
||||
}
|
||||
""");
|
||||
var e = assertThrows(AwsException.class, () -> loader.requireTestCase("Test", "Case"));
|
||||
assertTrue(e.getMessage().contains("Error"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void reportsMissingFile() {
|
||||
var loader = new SfnMockLoader(
|
||||
Optional.of(tempDir.resolve("absent.json").toString()), new ObjectMapper());
|
||||
var e = assertThrows(AwsException.class, () -> loader.requireTestCase("Test", "Case"));
|
||||
assertTrue(e.getMessage().contains("not found"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void reportsUnconfiguredLoader() {
|
||||
var loader = new SfnMockLoader(Optional.empty(), new ObjectMapper());
|
||||
var e = assertThrows(AwsException.class, () -> loader.requireTestCase("Test", "Case"));
|
||||
assertTrue(e.getMessage().contains("SFN_MOCK_CONFIG"));
|
||||
}
|
||||
|
||||
@Test
|
||||
void reloadsFileWhenModified() throws IOException, InterruptedException {
|
||||
var file = tempDir.resolve("mock-config.json");
|
||||
Files.writeString(file, CONFIG);
|
||||
var loader = new SfnMockLoader(Optional.of(file.toString()), new ObjectMapper());
|
||||
assertEquals(2, loader.requireTestCase("Test", "Case").stateResponses().get("Call API").size());
|
||||
|
||||
Thread.sleep(1100);
|
||||
Files.writeString(file, CONFIG.replace("\"1-2\"", "\"1\""));
|
||||
var steps = loader.requireTestCase("Test", "Case").stateResponses().get("Call API");
|
||||
assertEquals(1, steps.get(1).toAttempt());
|
||||
}
|
||||
}
|
||||
+327
@@ -0,0 +1,327 @@
|
||||
package io.github.hectorvent.floci.services.stepfunctions;
|
||||
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
import io.github.hectorvent.floci.testing.RestAssuredJsonUtils;
|
||||
import io.quarkus.test.junit.QuarkusTest;
|
||||
import io.restassured.response.Response;
|
||||
import org.junit.jupiter.api.BeforeAll;
|
||||
import org.junit.jupiter.api.MethodOrderer;
|
||||
import org.junit.jupiter.api.Order;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.TestMethodOrder;
|
||||
|
||||
import static io.restassured.RestAssured.given;
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.junit.jupiter.api.Assertions.assertFalse;
|
||||
import static org.junit.jupiter.api.Assertions.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.fail;
|
||||
|
||||
/**
|
||||
* Integration tests for Step Functions Local compatible mocked service integrations:
|
||||
* StartExecution against {@code <stateMachineArn>#<testCaseName>} with the mock
|
||||
* configuration file from src/test/resources/fixtures/sfn-mock-config.json.
|
||||
*/
|
||||
@QuarkusTest
|
||||
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
|
||||
class StepFunctionsMockedServiceIntegrationTest {
|
||||
|
||||
private static final String SFN_CONTENT_TYPE = "application/x-amz-json-1.0";
|
||||
private static final String DDB_CONTENT_TYPE = "application/x-amz-json-1.0";
|
||||
private static final String ROLE_ARN = "arn:aws:iam::000000000000:role/test-role";
|
||||
private static final String TABLE_NAME = "sfn-mock-items";
|
||||
private static final String UNSUPPORTED_RESOURCE = "arn:aws:states:::apigateway:invoke";
|
||||
private static final ObjectMapper mapper = new ObjectMapper();
|
||||
|
||||
private static String mockSmArn;
|
||||
private static String ddbSmArn;
|
||||
private static String expressSmArn;
|
||||
|
||||
@BeforeAll
|
||||
static void configureRestAssured() {
|
||||
RestAssuredJsonUtils.configureAwsContentTypes();
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(0)
|
||||
void setup_createStateMachinesAndTable() {
|
||||
mockSmArn = createStateMachine("sfn-mock-test", null, """
|
||||
{
|
||||
"StartAt": "Call API",
|
||||
"States": {
|
||||
"Call API": {
|
||||
"Type": "Task",
|
||||
"Resource": "%s",
|
||||
"Retry": [{
|
||||
"ErrorEquals": ["ApiGateway.429"],
|
||||
"IntervalSeconds": 1,
|
||||
"BackoffRate": 1.0,
|
||||
"MaxAttempts": 2
|
||||
}],
|
||||
"Catch": [{
|
||||
"ErrorEquals": ["ApiGateway.422"],
|
||||
"ResultPath": "$.error",
|
||||
"Next": "HandleError"
|
||||
}],
|
||||
"End": true
|
||||
},
|
||||
"HandleError": {
|
||||
"Type": "Pass",
|
||||
"End": true
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(UNSUPPORTED_RESOURCE));
|
||||
|
||||
ddbSmArn = createStateMachine("sfn-mock-ddb-test", null, """
|
||||
{
|
||||
"StartAt": "Call API",
|
||||
"States": {
|
||||
"Call API": {
|
||||
"Type": "Task",
|
||||
"Resource": "%s",
|
||||
"ResultPath": "$.api",
|
||||
"Next": "Save"
|
||||
},
|
||||
"Save": {
|
||||
"Type": "Task",
|
||||
"Resource": "arn:aws:states:::dynamodb:putItem",
|
||||
"Parameters": {
|
||||
"TableName": "%s",
|
||||
"Item": {
|
||||
"pk": {"S": "mocked-run"},
|
||||
"statusCode": {"N.$": "States.Format('{}', $.api.StatusCode)"}
|
||||
}
|
||||
},
|
||||
"End": true
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(UNSUPPORTED_RESOURCE, TABLE_NAME));
|
||||
|
||||
expressSmArn = createStateMachine("sfn-mock-express-test", "EXPRESS", """
|
||||
{
|
||||
"StartAt": "Call API",
|
||||
"States": {
|
||||
"Call API": {
|
||||
"Type": "Task",
|
||||
"Resource": "%s",
|
||||
"End": true
|
||||
}
|
||||
}
|
||||
}
|
||||
""".formatted(UNSUPPORTED_RESOURCE));
|
||||
|
||||
given()
|
||||
.header("X-Amz-Target", "DynamoDB_20120810.CreateTable")
|
||||
.contentType(DDB_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"TableName": "%s",
|
||||
"KeySchema": [{"AttributeName": "pk", "KeyType": "HASH"}],
|
||||
"AttributeDefinitions": [{"AttributeName": "pk", "AttributeType": "S"}],
|
||||
"BillingMode": "PAY_PER_REQUEST"
|
||||
}
|
||||
""".formatted(TABLE_NAME))
|
||||
.when().post("/")
|
||||
.then().statusCode(200);
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(1)
|
||||
void mockedReturnRunsUnsupportedIntegrationToCompletion() throws Exception {
|
||||
var execArn = startExecution(mockSmArn + "#HappyPath", "{}");
|
||||
assertFalse(execArn.contains("#"));
|
||||
|
||||
var describe = waitForTerminalState(execArn);
|
||||
assertEquals("SUCCEEDED", describe.jsonPath().getString("status"));
|
||||
assertEquals(mockSmArn, describe.jsonPath().getString("stateMachineArn"));
|
||||
|
||||
var output = mapper.readTree(describe.jsonPath().getString("output"));
|
||||
assertEquals(200, output.path("StatusCode").asInt());
|
||||
assertEquals(1, output.path("ResponseBody").path("id").asInt());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(2)
|
||||
void mockedThrowReachesCatchWithErrorAndCauseUnchanged() throws Exception {
|
||||
var execArn = startExecution(mockSmArn + "#Throw422", "{}");
|
||||
|
||||
var describe = waitForTerminalState(execArn);
|
||||
assertEquals("SUCCEEDED", describe.jsonPath().getString("status"));
|
||||
|
||||
var output = mapper.readTree(describe.jsonPath().getString("output"));
|
||||
assertEquals("ApiGateway.422", output.path("error").path("Error").asText());
|
||||
assertEquals("Unprocessable", output.path("error").path("Cause").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(3)
|
||||
void mockedThrowIsRetriedUsingAttemptKeyedResponses() throws Exception {
|
||||
var execArn = startExecution(mockSmArn + "#RetryOnce", "{}");
|
||||
|
||||
var describe = waitForTerminalState(execArn);
|
||||
assertEquals("SUCCEEDED", describe.jsonPath().getString("status"));
|
||||
assertTrue(mapper.readTree(describe.jsonPath().getString("output"))
|
||||
.path("ResponseBody").path("retried").asBoolean());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(4)
|
||||
void mockedStateCombinesWithRealDynamoDbIntegration() throws Exception {
|
||||
var execArn = startExecution(ddbSmArn + "#MockedApiRealDdb", "{}");
|
||||
|
||||
var describe = waitForTerminalState(execArn);
|
||||
assertEquals("SUCCEEDED", describe.jsonPath().getString("status"));
|
||||
|
||||
var getItem = given()
|
||||
.header("X-Amz-Target", "DynamoDB_20120810.GetItem")
|
||||
.contentType(DDB_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"TableName": "%s",
|
||||
"Key": {"pk": {"S": "mocked-run"}}
|
||||
}
|
||||
""".formatted(TABLE_NAME))
|
||||
.when().post("/");
|
||||
getItem.then().statusCode(200);
|
||||
var item = mapper.readTree(getItem.body().asString()).path("Item");
|
||||
assertEquals("mocked-run", item.path("pk").path("S").asText());
|
||||
assertEquals("200", item.path("statusCode").path("N").asText());
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(5)
|
||||
void syncExecutionRejectsMockTestCases() {
|
||||
// Verified against Step Functions Local 2.0.0, which rejects the suffix here with
|
||||
// UnsupportedOperation.
|
||||
var resp = given()
|
||||
.header("X-Amz-Target", "AWSStepFunctions.StartSyncExecution")
|
||||
.contentType(SFN_CONTENT_TYPE)
|
||||
.body("""
|
||||
{"stateMachineArn": "%s#HappyPath", "input": "{}"}
|
||||
""".formatted(expressSmArn))
|
||||
.when().post("/");
|
||||
resp.then().statusCode(400);
|
||||
assertTrue(resp.body().asString().contains("not supported for the StartSyncExecution"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(9)
|
||||
void syncExecutionDoesNotStripABareSuffix() {
|
||||
// Verified against Step Functions Local 2.0.0. StartSyncExecution looks up the raw ARN,
|
||||
// so a bare trailing '#' fails with StateMachineDoesNotExist instead of running unmocked.
|
||||
var resp = given()
|
||||
.header("X-Amz-Target", "AWSStepFunctions.StartSyncExecution")
|
||||
.contentType(SFN_CONTENT_TYPE)
|
||||
.body("""
|
||||
{"stateMachineArn": "%s#", "input": "{}"}
|
||||
""".formatted(expressSmArn))
|
||||
.when().post("/");
|
||||
resp.then().statusCode(400);
|
||||
assertTrue(resp.body().asString().contains("does not exist"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(6)
|
||||
void executionWithoutTestCaseSuffixStillCallsRealIntegration() {
|
||||
var execArn = startExecution(mockSmArn, "{}");
|
||||
|
||||
var describe = waitForTerminalState(execArn);
|
||||
assertEquals("FAILED", describe.jsonPath().getString("status"));
|
||||
assertEquals("States.TaskFailed", describe.jsonPath().getString("error"));
|
||||
assertTrue(describe.jsonPath().getString("cause").contains("Unsupported resource"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(7)
|
||||
void unknownTestCaseIsRejected() {
|
||||
// Intentional deviation. Step Functions Local 2.0.0 returns a plain HTTP 500 with the
|
||||
// text "No mock map found for test DoesNotExist". Floci returns a structured 400 instead.
|
||||
var resp = given()
|
||||
.header("X-Amz-Target", "AWSStepFunctions.StartExecution")
|
||||
.contentType(SFN_CONTENT_TYPE)
|
||||
.body("""
|
||||
{"stateMachineArn": "%s#DoesNotExist", "input": "{}"}
|
||||
""".formatted(mockSmArn))
|
||||
.when().post("/");
|
||||
resp.then().statusCode(400);
|
||||
assertTrue(resp.body().asString().contains("DoesNotExist"));
|
||||
}
|
||||
|
||||
@Test
|
||||
@Order(8)
|
||||
void blankSuffixRunsWithoutMocks() {
|
||||
// Verified against Step Functions Local 2.0.0. A bare trailing '#' selects no test case
|
||||
// and the execution runs its real integrations.
|
||||
var execArn = startExecution(mockSmArn + "#", "{}");
|
||||
|
||||
var describe = waitForTerminalState(execArn);
|
||||
assertEquals("FAILED", describe.jsonPath().getString("status"));
|
||||
assertEquals("States.TaskFailed", describe.jsonPath().getString("error"));
|
||||
assertTrue(describe.jsonPath().getString("cause").contains("Unsupported resource"));
|
||||
}
|
||||
|
||||
private static String createStateMachine(String name, String type, String definition) {
|
||||
var typeField = type != null ? "\"type\": \"%s\",".formatted(type) : "";
|
||||
var resp = given()
|
||||
.header("X-Amz-Target", "AWSStepFunctions.CreateStateMachine")
|
||||
.contentType(SFN_CONTENT_TYPE)
|
||||
.body("""
|
||||
{
|
||||
"name": "%s",
|
||||
%s
|
||||
"roleArn": "%s",
|
||||
"definition": %s
|
||||
}
|
||||
""".formatted(name, typeField, ROLE_ARN, quote(definition)))
|
||||
.when().post("/");
|
||||
resp.then().statusCode(200);
|
||||
return resp.jsonPath().getString("stateMachineArn");
|
||||
}
|
||||
|
||||
private static String startExecution(String smArn, String input) {
|
||||
var resp = given()
|
||||
.header("X-Amz-Target", "AWSStepFunctions.StartExecution")
|
||||
.contentType(SFN_CONTENT_TYPE)
|
||||
.body("""
|
||||
{"stateMachineArn": "%s", "input": %s}
|
||||
""".formatted(smArn, quote(input)))
|
||||
.when().post("/");
|
||||
resp.then().statusCode(200);
|
||||
return resp.jsonPath().getString("executionArn");
|
||||
}
|
||||
|
||||
private static Response waitForTerminalState(String execArn) {
|
||||
for (var i = 0; i < 100; i++) {
|
||||
var resp = given()
|
||||
.header("X-Amz-Target", "AWSStepFunctions.DescribeExecution")
|
||||
.contentType(SFN_CONTENT_TYPE)
|
||||
.body("""
|
||||
{"executionArn": "%s"}
|
||||
""".formatted(execArn))
|
||||
.when().post("/");
|
||||
var status = resp.jsonPath().getString("status");
|
||||
if (!"RUNNING".equals(status)) {
|
||||
return resp;
|
||||
}
|
||||
try {
|
||||
Thread.sleep(100);
|
||||
} catch (InterruptedException e) {
|
||||
Thread.currentThread().interrupt();
|
||||
fail("Interrupted while waiting for execution " + execArn);
|
||||
}
|
||||
}
|
||||
fail("Execution did not complete within timeout: " + execArn);
|
||||
return null;
|
||||
}
|
||||
|
||||
private static String quote(String raw) {
|
||||
return "\"" + raw
|
||||
.replace("\\", "\\\\")
|
||||
.replace("\"", "\\\"")
|
||||
.replace("\n", "\\n")
|
||||
.replace("\r", "\\r")
|
||||
.replace("\t", "\\t")
|
||||
+ "\"";
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user