在 requests_mock 中模拟 response.elapsed

mock response.elapsed in requests_mock

我在我的单元测试中使用 requests_mock 并想模拟 response.elapsed 属性,但还没有找到正确的方法。刚刚找到了将睡眠添加到文本回调的解决方法。

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)

有没有更好的方法来模拟 response.elapsed 使用 requests_mock?

上面给出的例子 response.elapsed 超过 2 秒。所以我只是用 unittest.mock.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