【发布时间】:2016-08-06 06:24:59
【问题描述】:
我正在尝试模拟一个特定的 boto3 函数。我的模块 Cleanup 导入 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_client 对象是具有 desribe_tags() 方法的对象。它是一个 botocore.client.EC2 对象,但我从不直接导入 botocore。
【问题讨论】:
-
在您的清理模块中。您究竟是如何导入 EC2 来使用它的?从外观上看,您正在做类似
import boto3的事情。正确的?所以,我怀疑你的补丁应该类似于Cleanup.boto3.EC2。如果您将模块命名为Cleanup。更多信息肯定会有所帮助。 -
添加的模块示例
-
@JeffTang 你找到解决方案了吗?我正在寻找类似的东西!
标签: python unit-testing mocking