From 176484f49fc1fdda0995d9bfcbd42dbb7e6ba1b9 Mon Sep 17 00:00:00 2001 From: MEPalma <64580864+MEPalma@users.noreply.github.com> Date: Wed, 30 Apr 2025 22:13:06 +0200 Subject: [PATCH 01/10] initial documentation on step functions mock --- .../user-guide/step-functions-tools/_index.md | 16 + .../mocked-service-integrations/index.md | 359 ++++++++++++++++++ 2 files changed, 375 insertions(+) create mode 100755 content/en/user-guide/step-functions-tools/_index.md create mode 100644 content/en/user-guide/step-functions-tools/mocked-service-integrations/index.md diff --git a/content/en/user-guide/step-functions-tools/_index.md b/content/en/user-guide/step-functions-tools/_index.md new file mode 100755 index 0000000000..fb31130dfa --- /dev/null +++ b/content/en/user-guide/step-functions-tools/_index.md @@ -0,0 +1,16 @@ +--- +title: "Step Functions Tools" +linkTitle: "Step Functions Tools" +weight: 45 +description: > + Develop your state machines more efficiently +aliases: + - /tools/step-functions-tools/ + - /user-guide/tools/step-functions-tools/ +--- + +Step Functions Tools by LocalStack gives you a single, purpose-built utilities that lets you design, deploy, and debug AWS Step Functions state machines entirely on your local machine. With LocalStack’s full Step Functions emulation—including integrations with other AWS services—you can iterate rapidly without ever deploying to AWS, getting instant feedback and a smoother developer-testing workflow. + +With Step Functions Tools, you can: + +- Mock any AWS integration, DynamoDB, SQS, API Gateway, and more, with configurable responses. Test success/failure paths, edge cases, and retries and catches locally, watching live state transitions. diff --git a/content/en/user-guide/step-functions-tools/mocked-service-integrations/index.md b/content/en/user-guide/step-functions-tools/mocked-service-integrations/index.md new file mode 100644 index 0000000000..9e657997fe --- /dev/null +++ b/content/en/user-guide/step-functions-tools/mocked-service-integrations/index.md @@ -0,0 +1,359 @@ +--- +title: "Mocked Service Integrations" +weight: 2 +description: > + Attach a debugger to your Lambda functions from within your IDE +aliases: + - /tools/step-functions-tools/mocked-service-integrations/ + - /user-guide/tools/step-functions-tools/mocked-service-integrations/ +--- + +# Introduction + +Mocked service integrations eliminate the need to deploy or invoke real AWS services during Step Functions testing. +Instead, each Task state returns a predefined output supplied through a mock configuration file. +The file lists one or more test cases per state machine, with a set of mocked responses mapped to individual states. +When a state machine is executed in mock mode, the runtime simply samples the specified responses, substituting them for calls to the actual integrated resources. States without a corresponding mock entry continue to invoke their real services, allowing selective mixing of mocked and live interactions within the same execution. + +The following definitions clarify key concepts used throughout this section: +- Mocked service integrations – Task states that are instructed to return predefined data instead of making live AWS calls. +- Mocked responses – The static payloads supplied to those Task states. +- Test cases – Individual state-machine runs that are executed with mocked service integrations enabled. +- Mock configuration file – A JSON document that declares the test cases, their mocked integrations, and the response data used for each state. + +## Mocking service integrations + +When mocked service integrations are enabled for specific Task states, one or more response payloads can be declared for each state. +During execution, the LocalStack runtime returns these payloads instead of calling the live AWS service. +Any Task state—using patterns such as .sync, .sync2, or .waitForTaskToken—can be mocked, and both success or failure scenarios can be reproduced. +Payload correctness is not validated by the tool, so it is up to the developer to supply responses that match the service’s expected structure. + +### 1. Identify a State Machine to Configure with Mocked Integrations + +Mocked service integrations are bound to specific state machine definitions. +Therefore, the first step is to choose the state machine where mocked responses will be applied. +LocalStack supports the latest AWS Step Functions features, including [JSONata expressions and Variables](https://blog.localstack.cloud/aws-step-functions-made-easy/). +In this example, the state machine LambdaSQSIntegration will be used with the following definition: + +```json +{ + "Comment":"This state machine is called: LambdaSQSIntegration", + "QueryLanguage":"JSONata", + "StartAt":"LambdaState", + "States":{ + "LambdaState":{ + "Type":"Task", + "Resource":"arn:aws:states:::lambda:invoke", + "Arguments":{ + "FunctionName":"GreetingsFunction", + "Payload":{ + "fullname":"{% $states.input.name & ' ' & $states.input.surname %}" + } + }, + "Retry":[ + { + "ErrorEquals":[ "States.ALL" ], + "IntervalSeconds":2, + "MaxAttempts": 4, + "BackoffRate":2 + } + ], + "Assign":{ + "greeting":"{% $states.result.Payload.greeting %}" + }, + "Next":"SQSState" + }, + "SQSState":{ + "Type":"Task", + "Resource":"arn:aws:states:::sqs:sendMessage", + "Arguments":{ + "QueueUrl":"http://sqs.us-east-1.localhost.localstack.cloud:4566/000000000000/localstack-queue", + "MessageBody":"{% $greeting %}" + }, + "End":true + } + } +} +``` + +### 2. Define mock integrations in a configuration file + +Mock integrations are declared in a single mock configuration file written in JSON. +The file must conform to the RawMockConfig schema shown above and is organised into two top-level sections: + +- StateMachines - maps each state machine name to the test scenarios that will run against it. +- MockedResponses - holds the reusable response sets that the test scenarios reference. + + +#### 2.1 StateMachines +The StateMachines section defines which Step Functions state machines will use mocked service integrations and how their test cases are configured. +Each entry under StateMachines corresponds to a specific state machine and contains one or more named test cases that specify how the states within that machine should behave during execution. + +```json +"StateMachines": { + "": { + "TestCases": { + "": { + "": "", + ... + } + } + } +} +``` +- StateMachineName – The exact name of the Step Functions state machine. This must match the name used when the state machine is created in LocalStack. +- TestCases – A set of named test scenarios. Each test case maps one or more state names to a predefined ResponseID from the MockedResponses section. + +Each test case defines the expected behavior of specific Task states by assigning them to mock response sets. +When the test case is selected at runtime, these bindings determine whether the state uses a mocked response or proceeds with a real service invocation (if no mock is provided). + +```json +"LambdaSQSIntegration": { + "TestCases": { + "LambdaRetryCase": { + "LambdaState": "MockedLambdaStateRetry", + "SQSState": "MockedSQSStateSuccess" + } + } +} +``` + +#### 2.2 MockedResponses +The MockedResponses section defines reusable response sets that simulate the behavior of specific Task states during test execution. +Each response set is identified by a unique ResponseID, which is then referenced in one or more test cases under the StateMachines section. + +```json +"MockedResponses": { + "": { + "": { "Return": ... }, + "": { "Throw": ... } + } +} +``` + +- ResponseID – A unique identifier for a set of mocked responses. These IDs are used in test cases to associate a state with its corresponding mocked behavior. +- step-key – Defines which execution attempt the response applies to. It can be: + - A single integer, e.g., "0" – applied on the first attempt. + - A range of integers, e.g., "1-5" – applied to multiple attempts. +- Steps are evaluated in sequential order, allowing simulation of retries or failures followed by success. + - Return – Defines a successful response payload to be returned by the state instead of invoking the actual integrated service. + - Throw – Defines an error response with required fields Error and Cause, simulating a failure. + - Each response entry must contain exactly one of Return or Throw. Including both or neither will result in an invalid configuration. + + +```json +"MockedLambdaStateRetry": { + "0": { + "Throw": { + "Error": "Lambda.ServiceException", + "Cause": "An internal service error occurred." + } + }, + "1-2": { + "Throw": { + "Error": "Lambda.TooManyRequestsException", + "Cause": "Invocation rate limit exceeded." + } + }, + "3": { + "Return": { + "StatusCode": 200, + "Payload": { + "greeting": "Hello John Smith, you’re now testing mocked integrations with LocalStack!" + } + } + } +} +``` + +The MockConfigFile.json shown below targets the previously defined LambdaSQSIntegration state machine for testing: +```json +{ + "StateMachines":{ + "LambdaSQSIntegration":{ + "TestCases":{ + "BaseCase":{ + "LambdaState":"MockedLambdaStateSuccess", + "SQSState":"MockedSQSStateSuccess" + }, + "LambdaRetryCase":{ + "LambdaState":"MockedLambdaStateRetry", + "SQSState":"MockedSQSStateSuccess" + }, + "HybridCase":{ + "LambdaState":"MockedLambdaSuccess" + } + } + } + }, + "MockedResponses":{ + "MockedLambdaStateSuccess":{ + "0":{ + "Return":{ + "StatusCode":200, + "Payload":{ + "greeting":"Hello John Smith, you’re now testing mocked integrations with LocalStack!" + } + } + } + }, + "MockedSQSStateSuccess":{ + "0":{ + "Return":{ + "MD5OfMessageBody":"3661896f-1287-45a3-8f89-53bd7b25a9a6", + "MessageId":"7c9ef661-c455-4779-a9c2-278531e231c2" + } + } + }, + "MockedLambdaStateRetry":{ + "0":{ + "Throw":{ + "Error":"Lambda.ServiceException", + "Cause":"An internal service error occurred." + } + }, + "1-2":{ + "Throw":{ + "Error":"Lambda.TooManyRequestsException", + "Cause":"Invocation rate limit exceeded." + } + }, + "3":{ + "Return":{ + "StatusCode":200, + "Payload":{ + "greeting":"Hello John Smith, you’re now testing mocked integrations with LocalStack!" + } + } + } + } + } +} +``` + +### 3. Provide the Mock Configuration to LocalStack + +The `SFN_MOCK_CONFIG` environment variable specifies the path to the mock-configuration file. +When starting LocalStack in Docker, set this variable and mount the configuration file, e.g., MockConfigFile.json—as shown in the following examples. +{{< tabpane >}} +{{< tab header="LocalStack CLI" lang="shell" >}} +LOCALSTACK_SFN_MOCK_CONFIG=/tmp/MockConfigFile.json \ +localstack start --volume /path/to/MockConfigFile.json:/tmp/MockConfigFile.json +{{< /tab >}} +{{< tab header="Docker Compose" lang="yaml" >}} +services: + localstack: + container_name: "${LOCALSTACK_DOCKER_NAME:-localstack-main}" + image: localstack/localstack-pro + ports: + - "127.0.0.1:4566:4566" # LocalStack Gateway + - "127.0.0.1:4510-4559:4510-4559" # external services port range + - "127.0.0.1:443:443" # LocalStack HTTPS Gateway (Pro) + environment: + # LocalStack configuration: https://docs.localstack.cloud/references/configuration/ + - DEBUG=${DEBUG:-0} + - SFN_MOCK_CONFIG=/tmp/MockConfigFile.json + volumes: + - "${LOCALSTACK_VOLUME_DIR:-./volume}:/var/lib/localstack" + - "/var/run/docker.sock:/var/run/docker.sock" + - "./MockConfigFile.json:/tmp/MockConfigFile.json" +{{< /tab >}} +{{< /tabpane >}} + + +### 4. Run Tests Cases with Mocked Integrations + +#### 4.1 Create the State Machine +The first step is to create the state machine for testing. +The name of the state machine must match the name defined in the mock configuration file. +Continuing from the example introduced earlier in this article, the state machine named LambdaSQSIntegration can be created with the following command: + +{{< command >}} +$ awslocal stepfunctions create-state-machine \ + --definition file://LambdaSQSIntegration.json \ + --name "LambdaSQSIntegration" \ + --role-arn "arn:aws:iam::000000000000:role/service-role/testrole" +{{< /command >}} + + +#### 4.2 Start the Mock Test +Once the state machine is created and correctly named, test cases defined in the mock configuration file can be executed using the StartExecution or StartSyncExecution API. +To specify a test case, append the test case name to the state machine ARN using the # symbol. +For example, to run the BaseCase test case for the `LambdaSQSIntegration` state machine: + +{{< command >}} +$ awslocal stepfunctions start-execution \ + --state-machine arn:aws:states:ca-central-1:000000000000:stateMachine:LambdaSQSIntegration#BaseCase \ + --input '{"name": "John", "surname": "smith"}' \ + --name "MockExecutionBaseCase" +{{< /command >}} +During execution, the state machine uses the mocked responses defined in the mock configuration file for each state. +If no mocked response is specified for a given state, the associated service integration will be invoked as normal. + +#### 4.3 Inspect the Execution +After a mock test case is initiated, the state machine execution behaves like a standard execution and can be monitored using API actions such as `GetExecutionHistory` and `DescribeExecution`. +Continuing from the previous example, the execution can be described with the following command: +{{< command >}} +$ awslocal stepfunctions describe-execution \ + --execution-arn "arn:aws:states:ca-central-1:000000000000:execution:LambdaSQSIntegration:MockExecutionBaseCase" +{{< /command >}} +The response will include the output defined in the mock configuration file for `SQSState`, in this case corresponding to `MockedSQSStateSuccess`. +```json +{ + "executionArn": "arn:aws:states:ca-central-1:000000000000:execution:LambdaSQSIntegration:MockExecutionBaseCase", + "stateMachineArn": "arn:aws:states:ca-central-1:000000000000:stateMachine:LambdaSQSIntegration", + "name": "MockExecutionBaseCase", + "status": "SUCCEEDED", + "startDate": "...", + "stopDate": "...", + "input": "{\"name\":\"John\",\"surname\":\"smith\"}", + "inputDetails": { + "included": true + }, + "output": "{\"MessageId\":\"7c9ef661-c455-4779-a9c2-278531e231c2\",\"MD5OfMessageBody\":\"3661896f-1287-45a3-8f89-53bd7b25a9a6\"}", + "outputDetails": { + "included": true + } +} +``` + +The execution history can also be retrieved using the following command: +{{< command >}} +$ awslocal stepfunctions get-execution-history \ + --execution-arn "arn:aws:states:ca-central-1:000000000000:execution:LambdaSQSIntegration:MockExecutionBaseCase" +{{< /command >}} + +This returns the full execution history, including entries that indicate how the mocked responses were applied to the Lambda and SQS states. +```json +... +{ + "timestamp": "...", + "type": "TaskSucceeded", + "id": 5, + "previousEventId": 4, + "taskSucceededEventDetails": { + "resourceType": "lambda", + "resource": "invoke", + "output": "{\"StatusCode\": 200, \"Payload\": {\"greeting\": \"Hello John Smith, you\\u2019re now testing mocked integrations with LocalStack!\"}}", + "outputDetails": { + "truncated": false + } + } +} +... +{ + "timestamp": "...", + "type": "TaskSucceeded", + "id": 10, + "previousEventId": 9, + "taskSucceededEventDetails": { + "resourceType": "sqs", + "resource": "sendMessage", + "output": "{\"MessageId\": \"7c9ef661-c455-4779-a9c2-278531e231c2\", \"MD5OfMessageBody\": \"3661896f-1287-45a3-8f89-53bd7b25a9a6\"}", + "outputDetails": { + "truncated": false + } + } +} +... +``` From cb67c29ecbf9e70f6b0c9bb410e77412f8936521 Mon Sep 17 00:00:00 2001 From: MEPalma <64580864+MEPalma@users.noreply.github.com> Date: Wed, 30 Apr 2025 22:24:59 +0200 Subject: [PATCH 02/10] lint --- .../user-guide/step-functions-tools/_index.md | 6 +- .../mocked-service-integrations/index.md | 88 ++++++++++--------- 2 files changed, 52 insertions(+), 42 deletions(-) diff --git a/content/en/user-guide/step-functions-tools/_index.md b/content/en/user-guide/step-functions-tools/_index.md index fb31130dfa..80bc28193d 100755 --- a/content/en/user-guide/step-functions-tools/_index.md +++ b/content/en/user-guide/step-functions-tools/_index.md @@ -9,8 +9,10 @@ aliases: - /user-guide/tools/step-functions-tools/ --- -Step Functions Tools by LocalStack gives you a single, purpose-built utilities that lets you design, deploy, and debug AWS Step Functions state machines entirely on your local machine. With LocalStack’s full Step Functions emulation—including integrations with other AWS services—you can iterate rapidly without ever deploying to AWS, getting instant feedback and a smoother developer-testing workflow. +Step Functions Tools by LocalStack gives you a single, purpose-built utilities that lets you design, deploy, and debug AWS Step Functions state machines entirely on your local machine. +With LocalStack’s full Step Functions emulation—including integrations with other AWS services—you can iterate rapidly without ever deploying to AWS, getting instant feedback and a smoother developer-testing workflow. With Step Functions Tools, you can: -- Mock any AWS integration, DynamoDB, SQS, API Gateway, and more, with configurable responses. Test success/failure paths, edge cases, and retries and catches locally, watching live state transitions. +- Mock any AWS integration, DynamoDB, SQS, API Gateway, and more, with configurable responses. + Test success/failure paths, edge cases, and retries and catches locally, watching live state transitions. diff --git a/content/en/user-guide/step-functions-tools/mocked-service-integrations/index.md b/content/en/user-guide/step-functions-tools/mocked-service-integrations/index.md index 9e657997fe..ce68ce1372 100644 --- a/content/en/user-guide/step-functions-tools/mocked-service-integrations/index.md +++ b/content/en/user-guide/step-functions-tools/mocked-service-integrations/index.md @@ -10,10 +10,11 @@ aliases: # Introduction -Mocked service integrations eliminate the need to deploy or invoke real AWS services during Step Functions testing. -Instead, each Task state returns a predefined output supplied through a mock configuration file. -The file lists one or more test cases per state machine, with a set of mocked responses mapped to individual states. -When a state machine is executed in mock mode, the runtime simply samples the specified responses, substituting them for calls to the actual integrated resources. States without a corresponding mock entry continue to invoke their real services, allowing selective mixing of mocked and live interactions within the same execution. +Mocked service integrations eliminate the need to deploy or invoke real AWS services during Step Functions testing. +Instead, each Task state returns a predefined output supplied through a mock configuration file. +The file lists one or more test cases per state machine, with a set of mocked responses mapped to individual states. +When a state machine is executed in mock mode, the runtime simply samples the specified responses, substituting them for calls to the actual integrated resources. +States without a corresponding mock entry continue to invoke their real services, allowing selective mixing of mocked and live interactions within the same execution. The following definitions clarify key concepts used throughout this section: - Mocked service integrations – Task states that are instructed to return predefined data instead of making live AWS calls. @@ -23,17 +24,17 @@ The following definitions clarify key concepts used throughout this section: ## Mocking service integrations -When mocked service integrations are enabled for specific Task states, one or more response payloads can be declared for each state. -During execution, the LocalStack runtime returns these payloads instead of calling the live AWS service. -Any Task state—using patterns such as .sync, .sync2, or .waitForTaskToken—can be mocked, and both success or failure scenarios can be reproduced. +When mocked service integrations are enabled for specific Task states, one or more response payloads can be declared for each state. +During execution, the LocalStack runtime returns these payloads instead of calling the live AWS service. +Any Task state—using patterns such as .sync, .sync2, or .waitForTaskToken—can be mocked, and both success or failure scenarios can be reproduced. Payload correctness is not validated by the tool, so it is up to the developer to supply responses that match the service’s expected structure. ### 1. Identify a State Machine to Configure with Mocked Integrations -Mocked service integrations are bound to specific state machine definitions. -Therefore, the first step is to choose the state machine where mocked responses will be applied. -LocalStack supports the latest AWS Step Functions features, including [JSONata expressions and Variables](https://blog.localstack.cloud/aws-step-functions-made-easy/). -In this example, the state machine LambdaSQSIntegration will be used with the following definition: +Mocked service integrations are bound to specific state machine definitions. +Therefore, the first step is to choose the state machine where mocked responses will be applied. +LocalStack supports the latest AWS Step Functions features, including [JSONata expressions and Variables](https://blog.localstack.cloud/aws-step-functions-made-easy/). +In this example, the state machine LambdaSQSIntegration will be used with the following definition: ```json { @@ -81,12 +82,12 @@ In this example, the state machine LambdaSQSIntegration will be used with the fo Mock integrations are declared in a single mock configuration file written in JSON. The file must conform to the RawMockConfig schema shown above and is organised into two top-level sections: -- StateMachines - maps each state machine name to the test scenarios that will run against it. -- MockedResponses - holds the reusable response sets that the test scenarios reference. +- StateMachines - maps each state machine name to the test scenarios that will run against it. +- MockedResponses - holds the reusable response sets that the test scenarios reference. #### 2.1 StateMachines -The StateMachines section defines which Step Functions state machines will use mocked service integrations and how their test cases are configured. +The StateMachines section defines which Step Functions state machines will use mocked service integrations and how their test cases are configured. Each entry under StateMachines corresponds to a specific state machine and contains one or more named test cases that specify how the states within that machine should behave during execution. ```json @@ -101,10 +102,13 @@ Each entry under StateMachines corresponds to a specific state machine and conta } } ``` -- StateMachineName – The exact name of the Step Functions state machine. This must match the name used when the state machine is created in LocalStack. -- TestCases – A set of named test scenarios. Each test case maps one or more state names to a predefined ResponseID from the MockedResponses section. -Each test case defines the expected behavior of specific Task states by assigning them to mock response sets. +- StateMachineName – The exact name of the Step Functions state machine. +This must match the name used when the state machine is created in LocalStack. +- TestCases – A set of named test scenarios. +Each test case maps one or more state names to a predefined ResponseID from the MockedResponses section. + +Each test case defines the expected behavior of specific Task states by assigning them to mock response sets. When the test case is selected at runtime, these bindings determine whether the state uses a mocked response or proceeds with a real service invocation (if no mock is provided). ```json @@ -119,7 +123,7 @@ When the test case is selected at runtime, these bindings determine whether the ``` #### 2.2 MockedResponses -The MockedResponses section defines reusable response sets that simulate the behavior of specific Task states during test execution. +The MockedResponses section defines reusable response sets that simulate the behavior of specific Task states during test execution. Each response set is identified by a unique ResponseID, which is then referenced in one or more test cases under the StateMachines section. ```json @@ -131,34 +135,36 @@ Each response set is identified by a unique ResponseID, which is then referenced } ``` -- ResponseID – A unique identifier for a set of mocked responses. These IDs are used in test cases to associate a state with its corresponding mocked behavior. -- step-key – Defines which execution attempt the response applies to. It can be: - - A single integer, e.g., "0" – applied on the first attempt. - - A range of integers, e.g., "1-5" – applied to multiple attempts. +- ResponseID – A unique identifier for a set of mocked responses. +These IDs are used in test cases to associate a state with its corresponding mocked behavior. +- step-key – Defines which execution attempt the response applies to. +It can be: + - A single integer, e.g., "0" – applied on the first attempt. + - A range of integers, e.g., "1-5" – applied to multiple attempts. - Steps are evaluated in sequential order, allowing simulation of retries or failures followed by success. - - Return – Defines a successful response payload to be returned by the state instead of invoking the actual integrated service. - - Throw – Defines an error response with required fields Error and Cause, simulating a failure. - - Each response entry must contain exactly one of Return or Throw. Including both or neither will result in an invalid configuration. - + - Return – Defines a successful response payload to be returned by the state instead of invoking the actual integrated service. + - Throw – Defines an error response with required fields Error and Cause, simulating a failure. + - Each response entry must contain exactly one of Return or Throw. + Including both or neither will result in an invalid configuration. ```json "MockedLambdaStateRetry": { "0": { - "Throw": { - "Error": "Lambda.ServiceException", - "Cause": "An internal service error occurred." + "Throw": { + "Error": "Lambda.ServiceException", + "Cause": "An internal service error occurred." } }, "1-2": { - "Throw": { - "Error": "Lambda.TooManyRequestsException", - "Cause": "Invocation rate limit exceeded." + "Throw": { + "Error": "Lambda.TooManyRequestsException", + "Cause": "Invocation rate limit exceeded." } }, "3": { "Return": { "StatusCode": 200, - "Payload": { + "Payload": { "greeting": "Hello John Smith, you’re now testing mocked integrations with LocalStack!" } } @@ -167,6 +173,7 @@ Each response set is identified by a unique ResponseID, which is then referenced ``` The MockConfigFile.json shown below targets the previously defined LambdaSQSIntegration state machine for testing: + ```json { "StateMachines":{ @@ -233,7 +240,7 @@ The MockConfigFile.json shown below targets the previously defined LambdaSQSInte ### 3. Provide the Mock Configuration to LocalStack -The `SFN_MOCK_CONFIG` environment variable specifies the path to the mock-configuration file. +The `SFN_MOCK_CONFIG` environment variable specifies the path to the mock-configuration file. When starting LocalStack in Docker, set this variable and mount the configuration file, e.g., MockConfigFile.json—as shown in the following examples. {{< tabpane >}} {{< tab header="LocalStack CLI" lang="shell" >}} @@ -264,8 +271,8 @@ services: ### 4. Run Tests Cases with Mocked Integrations #### 4.1 Create the State Machine -The first step is to create the state machine for testing. -The name of the state machine must match the name defined in the mock configuration file. +The first step is to create the state machine for testing. +The name of the state machine must match the name defined in the mock configuration file. Continuing from the example introduced earlier in this article, the state machine named LambdaSQSIntegration can be created with the following command: {{< command >}} @@ -277,8 +284,8 @@ $ awslocal stepfunctions create-state-machine \ #### 4.2 Start the Mock Test -Once the state machine is created and correctly named, test cases defined in the mock configuration file can be executed using the StartExecution or StartSyncExecution API. -To specify a test case, append the test case name to the state machine ARN using the # symbol. +Once the state machine is created and correctly named, test cases defined in the mock configuration file can be executed using the StartExecution or StartSyncExecution API. +To specify a test case, append the test case name to the state machine ARN using the # symbol. For example, to run the BaseCase test case for the `LambdaSQSIntegration` state machine: {{< command >}} @@ -287,17 +294,18 @@ $ awslocal stepfunctions start-execution \ --input '{"name": "John", "surname": "smith"}' \ --name "MockExecutionBaseCase" {{< /command >}} -During execution, the state machine uses the mocked responses defined in the mock configuration file for each state. +During execution, the state machine uses the mocked responses defined in the mock configuration file for each state. If no mocked response is specified for a given state, the associated service integration will be invoked as normal. #### 4.3 Inspect the Execution -After a mock test case is initiated, the state machine execution behaves like a standard execution and can be monitored using API actions such as `GetExecutionHistory` and `DescribeExecution`. +After a mock test case is initiated, the state machine execution behaves like a standard execution and can be monitored using API actions such as `GetExecutionHistory` and `DescribeExecution`. Continuing from the previous example, the execution can be described with the following command: {{< command >}} $ awslocal stepfunctions describe-execution \ --execution-arn "arn:aws:states:ca-central-1:000000000000:execution:LambdaSQSIntegration:MockExecutionBaseCase" {{< /command >}} The response will include the output defined in the mock configuration file for `SQSState`, in this case corresponding to `MockedSQSStateSuccess`. + ```json { "executionArn": "arn:aws:states:ca-central-1:000000000000:execution:LambdaSQSIntegration:MockExecutionBaseCase", From 49c24e03a14095d113c10291899124476d365ea1 Mon Sep 17 00:00:00 2001 From: MEPalma <64580864+MEPalma@users.noreply.github.com> Date: Wed, 30 Apr 2025 22:29:33 +0200 Subject: [PATCH 03/10] more lints --- .../mocked-service-integrations/index.md | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/content/en/user-guide/step-functions-tools/mocked-service-integrations/index.md b/content/en/user-guide/step-functions-tools/mocked-service-integrations/index.md index ce68ce1372..57304c6f79 100644 --- a/content/en/user-guide/step-functions-tools/mocked-service-integrations/index.md +++ b/content/en/user-guide/step-functions-tools/mocked-service-integrations/index.md @@ -85,7 +85,6 @@ The file must conform to the RawMockConfig schema shown above and is organised i - StateMachines - maps each state machine name to the test scenarios that will run against it. - MockedResponses - holds the reusable response sets that the test scenarios reference. - #### 2.1 StateMachines The StateMachines section defines which Step Functions state machines will use mocked service integrations and how their test cases are configured. Each entry under StateMachines corresponds to a specific state machine and contains one or more named test cases that specify how the states within that machine should behave during execution. @@ -139,12 +138,12 @@ Each response set is identified by a unique ResponseID, which is then referenced These IDs are used in test cases to associate a state with its corresponding mocked behavior. - step-key – Defines which execution attempt the response applies to. It can be: - - A single integer, e.g., "0" – applied on the first attempt. - - A range of integers, e.g., "1-5" – applied to multiple attempts. + - A single integer, e.g., "0" – applied on the first attempt. + - A range of integers, e.g., "1-5" – applied to multiple attempts. - Steps are evaluated in sequential order, allowing simulation of retries or failures followed by success. - - Return – Defines a successful response payload to be returned by the state instead of invoking the actual integrated service. - - Throw – Defines an error response with required fields Error and Cause, simulating a failure. - - Each response entry must contain exactly one of Return or Throw. + - Return – Defines a successful response payload to be returned by the state instead of invoking the actual integrated service. + - Throw – Defines an error response with required fields Error and Cause, simulating a failure. +- Each response entry must contain exactly one of Return or Throw. Including both or neither will result in an invalid configuration. ```json From 3f194a6808a2ee561cbe0fafe548f1170a36e717 Mon Sep 17 00:00:00 2001 From: MEPalma <64580864+MEPalma@users.noreply.github.com> Date: Wed, 30 Apr 2025 22:31:41 +0200 Subject: [PATCH 04/10] more lints --- .../step-functions-tools/mocked-service-integrations/index.md | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/content/en/user-guide/step-functions-tools/mocked-service-integrations/index.md b/content/en/user-guide/step-functions-tools/mocked-service-integrations/index.md index 57304c6f79..aa74376848 100644 --- a/content/en/user-guide/step-functions-tools/mocked-service-integrations/index.md +++ b/content/en/user-guide/step-functions-tools/mocked-service-integrations/index.md @@ -266,7 +266,6 @@ services: {{< /tab >}} {{< /tabpane >}} - ### 4. Run Tests Cases with Mocked Integrations #### 4.1 Create the State Machine @@ -281,7 +280,6 @@ $ awslocal stepfunctions create-state-machine \ --role-arn "arn:aws:iam::000000000000:role/service-role/testrole" {{< /command >}} - #### 4.2 Start the Mock Test Once the state machine is created and correctly named, test cases defined in the mock configuration file can be executed using the StartExecution or StartSyncExecution API. To specify a test case, append the test case name to the state machine ARN using the # symbol. @@ -331,6 +329,7 @@ $ awslocal stepfunctions get-execution-history \ {{< /command >}} This returns the full execution history, including entries that indicate how the mocked responses were applied to the Lambda and SQS states. + ```json ... { From 6f7bbec8f801f4eced9c6c8fcdf4c633bfc56326 Mon Sep 17 00:00:00 2001 From: MEPalma <64580864+MEPalma@users.noreply.github.com> Date: Wed, 30 Apr 2025 22:32:50 +0200 Subject: [PATCH 05/10] minor --- .../step-functions-tools/mocked-service-integrations/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/en/user-guide/step-functions-tools/mocked-service-integrations/index.md b/content/en/user-guide/step-functions-tools/mocked-service-integrations/index.md index aa74376848..896cbfd719 100644 --- a/content/en/user-guide/step-functions-tools/mocked-service-integrations/index.md +++ b/content/en/user-guide/step-functions-tools/mocked-service-integrations/index.md @@ -55,7 +55,7 @@ In this example, the state machine LambdaSQSIntegration will be used with the fo { "ErrorEquals":[ "States.ALL" ], "IntervalSeconds":2, - "MaxAttempts": 4, + "MaxAttempts":4, "BackoffRate":2 } ], From b21cbec602836745dd52ea31173100f4e73b9323 Mon Sep 17 00:00:00 2001 From: Harsh Mishra Date: Thu, 1 May 2025 18:04:41 +0530 Subject: [PATCH 06/10] push some improvements --- .../en/user-guide/aws/stepfunctions/index.md | 367 ++++++++++++++++++ .../user-guide/step-functions-tools/_index.md | 18 - .../mocked-service-integrations/index.md | 365 ----------------- 3 files changed, 367 insertions(+), 383 deletions(-) delete mode 100755 content/en/user-guide/step-functions-tools/_index.md delete mode 100644 content/en/user-guide/step-functions-tools/mocked-service-integrations/index.md diff --git a/content/en/user-guide/aws/stepfunctions/index.md b/content/en/user-guide/aws/stepfunctions/index.md index a972c55a35..447e1bd68f 100644 --- a/content/en/user-guide/aws/stepfunctions/index.md +++ b/content/en/user-guide/aws/stepfunctions/index.md @@ -133,6 +133,373 @@ LocalStack's Step Functions emulation supports the following AWS services: | | AWS Batch | ✓ | ✓ | | | | AWS SDK integrations | All LocalStack services | ✓ | | | ✓ | +## Mocked Service Integrations + +Mocked service integrations allow you to test AWS Step Functions without calling LocalStack's emulated AWS services. +Instead, Task states return predefined outputs from a mock configuration file. +They key components are: + +- **Mocked service integrations**: Task states that return predefined responses instead of invoking local AWS services. +- **Mocked responses**: Static payloads associated with mocked Task states. +- **Test cases**: State machine executions using mocked responses. +- **Mock configuration file**: JSON file that defines test cases, mocked states, and their response payloads. + +During execution, each Task state defined in the mock file returns its corresponding mocked response. +States not listed continue to invoke their real emulated services, allowing a mix of mocked and live interactions. + +You can provide one or more mocked payloads per Task state. +Supported patterns include `.sync`, `.sync2`, and `.waitForTaskToken`. +Both success and failure scenarios can be simulated. + +{{< callout >}} +LocalStack does not validate response formats. +Ensure the payload structure matches what the real service expects. +{{< /callout >}} + +### Identify a State Machine for Mocked Integrations + +Mocked service integrations apply to specific state machine definitions. +The first step is to select the state machine where mocked responses will be used. + +In this example, the `LambdaSQSIntegration` state machine will be used with the following definition: + +```json +{ + "Comment":"This state machine is called: LambdaSQSIntegration", + "QueryLanguage":"JSONata", + "StartAt":"LambdaState", + "States":{ + "LambdaState":{ + "Type":"Task", + "Resource":"arn:aws:states:::lambda:invoke", + "Arguments":{ + "FunctionName":"GreetingsFunction", + "Payload":{ + "fullname":"{% $states.input.name & ' ' & $states.input.surname %}" + } + }, + "Retry":[ + { + "ErrorEquals":[ "States.ALL" ], + "IntervalSeconds":2, + "MaxAttempts":4, + "BackoffRate":2 + } + ], + "Assign":{ + "greeting":"{% $states.result.Payload.greeting %}" + }, + "Next":"SQSState" + }, + "SQSState":{ + "Type":"Task", + "Resource":"arn:aws:states:::sqs:sendMessage", + "Arguments":{ + "QueueUrl":"http://sqs.us-east-1.localhost.localstack.cloud:4566/000000000000/localstack-queue", + "MessageBody":"{% $greeting %}" + }, + "End":true + } + } +} +``` + +### Define Mock Integrations in a Configuration File + +Mock integrations are defined in a JSON file that follows the `RawMockConfig` schema. +The file contains two top-level sections: + +- **StateMachines** – Maps each state machine to its test cases, specifying which states use which mocked responses. +- **MockedResponses** – Defines reusable mock payloads identified by `ResponseID`, which test cases refer to. + +#### `StateMachines` + +This section specifies the Step Functions state machines to mock and their test cases. +Each test case maps state names to response IDs defined in `MockedResponses`. + +```json +"StateMachines": { + "": { + "TestCases": { + "": { + "": "", + ... + } + } + } +} +``` + +In the example above: + +- `StateMachineName`: Must match the exact name used during creation in LocalStack. +- `TestCases`: Named scenarios that define mocked behavior for individual states. + +Each test case maps Task states to mock responses that define expected behavior. +At runtime, if a test case is selected, the state uses the mock response if defined; otherwise, it calls the emulated service. + +Here is a full example of the `StateMachines` section: + +```json +"LambdaSQSIntegration": { + "TestCases": { + "LambdaRetryCase": { + "LambdaState": "MockedLambdaStateRetry", + "SQSState": "MockedSQSStateSuccess" + } + } +} +``` + +#### `MockedResponses` + +This section defines mocked responses for Task states. +Each `ResponseID` contains one or more step keys and either a `Return` or `Throw`. + +```json +"MockedResponses": { + "": { + "": { "Return": ... }, + "": { "Throw": ... } + } +} +``` + +In the example above: + +- `ResponseID`: Unique identifier referenced in test cases. +- `step-key`: Indicates the attempt (e.g., `"0"` for first try, `"1-2"` for a range). +- `Return`: Simulates success with a response payload. +- `Throw`: Simulates failure with `Error` and `Cause`. + +{{< callout >}} +Each entry must have **either** `Return` or `Throw`—not both. +{{< /callout >}} + +Here is a full example of the `MockedResponses` section: + +```json +"MockedLambdaStateRetry": { + "0": { + "Throw": { + "Error": "Lambda.ServiceException", + "Cause": "An internal service error occurred." + } + }, + "1-2": { + "Throw": { + "Error": "Lambda.TooManyRequestsException", + "Cause": "Invocation rate limit exceeded." + } + }, + "3": { + "Return": { + "StatusCode": 200, + "Payload": { + "greeting": "Hello John Smith, you’re now testing mocked integrations with LocalStack!" + } + } + } +} +``` + +The `MockConfigFile.json` below is used to test the `LambdaSQSIntegration` state machine defined earlier. + +```json +{ + "StateMachines":{ + "LambdaSQSIntegration":{ + "TestCases":{ + "BaseCase":{ + "LambdaState":"MockedLambdaStateSuccess", + "SQSState":"MockedSQSStateSuccess" + }, + "LambdaRetryCase":{ + "LambdaState":"MockedLambdaStateRetry", + "SQSState":"MockedSQSStateSuccess" + }, + "HybridCase":{ + "LambdaState":"MockedLambdaSuccess" + } + } + } + }, + "MockedResponses":{ + "MockedLambdaStateSuccess":{ + "0":{ + "Return":{ + "StatusCode":200, + "Payload":{ + "greeting":"Hello John Smith, you’re now testing mocked integrations with LocalStack!" + } + } + } + }, + "MockedSQSStateSuccess":{ + "0":{ + "Return":{ + "MD5OfMessageBody":"3661896f-1287-45a3-8f89-53bd7b25a9a6", + "MessageId":"7c9ef661-c455-4779-a9c2-278531e231c2" + } + } + }, + "MockedLambdaStateRetry":{ + "0":{ + "Throw":{ + "Error":"Lambda.ServiceException", + "Cause":"An internal service error occurred." + } + }, + "1-2":{ + "Throw":{ + "Error":"Lambda.TooManyRequestsException", + "Cause":"Invocation rate limit exceeded." + } + }, + "3":{ + "Return":{ + "StatusCode":200, + "Payload":{ + "greeting":"Hello John Smith, you’re now testing mocked integrations with LocalStack!" + } + } + } + } + } +} +``` + +### Provide the Mock Configuration to LocalStack + +Set the `SFN_MOCK_CONFIG` configuration variable to the path of the mock configuration file. +When running LocalStack in Docker, mount the file and pass the variable as shown below: + +{{< tabpane >}} +{{< tab header="LocalStack CLI" lang="shell" >}} +LOCALSTACK_SFN_MOCK_CONFIG=/tmp/MockConfigFile.json \ +localstack start --volume /path/to/MockConfigFile.json:/tmp/MockConfigFile.json +{{< /tab >}} +{{< tab header="Docker Compose" lang="yaml" >}} +services: + localstack: + container_name: "${LOCALSTACK_DOCKER_NAME:-localstack-main}" + image: localstack/localstack-pro + ports: + - "127.0.0.1:4566:4566" # LocalStack Gateway + - "127.0.0.1:4510-4559:4510-4559" # external services port range + - "127.0.0.1:443:443" # LocalStack HTTPS Gateway (Pro) + environment: + # LocalStack configuration: https://docs.localstack.cloud/references/configuration/ + - DEBUG=${DEBUG:-0} + - SFN_MOCK_CONFIG=/tmp/MockConfigFile.json + volumes: + - "${LOCALSTACK_VOLUME_DIR:-./volume}:/var/lib/localstack" + - "/var/run/docker.sock:/var/run/docker.sock" + - "./MockConfigFile.json:/tmp/MockConfigFile.json" +{{< /tab >}} +{{< /tabpane >}} + +This tells LocalStack to use the specified file for mocked service integrations during Step Functions execution. + +### Run Test Cases with Mocked Integrations + +Create the state machine to match the name defined in the mock configuration file. +In this example, create the `LambdaSQSIntegration` state machine using: + +{{< command >}} +$ awslocal stepfunctions create-state-machine \ + --definition file://LambdaSQSIntegration.json \ + --name "LambdaSQSIntegration" \ + --role-arn "arn:aws:iam::000000000000:role/service-role/testrole" +{{< /command >}} + +After the state machine is created and named correctly, test cases from the mock configuration file can be run using the [`StartExecution`](https://docs.aws.amazon.com/step-functions/latest/apireference/API_StartExecution.html) or [StartSyncExecution](https://docs.aws.amazon.com/step-functions/latest/apireference/API_StartSyncExecution.html) APIs. + +To execute a test case, append the test case name to the state machine ARN using `#`. +This tells LocalStack to apply the mocked responses from the configuration file. +For example, run the `BaseCase` test case: + +{{< command >}} +$ awslocal stepfunctions start-execution \ + --state-machine arn:aws:states:ca-central-1:000000000000:stateMachine:LambdaSQSIntegration#BaseCase \ + --input '{"name": "John", "surname": "smith"}' \ + --name "MockExecutionBaseCase" +{{< /command >}} + +During execution, any state mapped in the mock config will use the predefined response. +States without mock entries invoke the actual emulated service as usual. + +You can inspect the execution using the [`DescribeExecution`](https://docs.aws.amazon.com/step-functions/latest/apireference/API_DescribeExecution.html) API: + +{{< command >}} +$ awslocal stepfunctions describe-execution \ + --execution-arn "arn:aws:states:ca-central-1:000000000000:execution:LambdaSQSIntegration:MockExecutionBaseCase" +{{< /command >}} + +The sample output shows the execution details, including the state machine ARN, execution ARN, status, start and stop dates, input, and output: + +```json +{ + "executionArn": "arn:aws:states:ca-central-1:000000000000:execution:LambdaSQSIntegration:MockExecutionBaseCase", + "stateMachineArn": "arn:aws:states:ca-central-1:000000000000:stateMachine:LambdaSQSIntegration", + "name": "MockExecutionBaseCase", + "status": "SUCCEEDED", + "startDate": "...", + "stopDate": "...", + "input": "{\"name\":\"John\",\"surname\":\"smith\"}", + "inputDetails": { + "included": true + }, + "output": "{\"MessageId\":\"7c9ef661-c455-4779-a9c2-278531e231c2\",\"MD5OfMessageBody\":\"3661896f-1287-45a3-8f89-53bd7b25a9a6\"}", + "outputDetails": { + "included": true + } +} +``` + +You can also use the [`GetExecutionHistory`](https://docs.aws.amazon.com/step-functions/latest/apireference/API_GetExecutionHistory.html) API to retrieve the execution history, including the events and their details. + +{{< command >}} +$ awslocal stepfunctions get-execution-history \ + --execution-arn "arn:aws:states:ca-central-1:000000000000:execution:LambdaSQSIntegration:MockExecutionBaseCase" +{{< /command >}} + +This will return the full execution history, including entries that indicate how the mocked responses were applied to the Lambda and SQS states. + +```json +... +{ + "timestamp": "...", + "type": "TaskSucceeded", + "id": 5, + "previousEventId": 4, + "taskSucceededEventDetails": { + "resourceType": "lambda", + "resource": "invoke", + "output": "{\"StatusCode\": 200, \"Payload\": {\"greeting\": \"Hello John Smith, you\\u2019re now testing mocked integrations with LocalStack!\"}}", + "outputDetails": { + "truncated": false + } + } +} +... +{ + "timestamp": "...", + "type": "TaskSucceeded", + "id": 10, + "previousEventId": 9, + "taskSucceededEventDetails": { + "resourceType": "sqs", + "resource": "sendMessage", + "output": "{\"MessageId\": \"7c9ef661-c455-4779-a9c2-278531e231c2\", \"MD5OfMessageBody\": \"3661896f-1287-45a3-8f89-53bd7b25a9a6\"}", + "outputDetails": { + "truncated": false + } + } +} +... +``` + ## Resource Browser The LocalStack Web Application provides a Resource Browser for managing Step Functions state machines. diff --git a/content/en/user-guide/step-functions-tools/_index.md b/content/en/user-guide/step-functions-tools/_index.md deleted file mode 100755 index 80bc28193d..0000000000 --- a/content/en/user-guide/step-functions-tools/_index.md +++ /dev/null @@ -1,18 +0,0 @@ ---- -title: "Step Functions Tools" -linkTitle: "Step Functions Tools" -weight: 45 -description: > - Develop your state machines more efficiently -aliases: - - /tools/step-functions-tools/ - - /user-guide/tools/step-functions-tools/ ---- - -Step Functions Tools by LocalStack gives you a single, purpose-built utilities that lets you design, deploy, and debug AWS Step Functions state machines entirely on your local machine. -With LocalStack’s full Step Functions emulation—including integrations with other AWS services—you can iterate rapidly without ever deploying to AWS, getting instant feedback and a smoother developer-testing workflow. - -With Step Functions Tools, you can: - -- Mock any AWS integration, DynamoDB, SQS, API Gateway, and more, with configurable responses. - Test success/failure paths, edge cases, and retries and catches locally, watching live state transitions. diff --git a/content/en/user-guide/step-functions-tools/mocked-service-integrations/index.md b/content/en/user-guide/step-functions-tools/mocked-service-integrations/index.md deleted file mode 100644 index 896cbfd719..0000000000 --- a/content/en/user-guide/step-functions-tools/mocked-service-integrations/index.md +++ /dev/null @@ -1,365 +0,0 @@ ---- -title: "Mocked Service Integrations" -weight: 2 -description: > - Attach a debugger to your Lambda functions from within your IDE -aliases: - - /tools/step-functions-tools/mocked-service-integrations/ - - /user-guide/tools/step-functions-tools/mocked-service-integrations/ ---- - -# Introduction - -Mocked service integrations eliminate the need to deploy or invoke real AWS services during Step Functions testing. -Instead, each Task state returns a predefined output supplied through a mock configuration file. -The file lists one or more test cases per state machine, with a set of mocked responses mapped to individual states. -When a state machine is executed in mock mode, the runtime simply samples the specified responses, substituting them for calls to the actual integrated resources. -States without a corresponding mock entry continue to invoke their real services, allowing selective mixing of mocked and live interactions within the same execution. - -The following definitions clarify key concepts used throughout this section: -- Mocked service integrations – Task states that are instructed to return predefined data instead of making live AWS calls. -- Mocked responses – The static payloads supplied to those Task states. -- Test cases – Individual state-machine runs that are executed with mocked service integrations enabled. -- Mock configuration file – A JSON document that declares the test cases, their mocked integrations, and the response data used for each state. - -## Mocking service integrations - -When mocked service integrations are enabled for specific Task states, one or more response payloads can be declared for each state. -During execution, the LocalStack runtime returns these payloads instead of calling the live AWS service. -Any Task state—using patterns such as .sync, .sync2, or .waitForTaskToken—can be mocked, and both success or failure scenarios can be reproduced. -Payload correctness is not validated by the tool, so it is up to the developer to supply responses that match the service’s expected structure. - -### 1. Identify a State Machine to Configure with Mocked Integrations - -Mocked service integrations are bound to specific state machine definitions. -Therefore, the first step is to choose the state machine where mocked responses will be applied. -LocalStack supports the latest AWS Step Functions features, including [JSONata expressions and Variables](https://blog.localstack.cloud/aws-step-functions-made-easy/). -In this example, the state machine LambdaSQSIntegration will be used with the following definition: - -```json -{ - "Comment":"This state machine is called: LambdaSQSIntegration", - "QueryLanguage":"JSONata", - "StartAt":"LambdaState", - "States":{ - "LambdaState":{ - "Type":"Task", - "Resource":"arn:aws:states:::lambda:invoke", - "Arguments":{ - "FunctionName":"GreetingsFunction", - "Payload":{ - "fullname":"{% $states.input.name & ' ' & $states.input.surname %}" - } - }, - "Retry":[ - { - "ErrorEquals":[ "States.ALL" ], - "IntervalSeconds":2, - "MaxAttempts":4, - "BackoffRate":2 - } - ], - "Assign":{ - "greeting":"{% $states.result.Payload.greeting %}" - }, - "Next":"SQSState" - }, - "SQSState":{ - "Type":"Task", - "Resource":"arn:aws:states:::sqs:sendMessage", - "Arguments":{ - "QueueUrl":"http://sqs.us-east-1.localhost.localstack.cloud:4566/000000000000/localstack-queue", - "MessageBody":"{% $greeting %}" - }, - "End":true - } - } -} -``` - -### 2. Define mock integrations in a configuration file - -Mock integrations are declared in a single mock configuration file written in JSON. -The file must conform to the RawMockConfig schema shown above and is organised into two top-level sections: - -- StateMachines - maps each state machine name to the test scenarios that will run against it. -- MockedResponses - holds the reusable response sets that the test scenarios reference. - -#### 2.1 StateMachines -The StateMachines section defines which Step Functions state machines will use mocked service integrations and how their test cases are configured. -Each entry under StateMachines corresponds to a specific state machine and contains one or more named test cases that specify how the states within that machine should behave during execution. - -```json -"StateMachines": { - "": { - "TestCases": { - "": { - "": "", - ... - } - } - } -} -``` - -- StateMachineName – The exact name of the Step Functions state machine. -This must match the name used when the state machine is created in LocalStack. -- TestCases – A set of named test scenarios. -Each test case maps one or more state names to a predefined ResponseID from the MockedResponses section. - -Each test case defines the expected behavior of specific Task states by assigning them to mock response sets. -When the test case is selected at runtime, these bindings determine whether the state uses a mocked response or proceeds with a real service invocation (if no mock is provided). - -```json -"LambdaSQSIntegration": { - "TestCases": { - "LambdaRetryCase": { - "LambdaState": "MockedLambdaStateRetry", - "SQSState": "MockedSQSStateSuccess" - } - } -} -``` - -#### 2.2 MockedResponses -The MockedResponses section defines reusable response sets that simulate the behavior of specific Task states during test execution. -Each response set is identified by a unique ResponseID, which is then referenced in one or more test cases under the StateMachines section. - -```json -"MockedResponses": { - "": { - "": { "Return": ... }, - "": { "Throw": ... } - } -} -``` - -- ResponseID – A unique identifier for a set of mocked responses. -These IDs are used in test cases to associate a state with its corresponding mocked behavior. -- step-key – Defines which execution attempt the response applies to. -It can be: - - A single integer, e.g., "0" – applied on the first attempt. - - A range of integers, e.g., "1-5" – applied to multiple attempts. -- Steps are evaluated in sequential order, allowing simulation of retries or failures followed by success. - - Return – Defines a successful response payload to be returned by the state instead of invoking the actual integrated service. - - Throw – Defines an error response with required fields Error and Cause, simulating a failure. -- Each response entry must contain exactly one of Return or Throw. - Including both or neither will result in an invalid configuration. - -```json -"MockedLambdaStateRetry": { - "0": { - "Throw": { - "Error": "Lambda.ServiceException", - "Cause": "An internal service error occurred." - } - }, - "1-2": { - "Throw": { - "Error": "Lambda.TooManyRequestsException", - "Cause": "Invocation rate limit exceeded." - } - }, - "3": { - "Return": { - "StatusCode": 200, - "Payload": { - "greeting": "Hello John Smith, you’re now testing mocked integrations with LocalStack!" - } - } - } -} -``` - -The MockConfigFile.json shown below targets the previously defined LambdaSQSIntegration state machine for testing: - -```json -{ - "StateMachines":{ - "LambdaSQSIntegration":{ - "TestCases":{ - "BaseCase":{ - "LambdaState":"MockedLambdaStateSuccess", - "SQSState":"MockedSQSStateSuccess" - }, - "LambdaRetryCase":{ - "LambdaState":"MockedLambdaStateRetry", - "SQSState":"MockedSQSStateSuccess" - }, - "HybridCase":{ - "LambdaState":"MockedLambdaSuccess" - } - } - } - }, - "MockedResponses":{ - "MockedLambdaStateSuccess":{ - "0":{ - "Return":{ - "StatusCode":200, - "Payload":{ - "greeting":"Hello John Smith, you’re now testing mocked integrations with LocalStack!" - } - } - } - }, - "MockedSQSStateSuccess":{ - "0":{ - "Return":{ - "MD5OfMessageBody":"3661896f-1287-45a3-8f89-53bd7b25a9a6", - "MessageId":"7c9ef661-c455-4779-a9c2-278531e231c2" - } - } - }, - "MockedLambdaStateRetry":{ - "0":{ - "Throw":{ - "Error":"Lambda.ServiceException", - "Cause":"An internal service error occurred." - } - }, - "1-2":{ - "Throw":{ - "Error":"Lambda.TooManyRequestsException", - "Cause":"Invocation rate limit exceeded." - } - }, - "3":{ - "Return":{ - "StatusCode":200, - "Payload":{ - "greeting":"Hello John Smith, you’re now testing mocked integrations with LocalStack!" - } - } - } - } - } -} -``` - -### 3. Provide the Mock Configuration to LocalStack - -The `SFN_MOCK_CONFIG` environment variable specifies the path to the mock-configuration file. -When starting LocalStack in Docker, set this variable and mount the configuration file, e.g., MockConfigFile.json—as shown in the following examples. -{{< tabpane >}} -{{< tab header="LocalStack CLI" lang="shell" >}} -LOCALSTACK_SFN_MOCK_CONFIG=/tmp/MockConfigFile.json \ -localstack start --volume /path/to/MockConfigFile.json:/tmp/MockConfigFile.json -{{< /tab >}} -{{< tab header="Docker Compose" lang="yaml" >}} -services: - localstack: - container_name: "${LOCALSTACK_DOCKER_NAME:-localstack-main}" - image: localstack/localstack-pro - ports: - - "127.0.0.1:4566:4566" # LocalStack Gateway - - "127.0.0.1:4510-4559:4510-4559" # external services port range - - "127.0.0.1:443:443" # LocalStack HTTPS Gateway (Pro) - environment: - # LocalStack configuration: https://docs.localstack.cloud/references/configuration/ - - DEBUG=${DEBUG:-0} - - SFN_MOCK_CONFIG=/tmp/MockConfigFile.json - volumes: - - "${LOCALSTACK_VOLUME_DIR:-./volume}:/var/lib/localstack" - - "/var/run/docker.sock:/var/run/docker.sock" - - "./MockConfigFile.json:/tmp/MockConfigFile.json" -{{< /tab >}} -{{< /tabpane >}} - -### 4. Run Tests Cases with Mocked Integrations - -#### 4.1 Create the State Machine -The first step is to create the state machine for testing. -The name of the state machine must match the name defined in the mock configuration file. -Continuing from the example introduced earlier in this article, the state machine named LambdaSQSIntegration can be created with the following command: - -{{< command >}} -$ awslocal stepfunctions create-state-machine \ - --definition file://LambdaSQSIntegration.json \ - --name "LambdaSQSIntegration" \ - --role-arn "arn:aws:iam::000000000000:role/service-role/testrole" -{{< /command >}} - -#### 4.2 Start the Mock Test -Once the state machine is created and correctly named, test cases defined in the mock configuration file can be executed using the StartExecution or StartSyncExecution API. -To specify a test case, append the test case name to the state machine ARN using the # symbol. -For example, to run the BaseCase test case for the `LambdaSQSIntegration` state machine: - -{{< command >}} -$ awslocal stepfunctions start-execution \ - --state-machine arn:aws:states:ca-central-1:000000000000:stateMachine:LambdaSQSIntegration#BaseCase \ - --input '{"name": "John", "surname": "smith"}' \ - --name "MockExecutionBaseCase" -{{< /command >}} -During execution, the state machine uses the mocked responses defined in the mock configuration file for each state. -If no mocked response is specified for a given state, the associated service integration will be invoked as normal. - -#### 4.3 Inspect the Execution -After a mock test case is initiated, the state machine execution behaves like a standard execution and can be monitored using API actions such as `GetExecutionHistory` and `DescribeExecution`. -Continuing from the previous example, the execution can be described with the following command: -{{< command >}} -$ awslocal stepfunctions describe-execution \ - --execution-arn "arn:aws:states:ca-central-1:000000000000:execution:LambdaSQSIntegration:MockExecutionBaseCase" -{{< /command >}} -The response will include the output defined in the mock configuration file for `SQSState`, in this case corresponding to `MockedSQSStateSuccess`. - -```json -{ - "executionArn": "arn:aws:states:ca-central-1:000000000000:execution:LambdaSQSIntegration:MockExecutionBaseCase", - "stateMachineArn": "arn:aws:states:ca-central-1:000000000000:stateMachine:LambdaSQSIntegration", - "name": "MockExecutionBaseCase", - "status": "SUCCEEDED", - "startDate": "...", - "stopDate": "...", - "input": "{\"name\":\"John\",\"surname\":\"smith\"}", - "inputDetails": { - "included": true - }, - "output": "{\"MessageId\":\"7c9ef661-c455-4779-a9c2-278531e231c2\",\"MD5OfMessageBody\":\"3661896f-1287-45a3-8f89-53bd7b25a9a6\"}", - "outputDetails": { - "included": true - } -} -``` - -The execution history can also be retrieved using the following command: -{{< command >}} -$ awslocal stepfunctions get-execution-history \ - --execution-arn "arn:aws:states:ca-central-1:000000000000:execution:LambdaSQSIntegration:MockExecutionBaseCase" -{{< /command >}} - -This returns the full execution history, including entries that indicate how the mocked responses were applied to the Lambda and SQS states. - -```json -... -{ - "timestamp": "...", - "type": "TaskSucceeded", - "id": 5, - "previousEventId": 4, - "taskSucceededEventDetails": { - "resourceType": "lambda", - "resource": "invoke", - "output": "{\"StatusCode\": 200, \"Payload\": {\"greeting\": \"Hello John Smith, you\\u2019re now testing mocked integrations with LocalStack!\"}}", - "outputDetails": { - "truncated": false - } - } -} -... -{ - "timestamp": "...", - "type": "TaskSucceeded", - "id": 10, - "previousEventId": 9, - "taskSucceededEventDetails": { - "resourceType": "sqs", - "resource": "sendMessage", - "output": "{\"MessageId\": \"7c9ef661-c455-4779-a9c2-278531e231c2\", \"MD5OfMessageBody\": \"3661896f-1287-45a3-8f89-53bd7b25a9a6\"}", - "outputDetails": { - "truncated": false - } - } -} -... -``` From efe83c8d253fd493501590fd61615994d5fed78f Mon Sep 17 00:00:00 2001 From: MEPalma <64580864+MEPalma@users.noreply.github.com> Date: Tue, 6 May 2025 13:13:17 +0200 Subject: [PATCH 07/10] pr items --- content/en/references/configuration.md | 6 ++ .../en/user-guide/aws/stepfunctions/index.md | 88 ++++++++++--------- 2 files changed, 51 insertions(+), 43 deletions(-) diff --git a/content/en/references/configuration.md b/content/en/references/configuration.md index c8ee8e1209..a033f74e5b 100644 --- a/content/en/references/configuration.md +++ b/content/en/references/configuration.md @@ -337,6 +337,12 @@ Please consult the [migration guide]({{< ref "user-guide/aws/lambda#migrating-to | `SQS_DISABLE_CLOUDWATCH_METRICS` | `0` (default) | Disables the CloudWatch Metrics for SQS when set to `1` | | `SQS_CLOUDWATCH_METRICS_REPORT_INTERVAL` | `60` (default) | Configures the report interval (in seconds) for `Approximate*` metrics that are sent to CloudWatch periodically. Sending will be disabled if `SQS_DISABLE_CLOUDWATCH_METRICS=1` | +### Step Functions + +| Variable | Example Values | Description | +| - | - | - | +| `SFN_MOCK_CONFIG` | `/tmp/MockConfigFile.json` | Specifies the file path to the mock configuration file that defines mock service integrations for Step Functions. | + ## Security {{< callout "warning" >}} diff --git a/content/en/user-guide/aws/stepfunctions/index.md b/content/en/user-guide/aws/stepfunctions/index.md index 447e1bd68f..dc41017e48 100644 --- a/content/en/user-guide/aws/stepfunctions/index.md +++ b/content/en/user-guide/aws/stepfunctions/index.md @@ -137,7 +137,7 @@ LocalStack's Step Functions emulation supports the following AWS services: Mocked service integrations allow you to test AWS Step Functions without calling LocalStack's emulated AWS services. Instead, Task states return predefined outputs from a mock configuration file. -They key components are: +The key components are: - **Mocked service integrations**: Task states that return predefined responses instead of invoking local AWS services. - **Mocked responses**: Static payloads associated with mocked Task states. @@ -148,12 +148,18 @@ During execution, each Task state defined in the mock file returns its correspon States not listed continue to invoke their real emulated services, allowing a mix of mocked and live interactions. You can provide one or more mocked payloads per Task state. -Supported patterns include `.sync`, `.sync2`, and `.waitForTaskToken`. +The Supported patterns include `.sync`, `.sync2`, and `.waitForTaskToken`. Both success and failure scenarios can be simulated. +### Compatibility with AWS Step Functions Local + +LocalStack can also serve as a drop-in replacement for [AWS Step Functions Local testing with mocked service integrations](https://docs.aws.amazon.com/step-functions/latest/dg/sfn-local-test-sm-exec.html). +It supports test cases with mocked Task states and maintains compatibility with existing Step Functions Local configurations. +This functionality is extended in LocalStack by providing access to the latest Step Functions features such as [JSONata and Variables](https://blog.localstack.cloud/aws-step-functions-made-easy/), as well as the ability to enable both mocked and emulated service interactions emulated by LocalStack. + {{< callout >}} LocalStack does not validate response formats. -Ensure the payload structure matches what the real service expects. +Ensure the payload structure in the mocked responses matches what the real service expects. {{< /callout >}} ### Identify a State Machine for Mocked Integrations @@ -161,44 +167,44 @@ Ensure the payload structure matches what the real service expects. Mocked service integrations apply to specific state machine definitions. The first step is to select the state machine where mocked responses will be used. -In this example, the `LambdaSQSIntegration` state machine will be used with the following definition: +In this example, the state machine with the name `LambdaSQSIntegration` state machine will be used with the following definition: ```json { - "Comment":"This state machine is called: LambdaSQSIntegration", - "QueryLanguage":"JSONata", - "StartAt":"LambdaState", - "States":{ - "LambdaState":{ - "Type":"Task", - "Resource":"arn:aws:states:::lambda:invoke", - "Arguments":{ - "FunctionName":"GreetingsFunction", - "Payload":{ - "fullname":"{% $states.input.name & ' ' & $states.input.surname %}" + "Comment": "This state machine is called: LambdaSQSIntegration", + "QueryLanguage": "JSONata", + "StartAt": "LambdaState", + "States": { + "LambdaState": { + "Type": "Task", + "Resource": "arn:aws:states:::lambda:invoke", + "Arguments": { + "FunctionName": "GreetingsFunction", + "Payload": { + "fullname": "{% $states.input.name & ' ' & $states.input.surname %}" } }, - "Retry":[ + "Retry": [ { - "ErrorEquals":[ "States.ALL" ], - "IntervalSeconds":2, - "MaxAttempts":4, - "BackoffRate":2 + "ErrorEquals": [ "States.ALL" ], + "IntervalSeconds": 2, + "MaxAttempts": 4, + "BackoffRate": 2 } ], - "Assign":{ - "greeting":"{% $states.result.Payload.greeting %}" + "Assign": { + "greeting": "{% $states.result.Payload.greeting %}" }, - "Next":"SQSState" + "Next": "SQSState" }, - "SQSState":{ - "Type":"Task", - "Resource":"arn:aws:states:::sqs:sendMessage", - "Arguments":{ - "QueueUrl":"http://sqs.us-east-1.localhost.localstack.cloud:4566/000000000000/localstack-queue", - "MessageBody":"{% $greeting %}" + "SQSState": { + "Type": "Task", + "Resource": "arn:aws:states:::sqs:sendMessage", + "Arguments": { + "QueueUrl": "http://sqs.us-east-1.localhost.localstack.cloud:4566/000000000000/localstack-queue", + "MessageBody": "{% $greeting %}" }, - "End":true + "End": true } } } @@ -206,8 +212,7 @@ In this example, the `LambdaSQSIntegration` state machine will be used with the ### Define Mock Integrations in a Configuration File -Mock integrations are defined in a JSON file that follows the `RawMockConfig` schema. -The file contains two top-level sections: +Mock integrations are defined in a JSON file with two top-level section: - **StateMachines** – Maps each state machine to its test cases, specifying which states use which mocked responses. - **MockedResponses** – Defines reusable mock payloads identified by `ResponseID`, which test cases refer to. @@ -273,7 +278,7 @@ In the example above: - `Throw`: Simulates failure with `Error` and `Cause`. {{< callout >}} -Each entry must have **either** `Return` or `Throw`—not both. +Each entry must have **either** `Return` or `Throw`, but cannot have both. {{< /callout >}} Here is a full example of the `MockedResponses` section: @@ -383,11 +388,10 @@ localstack start --volume /path/to/MockConfigFile.json:/tmp/MockConfigFile.json services: localstack: container_name: "${LOCALSTACK_DOCKER_NAME:-localstack-main}" - image: localstack/localstack-pro + image: localstack/localstack ports: - "127.0.0.1:4566:4566" # LocalStack Gateway - "127.0.0.1:4510-4559:4510-4559" # external services port range - - "127.0.0.1:443:443" # LocalStack HTTPS Gateway (Pro) environment: # LocalStack configuration: https://docs.localstack.cloud/references/configuration/ - DEBUG=${DEBUG:-0} @@ -399,8 +403,6 @@ services: {{< /tab >}} {{< /tabpane >}} -This tells LocalStack to use the specified file for mocked service integrations during Step Functions execution. - ### Run Test Cases with Mocked Integrations Create the state machine to match the name defined in the mock configuration file. @@ -413,7 +415,7 @@ $ awslocal stepfunctions create-state-machine \ --role-arn "arn:aws:iam::000000000000:role/service-role/testrole" {{< /command >}} -After the state machine is created and named correctly, test cases from the mock configuration file can be run using the [`StartExecution`](https://docs.aws.amazon.com/step-functions/latest/apireference/API_StartExecution.html) or [StartSyncExecution](https://docs.aws.amazon.com/step-functions/latest/apireference/API_StartSyncExecution.html) APIs. +After the state machine is created and named correctly, test cases from the mock configuration file can be run using the [`StartExecution`](https://docs.aws.amazon.com/step-functions/latest/apireference/API_StartExecution.html) API. To execute a test case, append the test case name to the state machine ARN using `#`. This tells LocalStack to apply the mocked responses from the configuration file. @@ -421,7 +423,7 @@ For example, run the `BaseCase` test case: {{< command >}} $ awslocal stepfunctions start-execution \ - --state-machine arn:aws:states:ca-central-1:000000000000:stateMachine:LambdaSQSIntegration#BaseCase \ + --state-machine arn:aws:states:us-east-1:000000000000:stateMachine:LambdaSQSIntegration#BaseCase \ --input '{"name": "John", "surname": "smith"}' \ --name "MockExecutionBaseCase" {{< /command >}} @@ -433,15 +435,15 @@ You can inspect the execution using the [`DescribeExecution`](https://docs.aws.a {{< command >}} $ awslocal stepfunctions describe-execution \ - --execution-arn "arn:aws:states:ca-central-1:000000000000:execution:LambdaSQSIntegration:MockExecutionBaseCase" + --execution-arn "arn:aws:states:us-east-1:000000000000:execution:LambdaSQSIntegration:MockExecutionBaseCase" {{< /command >}} The sample output shows the execution details, including the state machine ARN, execution ARN, status, start and stop dates, input, and output: ```json { - "executionArn": "arn:aws:states:ca-central-1:000000000000:execution:LambdaSQSIntegration:MockExecutionBaseCase", - "stateMachineArn": "arn:aws:states:ca-central-1:000000000000:stateMachine:LambdaSQSIntegration", + "executionArn": "arn:aws:states:us-east-1:000000000000:execution:LambdaSQSIntegration:MockExecutionBaseCase", + "stateMachineArn": "arn:aws:states:us-east-1:000000000000:stateMachine:LambdaSQSIntegration", "name": "MockExecutionBaseCase", "status": "SUCCEEDED", "startDate": "...", @@ -461,7 +463,7 @@ You can also use the [`GetExecutionHistory`](https://docs.aws.amazon.com/step-fu {{< command >}} $ awslocal stepfunctions get-execution-history \ - --execution-arn "arn:aws:states:ca-central-1:000000000000:execution:LambdaSQSIntegration:MockExecutionBaseCase" + --execution-arn "arn:aws:states:us-east-1:000000000000:execution:LambdaSQSIntegration:MockExecutionBaseCase" {{< /command >}} This will return the full execution history, including entries that indicate how the mocked responses were applied to the Lambda and SQS states. From 947c3cd3dad4729c9b03836b2773e45bad97168e Mon Sep 17 00:00:00 2001 From: MEPalma <64580864+MEPalma@users.noreply.github.com> Date: Wed, 7 May 2025 09:29:41 +0200 Subject: [PATCH 08/10] fix caps --- content/en/user-guide/aws/stepfunctions/index.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/en/user-guide/aws/stepfunctions/index.md b/content/en/user-guide/aws/stepfunctions/index.md index dc41017e48..7863539ac1 100644 --- a/content/en/user-guide/aws/stepfunctions/index.md +++ b/content/en/user-guide/aws/stepfunctions/index.md @@ -148,7 +148,7 @@ During execution, each Task state defined in the mock file returns its correspon States not listed continue to invoke their real emulated services, allowing a mix of mocked and live interactions. You can provide one or more mocked payloads per Task state. -The Supported patterns include `.sync`, `.sync2`, and `.waitForTaskToken`. +The supported patterns include `.sync`, `.sync2`, and `.waitForTaskToken`. Both success and failure scenarios can be simulated. ### Compatibility with AWS Step Functions Local From da6fd0ef7427b0f8051188327a0183f0f0199ad1 Mon Sep 17 00:00:00 2001 From: Quetzalli Date: Wed, 7 May 2025 17:07:50 -0700 Subject: [PATCH 09/10] improved mocked service integrations section --- .../en/user-guide/aws/stepfunctions/index.md | 20 ++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/content/en/user-guide/aws/stepfunctions/index.md b/content/en/user-guide/aws/stepfunctions/index.md index 7863539ac1..eeb527adf0 100644 --- a/content/en/user-guide/aws/stepfunctions/index.md +++ b/content/en/user-guide/aws/stepfunctions/index.md @@ -135,20 +135,22 @@ LocalStack's Step Functions emulation supports the following AWS services: ## Mocked Service Integrations -Mocked service integrations allow you to test AWS Step Functions without calling LocalStack's emulated AWS services. +Mocked service integrations let you test AWS Step Functions without invoking LocalStack’s emulated AWS services. Instead, Task states return predefined outputs from a mock configuration file. + The key components are: -- **Mocked service integrations**: Task states that return predefined responses instead of invoking local AWS services. -- **Mocked responses**: Static payloads associated with mocked Task states. -- **Test cases**: State machine executions using mocked responses. -- **Mock configuration file**: JSON file that defines test cases, mocked states, and their response payloads. +- **Mocked service integrations**: Task states that return predefined responses instead of calling local AWS services. +- **Mocked responses**: Static payloads linked to mocked Task states. +- **Test cases**: Executions of your state machine that use mocked responses. +- **Mock configuration file**: A JSON file that defines test cases, mocked states, and their response payloads. + +During execution, each Task state listed in the mock file returns its associated mocked response. States not included in the file continue to invoke the corresponding emulated services, allowing a mix of mocked and real interactions. + +You can define one or more mocked payloads per Task state. -During execution, each Task state defined in the mock file returns its corresponding mocked response. -States not listed continue to invoke their real emulated services, allowing a mix of mocked and live interactions. +Supported integration patterns include `.sync`, `.sync2`, and `.waitForTaskToken`. -You can provide one or more mocked payloads per Task state. -The supported patterns include `.sync`, `.sync2`, and `.waitForTaskToken`. Both success and failure scenarios can be simulated. ### Compatibility with AWS Step Functions Local From 9c390304cd8c4340bbceb9a1c0d3980a97bcf0c4 Mon Sep 17 00:00:00 2001 From: Quetzalli Date: Wed, 7 May 2025 17:48:49 -0700 Subject: [PATCH 10/10] improved more stuff --- .../en/user-guide/aws/stepfunctions/index.md | 67 +++++++++++-------- 1 file changed, 39 insertions(+), 28 deletions(-) diff --git a/content/en/user-guide/aws/stepfunctions/index.md b/content/en/user-guide/aws/stepfunctions/index.md index eeb527adf0..d9efe63536 100644 --- a/content/en/user-guide/aws/stepfunctions/index.md +++ b/content/en/user-guide/aws/stepfunctions/index.md @@ -166,10 +166,9 @@ Ensure the payload structure in the mocked responses matches what the real servi ### Identify a State Machine for Mocked Integrations -Mocked service integrations apply to specific state machine definitions. -The first step is to select the state machine where mocked responses will be used. +Mocked service integrations apply to specific state machine definitions. The first step is to select the state machine where mocked responses should be applied. -In this example, the state machine with the name `LambdaSQSIntegration` state machine will be used with the following definition: +In this example, we'll use a state machine named `LambdaSQSIntegration`, defined as follows: ```json { @@ -212,17 +211,21 @@ In this example, the state machine with the name `LambdaSQSIntegration` state ma } ``` -### Define Mock Integrations in a Configuration File +## Define Mock Integrations in a Configuration File -Mock integrations are defined in a JSON file with two top-level section: +Mock integrations are defined in a JSON file that follows the `RawMockConfig` schema. + +This file contains two top-level sections: - **StateMachines** – Maps each state machine to its test cases, specifying which states use which mocked responses. -- **MockedResponses** – Defines reusable mock payloads identified by `ResponseID`, which test cases refer to. +- **MockedResponses** – Defines reusable mock payloads, each identified by a `ResponseID`, which test cases can reference. + #### `StateMachines` -This section specifies the Step Functions state machines to mock and their test cases. -Each test case maps state names to response IDs defined in `MockedResponses`. +This section specifies the Step Functions state machines to mock, along with their corresponding test cases. + +Each test case maps state names to `ResponseID`s defined in the `MockedResponses` section. ```json "StateMachines": { @@ -239,13 +242,14 @@ Each test case maps state names to response IDs defined in `MockedResponses`. In the example above: -- `StateMachineName`: Must match the exact name used during creation in LocalStack. -- `TestCases`: Named scenarios that define mocked behavior for individual states. +- **`StateMachineName`**: Must exactly match the name used when the state machine was created in LocalStack. +- **`TestCases`**: Named scenarios that define mocked behavior for specific `Task` states. -Each test case maps Task states to mock responses that define expected behavior. -At runtime, if a test case is selected, the state uses the mock response if defined; otherwise, it calls the emulated service. +Each test case maps `Task` states to mock responses that define their expected behavior. -Here is a full example of the `StateMachines` section: +At runtime, if a test case is selected, the state uses the mocked response (if defined); otherwise, it falls back to calling the emulated service. + +Below is a complete example of the `StateMachines` section: ```json "LambdaSQSIntegration": { @@ -261,7 +265,8 @@ Here is a full example of the `StateMachines` section: #### `MockedResponses` This section defines mocked responses for Task states. -Each `ResponseID` contains one or more step keys and either a `Return` or `Throw`. + +Each `ResponseID` includes one or more step keys and defines either a `Return` value or a `Throw` error. ```json "MockedResponses": { @@ -274,16 +279,16 @@ Each `ResponseID` contains one or more step keys and either a `Return` or `Throw In the example above: -- `ResponseID`: Unique identifier referenced in test cases. -- `step-key`: Indicates the attempt (e.g., `"0"` for first try, `"1-2"` for a range). -- `Return`: Simulates success with a response payload. -- `Throw`: Simulates failure with `Error` and `Cause`. +- `ResponseID`: A unique identifier used in test cases to reference a specific mock response. +- `step-key`: Indicates the attempt number. For example, `"0"` refers to the first try, while `"1-2"` covers a range of attempts. +- `Return`: Simulates a successful response by returning a predefined payload. +- `Throw`: Simulates a failure by returning an `Error` and an optional `Cause`. {{< callout >}} Each entry must have **either** `Return` or `Throw`, but cannot have both. {{< /callout >}} -Here is a full example of the `MockedResponses` section: +Here is a complete example of the `MockedResponses` section: ```json "MockedLambdaStateRetry": { @@ -378,8 +383,9 @@ The `MockConfigFile.json` below is used to test the `LambdaSQSIntegration` state ### Provide the Mock Configuration to LocalStack -Set the `SFN_MOCK_CONFIG` configuration variable to the path of the mock configuration file. -When running LocalStack in Docker, mount the file and pass the variable as shown below: +Set the `SFN_MOCK_CONFIG` environment variable to the path of your mock configuration file. + +If you're running LocalStack in Docker, mount the file and pass the variable as shown below: {{< tabpane >}} {{< tab header="LocalStack CLI" lang="shell" >}} @@ -408,6 +414,7 @@ services: ### Run Test Cases with Mocked Integrations Create the state machine to match the name defined in the mock configuration file. + In this example, create the `LambdaSQSIntegration` state machine using: {{< command >}} @@ -417,11 +424,14 @@ $ awslocal stepfunctions create-state-machine \ --role-arn "arn:aws:iam::000000000000:role/service-role/testrole" {{< /command >}} -After the state machine is created and named correctly, test cases from the mock configuration file can be run using the [`StartExecution`](https://docs.aws.amazon.com/step-functions/latest/apireference/API_StartExecution.html) API. +After the state machine is created and correctly named, you can run test cases defined in the mock configuration file using the [`StartExecution`](https://docs.aws.amazon.com/step-functions/latest/apireference/API_StartExecution.html) API. + +To execute a test case, append the test case name to the state machine ARN using `#`. + +This tells LocalStack to apply the corresponding mocked responses from the configuration file. + +For example, to run the `BaseCase` test case: -To execute a test case, append the test case name to the state machine ARN using `#`. -This tells LocalStack to apply the mocked responses from the configuration file. -For example, run the `BaseCase` test case: {{< command >}} $ awslocal stepfunctions start-execution \ @@ -468,7 +478,7 @@ $ awslocal stepfunctions get-execution-history \ --execution-arn "arn:aws:states:us-east-1:000000000000:execution:LambdaSQSIntegration:MockExecutionBaseCase" {{< /command >}} -This will return the full execution history, including entries that indicate how the mocked responses were applied to the Lambda and SQS states. +This will return the full execution history, including entries that indicate how mocked responses were applied to Lambda and SQS states. ```json ... @@ -506,8 +516,9 @@ This will return the full execution history, including entries that indicate how ## Resource Browser -The LocalStack Web Application provides a Resource Browser for managing Step Functions state machines. -You can access the Resource Browser by opening the LocalStack Web Application in your browser, navigating to the **Resource Browser** section, and then clicking on **Step Functions** under the **App Integration** section. +The LocalStack Web Application includes a **Resource Browser** for managing Step Functions state machines. + +To access it, open the LocalStack Web UI in your browser, navigate to the **Resource Browser** section, and click **Step Functions** under **App Integration**. Step Functions Resource Browser