No exception is thrown when using side_effect with mock

I have a function of class "my_class" in module "my_module" which contains this snippet:

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')

      

And I'm trying to test it like this:

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()

      

I would expect the HTTPError to be raised in the test after I fix it. However, when I run the test, the exception is never thrown. in fact the "answer" is set to mock_bad, which contains the desired exception, even though it was never raised. Any idea where I am going wrong?

+3


source to share


1 answer


You are putting your exception in the wrong side effect. The call make_request_response()

now returns mock_bad

mock first , which by itself will not raise this exception before being called.

Put the exception in the list 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()

      

+3


source







All Articles