Build: A Local Testing Walkthrough with Moto and EC2
Build: A Local Testing Walkthrough with Moto and EC2
When you’re building Python tools that work with AWS services, you
don’t always want to reach into the cloud during development. It’s slow. It’s
expensive. And it’s dangerous if your code’s not fully baked. That’s where
Moto comes in — it mocks AWS APIs locally so you can simulate behavior and
write repeatable, offline tests.
Here’s a real-world walkthrough that uses Moto to fake EC2 instances, test a Python script, and return real JSON output — no AWS account required.
First Run (with a mistake)
Let's run the script:
Oops! Here's the error:
The instance came back in pending state. But our test expects
running.
Here’s a real-world walkthrough that uses Moto to fake EC2 instances, test a Python script, and return real JSON output — no AWS account required.
Step 1: Set Up Your Working
Directory
Start by creating a new folder:
Step 2: Create and Activate a Virtual Environment
We’ll isolate our dependencies:
(MacOS and Linux)
(Windows)
Step 3: Install Moto and boto3 (Specific Version)
We’ll pin Moto to a known working version for EC2 support:
Step 4: Create the Test Script
Create and open a file:
Paste the following code:
Make the script executable:
What This Script Does
Start by creating a new folder:
We’ll isolate our dependencies:
We’ll pin Moto to a known working version for EC2 support:
Create and open a file:
- Sets up a fake EC2 environment using Moto's @mock_ec2 decorator
- Creates a mock EC2 instance using run_instances
- Uses describe_instances to retrieve instance data
- Parses and formats the results as JSON
- Validates that one instance was returned and is in running state
- Prints the full report to the console
First Run (with a mistake)
Let's run the script:
The Fix
In the report_instances function, we need to manually set the instance state:
Or, to keep it simple for Moto (which may not simulate waiters
reliably), we can change the assertion:
Run Again (Fixed)
Expected Output EC2 Instance Report
Step 6: Deactivate the Virtual Environment
Once done:
This is a clean pattern you can reuse for mocking any supported
AWS service: S3, DynamoDB, Lambda, and more. Moto keeps your testing fast,
cheap, and entirely local.
In the report_instances function, we need to manually set the instance state:
Expected Output EC2 Instance Report
Once done:
Need AWS Expertise?
We'd love to help you with your AWS projects. Feel free to reach out to us at info@pacificw.com.
Written by Aaron Rose, software engineer and technology writer at Tech-Reader.blog.
Comments
Post a Comment