Ejemplo n.º 1
0
    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)
Ejemplo n.º 2
0
    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")
Ejemplo n.º 3
0
    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)
Ejemplo n.º 4
0
 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)
Ejemplo n.º 5
0
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())
Ejemplo n.º 8
0
 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)
Ejemplo n.º 9
0
 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)
Ejemplo n.º 10
0
 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')
Ejemplo n.º 11
0
 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')
Ejemplo n.º 12
0
 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)
Ejemplo n.º 13
0
 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, {})
Ejemplo n.º 15
0
 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")
Ejemplo n.º 16
0
 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)
Ejemplo n.º 17
0
    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]
Ejemplo n.º 18
0
    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)
Ejemplo n.º 19
0
 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
Ejemplo n.º 21
0
    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)
Ejemplo n.º 22
0
    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)
Ejemplo n.º 23
0
 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)
Ejemplo n.º 24
0
 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)
Ejemplo n.º 25
0
    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)
Ejemplo n.º 26
0
 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")
Ejemplo n.º 27
0
 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)
Ejemplo n.º 28
0
 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)
Ejemplo n.º 29
0
 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]
Ejemplo n.º 30
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()