mercredi 18 mai 2016

Mock requests exception not being thrown by side_effect

So I am trying to test exception handling code and side_effect is not working properly. The printed output shows that it is making the calls but the raise_for_status is not correctly throwing the exception in side_effect. Why is the exception not being thrown?

This is the code:

class Reboot(Resource):
  def post(self, server):
      server_info = find_server_url(server)
      try:
        response = requests.post(server_info + '/reboot')
        response.raise_for_status()
        return response.json()
      except requests.exceptions.RequestException as error:
        return_message = "Exception: {0}".format(str(error))
        app.logger.info(return_message)
        app.logger.info("Traceback: {0}".format(traceback.format_exc()))
        return abort(500, message=return_message, traceback=traceback.format_exc())
      except:
        return_message = "Exception: {0}".format(str(sys.exc_info()[0]))
        app.logger.info(return_message)
        app.logger.info("Traceback: {0}".format(traceback.format_exc()))
        return abort(500, message=return_message, traceback=traceback.format_exc())
    else:
      return abort(403, message='Proper SSL certificate authentication is required.')
api.add_resource(Reboot, ‘/reboot/<string:server>')

This is the test code:

@mock.patch(‘<package>.<src>.requests')
def test_request_exception(self, mock_requests):
  expected_status_code = 500

  http_error = requests.exceptions.HTTPError()           
  mock_raise_for_status = mock.Mock(side_effect=http_error)
  mock_post = mock.Mock()
  mock_post.raise_for_status = mock_raise_for_status
  mock_requests.post.return_value = mock_post

  with self.assertRaises(requests.exceptions.HTTPError):
    response = self.app.post(‘/reboot/{0}’.format(self.server))
    response_json = json.loads(response.data)
    print "\n"
    print id(mock_requests)
    pprint(mock_requests.__dict__)
    print "\n"
    print id(mock_post)
    pprint(mock_post.__dict__)
    print "\n"
    print id(mock_raise_for_status)
    pprint(mock_raise_for_status.__dict__)
    print "\n"

    self.assertEqual(expected_status_code, response.status_code)

Output:

50888528
{'_mock_call_args': None,
 '_mock_call_args_list': [],
 '_mock_call_count': 0,
 '_mock_called': False,
 '_mock_children': {'exceptions': <MagicMock name='requests.exceptions' id='50969104'>,
                'post': <MagicMock name='requests.post' id='50958160'>},
 '_mock_delegate': None,
 '_mock_methods': None,
 '_mock_mock_calls': [call.post('https://dcat-adopt- http://ift.tt/27BZwTq', data={'datacenter': u'P3',         'serial': u'HY0QZ12', 'state': u'initial_check_in', 'time_ran': u'Wed Apr 27 09:54:04 MST 2016', 'bmc_mac': u'34:17:EB:E4:60:D4'}), call.post().raise_for_status()],
 '_mock_name': 'requests',
 '_mock_new_name': '',
 '_mock_new_parent': None,
 '_mock_parent': None,
 '_mock_return_value': sentinel.DEFAULT,
 '_mock_side_effect': None,
 '_mock_unsafe': False,
 '_mock_wraps': None,
 '_spec_class': None,
 '_spec_set': None,
 '_spec_signature': None,
 'method_calls': [call.post('http://ift.tt/1sueTNe', data={'datacenter': u'P3', 'serial': u'HY0QZ12', 'state': u'initial_check_in', 'time_ran': u'Wed Apr 27 09:54:04 MST 2016', 'bmc_mac': u'34:17:EB:E4:60:D4'})]}


50958096
{'_mock_call_args': None,
 '_mock_call_args_list': [],
 '_mock_call_count': 0,
 '_mock_called': False,
 '_mock_children': {'raise_for_status': <Mock name='requests.post().raise_for_status' id='50942800'>},
 '_mock_delegate': None,
 '_mock_methods': None,
 '_mock_mock_calls': [call.raise_for_status()],
 '_mock_name': None,
 '_mock_new_name': '()',
 '_mock_new_parent': <MagicMock name='requests.post' id='50958160'>,
 '_mock_parent': None,
 '_mock_return_value': sentinel.DEFAULT,
 '_mock_side_effect': None,
 '_mock_unsafe': False,
 '_mock_wraps': None,
 '_spec_class': None,
 '_spec_set': None,
 '_spec_signature': None,
 'method_calls': [call.raise_for_status()],
 'raise_for_status': <Mock name='requests.post().raise_for_status' id='50942800'>}


50942800
{'_mock_call_args': call(),
 '_mock_call_args_list': [call()],
 '_mock_call_count': 1,
 '_mock_called': True,
 '_mock_children': {},
 '_mock_delegate': None,
 '_mock_methods': None,
 '_mock_mock_calls': [call()],
 '_mock_name': 'raise_for_status',
 '_mock_new_name': 'raise_for_status',
 '_mock_new_parent': <Mock name='requests.post()' id='50958096'>,
 '_mock_parent': <Mock name='requests.post()' id='50958096'>,
 '_mock_return_value': sentinel.DEFAULT,
 '_mock_side_effect': HTTPError(),
 '_mock_unsafe': False,
 '_mock_wraps': None,
 '_spec_class': None,
 '_spec_set': None,
 '_spec_signature': None,
 'method_calls': []}

Aucun commentaire:

Enregistrer un commentaire