2017-10-19 51 views
2

我正在写boto3函数的一些测试和使用moto库来模拟boto3嘲笑boto3调用实际boto3

他们提供的例子是这样的:

import boto3 
from moto import mock_ec2 

def add_servers(ami_id, count): 
    client = boto3.client('ec2', region_name='us-west-1') 
    client.run_instances(ImageId=ami_id, MinCount=count, MaxCount=count) 

@mock_ec2 
def test_add_servers(): 
    add_servers('ami-1234abcd', 2) 

    client = boto3.client('ec2', region_name='us-west-1') 
    instances = client.describe_instances()['Reservations'][0]['Instances'] 
    assert len(instances) == 2 
    instance1 = instances[0] 
    assert instance1['ImageId'] == 'ami-1234abcd' 

然而,当我尝试类似的东西,在这里使用一个简单的例子,这样做:

def start_instance(instance_id): 
    client = boto3.client('ec2') 
    client.start_instances(InstanceIds=[instance_id]) 

@mock_ec2 
def test_start_instance(): 
    start_instance('abc123') 
    client = boto3.client('ec2') 
    instances = client.describe_instances() 
    print instances 

test_start_instance() 

ClientError: An error occurred (InvalidInstanceID.NotFound) when calling the StartInstances operation: The instance ID '[u'abc123']' does not exist 

为什么它实际上使请求AWS,当我清楚地具有包装在模拟器中的功能?

+0

如果你需要一个真正的模拟S3服务,让你临时存储文件来测试S3的应用程序功能,那么还要研究像FakeS3这样的东西。 – mootmoot

+0

我正在做更多的EC2工作,但我会牢记它。我看到的另一个很酷的库是“安慰剂”,它记录了您对AWS的实际调用,并将结果存储在一个目录中,然后可以调用该目录来进行测试。 – eagle

+0

我通常会测试部署脚本以在t2.nano/micro实例上部署东西。我只是用实际实例替换t2实例来生产 – mootmoot

回答

1

综观moto for boto/boto3的README.md,我注意到 在S3连接代码,有言论

#我们需要创造的水桶,因为这是所有在MOTO的“虚拟” AWS帐户

如果我是正确的,显示的错误不是AWS错误,但摩托罗拉错误。您需要初始化所有您想要模拟到Moto虚拟空间的模拟资源。这意味着,在启动实例之前,您需要使用另一个脚本来使用moto来模拟“create_instance”。

+0

这就是它,我也在下面发表了我的评论。我会继续接受,因为这与我的解决方案完全相同。 – eagle

0

于是伸手一些贡献者后,我被告知:

Moto isn't like a MagicMock--it's an actual in-memory representation of the AWS resources. So you can't start an instance you haven't created, you can't create an instance in a vpc you haven't previously defined in Moto, etc.

为了使用需要一定的资源服务,你首先要创建一个模拟服务。对于我的工作功能,我继续前进,嘲笑create_instance,然后我可以使用它进一步测试。希望这有助于那些在未来某个时候偶然发现的人。