我正在为boto3函数编写一些测试,并使用moto库模拟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发出请求呢?
发布于 2017-10-20 14:04:42
看看README.md of boto/boto的moto 3,我注意到关于S3连接代码,有一个备注
我们需要创建这个桶,因为这都在Moto的“虚拟”AWS帐户中
如果我是正确的,所显示的错误不是AWS错误,而是Moto错误。您需要将所有要模拟的模拟资源初始化到Moto虚拟空间。这意味着,在启动实例之前,需要使用另一个脚本来使用moto来模拟"create_instance“。
发布于 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的调用,然后我可以使用它进行进一步的测试。希望这能帮助那些在未来某个时候偶然发现这个问题的人。
https://stackoverflow.com/questions/46835804
复制相似问题