Example #1
0
class PackageConfigurator(object):
    default_depth = 3

    def __init__(self, registry, resolve=None, target='includeme'):
        self.registry = registry
        self._resolve = resolve
        self._target = target
        self._depth = self.default_depth
        self._configurator_registry = Components()

    def add_configurator(self, configurator, name=''):
        self._configurator_registry.registerUtility(configurator, IConfigurator, name)

    def include(self, name, *args, **kwargs):
        _logger.debug('start include: name=%s, args=%s, kwds=%s', name, args, kwargs)
        includeme = name if callable(name) else get_includeme(name, resolve=self._resolve, depth=self._depth)
        _logger.debug('include -> %s.%s', includeme.__module__, includeme.__name__)
        return includeme(self)

    def scan(self, package=None, **kw):
        name = 'scan'
        if package is None:
            package = '.'

        if isinstance(package, (six.string_types, six.text_type, six.binary_type)):
            package = get_abs_dotted_name_caller_module(package, **kw)

        for cfg in self._configurator_registry.getAllUtilitiesRegisteredFor(IConfigurator):
            if hasattr(cfg, name) and callable(getattr(cfg, name)):
                _logger.debug('scanning...: %s: %s', cfg.__module__, package)
                cfg.scan(package)

    def __getattr__(self, name):
        if name.startswith('_'):
            raise AttributeError(name)

        configs = [cfg
                   for cfg in self._configurator_registry.getAllUtilitiesRegisteredFor(IConfigurator)
                   if hasattr(cfg, name) and callable(getattr(cfg, name))]

        if configs:
            for config in configs:
                return getattr(config, name)
        else:
            raise AttributeError(name)
Example #2
0
class PackageConfigurator(object):
    default_depth = 3

    def __init__(self, registry, resolve=None, target='includeme'):
        self.registry = registry
        self._resolve = resolve
        self._target = target
        self._depth = self.default_depth
        self._configurator_registry = Components()

    def add_configurator(self, configurator, name=''):
        self._configurator_registry.registerUtility(configurator,
                                                    IConfigurator, name)

    def include(self, name, *args, **kwargs):
        _logger.debug('start include: name=%s, args=%s, kwds=%s', name, args,
                      kwargs)
        includeme = name if callable(name) else get_includeme(
            name, resolve=self._resolve, depth=self._depth)
        _logger.debug('include -> %s.%s', includeme.__module__,
                      includeme.__name__)
        return includeme(self)

    def scan(self, package=None, **kw):
        name = 'scan'
        if package is None:
            package = '.'

        if isinstance(package,
                      (six.string_types, six.text_type, six.binary_type)):
            package = get_abs_dotted_name_caller_module(package, **kw)

        for cfg in self._configurator_registry.getAllUtilitiesRegisteredFor(
                IConfigurator):
            if hasattr(cfg, name) and callable(getattr(cfg, name)):
                _logger.debug('scanning...: %s: %s', cfg.__module__, package)
                cfg.scan(package)

    def __getattr__(self, name):
        if name.startswith('_'):
            raise AttributeError(name)

        configs = [
            cfg for cfg in self._configurator_registry.
            getAllUtilitiesRegisteredFor(IConfigurator)
            if hasattr(cfg, name) and callable(getattr(cfg, name))
        ]

        if configs:
            for config in configs:
                return getattr(config, name)
        else:
            raise AttributeError(name)
Example #3
0
bar = Bar()
assert IFoo.providedBy(bar)
assert IBaz.providedBy(bar)
assert zope.interface.verify.verifyObject(IBaz, bar)

bob = Bazz('bob')
ted = Bazz('ted')

registry.registerUtility(bob)
assert registry.queryUtility(IBaz) == bob

registry.registerUtility(ted, IBaz, name='ted')
assert registry.queryUtility(IFoo, 'ted') == ted

assert registry.getAllUtilitiesRegisteredFor(IBaz) == [bob, ted]


# adapter
class IGreeter(zope.interface.Interface):
    def greet():
        """Greet someone."""


class IPerson(zope.interface.Interface):
    name = zope.interface.Attribute("Name")


@zope.interface.implementer(IPerson)
class Person:
    def __init__(self, name):
Example #4
0
class TestUtility(unittest.TestCase):

    def setUp(self):
        self.components = Components('comps')

    def test_register_utility(self):
        test_object = U1(1)
        self.components.registerUtility(test_object)
        self.assertEqual(self.components.getUtility(I1), test_object)

    def test_register_utility_with_factory(self):
        test_object = U1(1)
        def factory():
           return test_object
        self.components.registerUtility(factory=factory)
        self.assertEqual(self.components.getUtility(I1), test_object)
        self.assertTrue(self.components.unregisterUtility(factory=factory))

    def test_register_utility_with_component_and_factory(self):
        def factory():
            return U1(1)
        self.assertRaises(
            TypeError,
            self.components.registerUtility, U1(1), factory=factory)

    def test_unregister_utility_with_and_without_component_and_factory(self):
        def factory():
            return U1(1)
        self.assertRaises(
            TypeError,
            self.components.unregisterUtility, U1(1), factory=factory)
        self.assertRaises(TypeError, self.components.unregisterUtility)

    def test_register_utility_with_no_interfaces(self):
        self.assertRaises(TypeError, self.components.registerUtility, A)

    def test_register_utility_with_two_interfaces(self):
        self.assertRaises(TypeError, self.components.registerUtility, U12(1))

    def test_register_utility_with_arguments(self):
        test_object1 = U12(1)
        test_object2 = U12(2)
        self.components.registerUtility(test_object1, I2)
        self.components.registerUtility(test_object2, I2, 'name')
        self.assertEqual(self.components.getUtility(I2), test_object1)
        self.assertEqual(self.components.getUtility(I2, 'name'), test_object2)

    def test_get_none_existing_utility(self):
        from zope.interface.interfaces import ComponentLookupError
        self.assertRaises(ComponentLookupError, self.components.getUtility, I3)

    def test_query_none_existing_utility(self):
        self.assertTrue(self.components.queryUtility(I3) is None)
        self.assertEqual(self.components.queryUtility(I3, default=42), 42)

    def test_registered_utilities_and_sorting(self):
        test_object1 = U1(1)
        test_object2 = U12(2)
        test_object3 = U12(3)
        self.components.registerUtility(test_object1)
        self.components.registerUtility(test_object3, I2, u'name')
        self.components.registerUtility(test_object2, I2)

        sorted_utilities = sorted(self.components.registeredUtilities())
        sorted_utilities_name = map(lambda x: getattr(x, 'name'),
                                    sorted_utilities)
        sorted_utilities_component = map(lambda x: getattr(x, 'component'),
                                         sorted_utilities)
        sorted_utilities_provided = map(lambda x: getattr(x, 'provided'),
                                        sorted_utilities)

        self.assertEqual(len(sorted_utilities), 3)
        self.assertEqual(sorted_utilities_name, [u'', u'', u'name'])
        self.assertEqual(
            sorted_utilities_component,
            [test_object1, test_object2, test_object3])
        self.assertEqual(sorted_utilities_provided, [I1, I2, I2])

    def test_duplicate_utility(self):
        test_object1 = U1(1)
        test_object2 = U12(2)
        test_object3 = U12(3)
        test_object4 = U1(4)
        self.components.registerUtility(test_object1)
        self.components.registerUtility(test_object2, I2)
        self.components.registerUtility(test_object3, I2, u'name')
        self.assertEqual(self.components.getUtility(I1), test_object1)

        self.components.registerUtility(test_object4, info=u'use 4 now')
        self.assertEqual(self.components.getUtility(I1), test_object4)

    def test_unregister_utility(self):
        test_object = U1(1)
        self.components.registerUtility(test_object)
        self.assertEqual(self.components.getUtility(I1), test_object)
        self.assertTrue(self.components.unregisterUtility(provided=I1))
        self.assertFalse(self.components.unregisterUtility(provided=I1))

    def test_unregister_utility_extended(self):
        test_object = U1(1)
        self.components.registerUtility(test_object)
        self.assertFalse(self.components.unregisterUtility(U1(1)))
        self.assertEqual(self.components.queryUtility(I1), test_object)
        self.assertTrue(self.components.unregisterUtility(test_object))
        self.assertTrue(self.components.queryUtility(I1) is None)

    def test_get_utilities_for(self):
        test_object1 = U1(1)
        test_object2 = U12(2)
        test_object3 = U12(3)
        self.components.registerUtility(test_object1)
        self.components.registerUtility(test_object2, I2)
        self.components.registerUtility(test_object3, I2, u'name')

        sorted_utilities = sorted(self.components.getUtilitiesFor(I2))
        self.assertEqual(len(sorted_utilities), 2)
        self.assertEqual(sorted_utilities[0], (u'', test_object2))
        self.assertEqual(sorted_utilities[1], (u'name', test_object3))

    def test_get_all_utilities_registered_for(self):
        test_object1 = U1(1)
        test_object2 = U12(2)
        test_object3 = U12(3)
        test_object4 = U('ext')
        self.components.registerUtility(test_object1)
        self.components.registerUtility(test_object2, I2)
        self.components.registerUtility(test_object3, I2, u'name')
        self.components.registerUtility(test_object4, I2e)

        sorted_utilities = sorted(self.components.getUtilitiesFor(I2))
        self.assertEqual(len(sorted_utilities), 2)
        self.assertEqual(sorted_utilities[0], (u'', test_object2))
        self.assertEqual(sorted_utilities[1], (u'name', test_object3))

        all_utilities = self.components.getAllUtilitiesRegisteredFor(I2)
        self.assertEqual(len(all_utilities), 3)
        self.assertTrue(test_object2 in all_utilities)
        self.assertTrue(test_object3 in all_utilities)
        self.assertTrue(test_object4 in all_utilities)

        self.assertTrue(self.components.unregisterUtility(test_object4, I2e))
        self.assertEqual(self.components.getAllUtilitiesRegisteredFor(I2e), [])

    def test_utility_events(self):
        from zope.event import subscribers
        old_subscribers = subscribers[:]
        subscribers[:] = []

        test_object = U1(1)
        def log_event(event):
            self.assertEqual(event.object.component, test_object)
        subscribers.append(log_event)
        self.components.registerUtility(test_object)

        subscribers[:] = old_subscribers

    def test_dont_leak_utility_registrations_in__subscribers(self):
        """
        We've observed utilities getting left in _subscribers when they
        get unregistered.

        """
        class C:
            def __init__(self, name):
                self.name = name
            def __repr__(self):
                return "C(%s)" % self.name

        c1 = C(1)
        c2 = C(2)

        self.components.registerUtility(c1, I1)
        self.components.registerUtility(c1, I1)
        utilities = list(self.components.getAllUtilitiesRegisteredFor(I1))
        self.assertEqual(len(utilities), 1)
        self.assertEqual(utilities[0], c1)

        self.assertTrue(self.components.unregisterUtility(provided=I1))
        utilities = list(self.components.getAllUtilitiesRegisteredFor(I1))
        self.assertEqual(len(utilities), 0)

        self.components.registerUtility(c1, I1)
        self.components.registerUtility(c2, I1)

        utilities = list(self.components.getAllUtilitiesRegisteredFor(I1))
        self.assertEqual(len(utilities), 1)
        self.assertEqual(utilities[0], c2)
Example #5
0
class TestUtility(unittest.TestCase):
    def setUp(self):
        self.components = Components('comps')

    def test_register_utility(self):
        test_object = U1(1)
        self.components.registerUtility(test_object)
        self.assertEqual(self.components.getUtility(I1), test_object)

    def test_register_utility_with_factory(self):
        test_object = U1(1)

        def factory():
            return test_object

        self.components.registerUtility(factory=factory)
        self.assertEqual(self.components.getUtility(I1), test_object)
        self.assertTrue(self.components.unregisterUtility(factory=factory))

    def test_register_utility_with_component_and_factory(self):
        def factory():
            return U1(1)

        self.assertRaises(TypeError,
                          self.components.registerUtility,
                          U1(1),
                          factory=factory)

    def test_unregister_utility_with_and_without_component_and_factory(self):
        def factory():
            return U1(1)

        self.assertRaises(TypeError,
                          self.components.unregisterUtility,
                          U1(1),
                          factory=factory)
        self.assertRaises(TypeError, self.components.unregisterUtility)

    def test_register_utility_with_no_interfaces(self):
        self.assertRaises(TypeError, self.components.registerUtility, A)

    def test_register_utility_with_two_interfaces(self):
        self.assertRaises(TypeError, self.components.registerUtility, U12(1))

    def test_register_utility_with_arguments(self):
        test_object1 = U12(1)
        test_object2 = U12(2)
        self.components.registerUtility(test_object1, I2)
        self.components.registerUtility(test_object2, I2, 'name')
        self.assertEqual(self.components.getUtility(I2), test_object1)
        self.assertEqual(self.components.getUtility(I2, 'name'), test_object2)

    def test_get_none_existing_utility(self):
        from zope.interface.interfaces import ComponentLookupError
        self.assertRaises(ComponentLookupError, self.components.getUtility, I3)

    def test_query_none_existing_utility(self):
        self.assertTrue(self.components.queryUtility(I3) is None)
        self.assertEqual(self.components.queryUtility(I3, default=42), 42)

    def test_registered_utilities_and_sorting(self):
        test_object1 = U1(1)
        test_object2 = U12(2)
        test_object3 = U12(3)
        self.components.registerUtility(test_object1)
        self.components.registerUtility(test_object3, I2, u'name')
        self.components.registerUtility(test_object2, I2)

        sorted_utilities = sorted(self.components.registeredUtilities())
        sorted_utilities_name = map(lambda x: getattr(x, 'name'),
                                    sorted_utilities)
        sorted_utilities_component = map(lambda x: getattr(x, 'component'),
                                         sorted_utilities)
        sorted_utilities_provided = map(lambda x: getattr(x, 'provided'),
                                        sorted_utilities)

        self.assertEqual(len(sorted_utilities), 3)
        self.assertEqual(sorted_utilities_name, [u'', u'', u'name'])
        self.assertEqual(sorted_utilities_component,
                         [test_object1, test_object2, test_object3])
        self.assertEqual(sorted_utilities_provided, [I1, I2, I2])

    def test_duplicate_utility(self):
        test_object1 = U1(1)
        test_object2 = U12(2)
        test_object3 = U12(3)
        test_object4 = U1(4)
        self.components.registerUtility(test_object1)
        self.components.registerUtility(test_object2, I2)
        self.components.registerUtility(test_object3, I2, u'name')
        self.assertEqual(self.components.getUtility(I1), test_object1)

        self.components.registerUtility(test_object4, info=u'use 4 now')
        self.assertEqual(self.components.getUtility(I1), test_object4)

    def test_unregister_utility(self):
        test_object = U1(1)
        self.components.registerUtility(test_object)
        self.assertEqual(self.components.getUtility(I1), test_object)
        self.assertTrue(self.components.unregisterUtility(provided=I1))
        self.assertFalse(self.components.unregisterUtility(provided=I1))

    def test_unregister_utility_extended(self):
        test_object = U1(1)
        self.components.registerUtility(test_object)
        self.assertFalse(self.components.unregisterUtility(U1(1)))
        self.assertEqual(self.components.queryUtility(I1), test_object)
        self.assertTrue(self.components.unregisterUtility(test_object))
        self.assertTrue(self.components.queryUtility(I1) is None)

    def test_get_utilities_for(self):
        test_object1 = U1(1)
        test_object2 = U12(2)
        test_object3 = U12(3)
        self.components.registerUtility(test_object1)
        self.components.registerUtility(test_object2, I2)
        self.components.registerUtility(test_object3, I2, u'name')

        sorted_utilities = sorted(self.components.getUtilitiesFor(I2))
        self.assertEqual(len(sorted_utilities), 2)
        self.assertEqual(sorted_utilities[0], (u'', test_object2))
        self.assertEqual(sorted_utilities[1], (u'name', test_object3))

    def test_get_all_utilities_registered_for(self):
        test_object1 = U1(1)
        test_object2 = U12(2)
        test_object3 = U12(3)
        test_object4 = U('ext')
        self.components.registerUtility(test_object1)
        self.components.registerUtility(test_object2, I2)
        self.components.registerUtility(test_object3, I2, u'name')
        self.components.registerUtility(test_object4, I2e)

        sorted_utilities = sorted(self.components.getUtilitiesFor(I2))
        self.assertEqual(len(sorted_utilities), 2)
        self.assertEqual(sorted_utilities[0], (u'', test_object2))
        self.assertEqual(sorted_utilities[1], (u'name', test_object3))

        all_utilities = self.components.getAllUtilitiesRegisteredFor(I2)
        self.assertEqual(len(all_utilities), 3)
        self.assertTrue(test_object2 in all_utilities)
        self.assertTrue(test_object3 in all_utilities)
        self.assertTrue(test_object4 in all_utilities)

        self.assertTrue(self.components.unregisterUtility(test_object4, I2e))
        self.assertEqual(self.components.getAllUtilitiesRegisteredFor(I2e), [])

    def test_utility_events(self):
        from zope.event import subscribers
        old_subscribers = subscribers[:]
        subscribers[:] = []

        test_object = U1(1)

        def log_event(event):
            self.assertEqual(event.object.component, test_object)

        subscribers.append(log_event)
        self.components.registerUtility(test_object)

        subscribers[:] = old_subscribers

    def test_dont_leak_utility_registrations_in__subscribers(self):
        """
        We've observed utilities getting left in _subscribers when they
        get unregistered.

        """
        class C:
            def __init__(self, name):
                self.name = name

            def __repr__(self):
                return "C(%s)" % self.name

        c1 = C(1)
        c2 = C(2)

        self.components.registerUtility(c1, I1)
        self.components.registerUtility(c1, I1)
        utilities = list(self.components.getAllUtilitiesRegisteredFor(I1))
        self.assertEqual(len(utilities), 1)
        self.assertEqual(utilities[0], c1)

        self.assertTrue(self.components.unregisterUtility(provided=I1))
        utilities = list(self.components.getAllUtilitiesRegisteredFor(I1))
        self.assertEqual(len(utilities), 0)

        self.components.registerUtility(c1, I1)
        self.components.registerUtility(c2, I1)

        utilities = list(self.components.getAllUtilitiesRegisteredFor(I1))
        self.assertEqual(len(utilities), 1)
        self.assertEqual(utilities[0], c2)