$ pip install 'moto[ec2,s3,all]'
Moto 是一个库,可让你的测试轻松模拟 AWS 服务。
假设你有以下要测试的 python 代码:
import boto3
class MyModel(object):
def __init__(self, name, value):
self.name = name
self.value = value
def save(self):
s3 = boto3.client('s3', region_name='us-east-1')
s3.put_object(Bucket='mybucket', Key=self.name, Body=self.value)
花点时间想想你过去会如何测试它。
现在看看如何使用Moto测试它:
import boto3
from moto import mock_s3
from mymodule import MyModel
@mock_s3
def test_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 account
conn.create_bucket(Bucket='mybucket')
model_instance = MyModel('steve', 'is awesome')
model_instance.save()
body = conn.Object('mybucket', 'steve').get()['Body'].read().decode("utf-8")
assert body == 'is awesome'
通过装饰器包装测试,对 s3 的所有调用都会自动模拟出来。模拟保持存储桶和键的状态。
有关涵盖哪些服务和功能的完整列表,请参阅我们的实施范围。
完整的文档可以在这里找到: