简体   繁体   English

如何从 requests_mock post 方法模拟 HTTP 响应

[英]How to emulate HTTP response from requests_mock post method

I'm trying to test how is @retry.retry decorator for my custom method works.我正在尝试测试我的自定义方法的 @retry.retry 装饰器是如何工作的。 For this I need to emulate the situation when response has HTTP statuses in ranges 2xx, 3xx, 4xx.为此,我需要模拟响应具有 2xx、3xx、4xx 范围内的 HTTP 状态的情况。 Right now I have an example with requests_mock:现在我有一个带有 requests_mock 的例子:

def some_method(request, *_):
    ...
    return {'jsonrpc': '2.0', 'id': 1, 'result': True}

with requests_mock.Mocker() as mock:
    mock.post('mock://test', json=some_method)
    ...
    ...
    my_sender.send(...) # <- tinyrpc.RPCClient.get_proxy somewhere inside

What some_method should return to emulate 404 for example, if it's possible?例如,如果可能的话, some_method应该返回什么来模拟 404?

In general, the situation is as follows: mocker returns j son rpc 2.0 now.一般情况是这样的: mocker现在返回json rpc 2.0 I would like to test the case when http status has specific codes, for some of which I need to make a repeated request.我想测试http 状态有特定代码时的情况,其中一些我需要重复请求。 How can I do this emulation?我怎样才能做这个模拟?

If someone interested, how to emulate this, this is very easy to do:如果有人感兴趣,如何模仿这一点,这很容易做到:

import requests
import requests_mock

session = requests.Session()

with requests_mock.Mocker() as adapter:
    adapter.post('mock://test.com/4', [
        {'text': '{"jsonrpc": "2.0", "id": 1, "body": {"verdicts": [], "errors": {"some_service": "server_error"}}}', 'status_code': 500},
    ] * 3 + [
        {'text': '{"jsonrpc": "2.0", "id": 1, "body": {"verdicts": []}}', 'status_code': 200},
    ])

    data = '{"jsonrpc": "2.0", "id": 1, "body": {"text": "hi"}}'
    resp = session.post('mock://test.com/4', data=data)
    print(resp.status_code, resp.text)
    resp = session.post('mock://test.com/4', data=data)
    print(resp.status_code, resp.text)
    resp = session.post('mock://test.com/4', data=data)
    print(resp.status_code, resp.text)
    resp = session.post('mock://test.com/4', data=data)
    print(resp.status_code, resp.text)
    resp = session.post('mock://test.com/4', data=data)
    print(resp.status_code, resp.text)
    resp = session.post('mock://test.com/4', data=data)
    print(resp.status_code, resp.text)
    resp = session.post('mock://test.com/4', data=data)
    print(resp.status_code, resp.text)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM