如何模拟boto3客户端对象/

2024-05-14 20:44:56 发布

您现在位置:Python中文网/ 问答频道 /正文

我试着模拟一个特定的boto3函数。我的模块,清理,进口boto3。Cleanup还有一个类“cleaner”。在初始化期间,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_客户端对象是具有desribe_tags()方法的对象。它是一个botocore.client.EC2对象,但我从不直接导入botocore。


Tags: 对象方法函数selfclient客户机objecttags
2条回答

你应该嘲笑你测试的地方。所以,如果您测试的是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,里面有很多例子可以做你想做的事情

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

希望有帮助:)

相关问题 更多 >

    热门问题