Pytest 如何模拟依赖于其父调用参数的函数调用的副作用



这是我目前的测试:

我的设置:

class CheckTestParentMocked:
@pytest.fixture(autouse=True)
def run_around_tests(self, mocker):
self.profile = 'myprofile'
self.region = 'eu-west-1'
mocked_boto = mocker.patch(self.boto_client_path) #mypackage.module.boto3
mocked_session = mocked_boto.Session()
self.mocked_client = mocked_session.client()

我的实际估计:

def test_gets_non_authorizer_api(self):
def side_effect(*args, **kwargs):
if args or kwargs:
# these are resources
return [{
'items': [
{
'id': 'resource-id-foo',
'path': '/',
'resourceMethods': ['GET']
}
]
}]
else:
# these are apis
return [{'items': [
{
'id': 'foo',
'name': 'foo-name'
}
]
}]
self.paginator.paginate.side_effect = side_effect
self.mocked_client.get_method.return_value = {
'authorizationType': 'NONE'
}
assertion = {
'API Name': 'foo-name', 'API Methods': 'GET', 'Resource Path': '/', 'Region': self.region,
'Authorization Type': 'NONE'
}
self.mocked_client.get_paginator('get_rest_apis').paginate()
self.mocked_client.get_paginator('get_resources').paginate(restApiId='someid')

paginate()的结果取决于传递给get_paginator的参数。现在我很幸运,我可以使用 paginate 的参数来确定行为应该是什么,但是我如何定义一个模拟,以便 paginate(( 根据get_paginator参数向我返回特定值?

您始终可以将模拟调用链中的任何部分替换为自己的方法来放置所需的逻辑。

例如:

def get_paginate_mock(paginator_param):
return {
'get_rest_apis': mock.Mock(
paginate=mock.Mock(return_value='called with get_rest_apis')),
'get_resources': mock.Mock(
paginate=mock.Mock(return_value='called with get_resources'))
}.get(paginator_param, mock.Mock())
self.mocked_client.get_paginator = get_paginate_mock
self.mocked_client.get_paginator('get_rest_apis').paginate()
'called with get_rest_apis'
self.mocked_client.get_paginator('get_resources').paginate()
'called with get_resources'

最新更新