我正在使用unittest框架为python程序编写单元测试。程序的功能之一是使用请求库连接到外部restapi。如果出现连接错误或超时,我希望函数在失败之前最多重试3次。因此,我编写了一个使用mock(实际上是httpretty)替换外部API并引发请求连接错误两次之后才还东西。在
class APITests(unittest.TestCase):
def mock_response(self, uri, body='OK', method=httpretty.GET,
status_code=200, error=None,
error_repeats=None):
"""
Function to register HTTPretty response
"""
responses = []
if error:
def callback(request, uri, headers):
raise error
if error_repeats:
responses += [httpretty.Response(body=callback)]*error_repeats
responses += [httpretty.Response(body=body,
status=status_code)]
else:
responses += [httpretty.Response(body=callback)]
else:
responses += [httpretty.Response(body=body, status=status_code)]
httpretty.register_uri(method, uri, responses=responses)
@httpretty.activate
def test_get_connection_error_then_success_doesnt_raise(self):
self.mock_response(
'http://irrelevant.com',
error=requests.ConnectionError,
error_repeats=2
)
api._get('http://irrelevant.com')
当第三次尝试未引发异常时,此方法工作正常,测试通过,但两个异常(故意)被引发并由代码捕获和处理,将打印到控制台,从而污染测试输出。有没有一个干净的方法来阻止这种情况的发生?在
更多信息
这是我正在测试的方法
^{pr2}$控制台输出为:
Exception in thread Thread-23:
Traceback (most recent call last):
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 810, in __bootstrap_inner
self.run()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/threading.py", line 763, in run
self.__target(*self.__args, **self.__kwargs)
File "/Users/lukecaldwell/Documents/Repos/other/AidTrends/venv/lib/python2.7/site-packages/httpretty/core.py", line 637, in fill_filekind
headers
File "/Users/lukecaldwell/Documents/Repos/other/AidTrends/aidtrends/tests/test_OECD.py", line 131, in callback
raise error
ConnectionError
目前没有回答
相关问题 更多 >
编程相关推荐