使用side_effect与mock时未调用异常

时间:2015-05-29 18:25:22

标签: python mocking python-mock

我在一个名为" my_class"的类中有一个函数。在名为" my_module"的模块中包含此代码段:

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。但是,当我运行测试时,永远不会引发异常。 "响应"实际上设置为mock_bad,它包含所需的异常,尽管它从未引发过。知道我在哪里出错吗?

1 个答案:

答案 0 :(得分:3)

您将异常置于错误的副作用中。现在调用make_request_response()首先返回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()