python 响应库将 URL 的一部分添加到请求参数中
python responses library prepends part of the URL to the request params
我正在尝试使用响应库模拟外部 API。
我想检查我是否在我的请求中正确传递了我的参数,所以我正在使用 responses docs:
中的这个最小工作示例
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'}
我错过了什么吗?
您可以将正则表达式作为 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
我正在尝试使用响应库模拟外部 API。 我想检查我是否在我的请求中正确传递了我的参数,所以我正在使用 responses docs:
中的这个最小工作示例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'}
我错过了什么吗?
您可以将正则表达式作为 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