将 side_effect 与模拟一起使用时未调用异常

Exception not called when using side_effect with mock

我在名为 "my_module" 的模块中有一个名为 "my_class" 的 class 函数,其中包含以下代码段:

try:
  response = self.make_request_response(requests.post, data, endpoint_path)
except requests.exceptions.HTTPError as err:
  if err.response.status_code == requests.codes.conflict:
    logging.info('Conflict error')

我正在尝试这样测试它:

error = requests.exceptions.HTTPError(mock.Mock(response=mock.Mock(status_code=409)), 'not found')
mock_bad = mock.Mock(side_effect=error)
mock_good = mock.Mock()
mock_good.return_value = [{'name': 'foo', 'id': 1}]


upsert = my_module.my_class(some_data)
with mock.patch.object(upsert, 'make_request_response', side_effect=[mock_bad, mock_good]) as mock_response:
    some_function()

我期望的是在我修补它之后在测试中引发 HTTPError。但是,当我 运行 测试时,从未引发异常。 "response" 实际上设置为 mock_bad,它包含所需的异常,尽管它从未引发过。知道我哪里出错了吗?

您将异常放入了错误的副作用中。现在首先调用 make_request_response() returns mock_bad 模拟,它本身不会在调用之前引发该异常。

将异常放入 mock.patch.object() side_effect 列表中:

error = requests.exceptions.HTTPError(mock.Mock(response=mock.Mock(status_code=409)), 'not found')
mock_good = mock.Mock()
mock_good.return_value = [{'name': 'foo', 'id': 1}]


upsert = my_module.my_class(some_data)
with mock.patch.object(upsert, 'make_request_response', side_effect=[error, mock_good]) as mock_response:
    some_function()