首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >模拟boto3调用实际的boto3

模拟boto3调用实际的boto3
EN

Stack Overflow用户
提问于 2017-10-19 17:39:40
回答 2查看 1.8K关注 0票数 2

我正在为boto3函数编写一些测试,并使用moto库模拟boto3

它们提供的例子如下:

代码语言:javascript
复制
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'

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

代码语言:javascript
复制
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发出请求呢?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2017-10-20 14:04:42

看看README.md of boto/boto的moto 3,我注意到关于S3连接代码,有一个备注

我们需要创建这个桶,因为这都在Moto的“虚拟”AWS帐户中

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

票数 1
EN

Stack Overflow用户

发布于 2017-10-20 15:21:22

因此,在接触了一些投稿人之后,我被告知:

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的调用,然后我可以使用它进行进一步的测试。希望这能帮助那些在未来某个时候偶然发现这个问题的人。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46835804

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档