简体   繁体   English

在 requests_mock 中模拟 response.elapsed

[英]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.我在我的单元测试中使用 requests_mock 并且想模拟 response.elapsed 属性但没有找到正确的方法来做到这一点。 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 ?有没有更好的方法来模拟response.elapsed使用requests_mock

With example given above response.elapsed is bit more than 2 seconds.上面给出的例子 response.elapsed 比 2 秒多一点。 So I just used unittest.mock.patch to patch requests.request所以我只是使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM