Search code examples
pythonjsonhttprpchttp-status-codes

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. For this I need to emulate the situation when response has HTTP statuses in ranges 2xx, 3xx, 4xx. Right now I have an example with 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?

In general, the situation is as follows: mocker returns json rpc 2.0 now. I would like to test the case when http status has specific codes, for some of which I need to make a repeated request. How can I do this emulation?


Solution

  • 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)