How to Mock RDS Snapshot Create and Restore in Python
Mock AWS RDS snapshot creation and restore operations in Python tests using moto and boto3 without hitting real AWS services.
pip install boto3 moto
Python code
29 linesimport boto3
from moto import mock_rds
@mock_rds
def create_and_restore_snapshot():
client = boto3.client("rds", region_name="us-east-1")
client.create_db_instance(
DBInstanceIdentifier="my-db",
DBInstanceClass="db.t3.micro",
Engine="postgres",
AllocatedStorage=20,
MasterUsername="admin",
MasterUserPassword="password123",
DBName="mydb",
)
snapshot = client.create_db_snapshot(
DBInstanceIdentifier="my-db",
DBSnapshotIdentifier="my-snapshot",
)
snapshot_id = snapshot["DBSnapshot"]["DBSnapshotIdentifier"]
restored = client.restore_db_instance_from_db_snapshot(
DBInstanceIdentifier="my-restored-db",
DBSnapshotIdentifier=snapshot_id,
)
return restored["DBInstance"]["DBInstanceIdentifier"]
if __name__ == "__main__":
print(create_and_restore_snapshot())
Output
my-restored-db
How it works
The @mock_rds decorator from moto intercepts all boto3 RDS API calls and returns simulated responses in memory. The code creates a DB instance, takes a snapshot, then restores a new instance from that snapshot. Since the mock replaces the real AWS endpoints, the function runs fast, costs nothing, and needs no network or credentials. The restore returns the new DB instance identifier, which create_db_snapshot and restore_db_instance_from_db_snapshot chain together through the snapshot ID. This pattern lets you verify the full lifecycle logic of RDS operations in unit tests without provisioning real infrastructure.
Common mistakes
- Forgetting that moto's `@mock_rds` only works inside the decorated function scope
- Using real AWS credentials in tests when the mock is already active
- Not draining/creating the DB instance before snapshotting, causing resource-not-found errors
Variations
- Use `mock_aws` from `moto` for a single context that mocks multiple AWS services
- Wrap the call in a `with mock_rds():` context manager for granular control
Real-world use cases
- Testing disaster-recovery automation that snapshots production DBs and restores them to a staging environment.
- Validating a backup pipeline that periodically creates RDS snapshots and restores them to verify data integrity.
- Running CI/CD tests for serverless functions that spin up a temporary DB from a snapshot for integration checks.
Sponsored
More from Cloud + Python
- Build a URL Shortener Client with Python medium
- Create a Cloud Storage Helper Class in Python easy
- Create a Data Helper Class for Beginners in Python easy
- Cross Account Role Chaining Mock Credentials in Python medium
- Exponential Backoff with Jitter for Cloud API Calls in Python medium
- Generate Mock CloudFormation Stack Events in Python easy
Keep learning
Related tutorials and quizzes for this topic.