### ThreadedMotoServer test setup example
Source: https://deepwiki.com/getmoto/moto/3.1-moto-server
Python example showing how to start a ThreadedMotoServer in a test fixture, configure a boto3 client to use it, and clean up after tests. Port 0 selects a random available port.
```python
# Example test setup
server = ThreadedMotoServer(port=0) # Port 0 means use a random available port
server.start()
host, port = server.get_host_and_port()
endpoint_url = f"http://{host}:{port}"
# Configure AWS client to use the mock server
client = boto3.client('s3', endpoint_url=endpoint_url)
# Run tests...
# Clean up
server.stop()
```
--------------------------------
### Install Moto with pip and optional extras
Source: https://deepwiki.com/getmoto/moto
Installation commands for Moto from PyPI. The basic installation installs Moto without extras. Use the extras to install support for specific AWS services (e.g., ec2, s3), all dependencies, or server dependencies.
```bash
# Basic installation
pip install moto
```
```bash
# Install with support for specific services
pip install 'moto[ec2,s3]'
```
```bash
# Install with all dependencies
pip install 'moto[all]'
```
```bash
# Install server dependencies
pip install 'moto[server]'
```
--------------------------------
### S3Backend Bucket Management Implementation
Source: https://deepwiki.com/getmoto/moto/2.1-backend-system
A simplified example showing how S3Backend initializes a bucket dictionary and handles bucket creation.
```python
class S3Backend(BaseBackend):
def __init__(self, region_name):
super().__init__(region_name)
self.buckets = {} # Maps bucket names to FakeBucket objects
def create_bucket(self, bucket_name, region_name):
if bucket_name in self.buckets:
raise BucketAlreadyExists(bucket_name)
bucket = FakeBucket(bucket_name, region_name)
self.buckets[bucket_name] = bucket
return bucket
```
--------------------------------
### Start Moto Server on all interfaces
Source: https://deepwiki.com/getmoto/moto/3.1-moto-server
Starts the Moto Server listening on all interfaces (0.0.0.0) on port 5000.
```bash
moto_server --host 0.0.0.0 --port 5000
```
--------------------------------
### Manually start and stop Moto mocking with start() and stop()
Source: https://deepwiki.com/getmoto/moto/3-usage-methods
Use `mock_aws()` to create a mock instance, then call `start()` to begin mocking and `stop()` to end it. This gives fine-grained control over when mocking is active, useful for complex test setups.
```python
import boto3
from moto import mock_aws
def test_explicit_start_stop():
# Create the mock but don't start it yet
my_mock = mock_aws()
# Start the mocking
my_mock.start()
# AWS API calls are now mocked
s3 = boto3.client('s3', region_name='us-east-1')
s3.create_bucket(Bucket='mybucket')
# Stop the mocking
my_mock.stop()
# AWS API calls are now real again
```
--------------------------------
### Install Moto via pip
Source: https://deepwiki.com/getmoto/moto/1-moto-overview
Commands to install the base Moto package or specific service-based extras.
```bash
# Basic installation
pip install moto
# Install with support for specific services
pip install 'moto[ec2,s3]'
# Install with all dependencies
pip install 'moto[all]'
# Install server dependencies
pip install 'moto[server]'
```
--------------------------------
### Implement cross-service resource creation
Source: https://deepwiki.com/getmoto/moto/7-extending-moto
This example demonstrates how to access the EC2 backend from another service to verify dependencies before creating a resource.
```python
# Example of cross-service integration
def create_resource_with_dependencies(self, resource_id, ec2_instance_id):
# Get EC2 backend
ec2_backend = ec2_backends[self.account_id][self.region_name]
# Verify EC2 instance exists
ec2_instance = ec2_backend.get_instance(ec2_instance_id)
if not ec2_instance:
raise InvalidInstanceError(f"Instance {ec2_instance_id} not found")
# Create resource with reference to EC2 instance
resource = Resource(resource_id, ec2_instance=ec2_instance)
self.resources[resource_id] = resource
return resource
```
--------------------------------
### Write Tests for Your Service
Source: https://deepwiki.com/getmoto/moto/7-extending-moto
Create a test directory and write tests for your implementation. The example uses boto3, pytest, and the mock_aws decorator to test a create_resource operation.
```python
import boto3
import pytest
from moto import mock_aws
@mock_aws
def test_create_resource():
client = boto3.client("your-service", region_name="us-east-1")
response = client.create_resource(
ResourceId="resource-1",
ResourceName="My Resource"
)
assert response["Resource"]["ResourceId"] == "resource-1"
assert response["Resource"]["ResourceName"] == "My Resource"
```
--------------------------------
### Update Coverage Document (IMPLEMENTATION_COVERAGE.md)
Source: https://deepwiki.com/getmoto/moto/7-extending-moto
Add your service to IMPLEMENTATION_COVERAGE.md with checkboxes for implemented operations. The example shows a details block with a percentage and a list of operations.
```markdown
## your-service
XX% implemented
- [X] create_resource
- [X] get_resource
- [ ] update_resource
- [ ] delete_resource
```
--------------------------------
### Implement Basic Service Test
Source: https://deepwiki.com/getmoto/moto/7.1-adding-new-services
A basic test example using pytest and the mock_aws decorator to verify service resource creation.
```python
import boto3
import pytest
from moto import mock_aws
@mock_aws
def test_create_resource():
client = boto3.client("your-service", region_name="us-east-1")
response = client.create_resource(
ResourceId="test-resource",
Name="Test Resource"
)
assert response["Resource"]["ResourceId"] == "test-resource"
assert response["Resource"]["Name"] == "Test Resource"
```
--------------------------------
### Implement backend class in models.py
Source: https://deepwiki.com/getmoto/moto/7.1-adding-new-services
Example backend class that manages resources and implements create, delete, and describe operations.
```python
from moto.core.base_backend import BackendDict, BaseBackend
class YourServiceBackend(BaseBackend):
def __init__(self, region_name=None):
super().__init__(region_name)
self.resources = {}
def create_resource(self, resource_id, **kwargs):
resource = YourResourceModel(resource_id, **kwargs)
self.resources[resource_id] = resource
return resource
def delete_resource(self, resource_id):
return self.resources.pop(resource_id, None)
def describe_resources(self, resource_ids=None):
if resource_ids:
return [self.resources[rid] for rid in resource_ids if rid in self.resources]
return list(self.resources.values())
```
--------------------------------
### Query Format Example (SQS)
Source: https://deepwiki.com/getmoto/moto/2.2-request-handling
Shows the query string format used by SQS requests, with the Action parameter and attributes encoded in the URL.
```text
?Action=CreateQueue&QueueName=test-queue&Attribute.1.Name=DelaySeconds&Attribute.1.Value=5
```
--------------------------------
### Example URL patterns from backend_index.py
Source: https://deepwiki.com/getmoto/moto/3.1-moto-server
Example regular expression patterns used to match host headers with AWS services. These patterns are from backend_index.py and cover s3, dynamodb, and ec2 endpoints.
```text
# Example patterns from backend_index.py
("s3", re.compile("https?://s3(?!(-control|tables))(.*)\\.amazonaws.com"))
("dynamodb", re.compile("https?://dynamodb\\.(.+)\\.amazonaws\\.com"))
("ec2", re.compile("https?://ec2\\.(.+)\\.amazonaws\\.com(|\\.cn)"))
```
--------------------------------
### Use mock_aws with Manual Start/Stop
Source: https://deepwiki.com/getmoto/moto/7.2-testing-patterns
Use manual start/stop for fine-grained control. Call start() before the mocked section and stop() in a finally block to ensure cleanup.
```python
def test_manual_control():
mock = mock_aws()
mock.start()
try:
s3 = boto3.client('s3', region_name='us-east-1')
s3.create_bucket(Bucket='mybucket')
finally:
mock.stop()
```
--------------------------------
### Create Hosted Zone with boto3 (create_hosted_zone)
Source: https://deepwiki.com/getmoto/moto/5.4-route53-implementation
Example of creating a hosted zone using boto3's create_hosted_zone method. The Name must end with a dot, CallerReference should be unique, and HostedZoneConfig can specify a comment and whether the zone is private.
```python
# Example usage
client = boto3.client('route53')
response = client.create_hosted_zone(
Name='example.com.',
CallerReference='unique-reference',
HostedZoneConfig={
'Comment': 'Test zone',
'PrivateZone': False
}
)
```
--------------------------------
### ResourceGroupsTaggingAPIBackend implementation
Source: https://deepwiki.com/getmoto/moto/2-core-architecture
Example of a backend class that connects to multiple service backends to query resources with specific tags.
```python
class ResourceGroupsTaggingAPIBackend(BaseBackend):
def __init__(self, region_name, account_id):
super().__init__(region_name, account_id)
# ...
@property
def s3_backend(self) -> S3Backend:
return s3_backends[self.account_id][self.partition]
@property
def ec2_backend(self):
return ec2_backends[self.account_id][self.region_name]
# More backend properties...
def _get_resources_generator(self, tag_filters=None, resource_type_filters=None):
# Query resources across multiple backends
# ...
```
--------------------------------
### EC2Instance resource class with CloudFormation support
Source: https://deepwiki.com/getmoto/moto/2-core-architecture
Example of a resource class implementing multiple interfaces (BaseModel, CloudFormationModel, TaggedEC2Resource). Shows typical methods for CloudFormation integration and attribute retrieval.
```python
class EC2Instance(BaseModel, CloudFormationModel, TaggedEC2Resource):
def __init__(self, ec2_backend, instance_id, image_id, ...):
# Initialize instance
@classmethod
def create_from_cloudformation_json(cls, resource_name, cloudformation_json, account_id, region_name, **kwargs):
# Create instance from CloudFormation
def get_cfn_attribute(self, attribute_name):
# Get CloudFormation attribute
# More methods...
```
--------------------------------
### JSON Format Example (DynamoDB)
Source: https://deepwiki.com/getmoto/moto/2.2-request-handling
Shows the JSON request format for DynamoDB, including the X-Amz-Target header and the JSON body with table schema and provisioned throughput.
```text
X-Amz-Target: DynamoDB_20120810.CreateTable
Content-Type: application/json
{
"TableName": "Test",
"KeySchema": [{"AttributeName": "id", "KeyType": "HASH"}],
"AttributeDefinitions": [{"AttributeName": "id", "AttributeType": "S"}],
"ProvisionedThroughput": {"ReadCapacityUnits": 5, "WriteCapacityUnits": 5}
}
```
--------------------------------
### Parameter Storage Structure Example
Source: https://deepwiki.com/getmoto/moto/4.8-ssm-implementation
Simplified representation of how parameters are stored in ParameterDict. Each parameter name maps to a list of Parameter objects representing different versions, with up to 100 versions per parameter.
```python
# Simplified representation of how parameters are stored
{
"/my/param1": [Parameter(version=1), Parameter(version=2), ...],
"/my/param2": [Parameter(version=1)]
}
```
--------------------------------
### Test ELBv2 load balancer creation with Moto
Source: https://deepwiki.com/getmoto/moto/5.1-elbv2-implementation
Simplified example of using Moto's ELBv2 mock in tests. Creates EC2 VPC, subnets, and security group, then creates an application load balancer, target group, and listener, and verifies the resources with describe calls.
```python
import boto3
from moto import mock_aws
@mock_aws
def test_create_load_balancer():
# Create EC2 resources
ec2 = boto3.resource('ec2', region_name='us-east-1')
vpc = ec2.create_vpc(CidrBlock='10.0.0.0/16')
subnet1 = ec2.create_subnet(VpcId=vpc.id, CidrBlock='10.0.1.0/24', AvailabilityZone='us-east-1a')
subnet2 = ec2.create_subnet(VpcId=vpc.id, CidrBlock='10.0.2.0/24', AvailabilityZone='us-east-1b')
security_group = ec2.create_security_group(GroupName='sg', Description='sg', VpcId=vpc.id)
# Create ELBv2 resources
elbv2 = boto3.client('elbv2', region_name='us-east-1')
# Create load balancer
lb_response = elbv2.create_load_balancer(
Name='test-lb',
Subnets=[subnet1.id, subnet2.id],
SecurityGroups=[security_group.id],
Scheme='internet-facing',
Tags=[{'Key': 'Name', 'Value': 'test-lb'}],
Type='application'
)
lb_arn = lb_response['LoadBalancers'][0]['LoadBalancerArn']
# Create target group
tg_response = elbv2.create_target_group(
Name='test-tg',
Protocol='HTTP',
Port=80,
VpcId=vpc.id,
HealthCheckProtocol='HTTP',
HealthCheckPath='/',
HealthCheckPort='80',
TargetType='instance'
)
tg_arn = tg_response['TargetGroups'][0]['TargetGroupArn']
# Create listener
listener_response = elbv2.create_listener(
LoadBalancerArn=lb_arn,
Protocol='HTTP',
Port=80,
DefaultActions=[{
'Type': 'forward',
'TargetGroupArn': tg_arn
}]
)
# Verify resources were created
lbs = elbv2.describe_load_balancers()
assert len(lbs['LoadBalancers']) == 1
tgs = elbv2.describe_target_groups()
assert len(tgs['TargetGroups']) == 1
listeners = elbv2.describe_listeners(LoadBalancerArn=lb_arn)
assert len(listeners['Listeners']) == 1
```
--------------------------------
### Mocking AWS Services for Local Development with moto_server and AWS CLI
Source: https://deepwiki.com/getmoto/moto/3.1-moto-server
Use this shell snippet to start Moto Server and configure AWS CLI to use it for local development. It sets endpoint URLs for S3 and DynamoDB, then demonstrates using AWS CLI commands against the mock server.
```shell
# Start the server
moto_server --host 0.0.0.0
# Configure AWS CLI to use the mock server
aws configure set s3.endpoint_url http://localhost:5000
aws configure set dynamodb.endpoint_url http://localhost:5000
# Use AWS CLI commands against the mock server
aws s3 mb s3://test-bucket
aws s3 cp file.txt s3://test-bucket/
```
--------------------------------
### Test SQS to Lambda integration with @mock_aws
Source: https://deepwiki.com/getmoto/moto/6.2-event-driven-integrations
This example demonstrates setting up an SQS queue, a Lambda function, and an event source mapping to test event-driven triggers. The test uses the @mock_aws decorator to intercept AWS calls.
```python
@mock_aws
def test_sqs_to_lambda_integration():
# Create SQS queue
sqs = boto3.resource('sqs', region_name='us-east-1')
queue = sqs.create_queue(QueueName='test-queue')
# Create Lambda function
lambda_client = boto3.client('lambda', region_name='us-east-1')
lambda_client.create_function(
FunctionName='test-function',
Runtime='python3.8',
Role='role-arn',
Handler='index.handler',
Code={'ZipFile': b'def handler(event, context): return event'},
)
# Create event source mapping
lambda_client.create_event_source_mapping(
EventSourceArn=queue.attributes['QueueArn'],
FunctionName='test-function',
BatchSize=1
)
# Send message to SQS
queue.send_message(MessageBody='test message')
# Verify Lambda was invoked (implementation depends on your application)
# ...
```
--------------------------------
### Integration Testing with ThreadedMotoServer
Source: https://deepwiki.com/getmoto/moto/3.1-moto-server
Use this Python snippet to set up Moto Server for integration testing. It starts a threaded server, configures a boto3 S3 client to use it, and tests bucket operations. The server is stopped after verification.
```python
# Set up a test with Moto Server
import boto3
import requests
from moto.server import ThreadedMotoServer
# Start Moto Server
server = ThreadedMotoServer()
server.start()
endpoint = f"http://{server.get_host_and_port()[0]}:{server.get_host_and_port()[1]}"
# Configure AWS client
s3 = boto3.client('s3', endpoint_url=endpoint, aws_access_key_id='test',
aws_secret_access_key='test')
# Test your application logic
s3.create_bucket(Bucket='mybucket')
s3.put_object(Bucket='mybucket', Key='mykey', Body=b'test data')
# Verify behavior
response = s3.get_object(Bucket='mybucket', Key='mykey')
assert response['Body'].read() == b'test data'
# Clean up
server.stop()
```
--------------------------------
### S3 Exception Hierarchy Implementation
Source: https://deepwiki.com/getmoto/moto/4-core-aws-service-implementations
Example of how Moto defines service-specific exceptions that mirror AWS API error responses, using S3 as a reference.
```python
# Example S3 exception hierarchy
class S3ClientError(RESTError):
request_id_tag_name = "RequestID"
# ...
class MissingBucket(BucketError):
code = 404
def __init__(self, bucket):
super().__init__(
"NoSuchBucket", "The specified bucket does not exist", bucket=bucket
)
```
--------------------------------
### Standalone Server Mode with moto_server
Source: https://deepwiki.com/getmoto/moto/1-moto-overview
Start a local HTTP endpoint that mimics the AWS API, allowing testing with any AWS SDK. Configure boto3 to use the server via endpoint_url='http://localhost:5000'.
```python
# Start server in a separate process/terminal:
# $ moto_server
# Then in your code:
import boto3
# Configure boto3 to use the local Moto server
s3_client = boto3.client('s3', endpoint_url='http://localhost:5000')
s3_client.create_bucket(Bucket='test-bucket')
```
--------------------------------
### AWS-Verified Tests with aws_verified decorator
Source: https://deepwiki.com/getmoto/moto/7.2-testing-patterns
Use the aws_verified decorator to run tests against both Moto and real AWS, verifying Moto's behavior matches AWS. The example expects a QueueDoesNotExist exception for an unknown queue name.
```python
from tests import aws_verified
@aws_verified
@pytest.mark.aws_verified
def test_get_unknown_queue_by_name():
sqs = boto3.resource("sqs", "us-east-1")
with pytest.raises(sqs.meta.client.exceptions.QueueDoesNotExist):
sqs.get_queue_by_name(QueueName="doesnotexist")
```
--------------------------------
### Integration with responses library
Source: https://deepwiki.com/getmoto/moto/7.2-testing-patterns
Use Moto with the responses library to mock both AWS services and external HTTP APIs in the same test. The example mocks an external API and uses Moto for S3, then verifies both calls.
```python
@mock_aws
@responses.activate
def test_aws_and_external_api():
# Mock external HTTP API
responses.add(
responses.GET,
'https://api.example.com/data',
json={'status': 'success'},
status=200
)
# Use Moto for AWS service
s3 = boto3.client('s3', region_name='us-east-1')
s3.create_bucket(Bucket='test-bucket')
# Make requests to both
requests.get('https://api.example.com/data')
buckets = s3.list_buckets()
# Verify results
assert len(responses.calls) == 1
assert len(buckets['Buckets']) == 1
```
--------------------------------
### create_backend_app flowchart
Source: https://deepwiki.com/getmoto/moto/3.1-moto-server
Mermaid flowchart illustrating the create_backend_app(service) function: it creates a Flask app, gets the backend via backends.get_backend(service), registers URL routes for each path in backend.flask_paths using app.add_url_rule, and converts handlers to Flask responses with convert_to_flask_response.
```mermaid
flowchart TD
CreateBackendApp["create_backend_app(service)"] -->|"Create Flask App"| App["Flask Application"]
App -->|"Get Backend for Service"| GetBackend["backends.get_backend(service)"]
GetBackend -->|"Return Backend"| Backend["Service Backend"]
App -->|"Register URL Routes"| RegisterRoutes["Register Flask Routes"]
RegisterRoutes -->|"For each path in backend.flask_paths"| AddUrlRule["app.add_url_rule"]
AddUrlRule -->|"Convert Handler to Flask View"| ConvertToFlask["convert_to_flask_response"]
```
--------------------------------
### Explicitly patch pre-existing boto3 client and resource with patch_client() and patch_resource()
Source: https://deepwiki.com/getmoto/moto/3-usage-methods
Use this when you have boto3 clients or resources created before Moto was initialized. The patch_client() and patch_resource() functions make these pre-existing objects use Moto's mock implementations. The example shows creating an S3 client and resource outside the mock context, then patching them inside a @mock_aws test to verify bucket creation.
```python
import boto3
from moto import mock_aws
from moto import patch_client, patch_resource
# Create an AWS client outside of Moto's context
s3_client = boto3.client('s3', region_name='us-east-1')
s3_resource = boto3.resource('s3', region_name='us-east-1')
@mock_aws
def test_with_explicit_patching():
# Explicitly patch the pre-existing client and resource
patch_client(s3_client)
patch_resource(s3_resource)
# Now they will use Moto's mock implementations
s3_client.create_bucket(Bucket='mybucket')
buckets = s3_resource.buckets.all()
# Verify the bucket was created
bucket_names = [bucket.name for bucket in buckets]
assert 'mybucket' in bucket_names
```
--------------------------------
### Concurrent Operation Testing with Moto
Source: https://deepwiki.com/getmoto/moto/7.2-testing-patterns
Test concurrent SQS operations using threads. The example creates a test client, defines producer and consumer functions, runs them concurrently, and verifies the number of messages received.
```python
@mock_aws
def test_concurrent_sqs_operations():
# Create test setup
backend = server.create_backend_app("sqs")
test_client = backend.test_client()
messages = []
test_client.put("/?Action=CreateQueue&QueueName=testqueue")
# Define producer function
def insert_messages():
messages_count = 5
while messages_count > 0:
test_client.put(
"/123/testqueue?MessageBody=test-message&Action=SendMessage"
)
messages_count -= 1
time.sleep(0.5)
# Define consumer function
def get_messages():
count = 0
while count < 5:
msg_res = test_client.get(
"/123/testqueue?Action=ReceiveMessage&MaxNumberOfMessages=1"
)
new_msgs = re.findall("
(.*?)", msg_res.data.decode("utf-8"))
count += len(new_msgs)
messages.append(new_msgs)
# Run concurrent operations
get_messages_thread = threading.Thread(target=get_messages)
insert_messages_thread = threading.Thread(target=insert_messages)
get_messages_thread.start()
insert_messages_thread.start()
get_messages_thread.join()
insert_messages_thread.join()
# Verify results
assert len(messages) == 5
```
--------------------------------
### Control Moto reset behavior with reset and remove_data decorator parameters
Source: https://deepwiki.com/getmoto/moto/3-usage-methods
Shows how to use @mock_aws(reset=True, remove_data=False) to reset state but keep data, and @mock_aws(reset=False) to skip resetting at the start of a test. This allows resources created in one test to persist for subsequent tests, useful for expensive setup scenarios.
```python
from moto import mock_aws
import boto3
# First test creates resources
@mock_aws(reset=True, remove_data=False) # Reset but don't remove data
def test_create_resources():
s3 = boto3.client('s3', region_name='us-east-1')
s3.create_bucket(Bucket='persistent-bucket')
# Verify the bucket exists
response = s3.list_buckets()
assert len(response['Buckets']) == 1
# Second test uses the resources created in the first test
@mock_aws(reset=False) # Don't reset at the start
def test_use_existing_resources():
s3 = boto3.client('s3', region_name='us-east-1')
# The bucket created in the previous test should still exist
response = s3.list_buckets()
assert len(response['Buckets']) == 1
assert response['Buckets'][0]['Name'] == 'persistent-bucket'
```
--------------------------------
### Dead Letter Queue: _setup_dlq method
Source: https://deepwiki.com/getmoto/moto/4.4-sqs-implementation
Parses and validates the redrive policy, finds the target DLQ, and sets up the relationship.
```python
def _setup_dlq(self, policy: Any) -> None:
# Parse and validate redrive policy
# Find the target DLQ
# Set up the relationship
```
--------------------------------
### Update setup.cfg for Service Registration
Source: https://deepwiki.com/getmoto/moto/7.1-adding-new-services
Adds the new service to the extras_require section in setup.cfg to manage dependencies.
```ini
[options.extras_require]
...
your_service =
# Any additional dependencies your service requires
...
```
--------------------------------
### S3 Bucket Response Template
Source: https://deepwiki.com/getmoto/moto/4-core-aws-service-implementations
An example of a Jinja2 template used to format XML responses for the S3 ListBucketResult API.
```python
S3_BUCKET_GET_RESPONSE = """
{{ bucket.name }}
"""
```
--------------------------------
### Accessing an S3 backend
Source: https://deepwiki.com/getmoto/moto/2.1-backend-system
Demonstrates how to retrieve an S3 backend instance for a specific account and partition using the global s3_backends variable.
```python
# Example of accessing an S3 backend
from moto.s3.models import s3_backends
# Get S3 backend for a specific account and partition
s3_backend = s3_backends[account_id][partition]
```
--------------------------------
### Direct Backend Reference Pattern
Source: https://deepwiki.com/getmoto/moto/6-cross-service-interactions
Demonstrates accessing another service's backend directly by importing the backend dictionary and using account and partition identifiers.
```python
from moto.s3.models import s3_backends
from moto.iam.models import iam_backends
# Lambda code accessing S3 backends
key = s3_backends[self.account_id][self.partition].get_object(
updated_spec["S3Bucket"], updated_spec["S3Key"]
)
```
--------------------------------
### Organize Test Class with unittest
Source: https://deepwiki.com/getmoto/moto/7.2-testing-patterns
Use the @mock_aws decorator with a unittest.TestCase class to ensure mocks are active during setup and test execution.
```python
@mock_aws
class TestWithSetup(unittest.TestCase):
def setUp(self):
# Setup runs for each test with mocking already active
self.s3 = boto3.client('s3', region_name='us-east-1')
self.s3.create_bucket(Bucket='test-bucket')
def test_object_creation(self):
self.s3.put_object(Bucket='test-bucket', Key='test-key', Body='data')
response = self.s3.get_object(Bucket='test-bucket', Key='test-key')
self.assertEqual(response['Body'].read().decode(), 'data')
```
--------------------------------
### ThreadedMotoServer class diagram
Source: https://deepwiki.com/getmoto/moto/3.1-moto-server
Mermaid class diagram showing the ThreadedMotoServer class with its public methods: __init__, start, get_host_and_port, stop, and private members.
```mermaid
classDiagram
class ThreadedMotoServer {
+__init__(ip_address, port, verbose)
+start()
+get_host_and_port()
+stop()
-_server_entry()
-_server_ready_event
}
```
--------------------------------
### Implement a Basic Resource Model
Source: https://deepwiki.com/getmoto/moto/7.1-adding-new-services
Create a model class inheriting from BaseModel to store resource state and behavior.
```python
from moto.core.common_models import BaseModel
class YourResourceModel(BaseModel):
def __init__(self, resource_id, **kwargs):
self.id = resource_id
self.name = kwargs.get("name")
self.created_time = datetime.now().isoformat()
# Set other attributes from kwargs
```
--------------------------------
### CloudFormationModel interface class diagram
Source: https://deepwiki.com/getmoto/moto/6.1-cloudformation-resource-creation
Mermaid class diagram showing the CloudFormationModel interface with its required methods and example implementing classes (EC2Instance, S3Bucket, IAMRole).
```mermaid
classDiagram
class CloudFormationModel {
<>
+create_from_cloudformation_json(resource_name, json_body, account_id, region_name) Resource
+update_from_cloudformation_json(original_resource, new_resource_name, json_body, account_id, region_name) Resource
+delete_from_cloudformation_json(resource_name, json_body, account_id, region_name) void
+has_cfn_attr(attribute) bool
+get_cfn_attribute(attribute) Any
}
class EC2Instance {
+create_from_cloudformation_json()
+update_from_cloudformation_json()
+delete_from_cloudformation_json()
+has_cfn_attr()
+get_cfn_attribute()
}
class S3Bucket {
+create_from_cloudformation_json()
+update_from_cloudformation_json()
+delete_from_cloudformation_json()
+has_cfn_attr()
+get_cfn_attribute()
}
class IAMRole {
+create_from_cloudformation_json()
+update_from_cloudformation_json()
+delete_from_cloudformation_json()
+has_cfn_attr()
+get_cfn_attribute()
}
CloudFormationModel <|-- EC2Instance
CloudFormationModel <|-- S3Bucket
CloudFormationModel <|-- IAMRole
```
--------------------------------
### Create service directory structure
Source: https://deepwiki.com/getmoto/moto/7.1-adding-new-services
Shows the required directory layout for a new service in the Moto repository. The directory name should match the service name used by boto3.
```text
moto/
└── your_service/
├── __init__.py
├── models.py
├── responses.py
└── urls.py
```
--------------------------------
### Configure boto3 to use Moto Server
Source: https://deepwiki.com/getmoto/moto/3.1-moto-server
Sets up a boto3 S3 client to interact with Moto Server at localhost:5000. Uses dummy credentials and demonstrates creating a bucket and putting an object, which are routed to Moto's S3 backend.
```python
import boto3
# Configure boto3 to use Moto Server
s3_client = boto3.client(
's3',
endpoint_url='http://localhost:5000',
aws_access_key_id='dummy',
aws_secret_access_key='dummy'
)
# Use the client as normal - it will interact with Moto Server
s3_client.create_bucket(Bucket='test-bucket')
s3_client.put_object(Bucket='test-bucket', Key='test-key', Body='test-content')
```
--------------------------------
### Sequence Diagram of mock_aws Internals
Source: https://deepwiki.com/getmoto/moto/7.2-testing-patterns
Mermaid sequence diagram showing how mock_aws works: it starts, enables the BotocoreStubber, routes API calls to the service backend, and stops/resets after the test.
```mermaid
sequenceDiagram
participant Test as "Test Code"
participant MockAWS as "mock_aws"
participant Boto3 as "boto3"
participant Stubber as "BotocoreStubber"
participant Backend as "Service Backend"
Test->>MockAWS: Decorate test or enter context
MockAWS->>MockAWS: start()
MockAWS->>Stubber: Enable stubber
Test->>Boto3: Make AWS API call
Boto3->>Stubber: Process request
Stubber->>Backend: Route to appropriate backend
Backend->>Stubber: Return mock response
Stubber->>Boto3: Return response
Boto3->>Test: Return result
Test->>MockAWS: Test completes or exit context
MockAWS->>MockAWS: stop()
MockAWS->>MockAWS: Reset state if needed
```
--------------------------------
### Error Case Testing: QueueDoesNotExist exception
Source: https://deepwiki.com/getmoto/moto/7.2-testing-patterns
Tests error handling by expecting a QueueDoesNotExist exception when getting a nonexistent queue. Moto implements common AWS error responses.
```python
@mock_aws
def test_nonexistent_queue():
sqs = boto3.resource("sqs", region_name="us-east-1")
with pytest.raises(sqs.meta.client.exceptions.QueueDoesNotExist) as exc:
sqs.get_queue_by_name(QueueName="doesnotexist")
```
--------------------------------
### IMPLEMENTATION_COVERAGE.md format
Source: https://deepwiki.com/getmoto/moto/1.1-implementation-coverage
The standard template used to document service implementation status, including method completion and additional notes.
```markdown
## service-name
xx% implemented
- [X] implemented_method_name
- [ ] not_implemented_method_name
- [X] implemented_method_with_notes
Additional notes about limitations
```
--------------------------------
### Implementation Status Visualization
Source: https://deepwiki.com/getmoto/moto/1.1-implementation-coverage
A Mermaid graph illustrating the distribution of AWS service implementation completeness within Moto, categorized by percentage ranges.
```mermaid
graph TD
subgraph "Implementation Status Visualization"
Complete["Fully Implemented Services
100%"] --> AGMA["apigatewaymanagementapi"]
VeryHigh["Highly Implemented Services
80-99%"] --> Batch["batch: 96%"]
High["Well Implemented Services
60-79%"] --> AppAS["application-autoscaling: 64%"]
High --> AS["autoscaling: 60%"]
High --> APIGW2["apigatewayv2: 75%"]
Medium["Moderately Implemented Services
40-59%"] --> APIGW["apigateway: 62%"]
Medium --> ACM["acm: 60%"]
Medium --> ACMPCA["acm-pca: 56%"]
Medium --> AMP["amp: 62%"]
Medium --> Cloud["cloudhsmv2: 50%"]
Low["Partially Implemented Services
10-39%"] --> CF["cloudformation: 39%"]
Low --> CW["cloudwatch: 39%"]
Low --> CT["cloudtrail: 28%"]
Low --> Athena["athena: 25%"]
Low --> AppSync["appsync: 27%"]
Low --> Bed["bedrock: 22%"]
VeryLow["Minimally Implemented Services
<10%"] --> Backup["backup: 9%"]
end
```
--------------------------------
### SecretsManager Parameter Retrieval
Source: https://deepwiki.com/getmoto/moto/4.8-ssm-implementation
Method to retrieve a parameter value from a SecretsManager secret using the path '/aws/reference/secretsmanager/'. It accesses the secretsmanager backend for the account and region, then describes the secret to get its value.
```python
def _get_secretsmanager_parameter(self, secret_name):
secrets_backend = secretsmanager_backends[self.account_id][self.region_name]
secret = secrets_backend.describe_secret(secret_name).to_dict()
# Get the secret value and return it as a parameter
# ...
```
--------------------------------
### Simplified S3 backend dictionary structure
Source: https://deepwiki.com/getmoto/moto/4-core-aws-service-implementations
This structure demonstrates how service backends are organized by account ID, partition, and region to support multi-account and multi-region testing.
```python
# Simplified backend dictionary structure
s3_backends = {
"123456789012": { # Account ID
"aws": { # Partition
# Region-specific backends
"us-east-1": S3Backend(),
"us-west-2": S3Backend(),
# ...
}
}
}
```
--------------------------------
### Implement CloudFront Distribution Creation
Source: https://deepwiki.com/getmoto/moto/7.1-adding-new-services
Defines the Distribution model and CloudFrontBackend logic for creating distributions, along with the corresponding response handling.
```python
# In models.py
class Distribution(BaseModel):
def __init__(self, distribution_id, distribution_config):
self.id = distribution_id
self.arn = f"arn:aws:cloudfront::{account_id}:distribution/{distribution_id}"
self.status = "InProgress"
self.domain_name = f"{distribution_id}.cloudfront.net"
self.distribution_config = distribution_config
self.created_time = datetime.now().isoformat()
class CloudFrontBackend(BaseBackend):
def __init__(self, region_name=None):
super().__init__(region_name)
self.distributions = {}
def create_distribution(self, distribution_config):
distribution_id = str(uuid.uuid4())[:8]
distribution = Distribution(distribution_id, distribution_config)
self.distributions[distribution_id] = distribution
return distribution
# In responses.py
class CloudFrontResponse(BaseResponse):
def create_distribution(self):
distribution_config = self._get_dict_param("DistributionConfig.")
distribution = self.cloudfront_backend.create_distribution(distribution_config)
template = self.response_template(CREATE_DISTRIBUTION_TEMPLATE)
return template.render(distribution=distribution)
```
--------------------------------
### CloudFormation Resource Creation Method
Source: https://deepwiki.com/getmoto/moto/6-cross-service-interactions
Illustrates the class method used by CloudFormation to instantiate resources by retrieving the appropriate backend and calling the creation logic.
```python
@classmethod
def create_from_cloudformation_json(cls, resource_name, cloudformation_json, account_id, region_name, **kwargs):
properties = cloudformation_json["Properties"]
backend = lambda_backends[account_id][region_name]
# Create the resource using the backend
return backend.create_function(...)
```
--------------------------------
### Authentication Token Flow Sequence
Source: https://deepwiki.com/getmoto/moto/5.2-cognito-idp-implementation
Visualizes the token creation process during initial authentication and token refresh.
```mermaid
sequenceDiagram
participant Client as Client Application
participant Moto as Moto CognitoIdP Backend
participant UserPool as CognitoIdpUserPool
Client->>Moto: initiate_auth(username, password)
Moto->>UserPool: authenticate user
alt Authentication successful
UserPool->>UserPool: create_refresh_token(client_id, username)
UserPool->>UserPool: create_access_token(client_id, username, origin_jti)
UserPool->>UserPool: create_id_token(client_id, username, origin_jti)
UserPool-->>Moto: Return tokens
Moto-->>Client: Return AuthenticationResult with tokens
else Authentication failed
UserPool-->>Moto: Error
Moto-->>Client: Return error
end
Client->>Moto: refresh_token_auth(refresh_token)
Moto->>UserPool: create_tokens_from_refresh_token(refresh_token)
UserPool->>UserPool: create_access_token(client_id, username, origin_jti)
UserPool->>UserPool: create_id_token(client_id, username, origin_jti)
UserPool-->>Moto: Return new tokens
Moto-->>Client: Return new tokens
```
--------------------------------
### Unittest: Use mock_aws decorator or manual start/stop
Source: https://deepwiki.com/getmoto/moto/3-usage-methods
Shows two unittest patterns: a class-level decorator and manual start/stop in setUp/tearDown. The manual approach requires calling mock.start() and mock.stop() explicitly. Use when writing unittest tests with Moto.
```python
import unittest
import boto3
from moto import mock_aws
# Using the decorator on the class
@mock_aws
class TestS3(unittest.TestCase):
def test_s3_operations(self):
s3 = boto3.client('s3', region_name='us-east-1')
# Test code here
# Using setUp and tearDown
class TestS3Manual(unittest.TestCase):
def setUp(self):
self.mock = mock_aws()
self.mock.start()
self.s3 = boto3.client('s3', region_name='us-east-1')
def tearDown(self):
self.mock.stop()
def test_s3_operations(self):
# self.s3 is already mocked
self.s3.create_bucket(Bucket='mybucket')
# Test code here
```
--------------------------------
### Unit testing with @mock_aws decorator
Source: https://deepwiki.com/getmoto/moto/2-core-architecture
The @mock_aws decorator patches boto3 client creation to redirect API calls to Moto's backend. This example demonstrates creating an S3 bucket and verifying its state within a test function.
```python
from moto import mock_aws
@mock_aws
def test_s3_bucket_creation():
import boto3
s3 = boto3.client('s3', region_name='us-east-1')
s3.create_bucket(Bucket='my-test-bucket')
# Moto maintains the state of created resources
response = s3.list_buckets()
assert len(response['Buckets']) == 1
assert response['Buckets'][0]['Name'] == 'my-test-bucket'
```
--------------------------------
### Pytest: Use mock_aws decorator and fixture
Source: https://deepwiki.com/getmoto/moto/3-usage-methods
Shows two pytest patterns: a decorator-based test and a fixture-based setup. The fixture 'aws_credentials' uses mock_aws() as a context manager, and 's3_client' depends on it. Use when writing pytest tests with Moto.
```python
import boto3
import pytest
from moto import mock_aws
# Using the decorator
@mock_aws
def test_with_decorator():
s3 = boto3.client('s3', region_name='us-east-1')
# Test code here
# Using a fixture
@pytest.fixture
def aws_credentials():
"""Mocked AWS Credentials for boto3."""
from moto import mock_aws
with mock_aws():
yield
@pytest.fixture
def s3_client(aws_credentials):
return boto3.client('s3', region_name='us-east-1')
def test_with_fixture(s3_client):
# s3_client is already mocked
s3_client.create_bucket(Bucket='mybucket')
# Test code here
```
--------------------------------
### Implement Pagination for AWS Resources
Source: https://deepwiki.com/getmoto/moto/7.1-adding-new-services
Standard pattern for implementing pagination using max_items and marker parameters to return a subset of resources and the next marker.
```python
def list_resources(self, max_items=None, marker=None):
resources = list(self.resources.values())
if marker:
start_idx = next(
(i for i, r in enumerate(resources) if r.id == marker),
0
)
resources = resources[start_idx + 1:]
if max_items:
resources = resources[:max_items]
if len(resources) < len(self.resources):
next_marker = resources[-1].id if resources else None
else:
next_marker = None
return resources, next_marker
```
--------------------------------
### Create Directory Structure
Source: https://deepwiki.com/getmoto/moto/7-extending-moto
The required directory structure for a new service within the moto/ folder.
```text
moto/
└── your_service/
├── __init__.py
├── models.py # Backend and resource model implementations
├── responses.py # Response handlers for API calls
└── urls.py # Optional, if service has unique URL patterns
```
--------------------------------
### Decorate a test function with @mock_aws
Source: https://deepwiki.com/getmoto/moto/3-usage-methods
Use @mock_aws on a test function to intercept all AWS API calls within that function and route them to Moto's mock implementations. The example creates an S3 bucket and verifies it exists via list_buckets.
```python
from moto import mock_aws
import boto3
@mock_aws
def test_create_s3_bucket():
# Create a connection to S3
s3 = boto3.client('s3', region_name='us-east-1')
# Create a bucket
s3.create_bucket(Bucket='mybucket')
# Verify the bucket exists
response = s3.list_buckets()
assert len(response['Buckets']) == 1
assert response['Buckets'][0]['Name'] == 'mybucket'
```
--------------------------------
### Multipart Upload Flow Diagram (Mermaid)
Source: https://deepwiki.com/getmoto/moto/4.1-s3-implementation
Mermaid flowchart illustrating the multipart upload workflow in Moto's S3 implementation. It shows the sequence from starting an upload, uploading parts, completing or aborting, and the associated errors (EntityTooSmall, InvalidPart, InvalidPartOrder).
```mermaid
flowchart TD
Start["Start Multipart Upload"]
UploadParts["Upload Parts (1-10000)"]
CompleteMPU["Complete Multipart Upload"]
AbortMPU["Abort Multipart Upload"]
Start -->|"Returns upload ID"| UploadParts
UploadParts -->|"All parts uploaded"| CompleteMPU
UploadParts -->|"Cancel upload"| AbortMPU
UploadParts -->|"Part too small"| EntityTooSmall["EntityTooSmall Error"]
CompleteMPU -->|"Invalid ETags"| InvalidPart["InvalidPart Error"]
CompleteMPU -->|"Wrong order"| InvalidPartOrder["InvalidPartOrder Error"]
```
--------------------------------
### SimpleSystemManagerResponse class implementation
Source: https://deepwiki.com/getmoto/moto/4.8-ssm-implementation
Python class extending Moto's BaseResponse for the SSM service. It initializes with service_name='ssm', provides a ssm_backend property, and includes a put_parameter method that parses request parameters, calls the backend, and returns a JSON response with the parameter version.
```python
class SimpleSystemManagerResponse(BaseResponse):
def __init__(self):
super().__init__(service_name="ssm")
@property
def ssm_backend(self):
return ssm_backends[self.current_account][self.region]
# Parameter Store methods
def put_parameter(self):
# Get parameters from request
name = self._get_param("Name")
description = self._get_param("Description")
value = self._get_param("Value")
type_ = self._get_param("Type")
# ...
# Call backend method
param = self.ssm_backend.put_parameter(
name, description, value, type_, ...
)
# Return response
response = {"Version": param.version}
return json.dumps(response)
# Document methods, Command methods, Maintenance Window methods...
```
--------------------------------
### Create backend dictionary in models.py
Source: https://deepwiki.com/getmoto/moto/7.1-adding-new-services
At the end of models.py, create a backend dictionary to store backends for different regions.
```python
your_service_backends = BackendDict(YourServiceBackend, "your-service")
```