繁体   English   中英

如何在 Python 单元测试中模拟 HTTPError 响应

[英]How to mock HTTPError response in Python unit test

我想根据我得到的错误响应内容为HTTPError异常部分写一个单元测试用例。 但我现在知道如何模拟响应,以便单元测试可以到达 doSomething1() 而不是 doSomething2()。

foo.py

def get_result_from_API():  
   #Try to call API here...

def getSomething():
  try:
    result = get_result_from_API()
  except HTTPError as error:
    error_json = error.response.json()
    if error_json.get("error").get("code") == "00001":
      doSomething1()
    else:
      doSomething2()
      raise error

单元测试

@patch('foo.doSomething2')
@patch('foo.doSomething1')
@patch('foo.get_result_from_API')    
def testGetSomething(get_result_from_API,doSomething1,doSomething2):
  mock_response = Mock()
  mock_response.return_value = {  
      "error":{                            
          "code": "00001",
          "message": "error message for foo reason"            
      }
  }
  get_result_from_API.side_effect = HTTPError(response=mock_response)

  with self.assertRaises(HTTPError):
    foo.getSomething()

  doSomething1.assert_called_once()

当前的结果是 doSomething1() 没有在调用 doSomething2() 的地方被调用。

由于getSomething function 调用:

error_json = error.response.json()

解决方案是模拟对.json()的调用

  mock_response.json.return_value = {  
      "error":{                            
          "code": "00001",
          "message": "error message for foo reason"            
      }
  }

正如最初编写的那样, getSomething必须直接调用response()

error_json = error.response()

这是一个更通用的示例:

>>> from unittest.mock import Mock                                                        
>>> mock_response = Mock() 
                                                               
>>> mock_response.return_value = {"hello": "world"}                                       
>>> mock_response()  # call response() directly
{'hello': 'world'}

>>> mock_response.json()  # no return_value is assigned to the json() call
<Mock name='mock.json()' id='4407756744'>

>>> mock_response.json.return_value = {"hello": "universe"} # assign a json() return_value                              
>>> mock_response.json()                                                              
{'hello': 'universe'}

如果你愿意,你甚至可以在实例化 Mock 时这样做:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM