【问题标题】:responses mock requests.ConnectionError, assert function响应模拟 requests.ConnectionError,断言函数
【发布时间】:2020-05-24 12:51:38
【问题描述】:

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

以下测试因异常而失败,而不是断言函数应返回 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)

【问题讨论】:

    标签: python exception python-requests mocking


    【解决方案1】:

    得到 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
    

    您可以像这样测试您的函数行为(在 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
    

    【讨论】:

      猜你喜欢
      • 2021-10-28
      • 2011-08-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-30
      相关资源
      最近更新 更多