[英]Check query string on the request using requests_mock
How to check if a request mocked by requests_mock added some query parameters to a URL?如何检查 requests_mock 模拟的请求是否向 URL 添加了一些查询参数?
I have a function func
thats do a HTTP POST on the url with some query string on the URL and I want to check if was called with this query string. I have a function func
thats do a HTTP POST on the url with some query string on the URL and I want to check if was called with this query string.
This is my attempt, but fails.这是我的尝试,但失败了。
query
is a empty string and qs
is a empty dict. query
是一个空字符串, qs
是一个空字典。
I have sure that my func is appending the query string on the request.我确定我的函数在请求中附加了查询字符串。
with requests_mock.Mocker() as mock:
mock.post(url, text=xml)
func() # This function will call url + query string
history = mock.request_history[0]
assert history.method == "POST" # OK
assert history.query is None # Returns an empty string, AssertionError: assert '' is None
assert history.qs is None # Returns an empty dict, assert {} is None
My func
我的func
def credilink():
url = settings["url"]
params = settings["params"]
params["CC"] = query
response = requests.post(url, params=params)
# ...
I tried to reproduce your problem and was unable to...我试图重现您的问题,但无法...
Here is the code I'm running:这是我正在运行的代码:
import requests
import requests_mock
url = "http://example.com"
settings = dict(url=url, params=dict(a=1))
query = "some-query"
xml = "some-xml"
def credilink():
url = settings["url"]
params = settings["params"]
params["CC"] = query
response = requests.post(url, params=params)
return response.text
# ...
def test():
with requests_mock.Mocker() as mock:
mock.post(url, text=xml)
data = credilink() # This function will call url + query string
history = mock.request_history[0]
assert history.method == "POST" # OK
assert history.qs == dict(a=['1'], cc=[query])
assert history.query == f"a=1&cc={query}"
assert data == xml
The assertions pass in this snippet.断言在此代码段中传递。 Maybe it's some version problem?可能是版本问题? I used requests==2.25.1 and requests-mock==1.8.0.我使用了 requests==2.25.1 和 requests-mock==1.8.0。
In my case, the problem was in mock://
URL schema, as it's present in the requests-mock
samples就我而言,问题出在mock://
URL 模式中,因为它存在于requests-mock
示例中
session.get('mock://test.com/path')
But requests
library skips query arguments for non "http" URLs.但是requests
库会跳过查询 arguments 以获取非“http”URL。 Here is the comment from the source code这是源代码中的注释
# Don't do any URL preparation for non-HTTP schemes like `mailto`,
# `data` etc to work around exceptions from `url_parse`, which
# handles RFC 3986 only.
if ':' in url and not url.lower().startswith('http'):
self.url = url
return
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.