响应模拟请求。连接错误,断言函数

时间:2020-05-24 12:51:38

标签: python exception python-requests mocking

我有一个函数,如果发生False,则返回requests.ConnectionError。 万一发生此异常,如何测试函数的结果?

以下测试失败并显示Exception,而不是断言该函数应返回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)

1 个答案:

答案 0 :(得分:0)

来自Github用户hramezani的帮助 假设函数是这样的:

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

您可以像这样测试功能行为(如果出现request.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