2017-10-19 80 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,然後我可以使用它進一步測試。希望這有助於那些在未來某個時候偶然發現的人。