[英]How to check if the expected data is sent by a post or put request?
I am using requests-mock and I am trying to figure out how to assert that the put
request has been called correctly:我正在使用requests-mock并试图弄清楚如何断言已正确调用put
请求:
def funtion_to_be_tested():
requests.put(
headers={'X-API-Key': 'api_key'},
url=url,
params={'param1': 'foo'},
data='This is the data'
)
def test_upload(requests_mock):
url = 'http://example.com/upload'
requests_mock.put(url, text='ok')
funtion_to_be_tested()
# how to check that `data` was `This is the data` and that `headers` contained the `X-API-Key`?
Edit: I refactored out the code to be tested to a function called funtion_to_be_tested
编辑:我将要测试的代码重构为一个名为funtion_to_be_tested
的函数
If you just want check the method being used, you can check that by verifying the sent request.如果您只想检查正在使用的方法,您可以通过验证发送的请求来检查。
def test_upload(requests_mock: Any):
url = 'http://example.com/upload'
requests_mock.put(url, text='ok')
r = requests.put(
headers={'X-API-Key': 'api_key'},
url=url,
params={'param1': 'foo'},
data='This is the data'
)
print(r.request.method) # Prints PUT/POST
print(r.request.headers) # Prints your headers sent
print(r.request.body) # Prints your data sent
I have included the request headers/body in the code above in case you want to check the other parameters as well.我在上面的代码中包含了请求标头/正文,以防您还想检查其他参数。
The standard way to do this is run through your function and then make assertions on the request_history :执行此操作的标准方法是运行您的函数,然后对request_history进行断言:
Altering the example because it always takes me a while to make pytest work correctly, but it will work basically the same way:更改示例,因为我总是需要一段时间才能使 pytest 正常工作,但它的工作方式基本相同:
import requests
import requests_mock
def funtion_to_be_tested():
requests.put(
headers={'X-API-Key': 'api_key'},
url=url,
params={'param1': 'foo'},
data='This is the data'
)
with requests_mock.mock() as m:
url = 'http://example.com/upload'
m.put(url, text='ok')
funtion_to_be_tested()
assert m.last_request.headers['X-API-Key'] == 'api_key'
assert m.last_request.text == 'This is the data'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.