def _wait_for_active(self, ironicclient, instance): """Wait for the node to be marked as ACTIVE in Ironic.""" node = _validate_instance_and_node(ironicclient, instance) if node.provision_state == ironic_states.ACTIVE: # job is done LOG.debug("Ironic node %(node)s is now ACTIVE", dict(node=node.uuid), instance=instance) raise loopingcall.LoopingCallDone() if node.target_provision_state in (ironic_states.DELETED, ironic_states.AVAILABLE): # ironic is trying to delete it now raise exception.InstanceNotFound(instance_id=instance.uuid) if node.provision_state in (ironic_states.NOSTATE, ironic_states.AVAILABLE): # ironic already deleted it raise exception.InstanceNotFound(instance_id=instance.uuid) if node.provision_state == ironic_states.DEPLOYFAIL: # ironic failed to deploy msg = (_("Failed to provision instance %(inst)s: %(reason)s") % { 'inst': instance.uuid, 'reason': node.last_error }) raise exception.InstanceDeployFailure(msg) _log_ironic_polling('become ACTIVE', node, instance)
def _test_instance_not_found_in_compute_api(self, action, method=None, body=None, compute_api_args_map=None): if method is None: method = action.replace('_', '') compute_api_args_map = compute_api_args_map or {} 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.InstanceNotFound(instance_id=instance.uuid)) self.mox.ReplayAll() controller_function = getattr(self.controller, action) self.assertRaises(webob.exc.HTTPNotFound, controller_function, self.req, instance.uuid, body=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 test_fping_show_with_not_found(self, mock_get_instance): mock_get_instance.side_effect = exception.InstanceNotFound( instance_id='') req = fakes.HTTPRequest.blank(self._get_url() + "os-fping/%s" % FAKE_UUID) self.assertRaises(webob.exc.HTTPNotFound, self.controller.show, req, FAKE_UUID)
def fake_list_ports(self, *args, **kwargs): uuid = kwargs.get('device_id', None) if not uuid: raise exception.InstanceNotFound(instance_id=None) port_data = { "id": "ce531f90-199f-48c0-816c-13e38010b442", "network_id": "3cb9bc59-5699-4588-a4b1-b87f96708bc6", "admin_state_up": True, "status": "ACTIVE", "mac_address": "fa:16:3e:4c:2c:30", "fixed_ips": [{ "ip_address": "192.168.1.3", "subnet_id": "f8a6e8f8-c2ec-497c-9f23-da9616de54ef" }], "device_id": uuid, } ports = {'ports': [port_data]} return ports
def test_get_serial_console_no_instance(self, get_serial_console): get_serial_console.side_effect = (exception.InstanceNotFound( instance_id='xxx')) body = {'os-getSerialConsole': {'type': 'serial'}} self._check_console_failure('self.controller.get_serial_console', webob.exc.HTTPNotFound, body) self.assertTrue(get_serial_console.called)
def get_info(self, instance): if instance.uuid not in self.instances: raise exception.InstanceNotFound(instance_id=instance.uuid) i = self.instances[instance.uuid] return hardware.InstanceInfo(state=i.state, max_mem_kb=0, mem_kb=0, num_cpu=2, cpu_time_ns=0)
def _validate_instance_and_node(ironicclient, instance): """Get the node associated with the instance. Check with the Ironic service that this instance is associated with a node, and return the node. """ try: return ironicclient.call("node.get_by_instance_uuid", instance.uuid) except ironic.exc.NotFound: raise exception.InstanceNotFound(instance_id=instance.uuid)
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=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 test_force_delete_instance_not_found(self): self.mox.StubOutWithMock(compute_api.API, 'get') compute_api.API.get( self.fake_context, self.fake_uuid, expected_attrs=None, want_objects=True).AndRaise( exception.InstanceNotFound(instance_id='instance-0000')) self.mox.ReplayAll() self.assertRaises(webob.exc.HTTPNotFound, self.extension._force_delete, self.fake_req, self.fake_uuid, self.fake_input_dict)
def test_vif_instance_not_found(self): self.mox.StubOutWithMock(compute_api.API, 'get') fake_context = context.RequestContext('fake', 'fake') fake_req = FakeRequest(fake_context) compute_api.API.get( fake_context, 'fake_uuid', expected_attrs=None, want_objects=True).AndRaise( exception.InstanceNotFound(instance_id='instance-0000')) self.mox.ReplayAll() self.assertRaises(webob.exc.HTTPNotFound, self.controller.index, fake_req, 'fake_uuid')
def fake_compute_api_get(self, context, instance_id, want_objects=False, **kwargs): # BAD_UUID is something that does not exist if instance_id == 'BAD_UUID': raise exception.InstanceNotFound(instance_id=instance_id) else: return fake_instance.fake_instance_obj(context, id=1, uuid=instance_id, task_state=None, host='host1', vm_state=vm_states.ACTIVE)
def get_info(self, instance): """Get information about the VM.""" LOG.debug("get_info called for instance", instance=instance) instance_name = instance.name if not self._vmutils.vm_exists(instance_name): raise exception.InstanceNotFound(instance_id=instance.uuid) info = self._vmutils.get_vm_summary_info(instance_name) state = constants.HYPERV_POWER_STATE[info['EnabledState']] return hardware.InstanceInfo(state=state, max_mem_kb=info['MemoryUsage'], mem_kb=info['MemoryUsage'], num_cpu=info['NumberOfProcessors'], cpu_time_ns=info['UpTime'])
def test_no_instance(self): self.mox.StubOutWithMock(self.compute_api, 'get') exc = exception.InstanceNotFound(instance_id='inst_ud') self.compute_api.get(self.context, self.uuid, expected_attrs=None, want_objects=True).AndRaise(exc) self.mox.ReplayAll() self.assertRaises(webob.exc.HTTPNotFound, self.admin_api._reset_state, self.request, self.uuid, body={"os-resetState": { "state": "active" }})
def _test_non_existing_instance(self, action, body_map=None): uuid = uuidutils.generate_uuid() self._stub_instance_get_failure( exception.InstanceNotFound(instance_id=uuid), uuid=uuid) self.mox.ReplayAll() controller_function = getattr(self.controller, action) self.assertRaises(webob.exc.HTTPNotFound, controller_function, self.req, uuid, body=body_map) # 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 _get_domain_by_name(self, instance_name): """Retrieve libvirt domain object given an instance name. All libvirt error handling should be handled in this method and relevant patron exceptions should be raised in response. """ try: conn = self.get_connection() return conn.lookupByName(instance_name) except libvirt.libvirtError as ex: error_code = ex.get_error_code() if error_code == libvirt.VIR_ERR_NO_DOMAIN: raise exception.InstanceNotFound(instance_id=instance_name) msg = (_('Error from libvirt while looking up %(instance_name)s: ' '[Error Code %(error_code)s] %(ex)s') % {'instance_name': instance_name, 'error_code': error_code, 'ex': ex}) raise exception.PatronException(msg)
def fake_create_console(cons_self, context, instance_id): raise exception.InstanceNotFound(instance_id=instance_id)
def not_found(context): raise exception.InstanceNotFound(instance_id=None)
class InterfaceAttachTestsV21(test.NoDBTestCase): controller_cls = attach_interfaces_v21.InterfaceAttachmentController validate_exc = exception.ValidationError in_use_exc = exc.HTTPConflict not_found_exc = exc.HTTPNotFound not_usable_exc = exc.HTTPBadRequest def setUp(self): super(InterfaceAttachTestsV21, self).setUp() self.flags(auth_strategy=None, group='neutron') self.flags(url='http://anyhost/', group='neutron') self.flags(timeout=30, group='neutron') self.stubs.Set(network_api.API, 'show_port', fake_show_port) self.stubs.Set(network_api.API, 'list_ports', fake_list_ports) self.stubs.Set(compute_api.API, 'get', fake_get_instance) self.expected_show = { 'interfaceAttachment': { 'net_id': FAKE_NET_ID1, 'port_id': FAKE_PORT_ID1, 'mac_addr': port_data1['mac_address'], 'port_state': port_data1['status'], 'fixed_ips': port_data1['fixed_ips'], } } self.attachments = self.controller_cls() self.req = fakes.HTTPRequest.blank('') @mock.patch.object(compute_api.API, 'get', side_effect=exception.InstanceNotFound(instance_id='')) def _test_instance_not_found(self, func, args, mock_get, kwargs=None): if not kwargs: kwargs = {} self.assertRaises(exc.HTTPNotFound, func, self.req, *args, **kwargs) def test_show_instance_not_found(self): self._test_instance_not_found(self.attachments.show, ('fake', 'fake')) def test_index_instance_not_found(self): self._test_instance_not_found(self.attachments.index, ('fake', )) def test_detach_interface_instance_not_found(self): self._test_instance_not_found(self.attachments.delete, ('fake', 'fake')) def test_attach_interface_instance_not_found(self): self._test_instance_not_found( self.attachments.create, ('fake', ), kwargs={'body': { 'interfaceAttachment': {} }}) def test_show(self): result = self.attachments.show(self.req, FAKE_UUID1, FAKE_PORT_ID1) self.assertEqual(self.expected_show, result) def test_show_with_port_not_found(self): self.assertRaises(exc.HTTPNotFound, self.attachments.show, self.req, FAKE_UUID2, FAKE_PORT_ID1) @mock.patch.object(network_api.API, 'show_port', side_effect=exception.Forbidden) def test_show_forbidden(self, show_port_mock): self.assertRaises(exc.HTTPForbidden, self.attachments.show, self.req, FAKE_UUID1, FAKE_PORT_ID1) def test_delete(self): self.stubs.Set(compute_api.API, 'detach_interface', fake_detach_interface) result = self.attachments.delete(self.req, FAKE_UUID1, FAKE_PORT_ID1) # NOTE: on v2.1, http status code is set as wsgi_code of API # method instead of status_int in a response object. if isinstance(self.attachments, attach_interfaces_v21.InterfaceAttachmentController): status_int = self.attachments.delete.wsgi_code else: status_int = result.status_int self.assertEqual(202, status_int) def test_detach_interface_instance_locked(self): def fake_detach_interface_from_locked_server(self, context, instance, port_id): raise exception.InstanceIsLocked(instance_uuid=FAKE_UUID1) self.stubs.Set(compute_api.API, 'detach_interface', fake_detach_interface_from_locked_server) self.assertRaises(exc.HTTPConflict, self.attachments.delete, self.req, FAKE_UUID1, FAKE_PORT_ID1) def test_delete_interface_not_found(self): self.stubs.Set(compute_api.API, 'detach_interface', fake_detach_interface) self.assertRaises(exc.HTTPNotFound, self.attachments.delete, self.req, FAKE_UUID1, 'invaid-port-id') def test_attach_interface_instance_locked(self): def fake_attach_interface_to_locked_server(self, context, instance, network_id, port_id, requested_ip): raise exception.InstanceIsLocked(instance_uuid=FAKE_UUID1) self.stubs.Set(compute_api.API, 'attach_interface', fake_attach_interface_to_locked_server) body = {} self.assertRaises(exc.HTTPConflict, self.attachments.create, self.req, FAKE_UUID1, body=body) def test_attach_interface_without_network_id(self): self.stubs.Set(compute_api.API, 'attach_interface', fake_attach_interface) body = {} result = self.attachments.create(self.req, FAKE_UUID1, body=body) self.assertEqual(result['interfaceAttachment']['net_id'], FAKE_NET_ID1) def test_attach_interface_with_network_id(self): self.stubs.Set(compute_api.API, 'attach_interface', fake_attach_interface) body = {'interfaceAttachment': {'net_id': FAKE_NET_ID2}} result = self.attachments.create(self.req, FAKE_UUID1, body=body) self.assertEqual(result['interfaceAttachment']['net_id'], FAKE_NET_ID2) def _attach_interface_bad_request_case(self, body): self.stubs.Set(compute_api.API, 'attach_interface', fake_attach_interface) self.assertRaises(exc.HTTPBadRequest, self.attachments.create, self.req, FAKE_UUID1, body=body) def _attach_interface_not_found_case(self, body): self.stubs.Set(compute_api.API, 'attach_interface', fake_attach_interface) self.assertRaises(self.not_found_exc, self.attachments.create, self.req, FAKE_UUID1, body=body) def test_attach_interface_with_port_and_network_id(self): body = { 'interfaceAttachment': { 'port_id': FAKE_PORT_ID1, 'net_id': FAKE_NET_ID2 } } self._attach_interface_bad_request_case(body) def test_attach_interface_with_not_found_network_id(self): body = {'interfaceAttachment': {'net_id': FAKE_BAD_NET_ID}} self._attach_interface_not_found_case(body) def test_attach_interface_with_not_found_port_id(self): body = {'interfaceAttachment': {'port_id': FAKE_NOT_FOUND_PORT_ID}} self._attach_interface_not_found_case(body) def test_attach_interface_with_invalid_state(self): def fake_attach_interface_invalid_state(*args, **kwargs): raise exception.InstanceInvalidState(instance_uuid='', attr='', state='', method='attach_interface') self.stubs.Set(compute_api.API, 'attach_interface', fake_attach_interface_invalid_state) body = {'interfaceAttachment': {'net_id': FAKE_NET_ID1}} self.assertRaises(exc.HTTPConflict, self.attachments.create, self.req, FAKE_UUID1, body=body) @mock.patch.object(compute_api.API, 'attach_interface', side_effect=NotImplementedError()) def test_attach_interface_with_not_implemented(self, _mock): body = {'interfaceAttachment': {'net_id': FAKE_NET_ID1}} self.assertRaises(exc.HTTPNotImplemented, self.attachments.create, self.req, FAKE_UUID1, body=body) def test_detach_interface_with_invalid_state(self): def fake_detach_interface_invalid_state(*args, **kwargs): raise exception.InstanceInvalidState(instance_uuid='', attr='', state='', method='detach_interface') self.stubs.Set(compute_api.API, 'detach_interface', fake_detach_interface_invalid_state) self.assertRaises(exc.HTTPConflict, self.attachments.delete, self.req, FAKE_UUID1, FAKE_NET_ID1) @mock.patch.object(compute_api.API, 'detach_interface', side_effect=NotImplementedError()) def test_detach_interface_with_not_implemented(self, _mock): self.assertRaises(exc.HTTPNotImplemented, self.attachments.delete, self.req, FAKE_UUID1, FAKE_NET_ID1) def test_attach_interface_invalid_fixed_ip(self): body = { 'interfaceAttachment': { 'net_id': FAKE_NET_ID1, 'fixed_ips': [{ 'ip_address': 'invalid_ip' }] } } self.assertRaises(self.validate_exc, self.attachments.create, self.req, FAKE_UUID1, body=body) @mock.patch.object(compute_api.API, 'get') @mock.patch.object(compute_api.API, 'attach_interface') def test_attach_interface_fixed_ip_already_in_use(self, attach_mock, get_mock): fake_instance = objects.Instance(uuid=FAKE_UUID1) get_mock.return_value = fake_instance attach_mock.side_effect = exception.FixedIpAlreadyInUse( address='10.0.2.2', instance_uuid=FAKE_UUID1) body = {} self.assertRaises(self.in_use_exc, self.attachments.create, self.req, FAKE_UUID1, body=body) ctxt = self.req.environ['patron.context'] attach_mock.assert_called_once_with(ctxt, fake_instance, None, None, None) get_mock.assert_called_once_with(ctxt, FAKE_UUID1, want_objects=True, expected_attrs=None) @mock.patch.object(compute_api.API, 'get') @mock.patch.object(compute_api.API, 'attach_interface') def test_attach_interface_port_in_use(self, attach_mock, get_mock): fake_instance = objects.Instance(uuid=FAKE_UUID1) get_mock.return_value = fake_instance attach_mock.side_effect = exception.PortInUse(port_id=FAKE_PORT_ID1) body = {} self.assertRaises(self.in_use_exc, self.attachments.create, self.req, FAKE_UUID1, body=body) ctxt = self.req.environ['patron.context'] attach_mock.assert_called_once_with(ctxt, fake_instance, None, None, None) get_mock.assert_called_once_with(ctxt, FAKE_UUID1, want_objects=True, expected_attrs=None) @mock.patch.object(compute_api.API, 'get') @mock.patch.object(compute_api.API, 'attach_interface') def test_attach_interface_port_not_usable(self, attach_mock, get_mock): fake_instance = objects.Instance(uuid=FAKE_UUID1) get_mock.return_value = fake_instance attach_mock.side_effect = exception.PortNotUsable( port_id=FAKE_PORT_ID1, instance=fake_instance.uuid) body = {} self.assertRaises(self.not_usable_exc, self.attachments.create, self.req, FAKE_UUID1, body=body) ctxt = self.req.environ['patron.context'] attach_mock.assert_called_once_with(ctxt, fake_instance, None, None, None) get_mock.assert_called_once_with(ctxt, FAKE_UUID1, want_objects=True, expected_attrs=None) @mock.patch.object(compute_api.API, 'get') @mock.patch.object(compute_api.API, 'attach_interface') def test_attach_interface_no_more_fixed_ips(self, attach_mock, get_mock): fake_instance = objects.Instance(uuid=FAKE_UUID1) get_mock.return_value = fake_instance attach_mock.side_effect = exception.NoMoreFixedIps(net=FAKE_NET_ID1) body = {} self.assertRaises(exc.HTTPBadRequest, self.attachments.create, self.req, FAKE_UUID1, body=body) ctxt = self.req.environ['patron.context'] attach_mock.assert_called_once_with(ctxt, fake_instance, None, None, None) get_mock.assert_called_once_with(ctxt, FAKE_UUID1, want_objects=True, expected_attrs=None) def _test_attach_interface_with_invalid_parameter(self, param): self.stubs.Set(compute_api.API, 'attach_interface', fake_attach_interface) body = {'interface_attachment': param} self.assertRaises(exception.ValidationError, self.attachments.create, self.req, FAKE_UUID1, body=body) def test_attach_interface_instance_with_non_uuid_net_id(self): param = {'net_id': 'non_uuid'} self._test_attach_interface_with_invalid_parameter(param) def test_attach_interface_instance_with_non_uuid_port_id(self): param = {'port_id': 'non_uuid'} self._test_attach_interface_with_invalid_parameter(param) def test_attach_interface_instance_with_non_array_fixed_ips(self): param = {'fixed_ips': 'non_array'} self._test_attach_interface_with_invalid_parameter(param)
def fake_get(self, context, instance_uuid, expected_attrs=None, want_objects=False): raise exception.InstanceNotFound(instance_id=instance_uuid)
def fake_get_domain_by_id(id): for vm in vms: if vm.ID() == id: return vm raise exception.InstanceNotFound(instance_id=id)
def fake_get_domain_by_name(name): for vm in vms: if vm.name() == name: return vm raise exception.InstanceNotFound(instance_id=name)
def fake_get_rdp_console_not_found(self, _context, instance, _console_type): raise exception.InstanceNotFound(instance_id=instance["uuid"])
def fake_get_not_found(*args, **kwargs): raise exception.InstanceNotFound(instance_id='fake')
def instance_get_by_uuid(self, ctxt, instance_uuid): raise exception.InstanceNotFound(instance_id=instance_uuid)
def fake_get_by_uuid(cls, context, uuid): try: return fake_instances[uuid] except KeyError: raise exception.InstanceNotFound(instance_id=uuid)
def return_server_nonexistent(context, server_id, columns_to_join=None, use_slave=False): raise exception.InstanceNotFound(instance_id=server_id)
class VolumeAttachTestsV21(test.NoDBTestCase): validation_error = exception.ValidationError def setUp(self): super(VolumeAttachTestsV21, self).setUp() self.stubs.Set(db, 'block_device_mapping_get_all_by_instance', fake_bdms_get_all_by_instance) self.stubs.Set(compute_api.API, 'get', fake_get_instance) self.stubs.Set(cinder.API, 'get', fake_get_volume) self.context = context.get_admin_context() self.expected_show = { 'volumeAttachment': { 'device': '/dev/fake0', 'serverId': FAKE_UUID, 'id': FAKE_UUID_A, 'volumeId': FAKE_UUID_A } } self._set_up_controller() def _set_up_controller(self): self.attachments = volumes_v21.VolumeAttachmentController() def test_show(self): req = fakes.HTTPRequest.blank( '/v2/servers/id/os-volume_attachments/uuid') req.method = 'POST' req.body = jsonutils.dumps({}) req.headers['content-type'] = 'application/json' req.environ['patron.context'] = self.context result = self.attachments.show(req, FAKE_UUID, FAKE_UUID_A) self.assertEqual(self.expected_show, result) @mock.patch.object( compute_api.API, 'get', side_effect=exception.InstanceNotFound(instance_id=FAKE_UUID)) def test_show_no_instance(self, mock_mr): req = fakes.HTTPRequest.blank( '/v2/servers/id/os-volume_attachments/uuid') req.method = 'POST' req.body = jsonutils.dumps({}) req.headers['content-type'] = 'application/json' req.environ['patron.context'] = self.context self.assertRaises(exc.HTTPNotFound, self.attachments.show, req, FAKE_UUID, FAKE_UUID_A) @mock.patch.object(objects.BlockDeviceMappingList, 'get_by_instance_uuid', return_value=None) def test_show_no_bdms(self, mock_mr): req = fakes.HTTPRequest.blank( '/v2/servers/id/os-volume_attachments/uuid') req.method = 'POST' req.body = jsonutils.dumps({}) req.headers['content-type'] = 'application/json' req.environ['patron.context'] = self.context self.assertRaises(exc.HTTPNotFound, self.attachments.show, req, FAKE_UUID, FAKE_UUID_A) def test_show_bdms_no_mountpoint(self): FAKE_UUID_NOTEXIST = '00000000-aaaa-aaaa-aaaa-aaaaaaaaaaaa' req = fakes.HTTPRequest.blank( '/v2/servers/id/os-volume_attachments/uuid') req.method = 'POST' req.body = jsonutils.dumps({}) req.headers['content-type'] = 'application/json' req.environ['patron.context'] = self.context self.assertRaises(exc.HTTPNotFound, self.attachments.show, req, FAKE_UUID, FAKE_UUID_NOTEXIST) def test_detach(self): self.stubs.Set(compute_api.API, 'detach_volume', fake_detach_volume) req = fakes.HTTPRequest.blank( '/v2/servers/id/os-volume_attachments/uuid') req.method = 'DELETE' req.headers['content-type'] = 'application/json' req.environ['patron.context'] = self.context result = self.attachments.delete(req, FAKE_UUID, FAKE_UUID_A) # NOTE: on v2.1, http status code is set as wsgi_code of API # method instead of status_int in a response object. if isinstance(self.attachments, volumes_v21.VolumeAttachmentController): status_int = self.attachments.delete.wsgi_code else: status_int = result.status_int self.assertEqual(202, status_int) def test_detach_vol_not_found(self): self.stubs.Set(compute_api.API, 'detach_volume', fake_detach_volume) req = fakes.HTTPRequest.blank( '/v2/servers/id/os-volume_attachments/uuid') req.method = 'DELETE' req.headers['content-type'] = 'application/json' req.environ['patron.context'] = self.context self.assertRaises(exc.HTTPNotFound, self.attachments.delete, req, FAKE_UUID, FAKE_UUID_C) @mock.patch('patron.objects.BlockDeviceMapping.is_root', new_callable=mock.PropertyMock) def test_detach_vol_root(self, mock_isroot): req = fakes.HTTPRequest.blank( '/v2/servers/id/os-volume_attachments/uuid') req.method = 'DELETE' req.headers['content-type'] = 'application/json' req.environ['patron.context'] = self.context mock_isroot.return_value = True self.assertRaises(exc.HTTPForbidden, self.attachments.delete, req, FAKE_UUID, FAKE_UUID_A) def test_detach_volume_from_locked_server(self): def fake_detach_volume_from_locked_server(self, context, instance, volume): raise exception.InstanceIsLocked(instance_uuid=instance['uuid']) self.stubs.Set(compute_api.API, 'detach_volume', fake_detach_volume_from_locked_server) req = fakes.HTTPRequest.blank( '/v2/servers/id/os-volume_attachments/uuid') req.method = 'DELETE' req.headers['content-type'] = 'application/json' req.environ['patron.context'] = self.context self.assertRaises(webob.exc.HTTPConflict, self.attachments.delete, req, FAKE_UUID, FAKE_UUID_A) def test_attach_volume(self): self.stubs.Set(compute_api.API, 'attach_volume', fake_attach_volume) body = { 'volumeAttachment': { 'volumeId': FAKE_UUID_A, 'device': '/dev/fake' } } req = fakes.HTTPRequest.blank('/v2/servers/id/os-volume_attachments') req.method = 'POST' req.body = jsonutils.dumps({}) req.headers['content-type'] = 'application/json' req.environ['patron.context'] = self.context result = self.attachments.create(req, FAKE_UUID, body=body) self.assertEqual(result['volumeAttachment']['id'], '00000000-aaaa-aaaa-aaaa-000000000000') def test_attach_volume_to_locked_server(self): def fake_attach_volume_to_locked_server(self, context, instance, volume_id, device=None): raise exception.InstanceIsLocked(instance_uuid=instance['uuid']) self.stubs.Set(compute_api.API, 'attach_volume', fake_attach_volume_to_locked_server) body = { 'volumeAttachment': { 'volumeId': FAKE_UUID_A, 'device': '/dev/fake' } } req = fakes.HTTPRequest.blank('/v2/servers/id/os-volume_attachments') req.method = 'POST' req.body = jsonutils.dumps({}) req.headers['content-type'] = 'application/json' req.environ['patron.context'] = self.context self.assertRaises(webob.exc.HTTPConflict, self.attachments.create, req, FAKE_UUID, body=body) def test_attach_volume_bad_id(self): self.stubs.Set(compute_api.API, 'attach_volume', fake_attach_volume) body = { 'volumeAttachment': { 'device': None, 'volumeId': 'TESTVOLUME', } } req = fakes.HTTPRequest.blank('/v2/servers/id/os-volume_attachments') req.method = 'POST' req.body = jsonutils.dumps({}) req.headers['content-type'] = 'application/json' req.environ['patron.context'] = self.context self.assertRaises(self.validation_error, self.attachments.create, req, FAKE_UUID, body=body) def test_attach_volume_without_volumeId(self): self.stubs.Set(compute_api.API, 'attach_volume', fake_attach_volume) body = {'volumeAttachment': {'device': None}} req = fakes.HTTPRequest.blank('/v2/servers/id/os-volume_attachments') req.method = 'POST' req.body = jsonutils.dumps({}) req.headers['content-type'] = 'application/json' req.environ['patron.context'] = self.context self.assertRaises(self.validation_error, self.attachments.create, req, FAKE_UUID, body=body) def test_attach_volume_with_extra_arg(self): body = { 'volumeAttachment': { 'volumeId': FAKE_UUID_A, 'device': '/dev/fake', 'extra': 'extra_arg' } } req = fakes.HTTPRequest.blank('/v2/servers/id/os-volume_attachments') req.method = 'POST' req.body = jsonutils.dumps({}) req.headers['content-type'] = 'application/json' req.environ['patron.context'] = self.context self.assertRaises(self.validation_error, self.attachments.create, req, FAKE_UUID, body=body) def _test_swap(self, attachments, uuid=FAKE_UUID_A, fake_func=None, body=None): fake_func = fake_func or fake_swap_volume self.stubs.Set(compute_api.API, 'swap_volume', fake_func) body = body or {'volumeAttachment': {'volumeId': FAKE_UUID_B}} req = fakes.HTTPRequest.blank( '/v2/servers/id/os-volume_attachments/uuid') req.method = 'PUT' req.body = jsonutils.dumps({}) req.headers['content-type'] = 'application/json' req.environ['patron.context'] = self.context return attachments.update(req, FAKE_UUID, uuid, body=body) def test_swap_volume_for_locked_server(self): def fake_swap_volume_for_locked_server(self, context, instance, old_volume, new_volume): raise exception.InstanceIsLocked(instance_uuid=instance['uuid']) self.assertRaises(webob.exc.HTTPConflict, self._test_swap, self.attachments, fake_func=fake_swap_volume_for_locked_server) def test_swap_volume(self): result = self._test_swap(self.attachments) # NOTE: on v2.1, http status code is set as wsgi_code of API # method instead of status_int in a response object. if isinstance(self.attachments, volumes_v21.VolumeAttachmentController): status_int = self.attachments.update.wsgi_code else: status_int = result.status_int self.assertEqual(202, status_int) def test_swap_volume_no_attachment(self): self.assertRaises(exc.HTTPNotFound, self._test_swap, self.attachments, FAKE_UUID_C) def test_swap_volume_without_volumeId(self): body = {'volumeAttachment': {'device': '/dev/fake'}} self.assertRaises(self.validation_error, self._test_swap, self.attachments, body=body) def test_swap_volume_with_extra_arg(self): body = { 'volumeAttachment': { 'volumeId': FAKE_UUID_A, 'device': '/dev/fake' } } self.assertRaises(self.validation_error, self._test_swap, self.attachments, body=body)
def fake_compute_get(*args, **kwargs): raise exception.InstanceNotFound(instance_id='fake')
class AdminPasswordTestV21(test.NoDBTestCase): validiation_error = exception.ValidationError def setUp(self): super(AdminPasswordTestV21, self).setUp() self.stubs.Set(compute_api.API, 'set_admin_password', fake_set_admin_password) self.stubs.Set(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('patron.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('patron.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.validiation_error, self._get_action(), self.fake_req, '1', body=body) @mock.patch('patron.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) def test_change_password_without_admin_password(self): body = {'changPassword': {}} self.assertRaises(self.validiation_error, self._get_action(), self.fake_req, '1', body=body) def test_change_password_none(self): body = {'changePassword': {'adminPass': None}} self.assertRaises(self.validiation_error, self._get_action(), self.fake_req, '1', body=body) def test_change_password_adminpass_none(self): body = {'changePassword': None} self.assertRaises(self.validiation_error, self._get_action(), self.fake_req, '1', body=body) def test_change_password_bad_request(self): body = {'changePassword': {'pass': '******'}} self.assertRaises(self.validiation_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) body = {'changePassword': {'adminPass': '******'}} res = self._get_action()(self.fake_req, '1', body=body) self._check_status(202, res, self._get_action()) @mock.patch('patron.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)