[英]How to magic mock long chained calls?
To test the following functino, I want to assert .filter()
is called once with parameter filters
.为了测试以下功能,我想断言.filter()
使用参数filters
调用一次。
def get_instances(session: boto3.session.Session, filters):
instances = session.resource('ec2').instances.filter(Filters=filters)
return instances
I tried to write the unit test,我试着写单元测试,
def test_get_instance():
mocked_session: boto3.session.Session = boto3.session.Session()
def resource(service_name) -> boto3.resources.base.ServiceResource:
if service_name == 'ec2':
return MagicMock()
raise Exception('Parameter should be ec2')
mocked_session.resource = MagicMock(side_effect=resource) # resource is set?
mocked_session.resource('ec2').instances = MagicMock()
# mocked_session.resource('ec2').instances. ??? # not finished
filters = None
Node.get_nodes(mocked_session, filters)
assert session.resource('ec2').instances.filter.call_count == 1
However, the test function got the following error但是,测试 function 得到以下错误
> assert session.resource('ec2').instances.filter.call_count == 1 E AttributeError: 'function' object has no attribute 'resource'
You can use the built-in monckeypatch
fixture for that purpose.为此,您可以使用内置的monckeypatch
固定装置。
def test_get_instance(monkeypatch):
# ... your code
filter_calls = []
monkeypatch.setattr(mocked_session.resource('ec2'), 'filter', lambda Filters: filter_calls.append(1))
assert len(filter_calls) == 1
I did not test it with the boto3
lib, however, the idea is here.我没有使用boto3
库对其进行测试,但是,想法就在这里。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.