如何模拟boto3客户端对象/调用

时间:2016-04-14 15:24:25

标签: python unit-testing mocking

我正在尝试模拟一个特定的boto3函数。我的模块Cleanup导入boto3。清理也有一个“清洁”类。在init期间,cleaner创建了一个ec2客户端:

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

我想模拟ec2客户端方法:desribe_tags(),python说是:

<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。

2 个答案:

答案 0 :(得分:2)

我在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()

希望有所帮助:)

答案 1 :(得分: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()

我建议阅读mocking documentation,其中有很多例子可以做你想做的事情