Add flag for returning unofficial types

In consuming code in openstacksdk and keystoneauth, the pattern:

  if stm.is_official(service_type):
      return stm.get_service_type(service_type)
  return service_type

Gets used in several places. Let's provide a way to say that with a
flag:

  return std.get_service_type(service_type, permissive=True)

which says "get me the official service_type for this, but if it's not
something I know about, give me the thing the user asked for.

Change-Id: Ib8fb14a88ecc690da67967b7e906deb7d923f869
This commit is contained in:
Monty Taylor 2018-07-24 10:38:15 -05:00
parent a064fe49ed
commit 2441006a71
No known key found for this signature in database
GPG Key ID: 7BAE94BC7141A594
3 changed files with 23 additions and 1 deletions

View File

@ -31,3 +31,11 @@ class AliasUsageWarning(Warning):
Requested service_type {given} is an old alias. Please update your
code to reference the official service_type {official}.
"""
class UnofficialUsageWarning(Warning):
"""Use of unofficial service-types is discouraged."""
details = """
Requested service_type {given} is not a known official OpenStack project.
"""

View File

@ -208,16 +208,24 @@ class ServiceTypes(object):
service_type = _normalize_type(service_type)
return self._service_types_data['forward'].get(service_type, [])
def get_service_type(self, service_type):
def get_service_type(self, service_type, permissive=False):
"""Given a possible service_type, return the official type.
:param str service_type: A potential service-type.
:param bool permissive:
Return the original type if the given service_type is not found.
:returns str: The official service-type, or None if there is no match.
"""
service_type = _normalize_type(service_type)
if self.is_official(service_type):
return service_type
official = self._service_types_data['reverse'].get(service_type)
if permissive and official is None:
if self._warn:
exc.warn(
exc.UnofficialUsageWarning,
given=service_type)
return service_type
if self._warn:
exc.warn(
exc.AliasUsageWarning, given=service_type, official=official)

View File

@ -118,6 +118,12 @@ class ServiceDataMixin(object):
self.assertIsNone(
self.service_types.get_service_type(self.service_type))
def test_get_service_type_permissive(self):
self.assertEqual(
self.official or self.service_type,
self.service_types.get_service_type(
self.service_type, permissive=True))
def test_get_aliases(self):
self.assertEqual(
self.aliases,