def find(
        self,
        path,
        value=None,
        attr=None,
    ):
        """Find a single resource by name or ID

        :param string path:
            The API-specific portion of the URL path
        :param string search:
            search expression
        :param string attr:
            name of attribute for secondary search
        """

        try:
            ret = self._request('GET', "/%s/%s" % (path, value)).json()
        except ksc_exceptions.NotFound:
            kwargs = {attr: value}
            try:
                ret = self.find_one("/%s/detail" % (path), **kwargs)
            except ksc_exceptions.NotFound:
                msg = "%s not found" % value
                raise ksc_exceptions.NotFound(msg)

        return ret
示例#2
0
 def test_delete_trust_not_found(self, mock_ks):
     mock_delete = mock_ks.return_value.trusts.delete
     mock_delete.side_effect = kc_exception.NotFound()
     ks_client = keystone.KeystoneClientV3(self.ctx)
     bay = mock.MagicMock()
     bay.trust_id = 'atrust123'
     self.assertIsNone(ks_client.delete_trust(self.ctx, bay))
    def setUp(self):
        super(TestServiceShow, self).setUp()

        self.services_mock.get.side_effect = identity_exc.NotFound(None)
        self.services_mock.find.return_value = self.service

        # Get the command object to test
        self.cmd = service.ShowService(self.app, None)
示例#4
0
 def find(self, name=None):
     if name == '9999':
         # NOTE(morganfainberg): special case that raises NoUniqueMatch.
         raise exceptions.NoUniqueMatch()
     for resource_id, resource in self.resources.items():
         if resource['name'] == str(name):
             return resource
     raise exceptions.NotFound(name)
    def setUp(self):
        super(TestServiceDelete, self).setUp()

        self.services_mock.get.side_effect = identity_exc.NotFound(None)
        self.services_mock.find.return_value = self.fake_service
        self.services_mock.delete.return_value = None

        # Get the command object to test
        self.cmd = service.DeleteService(self.app, None)
示例#6
0
def tenant_get(request, project, admin=True):
    if not uuidutils.is_uuid_like(project):
        raise keystone_exceptions.NotFound()

    manager = VERSIONS.get_project_manager(request, admin=admin)
    try:
        return manager.get(project)
    except keystone_exceptions.NotFound:
        LOG.info("Tenant '%s' not found.", project)
        raise
 def test_keystone_init_occ(self, mock_gkc, mock_init, mock_se, mock_gp):
     mock_ksc = mock.Mock()
     mock_gkc.return_value = mock_ksc
     mock_ksc.users.find.side_effect = kscexc.NotFound()
     sips = mock.Mock()
     sips.get.return_value = None
     ip = '192.0.2.1'
     args = mock.Mock()
     overcloud_deploy.DeployOvercloud(None, None)._keystone_init(
         ip, ip, args, sips)
     self.assertTrue(mock_init.called)
 def test_keystone_init_occ(self, mock_gkc, mock_init, mock_se, mock_gp):
     mock_ksc = mock.Mock()
     mock_gkc.return_value = mock_ksc
     mock_ksc.services.find.side_effect = kscexc.NotFound()
     stack = mock.Mock()
     stack.to_dict.return_value = fakes.FAKE_STACK
     ip = '192.0.2.1'
     args = mock.Mock()
     overcloud_deploy.DeployOvercloud(None, None)._keystone_init(
         ip, ip, args, stack)
     self.assertTrue(mock_init.called)
示例#9
0
 def test_create_admin_user_user_does_not_exist(self):
     self._patch_client()
     self.client.users.find.side_effect = exceptions.NotFound()
     keystone._create_admin_user(self.client, '*****@*****.**',
                                 'adminpasswd')
     self.client.tenants.find.assert_called_once_with(name='admin')
     self.client.users.create.assert_called_once_with(
         'admin',
         email='*****@*****.**',
         password='******',
         tenant_id=self.client.tenants.find.return_value.id)
示例#10
0
def _find_user(keystone, email=None, username=None):
    if email:
        user = keystone.users.find(name=email)
        return user
    elif username:
        user_list = keystone.users.list()
        for user in user_list:
            if hasattr(user, 'username') and user.username == username:
                return user
        # consistent behaviour with the keystoneclient api
        msg = "No user matching email=%s." % email
        raise ks_exceptions.NotFound(404, msg)
示例#11
0
    def find(self, **kwargs):
        """
        Find a single item with attributes matching ``**kwargs``.

        This isn't very efficient: it loads the entire list then filters on
        the Python side.
        """
        rl = self.findall(**kwargs)
        try:
            return rl[0]
        except IndexError:
            msg = "No %s matching %s." % (self.resource_class.__name__, kwargs)
            raise exceptions.NotFound(404, msg)
示例#12
0
def get_rule_id_from_name(client, parsed_args):
    results = client.list_policy_rules(parsed_args.policy_name)['results']
    rule_id = None
    for result in results:
        if result.get('name') == parsed_args.rule_id:
            if rule_id is None:
                rule_id = result.get('id')
            else:
                raise exceptions.Conflict(
                    "[Multiple rules with same name: %s]" %
                    parsed_args.rule_id)
    if rule_id is None:
        raise exceptions.NotFound("[No rule found with name: %s]" %
                                  parsed_args.rule_id)
    return rule_id
示例#13
0
    def find(self, **kwargs):
        """Find a single item with attributes matching ``**kwargs``.

        This isn't very efficient: it loads the entire list then filters on
        the Python side.
        """
        rl = self.findall(**kwargs)
        num = len(rl)

        if num == 0:
            msg = "No %s matching %s." % (self.resource_class.__name__, kwargs)
            raise exceptions.NotFound(404, msg)
        elif num > 1:
            raise exceptions.NoUniqueMatch
        else:
            return rl[0]
示例#14
0
 def get_version(self):
     if self._discover:
         for v in KeystoneVersionDiscover.supported_versions:
             try:
                 rsp = self._discover._calculate_version(v, unstable=False)
             except KeystoneExceptions.VersionNotAvailable as e:
                 self.log.debug(str(e))
                 self.log.info("Keystone API version %d not available",
                               v[0])
             else:
                 (major, minor) = rsp['version']
                 self.log.info(
                     "Found Keystone API major version: %d, minor version: %d",
                     major, minor)
                 return major, minor
     raise KeystoneExceptions.NotFound(
         "No supported keystone API version found")
示例#15
0
    def find(self, **kwargs):
        """Find a single item with attributes matching ``**kwargs``."""
        url = self.build_url(dict_args_in_out=kwargs)

        rl = self._list(
            '%(url)s%(query)s' % {
                'url': url,
                'query': '?%s' % urllib.urlencode(kwargs) if kwargs else '',
            }, self.collection_key)
        num = len(rl)

        if num == 0:
            msg = "No %s matching %s." % (self.resource_class.__name__, kwargs)
            raise exceptions.NotFound(404, msg)
        elif num > 1:
            raise exceptions.NoUniqueMatch
        else:
            return rl[0]
    def find_one(self, path, **kwargs):
        """Find a resource by name or ID

        :param string path:
            The API-specific portion of the URL path
        :returns:
            resource dict
        """

        bulk_list = self.find_bulk(path, **kwargs)
        num_bulk = len(bulk_list)
        if num_bulk == 0:
            msg = "none found"
            raise ksc_exceptions.NotFound(msg)
        elif num_bulk > 1:
            msg = "many found"
            raise RuntimeError(msg)
        return bulk_list[0]
示例#17
0
def find_by_name(object_name, objects, name, default=None):
    name_lower = name.lower()
    default_obj = None
    default_lower = default and default.lower()
    for obj in objects:
        obj_name = obj.name.lower()
        if obj_name == name_lower:
            return obj
        elif obj_name == default_lower:
            default_obj = obj
    LOG.warning('Object "%s" with name "%s" not found', object_name, name)
    if default_obj is not None:
        return default_obj
    else:
        if default is not None:
            LOG.warning('Could not find default "%s" with name "%s"',
                        object_name, default)
        raise ks_exceptions.NotFound(404,
                                     object_name + ' ' + name + ' not found!')
示例#18
0
文件: base.py 项目: darren-wang/ksc
    def find(self, **kwargs):
        """Find a single item with attributes matching ``**kwargs``."""
        url = self.build_url(dict_args_in_out=kwargs)

        query = self._build_query(kwargs)
        rl = self._list('%(url)s%(query)s' % {
            'url': url,
            'query': query,
        }, self.collection_key)
        num = len(rl)

        if num == 0:
            msg = _("No %(name)s matching %(kwargs)s.") % {
                'name': self.resource_class.__name__,
                'kwargs': kwargs
            }
            raise exceptions.NotFound(404, msg)
        elif num > 1:
            raise exceptions.NoUniqueMatch
        else:
            return rl[0]
示例#19
0
class TestIsNotFound(common.HeatTestCase):

    scenarios = [
        ('ceilometer_not_found', dict(
            is_not_found=True,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=False,
            plugin='ceilometer',
            exception=lambda: ceil_exc.HTTPNotFound(details='gone'),
        )),
        ('ceilometer_not_found_apiclient', dict(
            is_not_found=True,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=False,
            plugin='ceilometer',
            exception=lambda: c_a_exc.NotFound(details='gone'),
        )),
        ('ceilometer_exception', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=False,
            is_conflict=False,
            plugin='ceilometer',
            exception=lambda: Exception()
        )),
        ('ceilometer_overlimit', dict(
            is_not_found=False,
            is_over_limit=True,
            is_client_exception=True,
            is_conflict=False,
            plugin='ceilometer',
            exception=lambda: ceil_exc.HTTPOverLimit(details='over'),
        )),
        ('ceilometer_conflict', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=True,
            plugin='ceilometer',
            exception=lambda: ceil_exc.HTTPConflict(),
        )),
        ('cinder_not_found', dict(
            is_not_found=True,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=False,
            plugin='cinder',
            exception=lambda: cinder_exc.NotFound(code=404),
        )),
        ('cinder_exception', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=False,
            is_conflict=False,
            plugin='cinder',
            exception=lambda: Exception()
        )),
        ('cinder_overlimit', dict(
            is_not_found=False,
            is_over_limit=True,
            is_client_exception=True,
            is_conflict=False,
            plugin='cinder',
            exception=lambda: cinder_exc.OverLimit(code=413),
        )),
        ('cinder_conflict', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=True,
            plugin='cinder',
            exception=lambda: cinder_exc.ClientException(code=409),
        )),
        ('glance_not_found', dict(
            is_not_found=True,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=False,
            plugin='glance',
            exception=lambda: glance_exc.HTTPNotFound(details='gone'),
        )),
        ('glance_exception', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=False,
            is_conflict=False,
            plugin='glance',
            exception=lambda: Exception()
        )),
        ('glance_overlimit', dict(
            is_not_found=False,
            is_over_limit=True,
            is_client_exception=True,
            is_conflict=False,
            plugin='glance',
            exception=lambda: glance_exc.HTTPOverLimit(details='over'),
        )),
        ('glance_conflict', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=True,
            plugin='glance',
            exception=lambda: glance_exc.HTTPConflict(),
        )),
        ('heat_not_found', dict(
            is_not_found=True,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=False,
            plugin='heat',
            exception=lambda: heat_exc.HTTPNotFound(message='gone'),
        )),
        ('heat_exception', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=False,
            is_conflict=False,
            plugin='heat',
            exception=lambda: Exception()
        )),
        ('heat_overlimit', dict(
            is_not_found=False,
            is_over_limit=True,
            is_client_exception=True,
            is_conflict=False,
            plugin='heat',
            exception=lambda: heat_exc.HTTPOverLimit(message='over'),
        )),
        ('heat_conflict', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=True,
            plugin='heat',
            exception=lambda: heat_exc.HTTPConflict(),
        )),
        ('keystone_not_found', dict(
            is_not_found=True,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=False,
            plugin='keystone',
            exception=lambda: keystone_exc.NotFound(details='gone'),
        )),
        ('keystone_exception', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=False,
            is_conflict=False,
            plugin='keystone',
            exception=lambda: Exception()
        )),
        ('keystone_overlimit', dict(
            is_not_found=False,
            is_over_limit=True,
            is_client_exception=True,
            is_conflict=False,
            plugin='keystone',
            exception=lambda: keystone_exc.RequestEntityTooLarge(
                details='over'),
        )),
        ('keystone_conflict', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=True,
            plugin='keystone',
            exception=lambda: keystone_exc.Conflict(
                message='Conflict'),
        )),
        ('neutron_not_found', dict(
            is_not_found=True,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=False,
            plugin='neutron',
            exception=lambda: neutron_exc.NotFound,
        )),
        ('neutron_network_not_found', dict(
            is_not_found=True,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=False,
            plugin='neutron',
            exception=lambda: neutron_exc.NetworkNotFoundClient(),
        )),
        ('neutron_port_not_found', dict(
            is_not_found=True,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=False,
            plugin='neutron',
            exception=lambda: neutron_exc.PortNotFoundClient(),
        )),
        ('neutron_status_not_found', dict(
            is_not_found=True,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=False,
            plugin='neutron',
            exception=lambda: neutron_exc.NeutronClientException(
                status_code=404),
        )),
        ('neutron_exception', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=False,
            is_conflict=False,
            plugin='neutron',
            exception=lambda: Exception()
        )),
        ('neutron_overlimit', dict(
            is_not_found=False,
            is_over_limit=True,
            is_client_exception=True,
            is_conflict=False,
            plugin='neutron',
            exception=lambda: neutron_exc.NeutronClientException(
                status_code=413),
        )),
        ('neutron_conflict', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=True,
            plugin='neutron',
            exception=lambda: neutron_exc.Conflict(),
        )),
        ('nova_not_found', dict(
            is_not_found=True,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=False,
            is_unprocessable_entity=False,
            plugin='nova',
            exception=lambda: fakes_nova.fake_exception(),
        )),
        ('nova_exception', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=False,
            is_conflict=False,
            is_unprocessable_entity=False,
            plugin='nova',
            exception=lambda: Exception()
        )),
        ('nova_overlimit', dict(
            is_not_found=False,
            is_over_limit=True,
            is_client_exception=True,
            is_conflict=False,
            is_unprocessable_entity=False,
            plugin='nova',
            exception=lambda: fakes_nova.fake_exception(413),
        )),
        ('nova_unprocessable_entity', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=False,
            is_unprocessable_entity=True,
            plugin='nova',
            exception=lambda: fakes_nova.fake_exception(422),
        )),
        ('nova_conflict', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=True,
            is_unprocessable_entity=False,
            plugin='nova',
            exception=lambda: fakes_nova.fake_exception(409),
        )),
        ('swift_not_found', dict(
            is_not_found=True,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=False,
            plugin='swift',
            exception=lambda: swift_exc.ClientException(
                msg='gone', http_status=404),
        )),
        ('swift_exception', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=False,
            is_conflict=False,
            plugin='swift',
            exception=lambda: Exception()
        )),
        ('swift_overlimit', dict(
            is_not_found=False,
            is_over_limit=True,
            is_client_exception=True,
            is_conflict=False,
            plugin='swift',
            exception=lambda: swift_exc.ClientException(
                msg='ouch', http_status=413),
        )),
        ('swift_conflict', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=True,
            plugin='swift',
            exception=lambda: swift_exc.ClientException(
                msg='conflict', http_status=409),
        )),
        ('trove_not_found', dict(
            is_not_found=True,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=False,
            plugin='trove',
            exception=lambda: troveclient.exceptions.NotFound(message='gone'),
        )),
        ('trove_exception', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=False,
            is_conflict=False,
            plugin='trove',
            exception=lambda: Exception()
        )),
        ('trove_overlimit', dict(
            is_not_found=False,
            is_over_limit=True,
            is_client_exception=True,
            is_conflict=False,
            plugin='trove',
            exception=lambda: troveclient.exceptions.RequestEntityTooLarge(
                message='over'),
        )),
        ('trove_conflict', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=True,
            plugin='trove',
            exception=lambda: troveclient.exceptions.Conflict(
                message='Conflict'),
        )),
        ('sahara_not_found', dict(
            is_not_found=True,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=False,
            plugin='sahara',
            exception=lambda: sahara_base.APIException(
                error_message='gone1', error_code=404),
        )),
        ('sahara_exception', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=False,
            is_conflict=False,
            plugin='sahara',
            exception=lambda: Exception()
        )),
        ('sahara_overlimit', dict(
            is_not_found=False,
            is_over_limit=True,
            is_client_exception=True,
            is_conflict=False,
            plugin='sahara',
            exception=lambda: sahara_base.APIException(
                error_message='over1', error_code=413),
        )),
        ('sahara_conflict', dict(
            is_not_found=False,
            is_over_limit=False,
            is_client_exception=True,
            is_conflict=True,
            plugin='sahara',
            exception=lambda: sahara_base.APIException(
                error_message='conflict1', error_code=409),
        )),
    ]

    def test_is_not_found(self):
        con = mock.Mock()
        c = clients.Clients(con)
        client_plugin = c.client_plugin(self.plugin)
        try:
            raise self.exception()
        except Exception as e:
            if self.is_not_found != client_plugin.is_not_found(e):
                raise

    def test_ignore_not_found(self):
        con = mock.Mock()
        c = clients.Clients(con)
        client_plugin = c.client_plugin(self.plugin)
        try:
            exp = self.exception()
            exp_class = exp.__class__
            raise exp
        except Exception as e:
            if self.is_not_found:
                client_plugin.ignore_not_found(e)
            else:
                self.assertRaises(exp_class,
                                  client_plugin.ignore_not_found,
                                  e)

    def test_ignore_conflict_and_not_found(self):
        con = mock.Mock()
        c = clients.Clients(con)
        client_plugin = c.client_plugin(self.plugin)
        try:
            exp = self.exception()
            exp_class = exp.__class__
            raise exp
        except Exception as e:
            if self.is_conflict or self.is_not_found:
                client_plugin.ignore_conflict_and_not_found(e)
            else:
                self.assertRaises(exp_class,
                                  client_plugin.ignore_conflict_and_not_found,
                                  e)

    def test_is_over_limit(self):
        con = mock.Mock()
        c = clients.Clients(con)
        client_plugin = c.client_plugin(self.plugin)
        try:
            raise self.exception()
        except Exception as e:
            if self.is_over_limit != client_plugin.is_over_limit(e):
                raise

    def test_is_client_exception(self):
        con = mock.Mock()
        c = clients.Clients(con)
        client_plugin = c.client_plugin(self.plugin)
        try:
            raise self.exception()
        except Exception as e:
            ice = self.is_client_exception
            actual = client_plugin.is_client_exception(e)
            if ice != actual:
                raise

    def test_is_conflict(self):
        con = mock.Mock()
        c = clients.Clients(con)
        client_plugin = c.client_plugin(self.plugin)
        try:
            raise self.exception()
        except Exception as e:
            if self.is_conflict != client_plugin.is_conflict(e):
                raise

    def test_is_unprocessable_entity(self):
        con = mock.Mock()
        c = clients.Clients(con)
        # only 'nova' client plugin need to check this exception
        if self.plugin == 'nova':
            client_plugin = c.client_plugin(self.plugin)
            try:
                raise self.exception()
            except Exception as e:
                iue = self.is_unprocessable_entity
                if iue != client_plugin.is_unprocessable_entity(e):
                    raise
示例#20
0
 def delete_stack_user(self, name):
     raise kc_exceptions.NotFound()
示例#21
0
 def find(self, name=None):
     for resource_id, resource in self.resources.items():
         if resource['name'] == str(name):
             return resource
     raise exceptions.NotFound(name)
示例#22
0
 def test_delete_trust_not_found(self, mock_ks):
     """Test delete_trust when trust already deleted."""
     mock_delete = mock_ks.return_value.trusts.delete
     mock_delete.side_effect = kc_exception.NotFound()
     solum_ks_client = solum_keystoneclient.KeystoneClientV3(self.ctx)
     self.assertIsNone(solum_ks_client.delete_trust(trust_id='atrust123'))
示例#23
0
def user_get(request, user_id, admin=True):
    if not uuidutils.is_uuid_like(user_id):
        raise keystone_exceptions.NotFound()

    user = keystoneclient(request, admin=admin).users.get(user_id)
    return VERSIONS.upgrade_v2_user(user)
示例#24
0
 def get(self, resource_id):
     try:
         return self.resources[str(resource_id)]
     except KeyError:
         raise exceptions.NotFound(resource_id)