gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 08:32:06 25 4
gpt4 key购买 nike

这是我当前的测试:

我的设置:

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'

关于python - Pytest 如何模拟依赖于其父调用参数的函数调用的副作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59778666/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com