gpt4 book ai didi

python - 如何在 python 单元测试中模拟连接错误和请求超时

转载 作者:太空狗 更新时间:2023-10-29 20:30:41 25 4
gpt4 key购买 nike

假设我的 django/flask 应用程序从 API 中提取信息,我如何测试连接异常是否被正确捕获和处理?

例如,这里有一个调用 API 的函数:

import requests
def call_the_api():
url = 'http://httpbin.org/get'
try:
req = requests.get(url)
if req.json().get('errors'):
logger.warn("API error response")
return {'request_error': 'api_error_response'}
except requests.exceptions.ConnectionError:
logger.warn('ConnectionError')
return {'request_error': 'ConnectionTimeout'}
except requests.exception.Timeout:
logger.warn('API request timed out')
return {'request_error': 'Timeout'}
except Exception, ex:
logger.warn("API request Exception: %s", ex)
return {'request_error': ex}
else:
return req.json()

对于测试来自 API 的响应,我发现 mock 非常有用。

def mock_get_request():
response = requests.get.return_value
json_file = 'sample_response.json'
json_file_path = os.path.join(os.path.dirname(__file__), json_file)
with open(json_file_path, 'r') as f:
response.content = response.text = f.read()
response.status_code = 200
response.encoding = 'utf-8'
response.json = lambda: json.loads(response.content.decode(response.encoding))
response.url = u'%s' % args[0]
return response

class TestSuitabilityFunctions(TestCase):
def test_call_the_api(self):
requests.get = MagicMock(side_effect=mock_get_request)
resp = call_the_api()
self.assertEqual(resp.get('url'), "http://httpbin.org/get")

所以我的问题是如何模拟连接超时或错误?

最佳答案

未经测试的代码但是...

def connection_error():
raise requests.exceptions.ConnectionError

class TestSuitabilityFunctions(TestCase):
@patch.object(module_that_youre_testing, "requests")
def test_connection_error(self, mock_requests):
mock_requests.get = MagicMock(side_effect=connection_error)
with self.assertRaises(requests.exceptions.ConnectionError) as cm:
resp = call_the_api()
exception = cm.exception
self.assertEqual(resp, {'request_error': 'ConnectionTimeout'})

... 或类似的应该可以解决问题。在我的脑海中,我不记得 assertRaises 如何与捕获的错误交互。也许您甚至不需要 assertRaises 部分。

关于python - 如何在 python 单元测试中模拟连接错误和请求超时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20885841/

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