How to Start AWS Emulator Empty for Every Test Run
AWS Emulator keeps the tables and S3 files you create only in memory. Stopping it removes all of them, so restarting it is effectively cleaning up test data. This prevents integration tests in local runs or CI from failing because a table from a previous run is still there. Below are the results of running the same list operations before and after stopping the emulator, a script that restarts the emulator for every test run, and a pytest fixture. All of them were run in my test environment.
The test environment was Ubuntu 24.04 (x86_64), AWS Emulator 1.0.353 (Debian package), AWS CLI 2.40.3, Python 3.11, Boto3 1.44.3, and pytest 9.2.0. I did not use an AWS account; all requests went to the local emulator. I have not checked how things behave or what they cost on real AWS, and where the article mentions real AWS, it relies on the official documentation. I did not try running it with Docker or using SDKs other than Python.
- 1. Create a table and an S3 file first
- 2. Compare the same listings before and after stopping
- 3. Even after a crash, nothing created is kept
- 4. With the same emulator still running, the second test run fails
- 5. A script that restarts the emulator for every test run
- 6. A pytest fixture that starts a new emulator for each test function
- 7. How this differs from real AWS
Create a table and an S3 file first
I installed it by following the official guide's Linux instructions. I started it with -t off to turn off telemetry, then set the environment variables from the official documentation in a separate shell so that the AWS CLI pointed at the emulator. In my test, I started it in the background from a single script.
aws-emulator -t off
export AWS_ENDPOINT_URL=https://127.0.0.1:9297
export AWS_SHARED_CREDENTIALS_FILE=~/.aws/emulator/9297/emulator_credentials
export AWS_CONFIG_FILE=~/.aws/emulator/9297/config
export AWS_CA_BUNDLE=~/.aws/emulator/9297/ca.pem
export AWS_EC2_METADATA_DISABLED=true
export AWS_DISABLE_HOST_PREFIX_INJECTION=true
export AWS_REGION=us-east-1
export AWS_DEFAULT_REGION=us-east-1
unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN AWS_PROFILE
I created a DynamoDB table and wrote one item. A newly created table is CREATING, so I used aws dynamodb wait table-exists to wait until it became ACTIVE before writing.
$ aws dynamodb create-table --table-name example-table --attribute-definitions AttributeName=id,AttributeType=S --key-schema AttributeName=id,KeyType=HASH --billing-mode PAY_PER_REQUEST --query 'TableDescription.[TableName,TableStatus]' --output text
example-table CREATING
$ aws dynamodb wait table-exists --table-name example-table
$ aws dynamodb describe-table --table-name example-table --query 'Table.TableStatus' --output text
ACTIVE
$ aws dynamodb put-item --table-name example-table --item '{"id":{"S":"neko-1"},"name":{"S":"tama"}}'
For S3, I created a bucket and put a 5-byte text file in it.
$ aws s3api create-bucket --bucket example-bucket
{
"Location": "/example-bucket",
"BucketArn": "arn:aws:s3:::example-bucket"
}
$ aws s3 cp hello.txt s3://example-bucket/hello.txt
upload: ./hello.txt to s3://example-bucket/hello.txt
The output of aws s3 cp omits the progress display.
Compare the same listings before and after stopping
Before stopping it, I listed the tables, the buckets, the files in the bucket, and the table contents. Everything I had created was visible.
$ aws dynamodb list-tables
{
"TableNames": [
"example-table"
]
}
$ aws s3api list-buckets --query 'Buckets[].Name'
[
"example-bucket"
]
$ aws s3 ls s3://example-bucket
2026-11-14 03:52:32 5 hello.txt
$ aws dynamodb scan --table-name example-table --query 'Items'
[
{
"id": {
"S": "neko-1"
},
"name": {
"S": "tama"
}
}
]
I stopped the emulator by sending it SIGTERM. This is the same clean stop as pressing Ctrl+C in the terminal where it was started. The exit code was 0, and the folder named after the port, ~/.aws/emulator/9297/, was empty. In my test, I ran kill -TERM $PID inside the script, so the process ID is replaced with a placeholder below.
$ kill -TERM <エミュレーターのプロセスID>
emulator exit code: 0
$ ls -A ~/.aws/emulator/9297/
I started aws-emulator -t off again, kept the same environment variables, and ran the same four commands as before stopping.
$ aws dynamodb list-tables
{
"TableNames": []
}
$ aws s3api list-buckets --query 'Buckets[].Name'
[]
$ aws s3 ls s3://example-bucket
aws: [ERROR]: An error occurred (NoSuchBucket) when calling the ListObjectsV2 operation: The specified bucket does not exist
$ aws dynamodb scan --table-name example-table --query 'Items'
aws: [ERROR]: An error occurred (ResourceNotFoundException) when calling the Scan operation: Requested resource not found
No tables, buckets, files, or items remained. Creating example-table again with the same name worked without errors.

Even after a crash, nothing created is kept
The official command reference treats a stop by Ctrl+C, SIGTERM, or --idle-timeout as a clean stop, and says that in that case the files in the folder are deleted. After a crash, the files remain, and the emulator started next on the same port replaces them.
Instead of a crash, I stopped it with SIGKILL to check. The exit code was 137, and all four key and certificate files remained. Again, the process ID is replaced with a placeholder.
$ kill -KILL <エミュレーターのプロセスID>
emulator exit code: 137
$ ls -A ~/.aws/emulator/9297/
ca.pem
config
emulator_credentials
truststore.p12
When I started it again, the files were replaced with new ones. The SHA-256 of emulator_credentials changed from before the crash. The example-table I had recreated before the SIGKILL was also gone.
$ sha256sum ~/.aws/emulator/9297/emulator_credentials # before the crash
8c066c5a070b752df4e7e988eddb71d46fa9710d1ee02b4116778a7bfcd97b9a ~/.aws/emulator/9297/emulator_credentials
$ sha256sum ~/.aws/emulator/9297/emulator_credentials # after restarting
d2b1e731a4961a68d3200370f4ed8b6fceb5d87a564d748a47a7db004bb8bf73 ~/.aws/emulator/9297/emulator_credentials
$ aws dynamodb list-tables
{
"TableNames": []
}
$ aws s3api list-buckets --query 'Buckets[].Name'
[]
The reference says there is no management API for resetting the state of the emulator. All state is kept in memory, so to start from an empty state, restart it. The only management API shown by aws-emulator --help was the health check, GET /__admin/health.
With the same emulator still running, the second test run fails
Before looking at how to use this in tests, I checked what happens if you don't restart it. The following pytest tests create an orders table in DynamoDB and write one item, then create a receipts bucket in S3 and put one file in it.
import boto3
def test_save_order():
ddb = boto3.client("dynamodb")
ddb.create_table(
TableName="orders",
AttributeDefinitions=[{"AttributeName": "id", "AttributeType": "S"}],
KeySchema=[{"AttributeName": "id", "KeyType": "HASH"}],
BillingMode="PAY_PER_REQUEST",
)
ddb.get_waiter("table_exists").wait(TableName="orders")
ddb.put_item(TableName="orders", Item={"id": {"S": "order-1"}})
assert ddb.scan(TableName="orders")["Count"] == 1
def test_upload_receipt():
s3 = boto3.client("s3")
s3.create_bucket(Bucket="receipts")
s3.put_object(Bucket="receipts", Key="order-1.txt", Body=b"ok")
keys = [o["Key"] for o in s3.list_objects_v2(Bucket="receipts")["Contents"]]
assert keys == ["order-1.txt"]
I ran them twice in a row with one emulator running. In my test, every pytest run in this article used -p no:cacheprovider so that no cache files were created. The first run passed both tests. On the second run, test_save_order failed with Table already exists: orders (the second output shows only the error lines and the result line).
$ python -m pytest -q # first run
.. [100%]
2 passed in 3.25s
$ python -m pytest -q # second run
E botocore.errorfactory.ResourceInUseException: An error occurred (ResourceInUseException) when calling the CreateTable operation: Table already exists: orders
FAILED test_orders.py::test_save_order - botocore.errorfactory.ResourceInUseE...
1 failed, 1 passed in 0.24s
test_upload_receipt for S3 passed on the second run too. The bucket from the previous run was still there, but create_bucket did not raise an error, and the file was put under the same key, so the listing still had just one entry. Leftovers from a previous run do not always show up as errors.
A script that restarts the emulator for every test run
This is a shell script that starts the emulator each time the tests run and stops it when they finish. According to the official documentation's limitations section, AWS has not tested long-running use. It says to start the emulator for tests and stop it when they finish, or to let it stop by itself with --idle-timeout, and that restarting it makes tests start from an empty state.
#!/bin/bash
# Start a new emulator for each test run, and stop it when the run finishes
set -euo pipefail
LOG=$(mktemp)
aws-emulator -t off -p 0 --idle-timeout 600 > "$LOG" 2>/dev/null &
EMU_PID=$!
trap 'kill -TERM "$EMU_PID" 2>/dev/null; wait "$EMU_PID" 2>/dev/null || true; rm -f "$LOG"' EXIT
# Wait until the startup line (message is "emulator server information") appears, then read the endpoint
for i in $(seq 30); do
INFO=$(grep '"emulator server information"' "$LOG" || true)
[ -n "$INFO" ] && break
sleep 1
done
[ -n "$INFO" ] || { echo "emulator did not start" >&2; exit 1; }
ENDPOINT=$(echo "$INFO" | python3 -c 'import json,sys; print(json.load(sys.stdin)["fields"]["endpoint_url"])')
DIR=$(dirname "$(echo "$INFO" | python3 -c 'import json,sys; print(json.load(sys.stdin)["fields"]["config_file"])')")
export AWS_ENDPOINT_URL="$ENDPOINT"
export AWS_SHARED_CREDENTIALS_FILE="$DIR/emulator_credentials"
export AWS_CONFIG_FILE="$DIR/config"
export AWS_CA_BUNDLE="$DIR/ca.pem"
export AWS_EC2_METADATA_DISABLED=true
export AWS_DISABLE_HOST_PREFIX_INJECTION=true
export AWS_REGION=us-east-1
export AWS_DEFAULT_REGION=us-east-1
unset AWS_ACCESS_KEY_ID AWS_SECRET_ACCESS_KEY AWS_SESSION_TOKEN AWS_PROFILE
curl -sf --cacert "$AWS_CA_BUNDLE" "$ENDPOINT/__admin/health" > /dev/null
echo "emulator: $ENDPOINT"
python -m pytest -q "$@"
There are three things I focused on:
-p 0lets the OS choose a free port. Even if an emulator from an earlier run is somehow still alive, the ports do not collide. As the reference describes, the chosen port is read from theendpoint_urlfield in theemulator server informationline of the log. According to the reference, this line and its fields can be relied on, while other lines may change between releases.trap ... EXITsends SIGTERM to stop the emulator whether the tests fail or the script stops partway through.--idle-timeout 600is a fallback in case thetrapdoes not run and the emulator is left behind. If there are no API calls for 600 seconds, the emulator stops by itself.
Setting the environment variables inside the script follows the caution in the official documentation.
The official documentation warns that if AWS_ENDPOINT_URL is not set in the shell that runs the tests, code will call real AWS with whatever credentials it finds. It says to set the environment variables in the same script that runs the tests, and not to put real credentials in the test job's environment.
When I ran this script twice in a row, both runs passed both tests. A different port was chosen each time. The whole script took about 4.6 seconds each time.
$ ./run-tests.sh # first run
emulator: https://127.0.0.1:33901
.. [100%]
2 passed in 3.20s
$ ./run-tests.sh # second run
emulator: https://127.0.0.1:42575
.. [100%]
2 passed in 3.20s
After the runs finished, no aws-emulator processes were left. Folders named after each port remained under ~/.aws/emulator/, but they contained zero files.
A pytest fixture that starts a new emulator for each test function
If you do not want what one test function created to carry over to the next, restart the emulator for each test function. In my test environment, I measured the time from startup until the health check returned ok five times, and it ranged from 0.23 to 0.34 seconds. The following conftest.py is a fixture that starts an emulator for each test function, sets the environment variables, and stops it with SIGTERM when the test finishes.
import json
import os
import subprocess
import boto3
import pytest
@pytest.fixture(autouse=True)
def fresh_emulator(monkeypatch):
"""テスト関数ごとに、空のエミュレーターを起動して、終わったら止める"""
proc = subprocess.Popen(
["aws-emulator", "-t", "off", "-p", "0", "--idle-timeout", "600"],
stdout=subprocess.PIPE,
stderr=subprocess.DEVNULL,
text=True,
)
# Read until the startup line (message is "emulator server information") appears
info = None
for line in proc.stdout:
fields = json.loads(line).get("fields", {})
if fields.get("message") == "emulator server information":
info = fields
break
if info is None:
proc.kill()
pytest.fail("emulator did not start")
folder = os.path.dirname(info["config_file"])
monkeypatch.setenv("AWS_ENDPOINT_URL", info["endpoint_url"])
monkeypatch.setenv("AWS_SHARED_CREDENTIALS_FILE", os.path.join(folder, "emulator_credentials"))
monkeypatch.setenv("AWS_CONFIG_FILE", info["config_file"])
monkeypatch.setenv("AWS_CA_BUNDLE", info["ca_file"])
monkeypatch.setenv("AWS_EC2_METADATA_DISABLED", "true")
monkeypatch.setenv("AWS_DISABLE_HOST_PREFIX_INJECTION", "true")
monkeypatch.setenv("AWS_REGION", "us-east-1")
monkeypatch.setenv("AWS_DEFAULT_REGION", "us-east-1")
for name in ["AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY", "AWS_SESSION_TOKEN", "AWS_PROFILE"]:
monkeypatch.delenv(name, raising=False)
# The default session that boto3.client() uses remembers the key it read first.
# Make it rebuild for each test so that the previous test's key does not carry over
monkeypatch.setattr(boto3, "DEFAULT_SESSION", None)
yield info["endpoint_url"]
proc.terminate() # Stopping with SIGTERM removes the in-memory state and the files in the port folder
proc.wait(timeout=30)
I added a test_starts_empty test to the two above. It checks that there are no tables or buckets at startup.
def test_starts_empty():
assert boto3.client("dynamodb").list_tables()["TableNames"] == []
assert boto3.client("s3").list_buckets()["Buckets"] == []
I ran it twice in a row, and all three tests passed both times. Here is the first run's output (the heading line and the timing table from --durations=0 are omitted).
$ python -m pytest -v --durations=0
collecting ... collected 3 items
test_orders.py::test_save_order PASSED [ 33%]
test_orders.py::test_upload_receipt PASSED [ 66%]
test_orders.py::test_starts_empty PASSED [100%]
============================== 3 passed in 4.04s ===============================
With --durations=0, the fixture setup took 0.16 to 0.34 seconds per test, and teardown took 0.02 to 0.03 seconds.
Boto3's default session remembers the key from the previous emulator
If you run the fixture above without the last line, monkeypatch.setattr(boto3, "DEFAULT_SESSION", None), only the first test passes and the other two fail (the output shows only the error lines and the result line).
$ python -m pytest -q
E botocore.errorfactory.AccessDenied: An error occurred (AccessDenied) when calling the CreateBucket operation: Sign the request with the emulator credentials
E botocore.exceptions.ClientError: An error occurred (UnrecognizedClientException) when calling the ListTables operation: The security token included in the request is invalid.
FAILED test_orders.py::test_upload_receipt - botocore.errorfactory.AccessDeni...
FAILED test_orders.py::test_starts_empty - botocore.exceptions.ClientError: A...
2 failed, 1 passed in 3.95s
As described in the Boto3 session documentation, boto3.client() uses a default session that is created automatically. The emulator creates a new key each time it starts, so with the second emulator, requests signed with the old key were rejected. To confirm this, I started the emulator twice and compared the key in the credentials file with the key held by the default session after each start. The second run did not match.
$ python check_cache.py
run 1: key in file == key in DEFAULT_SESSION: True
run 2: key in file == key in DEFAULT_SESSION: False
If you set boto3.DEFAULT_SESSION back to None, the next boto3.client() call rebuilds the default session and reads the new key file. With the shell script approach that restarts the emulator for every run, the pytest process is also started fresh each time, so this problem did not occur.
How this differs from real AWS
What follows is based on the official documentation. The documentation says you do not need an AWS account to use AWS Emulator, and there are no additional charges for it. Charges apply only to real resources you deploy to AWS. Resources in the emulator live in memory, how much can be stored depends on the machine running it, and stopping it removes everything.
The documentation also says the emulator is for development and testing and should not be used for production workloads. It does not evaluate IAM policies the same way AWS does, so it cannot be used to verify permissions. How closely each service matches AWS varies by service, and the GitHub releases page lists the results for each service with every release.





