Search code examples
pythonunit-testingpython-requestsresponserequests-mock

mock response.elapsed in requests_mock


I'm using requests_mock in my unit tests and would like to mock response.elapsed attribute but have't found proper way to do it. Just found a workaround with adding sleep to text callback.

with requests_mock.mock() as m:
    def text_callback_with_delay(request, context):
        time.sleep(2)
        return "{}"

    m.get(GET_REQUEST_URL, text=text_callback_with_delay)

Is there a better way to mock response.elapsed using requests_mock?


Solution

  • With example given above response.elapsed is bit more than 2 seconds. So I just used unittest.mock.patch to patch requests.request

    mock_response = Mock(spec=requests.Response)
    mock_response.elapsed = datetime.timedelta(seconds=2.0)
    
    with patch("requests.request", return_value=mock_response):
         my_code_here