0

我正在尝试使用响应库来模拟外部 API。我想检查我是否在我的请求中正确传递了我的参数,所以我使用响应文档中的这个最小工作示例:

import responses
import requests

@responses.activate
def test_request_params():
    responses.add(
        method=responses.GET,
        url="http://example.com?hello=world",
        body="test",
        match_querystring=False,
    )

    resp = requests.get('http://example.com', params={"hello": "world"})
    assert responses.calls[0].request.params == {"hello": "world"}

问题是,一旦我用http://example.com类似于 API 端点的 URL 替换,这就会中断:

@responses.activate
def test_request_params():
    responses.add(
        method=responses.GET,
        url="http://example.com/api/endpoint?hello=world",
        body="test",
        match_querystring=False,
    )

    resp = requests.get('http://example.com/api/endpoint', params={"hello": "world"})
    assert responses.calls[0].request.params == {"hello": "world"}

现在响应已将部分 URL 添加到第一个查询参数中:

>       assert responses.calls[0].request.params == {"hello": "world"}
E       AssertionError: assert {'/api/endpoint?hello': 'world'} == {'hello': 'world'}

我错过了什么吗?

4

1 回答 1

0

您可以将正则表达式作为 url 参数传递,它会忽略参数:

@responses.activate
def test_request_params():

    url = r"http://example.com/api/endpoint"
    params = {"hello": "world", "a": "b"}

    # regex that matches the url and ignores anything that comes after
    rx = re.compile(rf"{url}*")
    responses.add(method=responses.GET, url=rx)

    response = requests.get(url, params=params)
    assert responses.calls[-1].request.params == params

    url_path, *queries = responses.calls[-1].request.url.split("?")
    assert url_path == url
于 2020-06-24T12:50:42.397 回答