Jef*_*ang 6 python unit-testing mocking
我正在尝试模拟一个特定的boto3函数.我的模块Cleanup导入boto3.清理也有一个"清洁"类.在init期间,cleaner创建了一个ec2客户端:
self.ec2_client = boto3.client('ec2')
Run Code Online (Sandbox Code Playgroud)
我想模拟ec2客户端方法:desribe_tags(),python说:
<bound method EC2.describe_tags of <botocore.client.EC2 object at 0x7fd98660add0>>
Run Code Online (Sandbox Code Playgroud)
我得到的最远的是在我的测试文件中导入botocore并尝试:
mock.patch(Cleaner.botocore.client.EC2.describe_tags)
Run Code Online (Sandbox Code Playgroud)
失败的是:
AttributeError: 'module' object has no attribute 'EC2'
Run Code Online (Sandbox Code Playgroud)
我该如何模仿这种方法?
清理看起来像:
import boto3
class cleaner(object):
def __init__(self):
self.ec2_client = boto3.client('ec2')
Run Code Online (Sandbox Code Playgroud)
ec2_client对象是具有desribe_tags()方法的对象.它是一个botocore.client.EC2对象,但我从不直接导入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()
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你 :)
你应该嘲笑你正在测试的地方。因此,如果您正在测试您的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()
Run Code Online (Sandbox Code Playgroud)
我建议阅读模拟文档,其中有很多示例可以完成您想要做的事情
| 归档时间: |
|
| 查看次数: |
5782 次 |
| 最近记录: |