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

2024-05-17 19:45:04 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我目前的测试:

我的设置:

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()

我的实际est:

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的参数来确定行为应该是什么,但是如何定义一个mock,以便paginate()根据get_paginator参数返回特定的值呢


Tags: nameselfclientid参数getreturnfoo
1条回答
网友
1楼 · 发布于 2024-05-17 19:45:04

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

例如:

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'

相关问题 更多 >