Skip to content

armgit / floci

Public Imported from GitHub
0

Light, fluffy, and always free - The AWS Local Emulator alternative

feat(sfn): support mocked service integrations (SFN_MOCK_CONFIG) (#2452)

TATSUNO “Taz” Yasuhirob6418dbfeea4
diff --git a/docs/services/step-functions.md b/docs/services/step-functions.md
index ada52fd411..0e8f39f3bf 100644
--- a/docs/services/step-functions.md
+++ b/docs/services/step-functions.md
@@ -66,11 +66,64 @@ uniformly between zero and the computed delay, as on AWS. One deviation. The del
between attempts is capped at 30 seconds, the same cap Floci applies to `Wait` states,
so emulated runs stay fast.
+## Mocked service integrations
+
+Floci supports the Step Functions Local mock configuration format
+(`MockConfigFile.json`). This lets a Task state return a predefined result or error
+instead of calling the integrated service. It is the standard way to unit test `Catch`
+and `Retry` branches, and it also lets you execute state machines whose integrations
+Floci does not implement yet.
+
+Point `SFN_MOCK_CONFIG` at the mock configuration file and start an execution against
+`<stateMachineArn>#<testCaseName>`:
+
+```bash
+# docker run -e SFN_MOCK_CONFIG=/tmp/mock.json -v ./MockConfigFile.json:/tmp/mock.json ...
+aws stepfunctions start-execution \
+ --state-machine-arn "$SM_ARN#Throw422" \
+ --input '{}' \
+ --endpoint-url $AWS_ENDPOINT_URL
+```
+
+```json
+{
+ "StateMachines": {
+ "Test": { "TestCases": { "Throw422": { "Call API": "ApiFailure" } } }
+ },
+ "MockedResponses": {
+ "ApiFailure": {
+ "0": { "Throw": { "Error": "ApiGateway.422", "Cause": "Unprocessable" } }
+ },
+ "ApiSuccess": {
+ "0-1": { "Return": { "StatusCode": 200, "ResponseBody": { "id": 1 } } }
+ }
+ }
+}
+```
+
+Each test case maps a state name to a `MockedResponses` entry. Each mocked response is
+keyed by retry attempt (`"0"`, `"1"`, or a range like `"1-2"`), so a state can fail on
+the first attempt and succeed on a retry. `Return` supplies the task result. `Throw`
+fails the task with the given `Error` and `Cause`, which flow through `Retry` and
+`Catch` unchanged. States not named in the test case run their real integration, so
+mocked and real service calls can be combined in one execution. The file is re-read
+when it changes, so it can be edited without restarting Floci.
+
+Behavior was verified against Step Functions Local 2.0.0. As there, `StartSyncExecution`
+rejects a test case suffix with `UnsupportedOperation` and does not strip a bare trailing
+`#`, a bare trailing `#` on `StartExecution` runs the execution unmocked, and a retry
+attempt with no mocked entry fails the execution with `States.Runtime`. One intentional deviation: Floci reports an unknown test case and any
+invalid mock configuration (unparseable file, bad attempt key, missing `MockedResponses`
+entry, `Return` and `Throw` together, `Throw` without `Error`) as a structured 400 error
+at `StartExecution`. Step Functions Local instead returns a plain HTTP 500 for most of
+these and starts the execution only to fail it with `States.Runtime` for the last two.
+
## Configuration
| Variable | Default | Description |
|---|---|---|
| `FLOCI_SERVICES_STEPFUNCTIONS_ENABLED` | `true` | Enable or disable the service |
+| `SFN_MOCK_CONFIG` | unset | Path to a Step Functions Local compatible mock configuration file (alias: `FLOCI_SERVICES_STEPFUNCTIONS_MOCK_CONFIG_FILE`) |
## Examples
diff --git a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
index 734958b721..813b118328 100644
--- a/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
+++ b/src/main/java/io/github/hectorvent/floci/config/EmulatorConfig.java
@@ -1162,6 +1162,16 @@ public interface EmulatorConfig {
/** Allows invoking plain HTTP endpoints. By default, AWS only allows HTTPS. */
@WithDefault("true")
boolean allowPlaintextHttp();
+
+ /**
+ * Path to a Step Functions Local compatible mock configuration file
+ * ({@code MockConfigFile.json}). When set, {@code StartExecution} on
+ * {@code <stateMachineArn>#<testCaseName>} runs the state machine with that test
+ * case's mocked service integration responses. The main application.yml defaults
+ * this to the {@code SFN_MOCK_CONFIG} environment variable for drop-in
+ * compatibility with Step Functions Local.
+ */
+ Optional<String> mockConfigFile();
}
interface SwfServiceConfig {
diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java
index 5ab24a1d21..4589329543 100644
--- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java
+++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutor.java
@@ -28,6 +28,8 @@ import io.github.hectorvent.floci.services.s3.model.S3Object;
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 com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.JsonNode;
@@ -71,6 +73,7 @@ import java.util.UUID;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
+import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
@@ -154,6 +157,7 @@ public class AslExecutor {
private final Instance<StepFunctionsService> sfnService;
private final WebClient webClient;
private final EmulatorConfig config;
+ private final Map<String, MockedTestCase> activeMocks = new ConcurrentHashMap<>();
private final ExecutorService executor = Executors.newCachedThreadPool(r -> {
Thread t = new Thread(r, "sfn-executor");
t.setDaemon(true);
@@ -201,6 +205,18 @@ public class AslExecutor {
*/
public void executeAsync(StateMachine sm, Execution exec, List<HistoryEvent> history,
BiConsumer<Execution, List<HistoryEvent>> onUpdate) {
+ executeAsync(sm, exec, history, null, onUpdate);
+ }
+
+ /**
+ * Variant of {@link #executeAsync(StateMachine, Execution, List, BiConsumer)} that runs the
+ * execution with a mock test case: Task states named in the test case return their mocked
+ * response instead of calling the integrated service.
+ */
+ public void executeAsync(StateMachine sm, Execution exec, List<HistoryEvent> history,
+ MockedTestCase mockedTestCase,
+ BiConsumer<Execution, List<HistoryEvent>> onUpdate) {
+ registerMocks(exec, mockedTestCase);
executor.submit(() -> runUnderExecutionAccount(sm, () -> doExecute(sm, exec, history, onUpdate)));
}
@@ -209,6 +225,17 @@ public class AslExecutor {
*/
public void executeSync(StateMachine sm, Execution exec, List<HistoryEvent> history,
BiConsumer<Execution, List<HistoryEvent>> onUpdate) {
+ executeSync(sm, exec, history, null, onUpdate);
+ }
+
+ /**
+ * Variant of {@link #executeSync(StateMachine, Execution, List, BiConsumer)} that runs the
+ * execution with a mock test case.
+ */
+ public void executeSync(StateMachine sm, Execution exec, List<HistoryEvent> history,
+ MockedTestCase mockedTestCase,
+ BiConsumer<Execution, List<HistoryEvent>> onUpdate) {
+ registerMocks(exec, mockedTestCase);
try {
Future<?> f = executor.submit(() ->
runUnderExecutionAccount(sm, () -> doExecute(sm, exec, history, onUpdate)));
@@ -371,6 +398,14 @@ public class AslExecutor {
exec.setStopDate(System.currentTimeMillis() / 1000.0);
exec.setStatus("FAILED");
onUpdate.accept(exec, history);
+ } finally {
+ activeMocks.remove(exec.getExecutionArn());
+ }
+ }
+
+ private void registerMocks(Execution exec, MockedTestCase mockedTestCase) {
+ if (mockedTestCase != null) {
+ activeMocks.put(exec.getExecutionArn(), mockedTestCase);
}
}
@@ -390,7 +425,7 @@ public class AslExecutor {
while (true) {
try {
return executeState(name, type, stateDef, input, history, eventId, sm, jsonata,
- topLevelQueryLanguage, context, variables);
+ topLevelQueryLanguage, context, variables, attempt);
} catch (FailStateException e) {
var retrierIndex = findMatchingRetrier(retriers, e);
if (retrierIndex < 0) {
@@ -455,10 +490,11 @@ public class AslExecutor {
private StateResult executeState(String name, String type, JsonNode stateDef, JsonNode input,
List<HistoryEvent> history, AtomicLong eventId, StateMachine sm,
boolean jsonata, String topLevelQueryLanguage, JsonNode context,
- ObjectNode variables) throws Exception {
+ ObjectNode variables, int attempt) throws Exception {
return switch (type) {
case "Pass" -> executePassState(stateDef, input, jsonata, context, variables);
- case "Task" -> executeTaskState(name, stateDef, input, history, eventId, sm, jsonata, context, variables);
+ case "Task" -> executeTaskState(name, stateDef, input, history, eventId, sm, jsonata, context,
+ variables, attempt);
case "Choice" -> executeChoiceState(stateDef, input, jsonata, context, variables);
case "Wait" -> executeWaitState(stateDef, input, jsonata, context, variables);
case "Succeed" -> executeSucceedState(stateDef, input, jsonata, context, variables);
@@ -496,14 +532,18 @@ public class AslExecutor {
private StateResult executeTaskState(String stateName, JsonNode stateDef, JsonNode input,
List<HistoryEvent> history, AtomicLong eventId, StateMachine sm,
- boolean jsonata, JsonNode context, ObjectNode variables) throws Exception {
- String resource = stateDef.path("Resource").asText();
- boolean isWaitForToken = resource.endsWith(".waitForTaskToken");
- String effectiveResource = isWaitForToken
+ boolean jsonata, JsonNode context, ObjectNode variables,
+ int attempt) throws Exception {
+ var resource = stateDef.path("Resource").asText();
+ var isWaitForToken = resource.endsWith(".waitForTaskToken");
+ var effectiveResource = isWaitForToken
? resource.substring(0, resource.length() - ".waitForTaskToken".length())
: resource;
- boolean isActivity = isActivityArn(effectiveResource);
- boolean needsToken = isWaitForToken || isActivity;
+ var isActivity = isActivityArn(effectiveResource);
+ var mockedSteps = findMockedResponses(context, stateName);
+ // A mocked task never calls the integrated service, so it neither registers a task token
+ // nor waits for one; the mocked response stands in for the whole interaction.
+ var needsToken = mockedSteps == null && (isWaitForToken || isActivity);
String taskToken = null;
CompletableFuture<JsonNode> tokenFuture = null;
@@ -515,18 +555,22 @@ public class AslExecutor {
JsonNode taskResult;
if (jsonata) {
- JsonNode effectiveInput = input;
+ var effectiveInput = input;
if (stateDef.has("Arguments")) {
- JsonNode statesVar = buildStatesVar(input, null, context);
+ var statesVar = buildStatesVar(input, null, context);
effectiveInput = jsonataEvaluator.resolveTemplate(stateDef.get("Arguments"), statesVar, variables);
}
- taskResult = invokeResource(effectiveResource, effectiveInput, sm, taskToken);
+ taskResult = mockedSteps != null
+ ? mockedTaskResult(mockedSteps, stateName, attempt)
+ : invokeResource(effectiveResource, effectiveInput, sm, taskToken);
} else {
- JsonNode effectiveInput = applyInputPath(stateDef, input);
+ var effectiveInput = applyInputPath(stateDef, input);
if (stateDef.has("Parameters")) {
effectiveInput = resolveParameters(stateDef.get("Parameters"), effectiveInput, context);
}
- taskResult = invokeResource(effectiveResource, effectiveInput, sm, taskToken);
+ taskResult = mockedSteps != null
+ ? mockedTaskResult(mockedSteps, stateName, attempt)
+ : invokeResource(effectiveResource, effectiveInput, sm, taskToken);
}
if (tokenFuture != null) {
@@ -547,6 +591,34 @@ public class AslExecutor {
}
}
+ private List<MockedResponseStep> findMockedResponses(JsonNode context, String stateName) {
+ if (activeMocks.isEmpty()) {
+ return null;
+ }
+ var executionArn = context.path("Execution").path("Id").asText(null);
+ if (executionArn == null) {
+ return null;
+ }
+ var testCase = activeMocks.get(executionArn);
+ return testCase != null ? testCase.stateResponses().get(stateName) : null;
+ }
+
+ private JsonNode mockedTaskResult(List<MockedResponseStep> steps, String stateName, int attempt) {
+ for (var step : steps) {
+ if (step.covers(attempt)) {
+ if (step.isThrow()) {
+ // The mocked Error and Cause must reach Retry/Catch unchanged; routing them
+ // through integration error translation would rewrite the error name that
+ // catchers match on.
+ throw new FailStateException(step.errorName(), step.errorCause());
+ }
+ return step.returnResult().deepCopy();
+ }
+ }
+ throw new FailStateException("States.Runtime",
+ "No mocked response defined for attempt " + attempt + " of state '" + stateName + "'");
+ }
+
private JsonNode awaitToken(CompletableFuture<JsonNode> future, JsonNode stateDef) throws Exception {
int timeout = stateDef.path("HeartbeatSeconds").asInt(0);
if (timeout <= 0) {
@@ -3081,22 +3153,25 @@ public class AslExecutor {
}
private boolean catchMatches(JsonNode catcher, String error) {
- JsonNode errors = catcher.path("ErrorEquals");
+ var errors = catcher.path("ErrorEquals");
if (!errors.isArray()) {
return false;
}
+ // States.Runtime is never retried or caught, even when named explicitly in
+ // ErrorEquals. Verified against real AWS: the execution fails immediately.
+ if ("States.Runtime".equals(error)) {
+ return false;
+ }
for (JsonNode candidate : errors) {
- String expected = candidate.asText();
+ var expected = candidate.asText();
if (expected.equals(error)) {
return true;
}
if ("States.TaskFailed".equals(expected)
- && !"States.Timeout".equals(error)
- && !"States.Runtime".equals(error)) {
+ && !"States.Timeout".equals(error)) {
return true;
}
if ("States.ALL".equals(expected)
- && !"States.Runtime".equals(error)
&& !"States.DataLimitExceeded".equals(error)) {
return true;
}
diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/SfnMockLoader.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/SfnMockLoader.java
new file mode 100644
index 0000000000..2035aa62b3
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/SfnMockLoader.java
@@ -0,0 +1,179 @@
+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.core.common.AwsException;
+import io.github.hectorvent.floci.services.stepfunctions.model.MockedResponseStep;
+import io.github.hectorvent.floci.services.stepfunctions.model.MockedTestCase;
+import jakarta.enterprise.context.ApplicationScoped;
+import jakarta.inject.Inject;
+import org.jboss.logging.Logger;
+
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.ArrayList;
+import java.util.Comparator;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.Optional;
+
+/**
+ * Loads the Step Functions Local compatible mock configuration file
+ * ({@code MockConfigFile.json}) referenced by {@code SFN_MOCK_CONFIG} or
+ * {@code floci.services.stepfunctions.mock-config-file}. The file is re-read when its
+ * modification time changes, so it can be edited without restarting the emulator.
+ */
+@ApplicationScoped
+public class SfnMockLoader {
+
+ private static final Logger LOG = Logger.getLogger(SfnMockLoader.class);
+
+ private final Optional<String> configuredPath;
+ private final ObjectMapper objectMapper;
+ private volatile CachedMockFile cache;
+
+ private record CachedMockFile(String path, long lastModified, JsonNode root) {
+ }
+
+ @Inject
+ public SfnMockLoader(EmulatorConfig config, ObjectMapper objectMapper) {
+ this(config.services().stepfunctions().mockConfigFile(), objectMapper);
+ }
+
+ SfnMockLoader(Optional<String> configuredPath, ObjectMapper objectMapper) {
+ this.configuredPath = configuredPath.filter(path -> !path.isBlank());
+ this.objectMapper = objectMapper;
+ }
+
+ /**
+ * Resolves a test case selected via {@code StartExecution} on
+ * {@code <stateMachineArn>#<testCaseName>}. Throws {@code ValidationException} when no
+ * mock configuration is configured or the test case cannot be resolved from it.
+ */
+ public MockedTestCase requireTestCase(String stateMachineName, String testCaseName) {
+ var path = configuredPath.orElseThrow(() -> new AwsException("ValidationException",
+ "Cannot run test case '" + testCaseName + "': no mock configuration file is configured. "
+ + "Set SFN_MOCK_CONFIG to the path of a mock configuration file.", 400));
+ var root = load(path);
+ var testCases = root.path("StateMachines").path(stateMachineName).path("TestCases");
+ if (!testCases.isObject()) {
+ throw new AwsException("ValidationException",
+ "State machine '" + stateMachineName + "' has no test cases in mock configuration file "
+ + path, 400);
+ }
+ var testCase = testCases.path(testCaseName);
+ if (!testCase.isObject()) {
+ throw new AwsException("ValidationException",
+ "Test case '" + testCaseName + "' is not defined for state machine '" + stateMachineName
+ + "' in mock configuration file " + path, 400);
+ }
+ var mockedResponses = root.path("MockedResponses");
+ var stateResponses = new LinkedHashMap<String, List<MockedResponseStep>>();
+ testCase.fields().forEachRemaining(entry -> {
+ var stateName = entry.getKey();
+ var responseKey = entry.getValue();
+ if (!responseKey.isTextual()) {
+ throw new AwsException("ValidationException",
+ "Test case '" + testCaseName + "' state '" + stateName
+ + "' must reference a MockedResponses entry by name", 400);
+ }
+ var responseNode = mockedResponses.path(responseKey.asText());
+ if (!responseNode.isObject()) {
+ throw new AwsException("ValidationException",
+ "Mocked response '" + responseKey.asText() + "' referenced by test case '"
+ + testCaseName + "' state '" + stateName + "' is not defined", 400);
+ }
+ stateResponses.put(stateName, parseSteps(responseKey.asText(), responseNode));
+ });
+ LOG.debugv("Resolved mock test case {0}#{1} covering states {2}",
+ stateMachineName, testCaseName, stateResponses.keySet());
+ return new MockedTestCase(stateMachineName, testCaseName, Map.copyOf(stateResponses));
+ }
+
+ private JsonNode load(String path) {
+ var file = Path.of(path);
+ long lastModified;
+ try {
+ lastModified = Files.getLastModifiedTime(file).toMillis();
+ } catch (IOException e) {
+ throw new AwsException("ValidationException",
+ "Mock configuration file not found: " + path, 400);
+ }
+ var cached = cache;
+ if (cached != null && cached.path().equals(path) && cached.lastModified() == lastModified) {
+ return cached.root();
+ }
+ JsonNode root;
+ try {
+ root = objectMapper.readTree(Files.readAllBytes(file));
+ } catch (IOException e) {
+ throw new AwsException("ValidationException",
+ "Failed to read mock configuration file " + path + ": " + e.getMessage(), 400);
+ }
+ if (root == null || !root.isObject()) {
+ throw new AwsException("ValidationException",
+ "Mock configuration file " + path + " must contain a JSON object", 400);
+ }
+ cache = new CachedMockFile(path, lastModified, root);
+ return root;
+ }
+
+ private List<MockedResponseStep> parseSteps(String responseKey, JsonNode responseNode) {
+ var steps = new ArrayList<MockedResponseStep>();
+ responseNode.fields().forEachRemaining(
+ entry -> steps.add(parseStep(responseKey, entry.getKey(), entry.getValue())));
+ if (steps.isEmpty()) {
+ throw new AwsException("ValidationException",
+ "Mocked response '" + responseKey + "' must define at least one attempt entry", 400);
+ }
+ steps.sort(Comparator.comparingInt(MockedResponseStep::fromAttempt));
+ return List.copyOf(steps);
+ }
+
+ private MockedResponseStep parseStep(String responseKey, String attemptRange, JsonNode step) {
+ var range = parseAttemptRange(responseKey, attemptRange);
+ var returnNode = step.get("Return");
+ var throwNode = step.get("Throw");
+ if ((returnNode == null) == (throwNode == null)) {
+ throw new AwsException("ValidationException",
+ "Mocked response '" + responseKey + "' attempt '" + attemptRange
+ + "' must contain exactly one of Return or Throw", 400);
+ }
+ if (returnNode != null) {
+ return new MockedResponseStep(range[0], range[1], returnNode, null, null);
+ }
+ var error = throwNode.path("Error").asText(null);
+ if (error == null || error.isBlank()) {
+ throw new AwsException("ValidationException",
+ "Mocked response '" + responseKey + "' attempt '" + attemptRange
+ + "' Throw must contain a non-empty Error", 400);
+ }
+ return new MockedResponseStep(range[0], range[1], null, error, throwNode.path("Cause").asText(""));
+ }
+
+ private int[] parseAttemptRange(String responseKey, String attemptRange) {
+ try {
+ var separator = attemptRange.indexOf('-');
+ int from;
+ int to;
+ if (separator < 0) {
+ from = Integer.parseInt(attemptRange.trim());
+ to = from;
+ } else {
+ from = Integer.parseInt(attemptRange.substring(0, separator).trim());
+ to = Integer.parseInt(attemptRange.substring(separator + 1).trim());
+ }
+ if (from < 0 || to < from) {
+ throw new NumberFormatException(attemptRange);
+ }
+ return new int[] {from, to};
+ } catch (NumberFormatException e) {
+ throw new AwsException("ValidationException",
+ "Mocked response '" + responseKey + "' has an invalid attempt key '" + attemptRange
+ + "'; expected a number like \"0\" or a range like \"1-2\"", 400);
+ }
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsService.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsService.java
index 857f80e893..e71dae0d5a 100644
--- a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsService.java
+++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsService.java
@@ -12,6 +12,7 @@ import io.github.hectorvent.floci.services.stepfunctions.model.Activity;
import io.github.hectorvent.floci.services.stepfunctions.model.ActivityTask;
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.MockedTestCase;
import io.github.hectorvent.floci.services.stepfunctions.model.StateMachine;
import io.github.hectorvent.floci.services.stepfunctions.model.StateMachineVersion;
import io.github.hectorvent.floci.core.common.Resettable;
@@ -45,6 +46,7 @@ public class StepFunctionsService implements Resettable {
private final RegionResolver regionResolver;
private final AslExecutor aslExecutor;
private final ObjectMapper objectMapper;
+ private final SfnMockLoader mockLoader;
// Fields that are valid only in JSONPath mode. Validated against real AWS:
// creating a JSONata state machine with any of these fields returns SCHEMA_VALIDATION_FAILED.
@@ -62,7 +64,8 @@ public class StepFunctionsService implements Resettable {
@Inject
public StepFunctionsService(StorageFactory storageFactory, RegionResolver regionResolver,
- AslExecutor aslExecutor, ObjectMapper objectMapper) {
+ AslExecutor aslExecutor, ObjectMapper objectMapper,
+ SfnMockLoader mockLoader) {
this.stateMachineStore = storageFactory.create("stepfunctions", "sfn-state-machines.json",
new TypeReference<Map<String, StateMachine>>() {});
this.executionStore = storageFactory.create("stepfunctions", "sfn-executions.json",
@@ -72,6 +75,7 @@ public class StepFunctionsService implements Resettable {
this.regionResolver = regionResolver;
this.aslExecutor = aslExecutor;
this.objectMapper = objectMapper;
+ this.mockLoader = mockLoader;
}
public void clear() {
@@ -457,25 +461,27 @@ public class StepFunctionsService implements Resettable {
// ──────────────────────────── Executions ────────────────────────────
public Execution startExecution(String stateMachineArn, String name, String input, String region) {
- StateMachine sm = describeStateMachine(stateMachineArn);
- String execName = (name != null && !name.isBlank()) ? name : UUID.randomUUID().toString();
- String arn = regionResolver.buildArn("states", region, "execution:" + sm.getName() + ":" + execName);
+ var selection = splitTestCaseSuffix(stateMachineArn);
+ var sm = describeStateMachine(selection.stateMachineArn());
+ var mockedTestCase = resolveMockedTestCase(sm, selection);
+ var execName = (name != null && !name.isBlank()) ? name : UUID.randomUUID().toString();
+ var arn = regionResolver.buildArn("states", region, "execution:" + sm.getName() + ":" + execName);
if (executionStore.get(arn).isPresent()) {
throw new AwsException("ExecutionAlreadyExists", "Execution already exists: " + arn, 400);
}
- Execution exec = new Execution();
+ var exec = new Execution();
exec.setExecutionArn(arn);
- exec.setStateMachineArn(stateMachineArn);
+ exec.setStateMachineArn(selection.stateMachineArn());
exec.setName(execName);
exec.setInput(input);
exec.setStatus("RUNNING");
executionStore.put(arn, exec);
- List<HistoryEvent> history = new ArrayList<>();
- HistoryEvent startEvent = new HistoryEvent();
+ var history = new ArrayList<HistoryEvent>();
+ var startEvent = new HistoryEvent();
startEvent.setId(1L);
startEvent.setType("ExecutionStarted");
startEvent.setDetails(Map.of("input", input != null ? input : "{}",
@@ -485,7 +491,7 @@ public class StepFunctionsService implements Resettable {
LOG.infov("Started execution: {0}", arn);
- aslExecutor.executeAsync(sm, exec, history, (updatedExec, updatedHistory) -> {
+ aslExecutor.executeAsync(sm, exec, history, mockedTestCase, (updatedExec, updatedHistory) -> {
executionStore.put(updatedExec.getExecutionArn(), updatedExec);
historyCache.put(updatedExec.getExecutionArn(), updatedHistory);
LOG.infov("Execution {0} completed with status {1}", updatedExec.getExecutionArn(), updatedExec.getStatus());
@@ -495,7 +501,16 @@ public class StepFunctionsService implements Resettable {
}
public Execution startSyncExecution(String stateMachineArn, String name, String input, String region) {
- StateMachine sm = describeStateMachine(stateMachineArn);
+ var selection = splitTestCaseSuffix(stateMachineArn);
+ if (selection.testCaseName() != null) {
+ // Matches Step Functions Local, which rejects a test case suffix here.
+ throw new AwsException("UnsupportedOperation",
+ "Service integration mocking is not supported for the StartSyncExecution operation.",
+ 400);
+ }
+ // A bare trailing '#' is not stripped on this operation: Step Functions Local looks up
+ // the raw ARN and fails with StateMachineDoesNotExist, so Floci does the same.
+ var sm = describeStateMachine(stateMachineArn);
if (!"EXPRESS".equals(sm.getType())) {
throw new AwsException("StateMachineTypeNotSupported",
"StartSyncExecution is only supported for EXPRESS state machines", 400);
@@ -510,15 +525,15 @@ public class StepFunctionsService implements Resettable {
String arn = regionResolver.buildArn("states", region,
"express:" + sm.getName() + ":" + startDate + ":" + execName);
- Execution exec = new Execution();
+ var exec = new Execution();
exec.setExecutionArn(arn);
exec.setStateMachineArn(stateMachineArn);
exec.setName(execName);
exec.setInput(input);
exec.setStatus("RUNNING");
- List<HistoryEvent> history = new ArrayList<>();
- HistoryEvent startEvent = new HistoryEvent();
+ var history = new ArrayList<HistoryEvent>();
+ var startEvent = new HistoryEvent();
startEvent.setId(1L);
startEvent.setType("ExecutionStarted");
startEvent.setDetails(Map.of("input", input != null ? input : "{}",
@@ -532,6 +547,61 @@ public class StepFunctionsService implements Resettable {
return exec;
}
+ private record TestCaseSelection(String stateMachineArn, String testCaseName) {
+ }
+
+ /**
+ * Splits the Step Functions Local mocked service integration suffix off a
+ * {@code StartExecution} ARN: {@code <stateMachineArn>#<testCaseName>} selects the named
+ * test case from the configured mock configuration file. A bare trailing {@code #} selects
+ * no test case and the execution runs unmocked, matching Step Functions Local.
+ */
+ private static TestCaseSelection splitTestCaseSuffix(String stateMachineArn) {
+ var separator = stateMachineArn != null ? stateMachineArn.indexOf('#') : -1;
+ if (separator < 0) {
+ return new TestCaseSelection(stateMachineArn, null);
+ }
+ var testCaseName = stateMachineArn.substring(separator + 1);
+ return new TestCaseSelection(stateMachineArn.substring(0, separator),
+ testCaseName.isBlank() ? null : testCaseName);
+ }
+
+ private MockedTestCase resolveMockedTestCase(StateMachine sm, TestCaseSelection selection) {
+ if (selection.testCaseName() == null) {
+ return null;
+ }
+ var mockedTestCase = mockLoader.requireTestCase(sm.getName(), selection.testCaseName());
+ warnOnMockedStatesMissingFromDefinition(sm, mockedTestCase);
+ return mockedTestCase;
+ }
+
+ private void warnOnMockedStatesMissingFromDefinition(StateMachine sm, MockedTestCase testCase) {
+ try {
+ var stateNames = new HashSet<String>();
+ collectStateNames(objectMapper.readTree(sm.getDefinition()), stateNames);
+ for (var stateName : testCase.stateResponses().keySet()) {
+ if (!stateNames.contains(stateName)) {
+ LOG.warnv("Mock test case {0} references state {1} which does not exist in state machine {2}",
+ testCase.testCaseName(), stateName, sm.getName());
+ }
+ }
+ } catch (Exception e) {
+ LOG.debugv("Could not check mocked state names for {0}: {1}", sm.getName(), e.getMessage());
+ }
+ }
+
+ private static void collectStateNames(JsonNode node, Set<String> names) {
+ if (node.isObject()) {
+ var states = node.get("States");
+ if (states != null && states.isObject()) {
+ states.fieldNames().forEachRemaining(names::add);
+ }
+ node.forEach(child -> collectStateNames(child, names));
+ } else if (node.isArray()) {
+ node.forEach(child -> collectStateNames(child, names));
+ }
+ }
+
public Execution describeExecution(String arn) {
return executionStore.get(arn)
.orElseThrow(() -> new AwsException("ExecutionDoesNotExist", "Execution does not exist", 400));
diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/model/MockedResponseStep.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/model/MockedResponseStep.java
new file mode 100644
index 0000000000..5a23fcbbe2
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/model/MockedResponseStep.java
@@ -0,0 +1,26 @@
+package io.github.hectorvent.floci.services.stepfunctions.model;
+
+import com.fasterxml.jackson.databind.JsonNode;
+
+/**
+ * One attempt-keyed entry of a mocked service integration response, parsed from the
+ * Step Functions Local {@code MockConfigFile.json} format. The attempt key {@code "0"}
+ * becomes the range 0..0 and {@code "1-2"} becomes 1..2. Exactly one of
+ * {@code returnResult} (a {@code Return} payload) or {@code errorName}/{@code errorCause}
+ * (a {@code Throw}) is set.
+ */
+public record MockedResponseStep(
+ int fromAttempt,
+ int toAttempt,
+ JsonNode returnResult,
+ String errorName,
+ String errorCause) {
+
+ public boolean covers(int attempt) {
+ return attempt >= fromAttempt && attempt <= toAttempt;
+ }
+
+ public boolean isThrow() {
+ return errorName != null;
+ }
+}
diff --git a/src/main/java/io/github/hectorvent/floci/services/stepfunctions/model/MockedTestCase.java b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/model/MockedTestCase.java
new file mode 100644
index 0000000000..1f47bfbaf4
--- /dev/null
+++ b/src/main/java/io/github/hectorvent/floci/services/stepfunctions/model/MockedTestCase.java
@@ -0,0 +1,15 @@
+package io.github.hectorvent.floci.services.stepfunctions.model;
+
+import java.util.List;
+import java.util.Map;
+
+/**
+ * A resolved mock test case for one execution: state name to the attempt-keyed mocked
+ * responses that replace that Task state's service call. States not present here run
+ * their real integration.
+ */
+public record MockedTestCase(
+ String stateMachineName,
+ String testCaseName,
+ Map<String, List<MockedResponseStep>> stateResponses) {
+}
diff --git a/src/main/resources/application.yml b/src/main/resources/application.yml
index 947bdc3357..f4ddf567f2 100644
--- a/src/main/resources/application.yml
+++ b/src/main/resources/application.yml
@@ -353,6 +353,7 @@ floci:
stepfunctions:
enabled: true
allow-plaintext-http: false
+ mock-config-file: ${SFN_MOCK_CONFIG:}
swf:
enabled: true
timeout-sweep-enabled: true
diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorMockedResponsesTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorMockedResponsesTest.java
new file mode 100644
index 0000000000..bdbf46b22d
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/AslExecutorMockedResponsesTest.java
@@ -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;
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/SfnMockLoaderTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/SfnMockLoaderTest.java
new file mode 100644
index 0000000000..7db290b797
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/SfnMockLoaderTest.java
@@ -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());
+ }
+}
diff --git a/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsMockedServiceIntegrationTest.java b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsMockedServiceIntegrationTest.java
new file mode 100644
index 0000000000..f495070341
--- /dev/null
+++ b/src/test/java/io/github/hectorvent/floci/services/stepfunctions/StepFunctionsMockedServiceIntegrationTest.java
@@ -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")
+ + "\"";
+ }
+}
diff --git a/src/test/resources/application.yml b/src/test/resources/application.yml
index 861e27ae30..3a66e44315 100644
--- a/src/test/resources/application.yml
+++ b/src/test/resources/application.yml
@@ -200,6 +200,7 @@ floci:
stepfunctions:
enabled: true
allow-plaintext-http: true
+ mock-config-file: ${SFN_MOCK_CONFIG:src/test/resources/fixtures/sfn-mock-config.json}
swf:
enabled: true
timeout-sweep-enabled: true
diff --git a/src/test/resources/fixtures/sfn-mock-config.json b/src/test/resources/fixtures/sfn-mock-config.json
new file mode 100644
index 0000000000..3c60ec2d3d
--- /dev/null
+++ b/src/test/resources/fixtures/sfn-mock-config.json
@@ -0,0 +1,28 @@
+{
+ "StateMachines": {
+ "sfn-mock-test": {
+ "TestCases": {
+ "HappyPath": { "Call API": "Ok200" },
+ "Throw422": { "Call API": "Throw422" },
+ "RetryOnce": { "Call API": "ThrowThenOk" }
+ }
+ },
+ "sfn-mock-ddb-test": {
+ "TestCases": {
+ "MockedApiRealDdb": { "Call API": "Ok200" }
+ }
+ }
+ },
+ "MockedResponses": {
+ "Ok200": {
+ "0": { "Return": { "StatusCode": 200, "ResponseBody": { "id": 1 } } }
+ },
+ "Throw422": {
+ "0": { "Throw": { "Error": "ApiGateway.422", "Cause": "Unprocessable" } }
+ },
+ "ThrowThenOk": {
+ "0": { "Throw": { "Error": "ApiGateway.429", "Cause": "Too many requests" } },
+ "1-2": { "Return": { "StatusCode": 200, "ResponseBody": { "retried": true } } }
+ }
+ }
+}