2016-04-14 68 views
5

我試圖模擬一個特定的boto3函數。我的模塊Cleanup導入boto3。清理也有一個班級,「清潔」。在初始化,清潔創建一個EC2的客戶:如何模擬一個boto3客戶端對象/調用

self.ec2_client = boto3.client('ec2') 

我想嘲笑EC2客戶端的方法:desribe_tags(),這蟒蛇說的是:

<bound method EC2.describe_tags of <botocore.client.EC2 object at 0x7fd98660add0>> 

我已經得到了最遠的是進口botocore在我的測試文件,並嘗試:

mock.patch(Cleaner.botocore.client.EC2.describe_tags) 

其失敗:

AttributeError: 'module' object has no attribute 'EC2' 

我該如何嘲笑這種方法?

清理看起來像:

import boto3 
class cleaner(object): 
    def __init__(self): 
     self.ec2_client = boto3.client('ec2') 

的ec2_client對象是具有desribe_tags()方法中的一個。這是一個botocore.client.EC2對象,但我從不直接導入botocore。

+0

裏面的清理模塊。您究竟如何導入EC2來使用它?從它的外觀來看,你正在做類似'import boto3'的事情。對?所以,我會懷疑你的補丁應該是'Cleanup.boto3.EC2'。如果你命名你的模塊「清理」。一些更多的信息肯定會有所幫助。 – idjaw

+0

添加模塊示例 –

+0

@JeffTang您找到了解決方案嗎?我正在尋找類似的東西! – ptimson

回答

0

應該將關於嘲諷到您正在測試。所以,如果你正在測試你的cleaner類(我建議你在這裏使用PEP8標準,並使它成爲Cleaner),那麼你想模擬你正在測試的地方。所以,你的補丁實際上應該東西沿着線:

class SomeTest(Unittest.TestCase): 
    @mock.patch('path.to.Cleaner.boto3.client', return_value=Mock()) 
    def setUp(self, boto_client_mock): 
     self.cleaner_client = boto_client_mock.return_value 

    def your_test(self): 
     # call the method you are looking to test here 

     # simple test to check that the method you are looking to mock was called 
     self.cleaner_client.desribe_tags.assert_called_with() 

我建議,通過它有很多例子可以做你正在嘗試做

+0

我不是在模擬'boto3.client'。我試圖嘲諷一個對象'botocore.client.EC2'的方法,即'describe_tags',它是'boto3.client'返回的。 –

+0

因此,您仍然在實例化一個EC2的工作客戶端,但想要模擬你創建的那個對象的方法?通常,當你進行單元測試和模擬補丁時,你想要模擬出外部,就像那個EC2客戶端一樣。您仍然可以通過'boto_client_mock'的return_value驗證您想要測試的方法。 – idjaw

+0

@JeffTang我提供了一個更詳細的例子(未經測試,只是想提供整體概念)你*可能*想要做的事情。 – idjaw

1

我找到了解決這個mocking documentation閱讀當trying to mock a different method for the S3 client

import botocore 
from mock import patch 
import boto3 

orig = botocore.client.BaseClient._make_api_call 

def mock_make_api_call(self, operation_name, kwarg): 
    if operation_name == 'DescribeTags': 
     # Your Operation here! 
     print(kwarg) 
    return orig(self, operation_name, kwarg) 

with patch('botocore.client.BaseClient._make_api_call', new=mock_make_api_call): 
    client = boto3.client('ec2') 
    # Calling describe tags will perform your mocked operation e.g. print args 
    e = client.describe_tags() 

希望它能幫助:)