Stu*_*Cat 5 python testing mocking
这是我当前的测试:
我的设置:
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()
Run Code Online (Sandbox Code Playgroud)
我的实际估计:
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')
Run Code Online (Sandbox Code Playgroud)
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'
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2558 次 |
| 最近记录: |