模拟使用HTTPretty超时的HTTP请求

时间:2015-02-23 14:24:22

标签: python unit-testing python-requests httpretty

使用Python的HTTPretty library,我可以创建选择的模拟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之类的无效服务器,无论如何都会超时。但是,我更愿意在不使用任何真实网络连接的情况下进行所有单元测试。

1 个答案:

答案 0 :(得分:7)

与此同时,我得到了它,使用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()