Running AWS Step Functions E2E Tests Locally and in GitHub Actions with AWS Emulator

This article was automatically translated from Japanese by AI. Read the original Japanese version →

Table of Contents

I previously introduced my serverless AWS game-ranking monitoring system on this blog, and this time I overhauled its testing setup.

Until now, the GitHub Actions test job connected to a real AWS account to validate the Step Functions definition and run E2E tests. Even for a personal project, hitting real AWS resources on every test run had always felt like something I wanted to fix.

Then, in November 2026, AWS officially released AWS Emulator (aws/aws-emulator), an official tool for emulating AWS APIs locally and in CI. It seemed like the right moment to migrate my Step Functions E2E tests to AWS Emulator and remove real AWS credentials and connectivity from the GitHub Actions test job.

In this post, I’ll walk through how I chose the tool, how the E2E tests are structured, the gotchas I hit along the way, and a latent bug in my existing workflow that the emulator helped uncover.

1. Overview of the Target System

For the broader background and diffing logic, see my earlier post:

Catching VR & PC Game Trends! Building an Automated Ranking Monitoring SystemHow I built a serverless AWS system (EventBridge, Step Functions, Lambda, S3, SNS) to monitor Meta Quest, Steam, and itch.io for newly ranked games.kazasiki.jp

Focusing just on the parts relevant to testing: the system is a serverless stack managed with AWS SAM, where a daily batch workflow is orchestrated by AWS Step Functions.

flowchart TD
    Start["EventBridge (Daily Schedule)"] --> Map["ProcessPlatforms (Map)"]
    Map --> Fetch["FetchRankings (Lambda)<br/>Fetch rankings & save to S3"]
    Fetch --> Compare["CompareRankings (Lambda)<br/>Compare with history & extract diff"]
    Compare --> Choice{"CheckNewGames<br/>newGamesFound?"}
    Choice -- true --> Notify["SendNotifications (Lambda)<br/>SNS Notification"]
    Choice -- false --> Log["LogNoNewGames (Pass)"]
    Notify --> Success["Success"]
    Log --> Success

    Fetch -. Catch .-> ErrNotify["NotifyError (SNS Publish)"]
    Compare -. Catch .-> ErrNotify
    Notify -. Catch .-> ErrNotify
    ErrNotify --> Fail["ExecutionFailed (Fail)"]

The four core AWS services involved are:

  • Step Functions: Orchestrates the overall workflow (statemachine/ranking_monitor.asl.yaml)
  • Lambda (Python 3.14): Three functions for fetching rankings, comparing history, and sending notifications
  • S3: Stores per-run snapshots and the historical list of previously ranked titles (history/{platform}/games.json)
  • SNS: Delivers new-game notifications and error alerts

Unit tests for individual Lambda functions were already running locally with moto, but executing the Step Functions workflow and verifying cross-service integration still depended on real AWS.

2. Why I Chose AWS Emulator

To decouple Step Functions tests from real AWS, I compared the main options available as of 2026:

  • moto: Still great for unit tests, but its Step Functions support is API-stub only without an ASL execution engine, so it cannot run workflows with Map or Choice states.
  • AWS Step Functions Local: Fast for Mock Config branch testing without an AWS account, but it is now marked unsupported in the official documentation and isn’t suited for integrating real Lambda code with S3 and SNS.
  • LocalStack: Feature-rich, but Community Edition support ended in March 2026, making account registration and LOCALSTACK_AUTH_TOKEN mandatory for recent images. While a free Hobby plan exists for non-commercial use, managing CI tokens and Docker-in-Docker adds extra friction.
  • AWS Emulator: Officially released by AWS in November 2026 under the CC0 license—free, with no account or token required. It ships as a native Rust binary, and on Linux you can install the official .deb package and run it without Docker, making it a natural fit for GitHub Actions ubuntu-latest.

Current Limitations and Trade-offs

Because it was just released, its current limitations are also clear:

  1. CloudFormation / SAM fidelity is still maturing: Deploying template.yml (AWS::Serverless::*) directly via sam deploy looked unstable, so for E2E tests I create the S3 bucket, SNS topic, Lambda functions, and Step Functions state machine directly via boto3.
  2. Gaps in ValidateStateMachineDefinition: There is a known issue (aws/aws-emulator#52) where ASL definitions missing required fields still return OK. I therefore kept the existing Node.js asl-validator for static ASL validation alongside the emulator.

Rather than forcing one tool to do everything, splitting responsibilities—moto for unit tests, asl-validator for static checks, and aws-emulator for workflow integration—made it practical right away.

3. Designing and Implementing E2E Tests with AWS Emulator

Installation and Startup

On Ubuntu (and GitHub Actions), installation is just grabbing and installing the official .deb package:

curl -fsSLo /tmp/aws-emulator.deb \
  https://downloads.aws.com/aws-emulator/packages/aws-emulator/LTS/latest/aws-emulator_amd64.deb
sudo apt-get install -y /tmp/aws-emulator.deb

During tests, I launch it with telemetry disabled:

aws-emulator -t off

By default, it listens on port 9297 (https://127.0.0.1:9297) and automatically generates temporary credentials (emulator_credentials) and a self-signed CA certificate (ca.pem) under ~/.aws/emulator/9297/. Reading those credentials into boto3.Session and passing the ca.pem path to verify lets tests communicate over HTTPS with SigV4 signing enabled and zero TLS warnings.

Environment Setup with a pytest Fixture

In tests/test_e2e.py, a scope="module" fixture automates the entire lifecycle:

  1. Start aws-emulator -t off as a subprocess and wait until sts.get_caller_identity() returns account 000000000000
  2. Create the IAM role, S3 bucket, SNS topic, and three Python 3.14 Lambda functions
  3. Load the real statemachine/ranking_monitor.asl.yaml, substitute ${...Arn} placeholders with actual ARNs, and create the state machine
  4. Terminate the emulator in finally after tests finish

boto3 Inside Lambda Connects Transparently to the Emulator

One particularly convenient detail is that calling standard boto3.client("s3") or boto3.client("sns") inside a Lambda running on AWS Emulator automatically routes to the emulator without configuring any custom endpoint URL. S3 reads/writes and SNS publishes worked out of the box without adding test-only branches inside Lambda code.

Test Scenarios Implemented

Since live scraping of external websites would be flaky, scraper and Pydantic model details remain covered by existing moto unit tests, while the E2E suite verifies three end-to-end workflow paths:

  1. First run (new games found): Traverses FetchRankings → CompareRankings → CheckNewGames → SendNotifications → Success and persists history to history/steam/games.json in S3
  2. Second run (no new games): Re-runs with the same ranking payload, confirms no new titles against S3 history, and takes LogNoNewGames → Success
  3. Failure path (Lambda exception): When FetchRankings raises an exception, verifies transition through Catch → NotifyError (SNS publish) → ExecutionFailed
@pytest.mark.e2e
def test_workflow_error_notification(emulator_env):
    sfn = emulator_env["sfn"]
    sm_arn = emulator_env["state_machine_arn"]

    exec_err = sfn.start_execution(
        stateMachineArn=sm_arn,
        input=json.dumps({"platforms": ["error-platform"]}),
    )
    desc_err = _wait_for_execution(sfn, exec_err["executionArn"])
    assert desc_err["status"] == "FAILED"
    assert desc_err.get("error") == "ExecutionFailed"

    states_err = _get_entered_states(sfn, exec_err["executionArn"])
    assert "NotifyError" in states_err
    assert "ExecutionFailed" in states_err

Triggering real error-notification paths on every CI run is awkward on live AWS, but with the emulator it’s effortless to run repeatedly.

4. Gotchas Encountered and a Latent Bug Discovered

Along the way, I ran into a few gotchas that highlighted both how faithful AWS Emulator is to real AWS and how its internals work.

Gotcha 1: Strict IAM Trust Policy and Permission Checks

With moto or default LocalStack setups, passing a dummy IAM role ARN often bypasses Trust Policy and cross-service permission checks. Out of habit, I reused a role whose Trust Policy only allowed states.amazonaws.com for Lambda as well—and CreateFunction immediately rejected it:

InvalidParameterValueException: The role defined for the function cannot be assumed by Lambda.

Even after adding lambda.amazonaws.com to the Trust Policy, Step Functions failed with AccessDeniedException because lambda:InvokeFunction wasn’t granted. AWS Emulator evaluates both Trust Policies and service-to-service IAM policies just like production AWS, so explicitly attaching lambda:InvokeFunction, sns:Publish, and s3:* via iam.put_role_policy resolved it.

Gotcha 2: The Post-Creation Pending State and Retry Trap

Next, Step Functions executions started hanging in RUNNING. Invoking Lambda directly revealed ResourceConflictException due to the function still being Pending right after CreateFunction.

Measuring locally, the Pending window before transitioning to Active on AWS Emulator is only about 0.5–0.6 seconds. However, invoking the function before that half-second elapsed threw Lambda.AWSLambdaException, which triggered the ASL’s Retry rule (IntervalSeconds: 30) and stalled execution for 30 seconds.

Using lam.get_waiter("function_active_v2").wait()—just as you would on production AWS—waits ~1 second per function (a few seconds total for three functions) until Active and cleanly fixed the issue.

Gotcha 3: Embedded Python Runtime Cannot Load Native Extensions (.so)

At first, I tried zipping the production CompareRankings and SendNotifications handlers together with pydantic and pydantic_core from .venv, which failed with:

Unable to import module 'lambda_function': No module named 'pydantic_core._pydantic_core'

Inspecting sys.version and importlib.machinery.EXTENSION_SUFFIXES inside an emulated Lambda revealed why:

  • It runs CPython 3.14.0 statically embedded inside the Rust binary (CPython 3.14.0 with rustc 1.99.1)
  • Lambda executes inside a sandbox isolated from the host filesystem, where EXTENSION_SUFFIXES is empty ([]) for discovering native extension modules (.so files)

In other words, it wasn’t a Python version mismatch—AWS Emulator’s embedded CPython sandbox does not support dynamically loading native extensions (like Rust-backed pydantic_core) from ZIP packages and only loads Pure Python modules.

Since Pydantic models and scrapers were already thoroughly tested by moto unit tests, I kept the E2E Lambda handlers to the standard library + boto3 only, focusing the E2E suite on S3, SNS, and Step Functions integration behavior.

Unexpected Bonus: Catching a Latent Bug in the Existing ASL

The biggest payoff came when running the failure-path test. Instead of reaching ExecutionFailed, the state machine crashed with States.Runtime:

States.Runtime: the request this task would have sent could not be built:
this task's 'Message' is a structure, which this emulator does not bind to that service's form-field protocol

The culprit was NotifyError in statemachine/ranking_monitor.asl.yaml:

        NotifyError:
          Type: Task
          Resource: arn:aws:states:::sns:publish
          Parameters:
            TopicArn: ${NotificationTopicArn}
            Subject: Game Ranking Monitor Error
            Message.$: $.error  # ← Passed a JSON object directly
          Next: ExecutionFailed

Catch with ResultPath: $.error produces a JSON object ({"Error": "...", "Cause": "..."}), whereas the SNS Publish API expects Message to be a string. Because I had never executed the error path in automated tests before, this bug had gone unnoticed.

Changing it to Message.$: States.JsonToString($.error) fixed the issue, and the execution flowed cleanly through NotifyError → ExecutionFailed. Catching a bug in a rarely triggered alert path ahead of time was a huge win.

5. Cleaning Up GitHub Actions and pre-commit

With E2E tests running completely locally, I removed real AWS dependencies from both CI and pre-commit:

  • GitHub Actions (.github/workflows/deploy.yml): Removed aws-actions/configure-aws-credentials from the test job and replaced it with installing the AWS Emulator .deb package. The deploy job (which only runs on merges to master) still uses OIDC auth, while PR test runs no longer touch real AWS credentials at all.
  • pre-commit (.pre-commit-config.yaml): Added stages: [manual] to the stepfunctions-validate hook that calls the real AWS CLI. Hooks marked stages: [manual] are skipped during normal git commit and CI’s pre-commit run --all-files, running only when explicitly invoked with --hook-stage manual. Day-to-day checks now rely on local asl-validator plus AWS Emulator’s validate_state_machine_definition inside the test suite.

Execution time came out to ~12 seconds locally for uv run pytest (all 33 tests), and ~1 minute 30 seconds for the entire GitHub Actions test job including .deb installation—noticeably snappier without Docker startup overhead.

6. Summary

Adopting AWS Emulator allowed me to run E2E tests spanning Step Functions, Lambda, S3, and SNS completely locally and inside GitHub Actions.

Beyond the peace of mind of not hitting real AWS during tests, being able to casually exercise failure paths uncovered a latent missing States.JsonToString bug in my existing ASL definition.

Since it’s a brand-new release, there are still trade-offs to accept around CloudFormation fidelity and native-extension Lambda support. Even so, when paired with moto for unit tests and asl-validator / cfn-lint for static analysis, AWS Emulator is already a strong addition to a CI pipeline.

kazasiki
kazasiki Software Engineer

Software engineer. Writing code, playing VR & PC games, and listening to hardcore techno.