【问题标题】:Mock a method that raise an exception a number of times模拟多次引发异常的方法
【发布时间】:2021-04-12 13:20:18
【问题描述】:

我整天都在寻找如何做到这一点,但没有运气。我正在使用 Django 1.11 和 Python 2.7(无法升级)。

我有一个调用外部 API 的方法。此 API 有时会因 504 或 502 错误而失败。因此,我们决定,在这种情况下,检索几次调用(目前为 3 次)。所以,我写了这样的东西。

def call_external_api(arg_1, arg_2):
        attempts = 3
        data = None

        ext_api = ExternalAPI() # wrapper class, its method call the external api
        while attempts > 0:
            try:
                data = ext_api.get_data_details(arg_1=arg_1, arg_2=arg_2)
            except Exception as exception:
                attempts -= 1
                log_message(exception)
                raise ExternalAPIError('Error calling EXT-API: %s' % str(exception))
        return data

所以,我想对此进行测试,但我不知道如何模拟异常。我知道可以使用@patch(SomeClass, 'method_name')来模拟对另一个类的调用,但是如何模拟异常,所以代码进入except分支,减少“尝试”,重复循环?

注意:我认为如果我可以模拟异常,我可以测试 log_message 被调用了 3 次。您如何看待这种方法?

【问题讨论】:

    标签: django python-2.7 mocking


    【解决方案1】:

    如果您在数据中收到 api 响应并且返回的不是 200,那么您可以引发异常。

    def call_external_api(arg_1, arg_2):
            attempts = 3
            data = None
    
            ext_api = ExternalAPI() # wrapper class, its method call the external api
            while attempts > 0:
                try:
                    data = ext_api.get_data_details(arg_1=arg_1, arg_2=arg_2)
                    if data.status_code != 200:
                       raise Exception("Server Error")
                except Exception as exception:
                    attempts -= 1
                    log_message(exception)
                    raise ExternalAPIError('Error calling EXT-API: %s' % str(exception))
            return data
    

    注意:get_data_details 应该返回响应。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-09
      • 2015-03-08
      • 2014-02-15
      • 2020-01-13
      • 2016-04-18
      • 1970-01-01
      • 2018-11-26
      • 1970-01-01
      相关资源
      最近更新 更多