def test_restore_raises_conflict_on_invalid_state(self): self.mox.StubOutWithMock(compute_api.API, 'get') self.mox.StubOutWithMock(compute_api.API, 'restore') fake_instance = 'fake_instance' exc = exception.InstanceInvalidState(attr='fake_attr', state='fake_state', method='fake_method', instance_uuid='fake') compute_api.API.get(self.fake_context, self.fake_uuid, expected_attrs=None, want_objects=True).AndReturn(fake_instance) compute_api.API.restore(self.fake_context, fake_instance).AndRaise(exc) self.mox.ReplayAll() self.assertRaises(webob.exc.HTTPConflict, self.extension._restore, self.fake_req, self.fake_uuid, self.fake_input_dict)
def test_restore_raises_conflict_on_invalid_state(self, mock_restore, mock_get): instance = fake_instance.fake_instance_obj( self.fake_req.environ['nova.context']) mock_get.return_value = instance mock_restore.side_effect = exception.InstanceInvalidState( attr='fake_attr', state='fake_state', method='fake_method', instance_uuid='fake') self.assertRaises(webob.exc.HTTPConflict, self.extension._restore, self.fake_req, self.fake_uuid, self.fake_input_dict) mock_get.assert_called_once_with(self.fake_context, self.fake_uuid, expected_attrs=None, cell_down_support=False) mock_restore.assert_called_once_with(self.fake_context, instance)
def _test_invalid_state(self, action, method=None, body_map=None, compute_api_args_map=None, exception_arg=None): # Reset the mock. self.mock_get.reset_mock() if method is None: method = action.replace('_', '') if body_map is None: body_map = {} if compute_api_args_map is None: compute_api_args_map = {} instance = self._stub_instance_get() args, kwargs = compute_api_args_map.get(action, ((), {})) with mock.patch.object(self.compute_api, method, side_effect=exception.InstanceInvalidState( attr='vm_state', instance_uuid=instance.uuid, state='foo', method=method)) as mock_method: controller_function = getattr(self.controller, action) ex = self.assertRaises(webob.exc.HTTPConflict, controller_function, self.req, instance.uuid, body=body_map) self.assertIn( "Cannot \'%(action)s\' instance %(id)s" % { 'action': exception_arg or method, 'id': instance.uuid }, ex.explanation) mock_method.assert_called_once_with(self.context, instance, *args, **kwargs) self.mock_get.assert_called_once_with(self.context, instance.uuid, expected_attrs=None)
def test_force_delete_raises_conflict_on_invalid_state(self): self.mox.StubOutWithMock(compute_api.API, 'get') self.mox.StubOutWithMock(compute_api.API, 'force_delete') fake_instance = 'fake_instance' compute_api.API.get(self.fake_context, self.fake_uuid).AndReturn(fake_instance) exc = exception.InstanceInvalidState(attr='fake_attr', state='fake_state', method='fake_method', instance_uuid='fake') compute_api.API.force_delete(self.fake_context, fake_instance)\ .AndRaise(exc) self.mox.ReplayAll() self.assertRaises(webob.exc.HTTPConflict, self.extension._force_delete, self.fake_req, self.fake_uuid, self.fake_input_dict)
class ServerDiagnosticsTest(test.NoDBTestCase): def setUp(self): super(ServerDiagnosticsTest, self).setUp() self.flags(verbose=True, osapi_compute_extension=[ 'nova.api.openstack.compute.contrib.select_extensions' ], osapi_compute_ext_list=['Server_diagnostics']) self.router = compute.APIRouter(init_only=('servers', 'diagnostics')) @mock.patch.object(compute_api.API, 'get_diagnostics', fake_get_diagnostics) @mock.patch.object(compute_api.API, 'get', fake_instance_get) def test_get_diagnostics(self): req = fakes.HTTPRequest.blank('/fake/servers/%s/diagnostics' % UUID) res = req.get_response(self.router) output = jsonutils.loads(res.body) self.assertEqual(output, {'data': 'Some diagnostic info'}) @mock.patch.object(compute_api.API, 'get_diagnostics', fake_get_diagnostics) @mock.patch.object(compute_api.API, 'get', side_effect=exception.InstanceNotFound(instance_id=UUID) ) def test_get_diagnostics_with_non_existed_instance(self, mock_get): req = fakes.HTTPRequest.blank('/fake/servers/%s/diagnostics' % UUID) res = req.get_response(self.router) self.assertEqual(res.status_int, 404) @mock.patch.object( compute_api.API, 'get_diagnostics', side_effect=exception.InstanceInvalidState('fake message')) @mock.patch.object(compute_api.API, 'get', fake_instance_get) def test_get_diagnostics_raise_conflict_on_invalid_state( self, mock_get_diagnostics): req = fakes.HTTPRequest.blank('/fake/servers/%s/diagnostics' % UUID) res = req.get_response(self.router) self.assertEqual(409, res.status_int)
def _test_invalid_state(self, action, method=None, body_map=None, compute_api_args_map=None, exception_arg=None, expected_attrs=None): if method is None: method = action.replace('_', '') if body_map is None: body_map = {} if compute_api_args_map is None: compute_api_args_map = {} instance = self._stub_instance_get(expected_attrs=expected_attrs) args, kwargs = compute_api_args_map.get(action, ((), {})) getattr(self.compute_api, method)(self.context, instance, *args, **kwargs).AndRaise( exception.InstanceInvalidState(attr='vm_state', instance_uuid=instance.uuid, state='foo', method=method)) self.mox.ReplayAll() controller_function = getattr(self.controller, action) ex = self.assertRaises(webob.exc.HTTPConflict, controller_function, self.req, instance.uuid, body=body_map) self.assertIn( "Cannot \'%(action)s\' instance %(id)s" % { 'action': exception_arg or method, 'id': instance.uuid }, ex.explanation) # Do these here instead of tearDown because this method is called # more than once for the same test case self.mox.VerifyAll() self.mox.UnsetStubs()
def update(self, context, instance, **kwargs): """Update an instance.""" cell_name = instance.cell_name if cell_name and self._cell_read_only(cell_name): raise exception.InstanceInvalidState(attr="vm_state", instance_uuid=instance.uuid, state="temporary_readonly", method='update') rv = super(ComputeCellsAPI, self).update(context, instance, **kwargs) kwargs_copy = kwargs.copy() # We need to skip vm_state/task_state updates as the child # cell is authoritative for these. The admin API does # support resetting state, but it has been converted to use # Instance.save() with an appropriate kwarg. kwargs_copy.pop('vm_state', None) kwargs_copy.pop('task_state', None) if kwargs_copy: try: self._cast_to_cells(context, instance, 'update', **kwargs_copy) except exception.InstanceUnknownCell: pass return rv
def _handle_cell_delete(self, context, instance, method, method_name): """Terminate an instance.""" # We can't use the decorator because we have special logic in the # case we don't know the cell_name... cell_name = instance['cell_name'] if cell_name and self._cell_read_only(cell_name): raise exception.InstanceInvalidState( attr="vm_state", instance_uuid=instance['uuid'], state="temporary_readonly", method=method_name) method(context, instance) try: self._cast_to_cells(context, instance, method_name) except exception.InstanceUnknownCell: # If there's no cell, there's also no host... which means # the instance was destroyed from the DB here. Let's just # broadcast a message down to all cells and hope this ends # up resolving itself... Worse case.. the instance will # show back up again here. delete_type = method == 'soft_delete' and 'soft' or 'hard' self.cells_rpcapi.instance_delete_everywhere( context, instance['uuid'], delete_type)
def _test_invalid_state(self, action, method=None, body_map=None, compute_api_args_map=None): if method is None: method = action if body_map is None: body_map = {} if compute_api_args_map is None: compute_api_args_map = {} instance = self._stub_instance_get() args, kwargs = compute_api_args_map.get(action, ((), {})) getattr(self.compute_api, method)(self.context, instance, *args, **kwargs).AndRaise( exception.InstanceInvalidState(attr='vm_state', instance_uuid=instance.uuid, state='foo', method=method)) self.mox.ReplayAll() res = self._make_request('/servers/%s/action' % instance.uuid, {action: body_map.get(action)}) self.assertEqual(409, res.status_int) self.assertIn( "Cannot \'%(action)s\' instance %(id)s" % { 'action': action, 'id': instance.uuid }, res.body) # Do these here instead of tearDown because this method is called # more than once for the same test case self.mox.VerifyAll() self.mox.UnsetStubs()
def fake_rescue(*args, **kwargs): raise exception.InstanceInvalidState('fake message')
def fake_revert_resize(*args, **kwargs): raise exception.InstanceInvalidState(attr='fake_attr', state='fake_state', method='fake_method', instance_uuid='fake')
def snapshot(*args, **kwargs): raise exception.InstanceInvalidState(attr='fake_attr', state='fake_state', method='fake_method', instance_uuid='fake')
def fake_swap_volume_instance_invalid_state(self, context, instance, volume_id, device): raise exception.InstanceInvalidState(instance_uuid=UUID1, state='', method='', attr='')
def test_migrate_live_instance_not_active(self): self._test_migrate_live_failed_with_exception( exception.InstanceInvalidState( instance_uuid='', state='', attr='', method=''), expected_status_code=409, check_response=False)
def test_migrate_live_instance_not_active(self): self._test_migrate_live_failed_with_exception( exception.InstanceInvalidState( instance_uuid='', state='', attr='', method=''), expected_exc=webob.exc.HTTPConflict, check_response=False)
class ServerDiagnosticsTest(test.NoDBTestCase): def setUp(self): super(ServerDiagnosticsTest, self).setUp() self.router = compute.APIRouterV3(init_only=('servers', 'os-server-diagnostics')) @mock.patch.object(compute_api.API, 'get_instance_diagnostics', fake_get_instance_diagnostics) @mock.patch.object(compute_api.API, 'get', fake_instance_get) def test_get_diagnostics(self): req = fakes.HTTPRequestV3.blank('/servers/%s/os-server-diagnostics' % UUID) res = req.get_response(self.router) output = jsonutils.loads(res.body) expected = { 'state': 'running', 'driver': 'fake', 'uptime': 7, 'cpu_details': [{ 'time': 1024 }], 'nic_details': [{ 'rx_octets': 0, 'rx_errors': 0, 'rx_drop': 0, 'rx_packets': 0, 'tx_octets': 0, 'tx_errors': 0, 'tx_drop': 0, 'tx_packets': 0 }], 'disk_details': [{ 'read_bytes': 0, 'read_requests': 0, 'write_bytes': 0, 'write_requests': 0, 'errors': 0 }], 'memory_details': { 'maximum': 512, 'used': 256 }, 'version': '1.0' } self.assertEqual(expected, output) @mock.patch.object(compute_api.API, 'get_instance_diagnostics', fake_get_instance_diagnostics) @mock.patch.object(compute_api.API, 'get', side_effect=exception.InstanceNotFound(instance_id=UUID) ) def test_get_diagnostics_with_non_existed_instance(self, mock_get): req = fakes.HTTPRequestV3.blank('/servers/%s/os-server-diagnostics' % UUID) res = req.get_response(self.router) self.assertEqual(res.status_int, 404) @mock.patch.object( compute_api.API, 'get_instance_diagnostics', side_effect=exception.InstanceInvalidState('fake message')) @mock.patch.object(compute_api.API, 'get', fake_instance_get) def test_get_diagnostics_raise_conflict_on_invalid_state( self, mock_get_diagnostics): req = fakes.HTTPRequestV3.blank('/servers/%s/os-server-diagnostics' % UUID) res = req.get_response(self.router) self.assertEqual(409, res.status_int)
class ServerDiagnosticsTestV21(test.NoDBTestCase): def _setup_router(self): self.router = compute.APIRouterV21(init_only=('servers', 'os-server-diagnostics')) def _get_request(self): return fakes.HTTPRequest.blank('/fake/servers/%s/diagnostics' % UUID) def setUp(self): super(ServerDiagnosticsTestV21, self).setUp() self._setup_router() @mock.patch.object(compute_api.API, 'get_diagnostics', fake_get_diagnostics) @mock.patch.object(compute_api.API, 'get', fake_instance_get) def test_get_diagnostics(self): req = self._get_request() res = req.get_response(self.router) output = jsonutils.loads(res.body) self.assertEqual(output, {'data': 'Some diagnostic info'}) @mock.patch.object(compute_api.API, 'get_diagnostics', fake_get_diagnostics) @mock.patch.object(compute_api.API, 'get', side_effect=exception.InstanceNotFound(instance_id=UUID) ) def test_get_diagnostics_with_non_existed_instance(self, mock_get): req = self._get_request() res = req.get_response(self.router) self.assertEqual(res.status_int, 404) @mock.patch.object( compute_api.API, 'get_diagnostics', side_effect=exception.InstanceInvalidState('fake message')) @mock.patch.object(compute_api.API, 'get', fake_instance_get) def test_get_diagnostics_raise_conflict_on_invalid_state( self, mock_get_diagnostics): req = self._get_request() res = req.get_response(self.router) self.assertEqual(409, res.status_int) @mock.patch.object(compute_api.API, 'get_diagnostics', side_effect=exception.InstanceNotReady('fake message')) @mock.patch.object(compute_api.API, 'get', fake_instance_get) def test_get_diagnostics_raise_instance_not_ready(self, mock_get_diagnostics): req = self._get_request() res = req.get_response(self.router) self.assertEqual(409, res.status_int) @mock.patch.object(compute_api.API, 'get_diagnostics', side_effect=NotImplementedError) @mock.patch.object(compute_api.API, 'get', fake_instance_get) def test_get_diagnostics_raise_no_notimplementederror( self, mock_get_diagnostics): req = self._get_request() res = req.get_response(self.router) self.assertEqual(501, res.status_int)
def fake_live_migrate(self, context, instance, block_migration, disk_over_commit, host_name): raise exception.InstanceInvalidState(instance_uuid='', attr='', state='', method='')
def test_assisted_delete_instance_invalid_state(self): api_error = exception.InstanceInvalidState( instance_uuid=FAKE_UUID, attr='task_state', state=task_states.UNSHELVING, method='volume_snapshot_delete') self._test_assisted_delete_instance_conflict(api_error)
# Correct args exc = exception.InstanceInvalidState(attr='fake_attr', state='fake_state', method='fake_method') try: common.raise_http_conflict_for_instance_invalid_state(exc, 'meow') except Exception, e: self.assertTrue(isinstance(e, webob.exc.HTTPConflict)) msg = str(e) self.assertEqual( msg, "Cannot 'meow' while instance is in fake_attr fake_state") else: self.fail("webob.exc.HTTPConflict was not raised") # Incorrect args exc = exception.InstanceInvalidState() try: common.raise_http_conflict_for_instance_invalid_state(exc, 'meow') except Exception, e: self.assertTrue(isinstance(e, webob.exc.HTTPConflict)) msg = str(e) self.assertEqual(msg, "Instance is in an invalid state for 'meow'") else: self.fail("webob.exc.HTTPConflict was not raised") def test_check_img_metadata_properties_quota_valid_metadata(self): ctxt = test_utils.get_test_admin_context() metadata1 = {"key": "value"} actual = common.check_img_metadata_properties_quota(ctxt, metadata1) self.assertEqual(actual, None)
def test_force_complete_instance_not_migrating(self): self._test_force_complete_failed_with_exception( exception.InstanceInvalidState(instance_uuid='', state='', attr='', method=''), webob.exc.HTTPConflict)
class AdminPasswordTestV21(test.NoDBTestCase): validation_error = exception.ValidationError def setUp(self): super(AdminPasswordTestV21, self).setUp() self.stub_out('nova.compute.api.API.set_admin_password', fake_set_admin_password) self.stub_out('nova.compute.api.API.get', fake_get) self.fake_req = fakes.HTTPRequest.blank('') def _get_action(self): return admin_password_v21.AdminPasswordController().change_password def _check_status(self, expected_status, res, controller_method): self.assertEqual(expected_status, controller_method.wsgi_code) def test_change_password(self): body = {'changePassword': {'adminPass': '******'}} res = self._get_action()(self.fake_req, '1', body=body) self._check_status(202, res, self._get_action()) def test_change_password_empty_string(self): body = {'changePassword': {'adminPass': ''}} res = self._get_action()(self.fake_req, '1', body=body) self._check_status(202, res, self._get_action()) @mock.patch('nova.compute.api.API.set_admin_password', side_effect=NotImplementedError()) def test_change_password_with_non_implement(self, mock_set_admin_password): body = {'changePassword': {'adminPass': '******'}} self.assertRaises(webob.exc.HTTPNotImplemented, self._get_action(), self.fake_req, '1', body=body) @mock.patch('nova.compute.api.API.get', side_effect=exception.InstanceNotFound(instance_id='1')) def test_change_password_with_non_existed_instance(self, mock_get): body = {'changePassword': {'adminPass': '******'}} self.assertRaises(webob.exc.HTTPNotFound, self._get_action(), self.fake_req, '1', body=body) def test_change_password_with_non_string_password(self): body = {'changePassword': {'adminPass': 1234}} self.assertRaises(self.validation_error, self._get_action(), self.fake_req, '1', body=body) @mock.patch('nova.compute.api.API.set_admin_password', side_effect=exception.InstancePasswordSetFailed(instance="1", reason='')) def test_change_password_failed(self, mock_set_admin_password): body = {'changePassword': {'adminPass': '******'}} self.assertRaises(webob.exc.HTTPConflict, self._get_action(), self.fake_req, '1', body=body) @mock.patch('nova.compute.api.API.set_admin_password', side_effect=exception.SetAdminPasswdNotSupported(instance="1", reason='')) def test_change_password_not_supported(self, mock_set_admin_password): body = {'changePassword': {'adminPass': '******'}} self.assertRaises(webob.exc.HTTPConflict, self._get_action(), self.fake_req, '1', body=body) @mock.patch('nova.compute.api.API.set_admin_password', side_effect=exception.InstanceAgentNotEnabled(instance="1", reason='')) def test_change_password_guest_agent_disabled(self, mock_set_admin_password): body = {'changePassword': {'adminPass': '******'}} self.assertRaises(webob.exc.HTTPConflict, self._get_action(), self.fake_req, '1', body=body) def test_change_password_without_admin_password(self): body = {'changPassword': {}} self.assertRaises(self.validation_error, self._get_action(), self.fake_req, '1', body=body) def test_change_password_none(self): body = {'changePassword': {'adminPass': None}} self.assertRaises(self.validation_error, self._get_action(), self.fake_req, '1', body=body) def test_change_password_adminpass_none(self): body = {'changePassword': None} self.assertRaises(self.validation_error, self._get_action(), self.fake_req, '1', body=body) def test_change_password_bad_request(self): body = {'changePassword': {'pass': '******'}} self.assertRaises(self.validation_error, self._get_action(), self.fake_req, '1', body=body) def test_server_change_password_pass_disabled(self): # run with enable_instance_password disabled to verify adminPass # is missing from response. See lp bug 921814 self.flags(enable_instance_password=False, group='api') body = {'changePassword': {'adminPass': '******'}} res = self._get_action()(self.fake_req, '1', body=body) self._check_status(202, res, self._get_action()) @mock.patch('nova.compute.api.API.set_admin_password', side_effect=exception.InstanceInvalidState( instance_uuid='fake', attr='vm_state', state='stopped', method='set_admin_password')) def test_change_password_invalid_state(self, mock_set_admin_password): body = {'changePassword': {'adminPass': '******'}} self.assertRaises(webob.exc.HTTPConflict, self._get_action(), self.fake_req, 'fake', body=body)
def test_cancel_live_migration_invalid_state(self): self._test_cancel_live_migration_failed( exception.InstanceInvalidState(instance_uuid='', state='', attr='', method=''), webob.exc.HTTPConflict)
def fake_compute_api_raises_invalid_state(*args, **kwargs): raise exception.InstanceInvalidState(attr='fake_attr', state='fake_state', method='fake_method', instance_uuid='fake')
def fake_detach_interface_invalid_state(*args, **kwargs): raise exception.InstanceInvalidState(instance_uuid='', attr='', state='', method='detach_interface')
def test_get_diagnostics_raise_conflict_on_invalid_state(self): req = self._get_request() with mock.patch.object(compute_api.API, self.mock_diagnostics_method, side_effect=exception.InstanceInvalidState('fake message')): res = req.get_response(self.router) self.assertEqual(409, res.status_int)