1

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?

Akshat Zala
  • 710
  • 1
  • 8
  • 23
Alex M981
  • 2,264
  • 14
  • 24
  • 1
    Do you want to mock the elapsed attribute of the returned response object or do you want the mocked request to take 2 seconds? – Iain Shelvington Jun 16 '20 at 04:47
  • 1
    I need to mock the elapsed attribute of the returned response object. With example given above response.elapsed is bit more than 2 seconds. So I just used unittest.mock.patch to patch requests.request – Alex M981 Jun 16 '20 at 05:19

1 Answers1

0

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
Alex M981
  • 2,264
  • 14
  • 24