Moto
Moto is a Python library that allows developers to easily mock AWS services for testing purposes. It intercepts Boto3 calls and routes them to an in-memory mock, simulating AWS API behavior locally without actual AWS interaction. The current version is 5.1.22, and it typically sees new releases every 1-2 weeks, ensuring continuous updates for AWS service support.
Warnings
- breaking Moto v5.x introduced a significant breaking change: all individual service decorators (e.g., `@mock_s3`, `@mock_dynamodb`, `@mock_sqs`) have been removed and replaced by a single, unified `@mock_aws` decorator.
- gotcha Boto3 clients/resources must be created *after* the `moto` mock has been established. If a Boto3 client is initialized globally (e.g., at the module level) before the `@mock_aws` decorator or context manager is activated, `moto` will not intercept those calls, and they may hit real AWS.
- gotcha Always specify `region_name` explicitly when creating `boto3` clients and resources (e.g., `boto3.client('s3', region_name='us-east-1')`). Moto can sometimes exhibit inconsistent behavior or default to unexpected regions if `region_name` is omitted, potentially leading to hard-to-debug test failures.
- breaking In Moto v3.x, the behavior of class decorators changed: the mock state is now reset before *every* test method within a decorated class. Previously, the state was global and shared across methods in the same class.
- gotcha For Pytest users, ensure that any `boto3` client-creating fixtures are correctly integrated with Moto's mocking. If a fixture creates a client before `mock_aws` is active, it won't be mocked.
- gotcha Moto intercepts HTTP requests and requires dummy AWS credentials to be set (either via environment variables or `~/.aws/credentials`). Without them, `botocore` might attempt to resolve actual credentials or hit real AWS endpoints, leading to errors or unintended side effects.
Install
-
pip install moto[all] -
pip install 'moto[s3,dynamodb]'
Imports
- mock_aws
from moto import mock_aws
Quickstart
import boto3
from moto import mock_aws
import os
@mock_aws
def test_s3_bucket_creation():
# Ensure dummy AWS credentials are set for botocore to not attempt real calls
os.environ['AWS_ACCESS_KEY_ID'] = 'testing'
os.environ['AWS_SECRET_ACCESS_KEY'] = 'testing'
os.environ['AWS_SECURITY_TOKEN'] = 'testing'
os.environ['AWS_SESSION_TOKEN'] = 'testing'
os.environ['AWS_DEFAULT_REGION'] = 'us-east-1'
s3_client = boto3.client('s3', region_name='us-east-1')
bucket_name = 'my-test-bucket-123'
# Create a bucket in the mocked AWS environment
s3_client.create_bucket(Bucket=bucket_name)
# List buckets and verify the new bucket exists
response = s3_client.list_buckets()
buckets = [b['Name'] for b in response['Buckets']]
assert bucket_name in buckets
print(f"Successfully created and verified bucket: {bucket_name}")
if __name__ == '__main__':
test_s3_bucket_creation()