python - 使用 HTTPretty 模拟超时的 HTTP 请求

标签 python unit-testing python-requests httpretty

使用 HTTPretty library对于 Python,我可以创建选择的模拟 HTTP 响应,然后选择它们,即使用 requests library像这样:

import httpretty
import requests

# set up a mock
httpretty.enable()
httpretty.register_uri(
            method=httpretty.GET,
            uri='http://www.fakeurl.com',
            status=200,
            body='My Response Body'
        )

response = requests.get('http://www.fakeurl.com')

# clean up
httpretty.disable()
httpretty.reset()

print(response)

输出:<Response [200]>

是否也有可能注册一个无法到达的 uri(例如连接超时,连接被拒绝,......)这样根本就没有收到任何响应(这与给出一个已建立的连接不同) HTTP 错误代码如 404)?

我想在单元测试中使用此行为来确保我的错误处理按预期工作(在“未建立连接”和“已建立连接,错误的 HTTP 状态代码”的情况下会做不同的事情)。作为一种解决方法,我可以尝试连接到一个无效的服务器,如 http://192.0.2.0无论如何都会超时。但是,我更愿意在不使用任何真实网络连接的情况下进行所有单元测试。

最佳答案

与此同时,我使用 HTTPretty callback body 得到了它似乎产生了所需的行为。请参阅下面的内联评论。 这实际上与我正在寻找的不完全相同(它不是无法访问的服务器,因此请求超时 而是 抛出异常的服务器一旦达到超时异常,但是,对于我的用例,效果是相同的。

不过,如果有人知道不同的解决方案,我很期待。

import httpretty
import requests

# enable HTTPretty
httpretty.enable()

# create a callback body that raises an exception when opened
def exceptionCallback(request, uri, headers):

    # raise your favourite exception here, e.g. requests.ConnectionError or requests.Timeout
    raise requests.Timeout('Connection timed out.')

# set up a mock and use the callback function as response's body
httpretty.register_uri(
            method=httpretty.GET,
            uri='http://www.fakeurl.com',
            status=200,
            body=exceptionCallback
        )

# try to get a response from the mock server and catch the exception
try:
    response = requests.get('http://www.fakeurl.com')
except requests.Timeout as e:

    print('requests.Timeout exception got caught...')
    print(e)

    # do whatever...

# clean up
httpretty.disable()
httpretty.reset()

关于python - 使用 HTTPretty 模拟超时的 HTTP 请求,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28675952/

相关文章:

python - Pandas 中的日期时间转换问题

python - 在模拟上设置属性不起作用

android - 单元测试使用 ViewModelScope.launch 调用具有延迟的挂起函数的 ViewModel 方法

python-requests 在函数之间保持 session

Python:请求模块使用 Gevent 抛出异常

python - 遍历模型字段 - Django

python - aggregate(Max ('id' )) 返回异常 'str' 对象没有属性 'email'

python - Numpy 在矩阵上按百分比拆分

android - 使用捕获和模拟对类进行单元测试

Python - 通过 Url/Request 错误获取页面的完整 HTML