Merge "normalize_name helper"
This commit is contained in:
commit
333d1109d9
@ -14,6 +14,7 @@
|
||||
|
||||
import importlib
|
||||
import pkgutil
|
||||
import re
|
||||
import sys
|
||||
|
||||
import pbr.version
|
||||
@ -107,3 +108,22 @@ def is_custom(trait):
|
||||
:param trait: String name of the trait
|
||||
"""
|
||||
return trait.startswith(CUSTOM_NAMESPACE)
|
||||
|
||||
|
||||
def normalize_name(name):
|
||||
"""Converts an input string to a legal* custom trait name.
|
||||
|
||||
Legal custom trait names are prefixed with CUSTOM_ and contain only the
|
||||
characters A-Z, 0-9, and _ (underscore).
|
||||
|
||||
*Does not attempt to handle length restrictions.
|
||||
|
||||
:param name: A string to be converted.
|
||||
:return: A legal* custom trait name.
|
||||
"""
|
||||
if name is None:
|
||||
return None
|
||||
# Replace non-alphanumeric characters with underscores
|
||||
norm_name = re.sub('[^0-9A-Za-z]+', '_', name)
|
||||
# Bug #1762789: Do .upper after replacing non alphanumerics.
|
||||
return CUSTOM_NAMESPACE + norm_name.upper()
|
||||
|
@ -107,3 +107,20 @@ class TestSymbols(base.TestCase):
|
||||
match = valid_name.match(t)
|
||||
if not match:
|
||||
self.fail("Trait %s does not validate name regex." % t)
|
||||
|
||||
def test_normalize_name(self):
|
||||
values = [
|
||||
("foo", "CUSTOM_FOO"),
|
||||
("VCPU", "CUSTOM_VCPU"),
|
||||
("CUSTOM_BOB", "CUSTOM_CUSTOM_BOB"),
|
||||
("CUSTM_BOB", "CUSTOM_CUSTM_BOB"),
|
||||
(u"Fu\xdfball", u"CUSTOM_FU_BALL"),
|
||||
("abc-123", "CUSTOM_ABC_123"),
|
||||
("Hello, world! This is a test ^_^",
|
||||
"CUSTOM_HELLO_WORLD_THIS_IS_A_TEST_"),
|
||||
(" leading and trailing spaces ",
|
||||
"CUSTOM__LEADING_AND_TRAILING_SPACES_"),
|
||||
]
|
||||
for test_value, expected in values:
|
||||
result = ot.normalize_name(test_value)
|
||||
self.assertEqual(expected, result)
|
||||
|
Loading…
Reference in New Issue
Block a user