def test__get_validated_flavor_from_context_failed( self, mock_flavor_resource_type_transform): clients = mock.MagicMock() clients.nova().flavors.get.side_effect = nova_exc.NotFound("") config = { "args": { "flavor": { "name": "test" } }, "context": { "flavors": [{ "name": "othername", "ram": 32, }] } } result = validation._get_validated_flavor(config, clients, "flavor") self.assertFalse(result[0].is_valid, result[0].msg) config = { "args": { "flavor": { "name": "test" } }, } result = validation._get_validated_flavor(config, clients, "flavor") self.assertFalse(result[0].is_valid, result[0].msg)
def test_image_valid_on_flavor_flavor_not_exist(self, mock_osclients): fakegclient = fakes.FakeGlanceClient() mock_osclients.glance.return_value = fakegclient fakenclient = fakes.FakeNovaClient() fakenclient.flavors = mock.MagicMock() fakenclient.flavors.get.side_effect = nova_exc.NotFound(code=404) mock_osclients.nova.return_value = fakenclient validator = validation.image_valid_on_flavor("flavor", "image") test_img_id = "test_image_id" test_flavor_id = 101 config = { "args": { "flavor": { "id": test_flavor_id }, "image": { "id": test_img_id } } } result = validator(config, clients=mock_osclients, task=None) fakenclient.flavors.get.assert_called_once_with(flavor=test_flavor_id) self.assertFalse(result.is_valid) self.assertEqual(result.msg, "Flavor with id '101' not found")
def test_image_valid_on_flavor_context( self, mock__get_validated_image, mock_flavor_resource_type_transform): clients = mock.MagicMock() clients.nova().flavors.get.side_effect = nova_exc.NotFound("") image = {"min_ram": 24, "id": "fake_id"} success = validation.ValidationResult(True) mock__get_validated_image.return_value = (success, image) validator = self._unwrap_validator(validation.image_valid_on_flavor, "flavor", "image") config = { "args": { "flavor": { "name": "test" } }, "context": { "flavors": [{ "name": "test", "ram": 32, }] } } # test ram image["min_ram"] = None result = validator(config, clients, None) self.assertTrue(result.is_valid, result.msg) image["min_ram"] = 64 result = validator(config, clients, None) self.assertFalse(result.is_valid, result.msg)
def test__get_validated_flavor_not_found(self, mock_flavor_transform): clients = mock.MagicMock() clients.nova().flavors.get.side_effect = nova_exc.NotFound("") result = validation._get_validated_flavor({"args": { "a": "test" }}, clients, "a") self.assertFalse(result[0].is_valid, result[0].msg)
def find_resource(manager, name_or_id, wrap_exception=True, **find_args): """Helper for the _find_* methods.""" # for str id which is not uuid (for Flavor, Keypair and hypervsior in cells # environments search currently) if getattr(manager, 'is_alphanum_id_allowed', False): try: return manager.get(name_or_id) except exceptions.NotFound: pass # first try to get entity as uuid try: tmp_id = encodeutils.safe_encode(name_or_id) if six.PY3: tmp_id = tmp_id.decode() uuid.UUID(tmp_id) return manager.get(tmp_id) except (TypeError, ValueError, exceptions.NotFound): pass # then try to get entity as name try: try: resource = getattr(manager, 'resource_class', None) name_attr = resource.NAME_ATTR if resource else 'name' kwargs = {name_attr: name_or_id} kwargs.update(find_args) return manager.find(**kwargs) except exceptions.NotFound: pass # then try to find entity by human_id try: return manager.find(human_id=name_or_id, **find_args) except exceptions.NotFound: pass except exceptions.NoUniqueMatch: msg = (_("Multiple %(class)s matches found for '%(name)s', use an ID " "to be more specific.") % { 'class': manager.resource_class.__name__.lower(), 'name': name_or_id }) if wrap_exception: raise exceptions.CommandError(msg) raise exceptions.NoUniqueMatch(msg) # finally try to get entity as integer id try: return manager.get(int(name_or_id)) except (TypeError, ValueError, exceptions.NotFound): msg = (_("No %(class)s with a name or ID of '%(name)s' exists.") % { 'class': manager.resource_class.__name__.lower(), 'name': name_or_id }) if wrap_exception: raise exceptions.CommandError(msg) raise exceptions.NotFound(404, msg)
def test_detach_already_detached(self, *kwargs): fake_client = mock.MagicMock() fake_client().servers.get = mock.MagicMock() fake_client().servers.get().remove_security_group = mock.MagicMock( side_effect=nova_exceptions.NotFound('test')) with mock.patch('openstack_plugin_common.NovaClientWithSugar', fake_client): nova_plugin.server.disconnect_security_group()
def test_when_project_is_cleaned_all_resources_are_deleted(self): self.mocked_nova().servers.get.side_effect = nova_exceptions.NotFound( code=404) ProjectCleanupExecutor.execute(self.project, async=False) self.assertFalse(Project.objects.filter(id=self.project.id).exists()) self.assertFalse( models.Instance.objects.filter(id=self.instance.id).exists())
def get_size(self, flavor_id): ''' OpenStack flavor ids are integers. If the value is not an integer we know it is for euca or aws so we can fail fast''' try: int(flavor_id) except Exception: raise nova_exceptions.NotFound(404) return self._get(self.client.flavors, flavor_id)
def test_find_instance_multiple(self, mock_exit, mock_nova, mock_log, mock_init): self._create_bmc(mock_nova) mock_server = mock.Mock() self.mock_client.servers.get.side_effect = exceptions.NotFound('foo') self.mock_client.servers.list.return_value = [mock_server, mock_server] self.bmc._find_instance('abc-123') mock_exit.assert_called_once_with(1)
def test_validate_keypair_with_invalid_keypair(self): mock_nova = mock.MagicMock() mock_nova.keypairs.get.side_effect = nova_exc.NotFound('test-keypair') mock_os_cli = mock.MagicMock() mock_os_cli.nova.return_value = mock_nova self.assertRaises(exception.KeyPairNotFound, attr_validator.validate_keypair, mock_os_cli, 'test_keypair')
def test_remove_computehost_with_wrong_hosts(self): self._patch_get_aggregate_from_name_or_id() self.nova.aggregates.remove_host.side_effect = ( nova_exceptions.NotFound(404)) self.assertRaises(manager_exceptions.CantRemoveHost, self.pool.remove_computehost, 'pool', 'host3')
def test_find_instance_by_name(self, mock_nova, mock_log, mock_init): self._create_bmc(mock_nova) mock_server = mock.Mock() mock_server.id = 'abc-123' self.mock_client.servers.get.side_effect = exceptions.NotFound('foo') self.mock_client.servers.list.return_value = [mock_server] instance = self.bmc._find_instance('abc-123') self.assertEqual('abc-123', instance)
def get_by_href(self, href): for id in self.db: value = self.db[id] # Use inexact match since faking the exact endpoints would be # difficult. if href.endswith(value.href_suffix): return value raise nova_exceptions.NotFound(404, "Flavor href not found %s" % href)
def test_create_invalid_flavor_specified(self, mock_client): (mock_client.return_value.flavors.get) = Mock( side_effect=nova_exceptions.NotFound( 404, "Flavor id not found %s" % id)) self.assertRaises(exception.FlavorNotFound, Cluster.create, Mock(), self.cluster_name, self.datastore, self.datastore_version, self.instances_w_volumes, {})
def test_validate_flavor_with_exception(self): self.manager.flavor_manager.get.side_effect = [ nova_exceptions.NotFound(404), exceptions.OctaviaException ] self.assertRaises(exceptions.InvalidSubresource, self.manager.validate_flavor, "bogus") self.assertRaises(exceptions.OctaviaException, self.manager.validate_flavor, "bogus")
def test_reset_instances(self, mock_reset): mock_reset.side_effect = n_exc.NotFound("") instance = ["instance_uuid"] try: self.endpoint._reset_instances(instance) self.assertTrue(True) except Exception: self.assertTrue(False)
def get(self, id): try: id = int(id) except ValueError: pass if id not in self.db: raise nova_exceptions.NotFound(404, "Flavor id not found %s" % id) return self.db[id]
def delete_vm_group(self, id, **kwargs): """Mock'd version of novaclient...server_group_delete() :param id: vm server group id """ try: del (self._vm_group_list[str(id)]) except KeyError: raise nova_exc.NotFound(404)
def find(id): try: vm = FakeNovaClient.vnc_lib.virtual_machine_read(id=id) except vnc_api.NoIdError: raise nc_exc.NotFound(404, "") vm.delete = FakeNovaClient.delete_vm.__get__( vm, vnc_api.VirtualMachine) vm.status = 'OK' return vm
def setUp(self): super(InstanceDeleteTest, self).setUp() self.instance = factories.InstanceFactory( state=models.Instance.States.OK, runtime_state=models.Instance.RuntimeStates.SHUTOFF, backend_id='VALID_ID') self.instance.increase_backend_quotas_usage() self.mocked_nova().servers.get.side_effect = nova_exceptions.NotFound( code=404) views.InstanceViewSet.async_executor = False
def test_filter_non_existing_instance(self): opts = copy.deepcopy(self.opts) opts['search_opts_tenant'] = {'tenant_id': ['existing_tenant_id']} opts['search_opts'] = {'id': ['non_existing_instance_id']} self.src_compute.nova_client.servers.get.side_effect = ( nova_exc.NotFound(404)) self.assertRaises(exception.AbortMigrationError, self.fake_action.run, **opts)
def test_delete_floating_ip_not_found( self, mock_get_floating_ip, mock_nova_client): mock_get_floating_ip.return_value = None mock_nova_client.floating_ips.delete.side_effect = n_exc.NotFound( code=404) ret = self.client.delete_floating_ip( floating_ip_id='a-wild-id-appears') self.assertFalse(ret)
def get_item(self, name, callback): item = None for cloud in self.registry.all_clouds(flask.g.auth_token): try: item = callback(cloud) if item: return json.dumps({name: self.tag(item, cloud)}) except (nova_exceptions.NotFound, cinder_exceptions.NotFound): pass raise nova_exceptions.NotFound(404)
def get_cloud_from_item(self, callback): item = None for cloud in self.registry.all_clouds(flask.g.auth_token): try: item = callback(cloud) if item: return cloud except (nova_exceptions.NotFound, cinder_exceptions.NotFound): pass raise nova_exceptions.NotFound(404)
def test_delete_floating_ip_not_found( self, mock_has_service, mock_nova_client): mock_has_service.side_effect = has_service_side_effect mock_nova_client.floating_ips.delete.side_effect = n_exc.NotFound( code=404) ret = self.client.delete_floating_ip( floating_ip_id='a-wild-id-appears') self.assertFalse(ret)
def find(self, name, **kwargs): kwargs["name"] = name for resource in self.cache.values(): match = True for key, value in kwargs.items(): if getattr(resource, key, None) != value: match = False break if match: return resource raise nova_exceptions.NotFound("Security Group not found")
def test_get_server(self): """Tests the get_server function.""" my_server = mock.MagicMock() self.nova_client.servers.get.side_effect = [ my_server, nova_exceptions.NotFound(404) ] self.assertEqual(my_server, self.nova_plugin.get_server('my_server')) self.assertRaises(exception.EntityNotFound, self.nova_plugin.get_server, 'idontexist') calls = [mock.call('my_server'), mock.call('idontexist')] self.nova_client.servers.get.assert_has_calls(calls)
def test_flavor_exists_fail(self, mock_osclients): fakenclient = fakes.FakeNovaClient() fakenclient.flavors = mock.MagicMock() fakenclient.flavors.get.side_effect = nova_exc.NotFound(code=404) mock_osclients.nova.return_value = fakenclient validator = validation.flavor_exists("flavor_id") test_flavor_id = 101 result = validator(clients=mock_osclients, flavor_id=test_flavor_id) fakenclient.flavors.get.assert_called_once_with(flavor=test_flavor_id) self.assertFalse(result.is_valid) self.assertIsNotNone(result.msg)
def find(self, **kwargs): """Find a single item with attributes matching ``**kwargs``.""" matches = self.findall(**kwargs) num_matches = len(matches) if num_matches == 0: msg = "No %s matching %s." % (self.resource_class.__name__, kwargs) raise exceptions.NotFound(404, msg) elif num_matches > 1: raise exceptions.NoUniqueMatch else: return matches[0]
def test_delete_key_not_found(self): """Test delete non-existant key.""" test_res = self._get_test_resource(self.kp_template) test_res.resource_id = "key_name" test_res.state_set(test_res.CREATE, test_res.COMPLETE) (self.fake_keypairs.delete("key_name").AndRaise( nova_exceptions.NotFound(404))) self.m.ReplayAll() scheduler.TaskRunner(test_res.delete)() self.assertEqual((test_res.DELETE, test_res.COMPLETE), test_res.state) self.m.VerifyAll()