如何模拟Boto3客户端对象/调用 [英] How to mock a boto3 client object/call

查看:121
本文介绍了如何模拟Boto3客户端对象/调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试模拟一个特定的boto3函数.我的模块Cleanup导入boto3.清理也有一个类,清理器".在初始化过程中,cleaner创建一个ec2客户端:

I'm trying to mock one particular boto3 function. My module, Cleanup, imports boto3. Cleanup also has a class, "cleaner". During init, cleaner creates an ec2 client:

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

我想模拟ec2客户端方法:desribe_tags(),python表示为:

I want to mock the ec2 client method: desribe_tags(), which python says is:

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

我最了解的是在测试文件中导入botocore并尝试:

the furthest I've gotten is importing botocore in my test file and trying:

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

失败,并显示以下信息:

which fails with:

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.

The ec2_client object is the one that has the desribe_tags() method. It's a botocore.client.EC2 object, but I never directly import botocore.

推荐答案

尝试模拟其他方法时,我找到了解决方案用于S3客户端

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

希望它会有所帮助:)

这篇关于如何模拟Boto3客户端对象/调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆