コード例 #1
0
    def test_get_network_id_by_label(self):
        """Tests the get_net_id_by_label function."""
        net = mock.MagicMock()
        net.id = str(uuid.uuid4())
        self.nova_client.networks.find.side_effect = [
            net,
            nova_exceptions.NotFound(404),
            nova_exceptions.NoUniqueMatch()
        ]
        self.assertEqual(net.id,
                         self.nova_plugin.get_net_id_by_label('net_label'))

        exc = self.assertRaises(exception.EntityNotFound,
                                self.nova_plugin.get_net_id_by_label,
                                'idontexist')
        expected = 'The Nova network (idontexist) could not be found'
        self.assertIn(expected, six.text_type(exc))
        exc = self.assertRaises(exception.PhysicalResourceNameAmbiguity,
                                self.nova_plugin.get_net_id_by_label,
                                'notUnique')
        expected = ('Multiple physical resources were found '
                    'with name (notUnique)')
        self.assertIn(expected, six.text_type(exc))
        calls = [
            mock.call(label='net_label'),
            mock.call(label='idontexist'),
            mock.call(label='notUnique')
        ]
        self.nova_client.networks.find.assert_has_calls(calls)
コード例 #2
0
ファイル: test_nova_client.py プロジェクト: kanaka/heat
    def test_get_network_id_by_label(self):
        """Tests the get_net_id_by_label function."""
        net = self.m.CreateMockAnything()
        net.id = str(uuid.uuid4())
        self.nova_client.networks = self.m.CreateMockAnything()
        self.nova_client.networks.find(label='net_label').AndReturn(net)
        self.nova_client.networks.find(label='idontexist').AndRaise(
            nova_exceptions.NotFound(404))
        self.nova_client.networks.find(label='notUnique').AndRaise(
            nova_exceptions.NoUniqueMatch())
        self.m.ReplayAll()
        self.assertEqual(net.id,
                         self.nova_plugin.get_net_id_by_label('net_label'))

        exc = self.assertRaises(exception.NovaNetworkNotFound,
                                self.nova_plugin.get_net_id_by_label,
                                'idontexist')
        expected = 'The Nova network (idontexist) could not be found'
        self.assertIn(expected, six.text_type(exc))
        exc = self.assertRaises(exception.PhysicalResourceNameAmbiguity,
                                self.nova_plugin.get_net_id_by_label,
                                'notUnique')
        expected = ('Multiple physical resources were found '
                    'with name (notUnique)')
        self.assertIn(expected, six.text_type(exc))
        self.m.VerifyAll()
コード例 #3
0
    def test_validate(self):
        client = fakes_nova.FakeClient()
        self.stub_keystoneclient()
        self.patchobject(nova.NovaClientPlugin, '_create', return_value=client)
        client.networks = mock.Mock()

        network = collections.namedtuple("Network", ['id', 'label'])
        network.id = '7f47ff06-0353-4013-b814-123b70b1b27d'
        network.label = 'foo'
        client.networks.get.return_value = network

        constraint = nova.NetworkConstraint()
        ctx = utils.dummy_context()

        self.assertTrue(constraint.validate(network.id, ctx))
        client.networks.get.side_effect = nova_exceptions.NotFound('')
        client.networks.find.return_value = network
        self.assertTrue(constraint.validate(network.id, ctx))

        client.networks.find.side_effect = nova_exceptions.NotFound('')
        self.assertFalse(constraint.validate(network.id, ctx))

        client.networks.find.side_effect = nova_exceptions.NoUniqueMatch()
        self.assertFalse(constraint.validate(network.id, ctx))

        network.id = 'nonuuid'
        client.networks.find.return_value = network
        client.networks.find.side_effect = None
        self.assertTrue(constraint.validate(network.id, ctx))
コード例 #4
0
ファイル: images.py プロジェクト: songhao8080/nova-client
    def find_image(self, name_or_id):
        """Find an image by name or id (user provided input)."""

        with self.alternate_service_type('image', allowed_types=('image', )):
            # glance catalog entries are the unversioned endpoint, so
            # we need to jam a version bit in here.
            if uuidutils.is_uuid_like(name_or_id):
                # if it's a uuid, then just go collect the info and be
                # done with it.
                return self._get('/v2/images/%s' % name_or_id, None)
            else:
                matches = self._list('/v2/images?name=%s' % name_or_id,
                                     "images")
                num_matches = len(matches)
                if num_matches == 0:
                    msg = "No %s matching %s." % (self.resource_class.__name__,
                                                  name_or_id)
                    raise exceptions.NotFound(404, msg)
                elif num_matches > 1:
                    msg = (_("Multiple %(class)s matches found for "
                             "'%(name)s', use an ID to be more specific.") % {
                                 'class': self.resource_class.__name__.lower(),
                                 'name': name_or_id
                             })
                    raise exceptions.NoUniqueMatch(msg)
                else:
                    matches[0].append_request_ids(matches.request_ids)
                    return matches[0]
コード例 #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)
コード例 #6
0
ファイル: utils.py プロジェクト: UTSA-ICS/novaclient-kerberos
def get_resource_manager_extra_kwargs(f, args, allow_conflicts=False):
    """Return extra_kwargs by calling resource manager kwargs hooks."""
    hooks = getattr(f, "resource_manager_kwargs_hooks", [])
    extra_kwargs = {}
    for hook in hooks:
        hook_kwargs = hook(args)
        hook_name = hook.__name__
        conflicting_keys = set(hook_kwargs.keys()) & set(extra_kwargs.keys())
        if conflicting_keys and not allow_conflicts:
            msg = (_("Hook '%(hook_name)s' is attempting to redefine "
                     "attributes '%(conflicting_keys)s'") %
                   {'hook_name': hook_name,
                    'conflicting_keys': conflicting_keys})
            raise exceptions.NoUniqueMatch(msg)

        extra_kwargs.update(hook_kwargs)

    return extra_kwargs
コード例 #7
0
    def find_network(self, name):
        """Find a network by name (user provided input)."""

        with self.alternate_service_type(
                'network', allowed_types=('network',)):

            matches = self._list('/v2.0/networks?name=%s' % name, 'networks')

            num_matches = len(matches)
            if num_matches == 0:
                msg = "No %s matching %s." % (
                    self.resource_class.__name__, name)
                raise exceptions.NotFound(404, msg)
            elif num_matches > 1:
                msg = (_("Multiple %(class)s matches found for "
                         "'%(name)s', use an ID to be more specific.") %
                       {'class': self.resource_class.__name__.lower(),
                        'name': name})
                raise exceptions.NoUniqueMatch(msg)
            else:
                matches[0].append_request_ids(matches.request_ids)
                return matches[0]