如何使用 side_effect 模拟 requests.get().url?

问题描述 投票:0回答:1

我有以下代码:

def consuming_api_swapi_index_page(initial_page: int = 1):
    """Swapi index page."""
    check = HTTPStatus.OK
    results = []
    while check == HTTPStatus.OK:
        response = requests.get(
            f'https://swapi.dev/api/people/?page={initial_page}'
        )
        results.append(url := response.url)
        print(url)
        check = response.status_code
        initial_page += 1
    return results


def test_consuming_api_swapi_index_page() -> None:
    """Test it."""
    values = [
        'https://swapi.dev/api/people/?page=1',
        'https://swapi.dev/api/people/?page=2',
        'https://swapi.dev/api/people/?page=3',
        'https://swapi.dev/api/people/?page=4',
        'https://swapi.dev/api/people/?page=5',
        'https://swapi.dev/api/people/?page=6',
        'https://swapi.dev/api/people/?page=7',
        'https://swapi.dev/api/people/?page=8',
        'https://swapi.dev/api/people/?page=9',
        'https://swapi.dev/api/people/?page=10',
    ]

    assert consuming_api_swapi_index_page() == values

我需要模拟它,我该怎么做?

python mocking pytest
1个回答
0
投票

使用 https://requests-mock.readthedocs.io/en/latest/matching.html 您将能够模拟与正则表达式匹配的请求,如

matcher = re.compile(r"https://swapi.dev/api/people/\?page=\d")
adapter.register_uri('GET', matcher, text='response')
© www.soinside.com 2019 - 2024. All rights reserved.