gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 21:42:58 24 4
gpt4 key购买 nike

使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com