End-to-End Serverless Testing with LocalStack
LocalStack runs a local AWS cloud stack in Docker, letting you test S3, SQS, DynamoDB, Lambda, and API Gateway without an AWS account. Set it up with Docker Compose, point your AWS SDK at http://localhost:4566, and write end-to-end tests that cover your entire serverless data flow. It's fast, free, and runs in CI — but it's not a perfect AWS substitute.
Mocking boto3 with moto gives you isolated unit tests. SAM CLI gives you local Lambda invocation. But neither lets you test the flow: an S3 upload triggers a Lambda, which processes the file and writes to DynamoDB, which triggers a DynamoDB Stream, which publishes to SNS. To test that entire chain without deploying to AWS, you need LocalStack.
LocalStack runs a local implementation of the AWS cloud inside Docker. It supports over 80 AWS services — not perfectly, but well enough to catch the most common integration bugs before they hit production.
What LocalStack Provides
LocalStack's Community edition (free, open source) covers the services most serverless applications use:
- S3 — buckets, objects, multipart uploads, presigned URLs, event notifications
- SQS — queues, messages, dead-letter queues, long polling
- SNS — topics, subscriptions, message filtering
- DynamoDB — tables, streams, GSIs, transactions
- Lambda — function invocation (not the full execution environment — see Limitations)
- API Gateway — REST APIs, HTTP APIs, routing
- IAM — basic role/policy simulation
- CloudFormation — stack creation from templates
- Secrets Manager, SSM Parameter Store — configuration storage
- EventBridge — event buses and rules
- Kinesis — streams and shards
The Pro edition adds more services and better Lambda execution fidelity — but the Community edition is sufficient for most testing scenarios.
Setup: Docker Compose + LocalStack
Create a docker-compose.yml at the root of your project:
# docker-compose.yml
version: "3.9"
services:
localstack:
image: localstack/localstack:3.4
ports:
- "4566:4566"
- "4510-4559:4510-4559"
environment:
- SERVICES=s3,sqs,sns,dynamodb,lambda,apigateway,iam,cloudformation,secretsmanager,events
- DEFAULT_REGION=us-east-1
- AWS_DEFAULT_REGION=us-east-1
- AWS_ACCESS_KEY_ID=test
- AWS_SECRET_ACCESS_KEY=test
- DOCKER_HOST=unix:///var/run/docker.sock
- LAMBDA_EXECUTOR=docker # Run Lambda in Docker containers (more realistic)
volumes:
- "/var/run/docker.sock:/var/run/docker.sock"
- "./localstack-init:/etc/localstack/init/ready.d" # Init scripts
healthcheck:
test: ["CMD", "curl", "-f", "http://localhost:4566/_localstack/health"]
interval: 5s
timeout: 5s
retries: 10Add an initialization script to create resources on startup:
# localstack-init/01-create-resources.sh
#!/bin/bash
set -e
echo "Creating DynamoDB table..."
awslocal dynamodb create-table \
--table-name items \
--attribute-definitions AttributeName=id,AttributeType=S \
--key-schema AttributeName=id,KeyType=HASH \
--billing-mode PAY_PER_REQUEST
echo "Creating S3 bucket..."
awslocal s3 mb s3://uploads
echo "Creating SQS queue..."
awslocal sqs create-queue --queue-name item-events
echo "LocalStack resources initialized."Start LocalStack:
docker compose up -d localstack
docker compose exec localstack awslocal dynamodb list-tables # Verify it's upConfiguring the AWS SDK to Use LocalStack
All AWS SDK clients need to be redirected to http://localhost:4566. Use the AWS_ENDPOINT_URL environment variable (supported in all modern SDK versions):
export AWS_ENDPOINT_URL=http://localhost:4566
export AWS_DEFAULT_REGION=us-east-1
export AWS_ACCESS_KEY_ID=test
export AWS_SECRET_ACCESS_KEY=testOr configure it explicitly in code:
# Python — boto3
import boto3
def get_client(service):
return boto3.client(
service,
endpoint_url="http://localhost:4566",
region_name="us-east-1",
aws_access_key_id="test",
aws_secret_access_key="test",
)
s3 = get_client("s3")
dynamodb = boto3.resource(
"dynamodb",
endpoint_url="http://localhost:4566",
region_name="us-east-1",
aws_access_key_id="test",
aws_secret_access_key="test",
)// JavaScript — AWS SDK v3
const { S3Client } = require("@aws-sdk/client-s3");
const { DynamoDBClient } = require("@aws-sdk/client-dynamodb");
const { SQSClient } = require("@aws-sdk/client-sqs");
const localstackConfig = {
endpoint: "http://localhost:4566",
region: "us-east-1",
credentials: { accessKeyId: "test", secretAccessKey: "test" },
forcePathStyle: true, // Required for S3
};
const s3 = new S3Client(localstackConfig);
const dynamodb = new DynamoDBClient(localstackConfig);
const sqs = new SQSClient(localstackConfig);In production code, check for a LOCALSTACK_ENDPOINT or AWS_ENDPOINT_URL environment variable and fall back to the default AWS endpoint:
import os
import boto3
ENDPOINT_URL = os.environ.get("AWS_ENDPOINT_URL") # None in production
def get_dynamodb_table(table_name):
kwargs = {"region_name": "us-east-1"}
if ENDPOINT_URL:
kwargs["endpoint_url"] = ENDPOINT_URL
kwargs["aws_access_key_id"] = "test"
kwargs["aws_secret_access_key"] = "test"
resource = boto3.resource("dynamodb", **kwargs)
return resource.Table(table_name)Testing S3 with LocalStack
# tests/localstack/test_s3_handler.py
import os
import uuid
import boto3
import pytest
from myapp.handlers import process_upload # Your Lambda handler
ENDPOINT = "http://localhost:4566"
BUCKET = "uploads"
@pytest.fixture(scope="session")
def s3():
return boto3.client(
"s3",
endpoint_url=ENDPOINT,
region_name="us-east-1",
aws_access_key_id="test",
aws_secret_access_key="test",
)
def test_upload_triggers_processing(s3):
key = f"test/{uuid.uuid4()}.csv"
content = b"id,name,price\nabc,Widget,9.99\ndef,Gadget,19.99"
# Upload file to LocalStack S3
s3.put_object(Bucket=BUCKET, Key=key, Body=content)
# Simulate the S3 event that Lambda would receive
event = {
"Records": [{
"eventSource": "aws:s3",
"eventName": "ObjectCreated:Put",
"s3": {
"bucket": {"name": BUCKET},
"object": {"key": key, "size": len(content)},
},
}]
}
result = process_upload(event, None)
assert result["processed"] == 2 # Two CSV rows
# Verify side effects — e.g., processed file moved to another prefix
response = s3.list_objects_v2(Bucket=BUCKET, Prefix="processed/")
keys = [o["Key"] for o in response.get("Contents", [])]
assert any(key.split("/")[-1] in k for k in keys)Testing SQS with LocalStack
# tests/localstack/test_sqs_handler.py
import json
import uuid
import boto3
import pytest
from myapp.handlers import process_queue_messages
ENDPOINT = "http://localhost:4566"
QUEUE_NAME = "item-events"
@pytest.fixture(scope="session")
def sqs():
client = boto3.client(
"sqs",
endpoint_url=ENDPOINT,
region_name="us-east-1",
aws_access_key_id="test",
aws_secret_access_key="test",
)
return client
@pytest.fixture(scope="session")
def queue_url(sqs):
response = sqs.get_queue_url(QueueName=QUEUE_NAME)
return response["QueueUrl"]
def test_processes_valid_sqs_message(sqs, queue_url):
# Send a test message
message_body = json.dumps({"orderId": str(uuid.uuid4()), "total": 59.99})
receipt = sqs.send_message(QueueUrl=queue_url, MessageBody=message_body)
# Build the SQS event shape Lambda receives
event = {
"Records": [{
"messageId": receipt["MessageId"],
"receiptHandle": "test-handle",
"body": message_body,
"attributes": {"ApproximateReceiveCount": "1"},
"eventSource": "aws:sqs",
"eventSourceARN": f"arn:aws:sqs:us-east-1:000000000000:{QUEUE_NAME}",
}]
}
result = process_queue_messages(event, None)
assert result["batchItemFailures"] == []
def test_dead_letter_queue_receives_poison_messages(sqs):
"""Verify that malformed messages end up in the DLQ."""
# Create DLQ and main queue linked to it (if not already in init script)
dlq = sqs.create_queue(QueueName="item-events-dlq")
dlq_url = dlq["QueueUrl"]
dlq_arn = sqs.get_queue_attributes(
QueueUrl=dlq_url, AttributeNames=["QueueArn"]
)["Attributes"]["QueueArn"]
main_queue = sqs.create_queue(
QueueName="item-events-with-dlq",
Attributes={
"RedrivePolicy": json.dumps({
"deadLetterTargetArn": dlq_arn,
"maxReceiveCount": "1",
})
},
)
# Send a poison message (invalid JSON)
sqs.send_message(
QueueUrl=main_queue["QueueUrl"],
MessageBody="this is not valid json {{{",
)
# Receive and fail to process it (would go to DLQ after maxReceiveCount)
messages = sqs.receive_message(
QueueUrl=main_queue["QueueUrl"], MaxNumberOfMessages=1
).get("Messages", [])
assert len(messages) == 1
assert "this is not valid json" in messages[0]["Body"]Testing DynamoDB with LocalStack
# tests/localstack/test_dynamodb.py
import uuid
import boto3
import pytest
from myapp.repository import ItemRepository
ENDPOINT = "http://localhost:4566"
@pytest.fixture(scope="session")
def dynamodb():
return boto3.resource(
"dynamodb",
endpoint_url=ENDPOINT,
region_name="us-east-1",
aws_access_key_id="test",
aws_secret_access_key="test",
)
@pytest.fixture(scope="session")
def repo(dynamodb):
return ItemRepository(table=dynamodb.Table("items"))
def test_save_and_retrieve_item(repo):
item_id = str(uuid.uuid4())
repo.save({"id": item_id, "name": "LocalStack Widget", "price": 14.99})
item = repo.get(item_id)
assert item["name"] == "LocalStack Widget"
assert float(item["price"]) == 14.99
def test_get_nonexistent_item_returns_none(repo):
result = repo.get("does-not-exist")
assert result is None
def test_batch_save_and_query(repo):
prefix = f"batch-{uuid.uuid4()}"
items = [{"id": f"{prefix}-{i}", "name": f"Item {i}", "category": "test"} for i in range(5)]
repo.batch_save(items)
results = repo.query_by_category("test")
saved_ids = {item["id"] for item in results}
assert all(f"{prefix}-{i}" in saved_ids for i in range(5))Testing API Gateway with LocalStack
LocalStack supports deploying API Gateway configurations locally. The easier approach for most projects is to use SAM CLI for API Gateway testing (since it handles the template translation) and LocalStack for the backing services:
# tests/localstack/test_api_gateway.py
"""
Test the full API Gateway → Lambda → DynamoDB flow using LocalStack.
Assumes API is deployed to LocalStack via CloudFormation or awslocal.
"""
import json
import uuid
import boto3
import httpx
import pytest
LOCALSTACK_URL = "http://localhost:4566"
@pytest.fixture(scope="session")
def api_id():
"""Deploy or retrieve the API Gateway ID from LocalStack."""
apigw = boto3.client(
"apigateway",
endpoint_url=LOCALSTACK_URL,
region_name="us-east-1",
aws_access_key_id="test",
aws_secret_access_key="test",
)
apis = apigw.get_rest_apis()["items"]
assert apis, "No API Gateway found in LocalStack — run the deploy script first"
return apis[0]["id"]
@pytest.fixture(scope="session")
def api_base_url(api_id):
return f"{LOCALSTACK_URL}/restapis/{api_id}/test/_user_request_"
def test_end_to_end_create_and_get(api_base_url):
item_id = str(uuid.uuid4())
# Create via API
create_res = httpx.post(
f"{api_base_url}/items",
json={"id": item_id, "name": "E2E Test Item"},
timeout=15,
)
assert create_res.status_code == 201, f"Create failed: {create_res.text}"
# Retrieve via API
get_res = httpx.get(f"{api_base_url}/items/{item_id}", timeout=15)
assert get_res.status_code == 200
assert get_res.json()["name"] == "E2E Test Item"CI Integration
# .github/workflows/localstack-tests.yml
name: LocalStack Integration Tests
on: [push, pull_request]
jobs:
localstack-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- name: Set up Python
uses: actions/setup-python@v5
with:
python-version: "3.12"
- name: Install dependencies
run: pip install -r requirements-test.txt
- name: Start LocalStack
run: docker compose up -d localstack
- name: Wait for LocalStack to be ready
run: |
for i in {1..30}; do
curl -sf http://localhost:4566/_localstack/health && break || sleep 2
done
- name: Run LocalStack tests
env:
AWS_ENDPOINT_URL: http://localhost:4566
AWS_DEFAULT_REGION: us-east-1
AWS_ACCESS_KEY_ID: test
AWS_SECRET_ACCESS_KEY: test
run: pytest tests/localstack/ -v --tb=short
- name: Stop LocalStack
if: always()
run: docker compose downLimitations vs Real AWS
LocalStack is not a perfect AWS replica. Know where it falls short:
Lambda execution environment. Community edition LocalStack runs Lambda in a simplified environment. The actual Node.js/Python runtime, filesystem layout, and /tmp limitations are not identical to real AWS. Use SAM CLI's Docker-based invocation for more accurate Lambda testing.
IAM enforcement. LocalStack does not enforce IAM policies by default. A call that would be rejected by real AWS for missing permissions will succeed against LocalStack. You must test IAM separately with real AWS.
Service limits and throttling. LocalStack does not simulate DynamoDB capacity throttling, Lambda concurrency limits, SQS in-flight message limits, or S3 rate limits. Throttling bugs will only appear against real AWS.
API Gateway fidelity. Request/response mapping templates, custom authorizers, and WAF integration have varying levels of support. Test auth flows against real AWS.
Event source mappings. Lambda triggers (DynamoDB Streams → Lambda, S3 event notifications → Lambda) work in LocalStack Pro but are limited in the Community edition. Simulate these by constructing event payloads manually in Community edition.
Eventual consistency. LocalStack is often more consistent than real AWS — tests that rely on eventual consistency may pass locally but fail in production. Add explicit delays or polling in integration tests that depend on propagation.
Summary
LocalStack is the most cost-effective way to run end-to-end serverless tests without an AWS account. Set it up with Docker Compose, redirect your AWS SDK to http://localhost:4566, and write tests that cover the full data flow — S3 upload, SQS message processing, DynamoDB reads and writes. It runs in 30 seconds in CI and costs nothing. Use it for the happy-path integration tests and complement it with real AWS tests for IAM, throttling, and Lambda execution environment validation.