简体   繁体   English

模拟 boto3 调用实际的 boto3

[英]Mocking boto3 calls actual boto3

I'm writing some test for boto3 functions and using the moto library to mock boto3 .我正在为boto3函数编写一些测试并使用moto库来模拟boto3

The example they provide is as such:他们提供的例子是这样的:

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'

However when I try something similar, using a trivial example here, by doing this:然而,当我尝试类似的东西时,在这里使用一个简单的例子,通过这样做:

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

Why is it actually making request to AWS when I clearly have the function wrapped in the mocker?当我清楚地将函数包装在 mocker 中时,为什么它实际上向 AWS 发出请求?

Looking at the README.md of moto for boto/boto3 , I notice on the S3 connection code, there is a remarks查看moto for boto/boto3 的 README.md ,我注意到在 S3 连接代码上,有一个注释

# We need to create the bucket since this is all in Moto's 'virtual' AWS account # 我们需要创建存储桶,因为这一切都在 Moto 的“虚拟”AWS 账户中

If I am correct, the error shown is not AWS error, but Moto error.如果我是对的,显示的错误不是 AWS 错误,而是 Moto 错误。 You need to initialise all the mock resources you want to mock to the Moto virtual space.您需要将所有要模拟的模拟资源初始化到 Moto 虚拟空间。 This mean, you need to use another script to use moto to mock "create_instance" before you can start the instance.这意味着,在启动实例之前,您需要使用另一个脚本来使用 moto 来模拟“create_instance”。

So after reaching out to some of the contributors I was told that:因此,在联系了一些贡献者后,我被告知:

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.

In order to use services that require a certain resource, you first have to create that mock service.为了使用需要特定资源的服务,您首先必须创建该模拟服务。 For my function to work I went ahead and mocked a call to create_instance which I can then use to test further.为了让我的函数正常工作,我继续模拟了对create_instance的调用,然后我可以用它来进一步测试。 Hope this helps those who stumble on this at some point in the future.希望这可以帮助那些在未来某个时候偶然发现的人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM