[英]responses mock requests.ConnectionError, assert function
我有一个 function 如果发生requests.ConnectionError
则返回False
。 如果发生此异常,如何测试 function 的结果?
以下测试因异常而失败,而不是断言 function 应返回False
@responses.activate
def test_get_system_mem_failure(self):
responses.add(responses.GET,"https://myapi.com/api",
body=Exception(requests.ConnectionError))
with pytest.raises(requests.ConnectionError):
self.assertEqual(sm.get_system_mem(),False)
从 Github 用户 hramezani 获得帮助假设 function 是这样的:
def test_func():
try:
# some code which calls https://myapi.com/api and
# might cause requests.ConnectionError
requests.get("https://myapi.com/api")
except requests.ConnectionError:
return False
您可以像这样测试您的 function 行为(在 requests.ConnectionError 的情况下返回 Fales):
@responses.activate
def test_get_system_mem_failure():
responses.add(responses.GET,"https://myapi.com/api",
body=requests.ConnectionError())
assert test_func() is False
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.