Moto is a library that allows your tests to easily mock out AWS Services.
Imagine you have the following python code that you want to test:
importboto3classMyModel(object):
def__init__(self, name, value):
self.name=nameself.value=valuedefsave(self):
s3=boto3.client('s3', region_name='us-east-1')
s3.put_object(Bucket='mybucket', Key=self.name, Body=self.value)Take a minute to think how you would have tested that in the past.
Now see how you could test it with Moto:
importboto3frommotoimportmock_s3frommymoduleimportMyModel@mock_s3deftest_my_model_save():
conn=boto3.resource('s3', region_name='us-east-1')
# We need to create the bucket since this is all in Moto's 'virtual' AWS accountconn.create_bucket(Bucket='mybucket')
model_instance=MyModel('steve', 'is awesome')
model_instance.save()
body=conn.Object('mybucket', 'steve').get()['Body'].read().decode("utf-8")
assertbody=='is awesome'With the decorator wrapping the test, all the calls to s3 are automatically mocked out. The mock keeps the state of the buckets and keys.
It gets even better! Moto isn't just for Python code and it isn't just for S3. Look at the standalone server mode for more information about running Moto with other languages. Here's the status of the other AWS services implemented:
|-------------------------------------------------------------------------------------|| ServiceName | Decorator | DevelopmentStatus ||-------------------------------------------------------------------------------------|| ACM | @mock_acm | allendpointsdone ||-------------------------------------------------------------------------------------|| APIGateway | @mock_apigateway | coreendpointsdone ||-------------------------------------------------------------------------------------|| Autoscaling | @mock_autoscaling | coreendpointsdone ||-------------------------------------------------------------------------------------|| Cloudformation | @mock_cloudformation | coreendpointsdone ||-------------------------------------------------------------------------------------|| Cloudwatch | @mock_cloudwatch | basicendpointsdone ||-------------------------------------------------------------------------------------|| CloudwatchEvents | @mock_events | allendpointsdone ||-------------------------------------------------------------------------------------|| CognitoIdentity | @mock_cognitoidentity | basicendpointsdone ||-------------------------------------------------------------------------------------|| CognitoIdentityProvider | @mock_cognitoidp | basicendpointsdone ||-------------------------------------------------------------------------------------|| Config | @mock_config | basicendpointsdone || | | coreendpointsdone ||-------------------------------------------------------------------------------------|| DataPipeline | @mock_datapipeline | basicendpointsdone ||-------------------------------------------------------------------------------------|| DynamoDB | @mock_dynamodb | coreendpointsdone || DynamoDB2 | @mock_dynamodb2 | allendpoints + partialindexes ||-------------------------------------------------------------------------------------|| EC2 | @mock_ec2 | coreendpointsdone || - AMI | | coreendpointsdone || - EBS | | coreendpointsdone || - Instances | | allendpointsdone || - SecurityGroups | | coreendpointsdone || - Tags | | allendpointsdone ||-------------------------------------------------------------------------------------|| ECR | @mock_ecr | basicendpointsdone ||-------------------------------------------------------------------------------------|| ECS | @mock_ecs | basicendpointsdone ||-------------------------------------------------------------------------------------|| ELB | @mock_elb | coreendpointsdone ||-------------------------------------------------------------------------------------|| ELBv2 | @mock_elbv2 | allendpointsdone ||-------------------------------------------------------------------------------------|| EMR | @mock_emr | coreendpointsdone ||-------------------------------------------------------------------------------------|| Glacier | @mock_glacier | coreendpointsdone ||-------------------------------------------------------------------------------------|| IAM | @mock_iam | coreendpointsdone ||-------------------------------------------------------------------------------------|| IoT | @mock_iot | coreendpointsdone || | @mock_iotdata | coreendpointsdone ||-------------------------------------------------------------------------------------|| Kinesis | @mock_kinesis | coreendpointsdone ||-------------------------------------------------------------------------------------|| KMS | @mock_kms | basicendpointsdone ||-------------------------------------------------------------------------------------|| Lambda | @mock_lambda | basicendpointsdone, requires || | | docker ||-------------------------------------------------------------------------------------|| Logs | @mock_logs | basicendpointsdone ||-------------------------------------------------------------------------------------|| Organizations | @mock_organizations | somecoreendpointsdone ||-------------------------------------------------------------------------------------|| Polly | @mock_polly | allendpointsdone ||-------------------------------------------------------------------------------------|| RDS | @mock_rds | coreendpointsdone ||-------------------------------------------------------------------------------------|| RDS2 | @mock_rds2 | coreendpointsdone ||-------------------------------------------------------------------------------------|| Redshift | @mock_redshift | coreendpointsdone ||-------------------------------------------------------------------------------------|| Route53 | @mock_route53 | coreendpointsdone ||-------------------------------------------------------------------------------------|| S3 | @mock_s3 | coreendpointsdone ||-------------------------------------------------------------------------------------|| SecretsManager | @mock_secretsmanager | basicendpointsdone ||-------------------------------------------------------------------------------------|| SES | @mock_ses | allendpointsdone ||-------------------------------------------------------------------------------------|| SNS | @mock_sns | allendpointsdone ||-------------------------------------------------------------------------------------|| SQS | @mock_sqs | coreendpointsdone ||-------------------------------------------------------------------------------------|| SSM | @mock_ssm | coreendpointsdone ||-------------------------------------------------------------------------------------|| STS | @mock_sts | coreendpointsdone ||-------------------------------------------------------------------------------------|| SWF | @mock_swf | basicendpointsdone ||-------------------------------------------------------------------------------------|| X-Ray | @mock_xray | allendpointsdone ||-------------------------------------------------------------------------------------|For a full list of endpoint implementation coverage
Imagine you have a function that you use to launch new ec2 instances:
importboto3defadd_servers(ami_id, count):
client=boto3.client('ec2', region_name='us-west-1')
client.run_instances(ImageId=ami_id, MinCount=count, MaxCount=count)To test it:
from . importadd_serversfrommotoimportmock_ec2@mock_ec2deftest_add_servers():
add_servers('ami-1234abcd', 2)
client=boto3.client('ec2', region_name='us-west-1')
instances=client.describe_instances()['Reservations'][0]['Instances']
assertlen(instances) ==2instance1=instances[0]
assertinstance1['ImageId'] =='ami-1234abcd'moto 1.0.X mock decorators are defined for boto3 and do not work with boto2. Use the @mock_AWSSVC_deprecated to work with boto2.
Using moto with boto2
frommotoimportmock_ec2_deprecatedimportboto@mock_ec2_deprecateddeftest_something_with_ec2():
ec2_conn=boto.ec2.connect_to_region('us-east-1')
ec2_conn.get_only_instances(instance_ids='i-123456')When using both boto2 and boto3, one can do this to avoid confusion:
frommotoimportmock_ec2_deprecatedasmock_ec2_b2frommotoimportmock_ec2All of the services can be used as a decorator, context manager, or in a raw form.
@mock_s3deftest_my_model_save():
# Create Bucket so that test can runconn=boto3.resource('s3', region_name='us-east-1')
conn.create_bucket(Bucket='mybucket')
model_instance=MyModel('steve', 'is awesome')
model_instance.save()
body=conn.Object('mybucket', 'steve').get()['Body'].read().decode()
assertbody=='is awesome'deftest_my_model_save():
withmock_s3():
conn=boto3.resource('s3', region_name='us-east-1')
conn.create_bucket(Bucket='mybucket')
model_instance=MyModel('steve', 'is awesome')
model_instance.save()
body=conn.Object('mybucket', 'steve').get()['Body'].read().decode()
assertbody=='is awesome'deftest_my_model_save():
mock=mock_s3()
mock.start()
conn=boto3.resource('s3', region_name='us-east-1')
conn.create_bucket(Bucket='mybucket')
model_instance=MyModel('steve', 'is awesome')
model_instance.save()
assertconn.Object('mybucket', 'steve').get()['Body'].read().decode() =='is awesome'mock.stop()Moto also has the ability to authenticate and authorize actions, just like it's done by IAM in AWS. This functionality can be enabled by either setting the INITIAL_NO_AUTH_ACTION_COUNT environment variable or using the set_initial_no_auth_action_count decorator. Note that the current implementation is very basic, see this file for more information.
If this environment variable is set, moto will skip performing any authentication as many times as the variable's value, and only starts authenticating requests afterwards. If it is not set, it defaults to infinity, thus moto will never perform any authentication at all.
This is a decorator that works similarly to the environment variable, but the settings are only valid in the function's scope. When the function returns, everything is restored.
@set_initial_no_auth_action_count(4)@mock_ec2deftest_describe_instances_allowed():
policy_document= {
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Action": "ec2:Describe*",
"Resource": "*"
}
]
}
access_key= ...
# create access key for an IAM user/assumed role that has the policy above.# this part should call __exactly__ 4 AWS actions, so that authentication and authorization starts exactly after thisclient=boto3.client('ec2', region_name='us-east-1',
aws_access_key_id=access_key['AccessKeyId'],
aws_secret_access_key=access_key['SecretAccessKey'])
# if the IAM principal whose access key is used, does not have the permission to describe instances, this will failinstances=client.describe_instances()['Reservations'][0]['Instances']
assertlen(instances) ==0See the related test suite for more examples.
For details about the experimental AWS Config support please see the AWS Config readme here.
There are some important caveats to be aware of when using moto:
Failure to follow these guidelines could result in your tests mutating your REAL infrastructure!
You need to ensure that the mocks are actually in place. Changes made to recent versions of botocore
have altered some of the mock behavior. In short, you need to ensure that you always do the following:
Ensure that your tests have dummy environment variables set up:
export AWS_ACCESS_KEY_ID='testing' export AWS_SECRET_ACCESS_KEY='testing' export AWS_SECURITY_TOKEN='testing' export AWS_SESSION_TOKEN='testing'VERY IMPORTANT: ensure that you have your mocks set up BEFORE your
boto3client is established. This can typically happen if you import a module that has aboto3client instantiated outside of a function. See the pesky imports section below on how to work around this.
If you are a user of pytest, you can leverage pytest fixtures to help set up your mocks and other AWS resources that you would need.
Here is an example:
@pytest.fixture(scope='function')defaws_credentials():
"""Mocked AWS Credentials for moto."""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'@pytest.fixture(scope='function')defs3(aws_credentials):
withmock_s3():
yieldboto3.client('s3', region_name='us-east-1')
@pytest.fixture(scope='function')defsts(aws_credentials):
withmock_sts():
yieldboto3.client('sts', region_name='us-east-1')
@pytest.fixture(scope='function')defcloudwatch(aws_credentials):
withmock_cloudwatch():
yieldboto3.client('cloudwatch', region_name='us-east-1')
... etc.In the code sample above, all of the AWS/mocked fixtures take in a parameter of aws_credentials,
which sets the proper fake environment variables. The fake environment variables are used so that botocore doesn't try to locate real
credentials on your system.
Next, once you need to do anything with the mocked AWS environment, do something like:
deftest_create_bucket(s3):
# s3 is a fixture defined above that yields a boto3 s3 client.# Feel free to instantiate another boto3 S3 client -- Keep note of the region though.s3.create_bucket(Bucket="somebucket")
result=s3.list_buckets()
assertlen(result['Buckets']) ==1assertresult['Buckets'][0]['Name'] =='somebucket'Recall earlier, it was mentioned that mocks should be established BEFORE the clients are set up. One way to avoid import issues is to make use of local Python imports -- i.e. import the module inside of the unit test you want to run vs. importing at the top of the file.
Example:
deftest_something(s3):
fromsome.package.that.does.something.with.s3importsome_func# <-- Local import for unit test# ^^ Importing here ensures that the mock has been established. some_func() # The mock has been established from the "s3" pytest fixture, so this function that uses# a package-level S3 client will properly use the mock and not reach out to AWS.For Tox, Travis CI, and other build systems, you might need to also perform a touch ~/.aws/credentials
command before running the tests. As long as that file is present (empty preferably) and the environment
variables above are set, you should be good to go.
Moto also has a stand-alone server mode. This allows you to utilize the backend structure of Moto even if you don't use Python.
It uses flask, which isn't a default dependency. You can install the server 'extra' package with:
pipinstall"moto[server]"You can then start it running a service:
$ moto_server ec2 * Running on http://127.0.0.1:5000/You can also pass the port:
$ moto_server ec2 -p3000 * Running on http://127.0.0.1:3000/If you want to be able to use the server externally you can pass an IP address to bind to as a hostname or allow any of your external interfaces with 0.0.0.0:
$ moto_server ec2 -H 0.0.0.0 * Running on http://0.0.0.0:5000/Please be aware this might allow other network users to access your server.
Then go to localhost to see a list of running instances (it will be empty since you haven't added any yet).
If you want to use boto with this (using the simpler decorators above instead is strongly encouraged), the easiest way is to create a boto config file (~/.boto) with the following values:
[Boto]
is_secure = False
https_validate_certificates = False
proxy_port = 5000
proxy = 127.0.0.1
If you want to use boto3 with this, you can pass an endpoint_url to the resource
boto3.resource(
service_name='s3',
region_name='us-west-1',
endpoint_url='http://localhost:5000',
)The standalone server has some caveats with some services. The following services require that you update your hosts file for your code to work properly:
s3-control
For the above services, this is required because the hostname is in the form of AWS_ACCOUNT_ID.localhost.
As a result, you need to add that entry to your host file for your tests to function properly.
$ pip install motoReleases are done from travisci. Fairly closely following this: https://docs.travis-ci.com/user/deployment/pypi/
- Commits to
masterbranch do a dev deploy to pypi. - Commits to a tag do a real deploy to pypi.