首页 > 解决方案 > 在 requests_mock 中模拟 response.elapsed

问题描述

我在我的单元测试中使用 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

标签: pythonunit-testingpython-requestsresponserequests-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

推荐阅读