From 56fa454fdd229524999127a5b89cc7c9077b9bd6 Mon Sep 17 00:00:00 2001 From: Jason Gerard DeRose Date: Tue, 5 Aug 2008 06:33:09 +0000 Subject: [PATCH] 47: Added plugable.check_identifier() function; added corresponding unit tests --- ipalib/errors.py | 5 ++++- ipalib/plugable.py | 11 +++++++++++ ipalib/tests/test_plugable.py | 24 ++++++++++++++++++++++++ 3 files changed, 39 insertions(+), 1 deletion(-) diff --git a/ipalib/errors.py b/ipalib/errors.py index 53a0870e6..e9f784773 100644 --- a/ipalib/errors.py +++ b/ipalib/errors.py @@ -56,13 +56,16 @@ class SetError(IPAError): - class RegistrationError(IPAError): """ Base class for errors that occur during plugin registration. """ +class NameSpaceError(RegistrationError): + msg = 'name %r does not re.match %r' + + class SubclassError(RegistrationError): """ Raised when registering a plugin that is not a subclass of one of the diff --git a/ipalib/plugable.py b/ipalib/plugable.py index 70743f5a2..8f2cbc27a 100644 --- a/ipalib/plugable.py +++ b/ipalib/plugable.py @@ -21,6 +21,7 @@ Utility classes for registering plugins, base classes for writing plugins. """ +import re import inspect import errors @@ -43,6 +44,16 @@ def from_cli(cli_name): return cli_name.replace('-', '_').replace('.', '__') +def check_identifier(name): + """ + Raises errors.NameSpaceError if `name` is not a valid Python identifier + suitable for use in a NameSpace. + """ + regex = r'^[a-z][_a-z0-9]*[a-z0-9]$' + if re.match(regex, name) is None: + raise errors.NameSpaceError(name, regex) + + class Plugin(object): """ Base class for all plugins. diff --git a/ipalib/tests/test_plugable.py b/ipalib/tests/test_plugable.py index 2e87ea2c0..1fa34bd56 100644 --- a/ipalib/tests/test_plugable.py +++ b/ipalib/tests/test_plugable.py @@ -41,6 +41,30 @@ def test_from_cli(): assert f('meta-service.do-something') == 'meta_service__do_something' +def test_valid_identifier(): + f = plugable.check_identifier + okay = [ + 'user_add', + 'stuff2junk', + 'sixty9', + ] + nope = [ + '_user_add', + '__user_add', + 'user_add_', + 'user_add__', + '_user_add_', + '__user_add__', + '60nine', + ] + for name in okay: + f(name) + for name in nope: + raises(errors.NameSpaceError, f, name) + for name in okay: + raises(errors.NameSpaceError, f, name.upper()) + + def test_Plugin(): api = 'the api instance' p = plugable.Plugin()