basic ExtensionManager implementation

This commit is contained in:
Doug Hellmann 2012-06-19 15:05:03 -04:00
parent ea49b6a9e1
commit a4ad1e1074
4 changed files with 78 additions and 1 deletions

View File

@ -57,7 +57,12 @@ setup(
# only_in_packages=False,
# ),
entry_points={},
entry_points={
'stevedore.test.extension': [
't1 = stevedore.tests.test_extension:FauxExtension',
't2 = stevedore.tests.test_extension:FauxExtension',
],
},
zip_safe=False,
)

43
stevedore/extension.py Normal file
View File

@ -0,0 +1,43 @@
"""ExtensionManager
"""
import pkg_resources
import logging
LOG = logging.getLogger(__name__)
class Extension(object):
def __init__(self, name, entry_point, plugin, obj):
self.name = name
self.entry_point = entry_point
self.plugin = plugin
self.obj = obj
class ExtensionManager(object):
def __init__(self, namespace, invoke_on_load=False, invoke_args=(), invoke_kwds={}):
self.namespace = namespace
self.extensions = []
for ep in pkg_resources.iter_entry_points(self.namespace):
LOG.debug('found extension %r', ep.name)
try:
plugin = ep.load()
if invoke_on_load:
obj = plugin(ep.name, *invoke_args, **invoke_kwds)
else:
obj = None
except KeyboardInterrupt:
raise
except Exception as err:
LOG.error('Could not load %s: %s', ep.name, err)
else:
self.extensions.append(Extension(ep.name, ep, plugin, obj))
return
def names(self):
return [e.name for e in self.extensions]

View File

View File

@ -0,0 +1,29 @@
"""Tests for stevedore.extension
"""
from stevedore import extension
class FauxExtension(object):
def __init__(self, name, *args, **kwds):
self.name = name
self.args = args
self.kwds = kwds
def test_detect_plugins():
em = extension.ExtensionManager('stevedore.test.extension')
names = sorted(em.names())
assert names == ['t1', 't2']
def test_invoke_on_load():
em = extension.ExtensionManager('stevedore.test.extension',
invoke_on_load=True,
invoke_args=('a',),
invoke_kwds={'b': 'B'},
)
assert len(em.extensions) == 2
for e in em.extensions:
assert e.obj.args == ('a',)
assert e.obj.kwds == {'b': 'B'}