class JSON(object):

        def __init__(self, serializer=json.dumps, adapters=(), **kw):
            """ Any keyword arguments will be passed to the ``serializer``
            function."""
            self.serializer = serializer
            self.kw = kw
            self.components = Components()

        def add_adapter(self, type_or_iface, adapter):
            self.components.registerAdapter(adapter, (type_or_iface,),
                                            IJSONAdapter)

        def __call__(self, info):
            def _render(value, system):
                request = system.get('request')
                if request is not None:
                    response = request.response
                    ct = response.content_type
                    if ct == response.default_content_type:
                        response.content_type = 'application/json'
                default = self._make_default(request)
                return self.serializer(value, default=default, **self.kw)

            return _render

        def _make_default(self, request):
            def default(obj):
                obj_iface = providedBy(obj)
                adapters = self.components.adapters
                result = adapters.lookup((obj_iface,), IJSONAdapter,
                                         default=None)
                return result(obj, request)
            return default
Пример #2
0
 def test_nested(self):
     from zope.interface import Interface
     from zope.interface import implementer
     from zope.interface.registry import Components
     from guillotina.component import get_global_components
     from guillotina.component.tests.examples import ConformsToIComponentLookup
     class IFoo(Interface):
         pass
     class IBar(Interface):
         pass
     @implementer(IFoo)
     class Global(object):
         def __init__(self, context):
             self.context = context
     @implementer(IFoo)
     class Local(object):
         def __init__(self, context):
             self.context = context
     @implementer(IBar)
     class Bar(object):
         pass
     class Context(ConformsToIComponentLookup):
         def __init__(self, sm):
             self.sitemanager = sm
     gsm = get_global_components()
     gsm.registerAdapter(Global, (IBar,), IFoo, '')
     sm1 = Components('sm1', bases=(gsm, ))
     sm1.registerAdapter(Local, (IBar,), IFoo, '')
     bar = Bar()
     adapted = self._callFUT(bar, IFoo, '', context=Context(sm1))
     self.assertTrue(adapted.__class__ is Local)
     self.assertTrue(adapted.context is bar)
Пример #3
0
def initialize(packages=None, excludes=(), reg=None):
    """ Load memphis packages, scan and execute all configuration
    directives. """

    if reg is None:
        reg = Components('memphis')
        reg.registerHandler(objectEventNotify, (IObjectEvent,))

    sys.modules['memphis.config'].registry = reg
    sys.modules['memphis.config.api'].registry = reg

    def exclude_filter(modname):
        if modname in packages:
            return True
        return exclude(modname, excludes)

    # list all packages
    if packages is None:
        packages = loadPackages(excludes=excludes)
        packages.extend([mod for mod in mods if exclude_filter(mod)])
    else:
        packages = loadPackages(packages, excludes=excludes)

    # scan packages and load all actions
    seen = set()
    actions = []

    for pkg in packages:
        actions.extend(directives.scan(pkg, seen, exclude_filter))

    # execute actions
    actions = directives.resolveConflicts(actions)
    for action in actions:
        action()
Пример #4
0
 def __init__(self, package_name=CALLER_PACKAGE, *args, **kw):
     # add a registry-instance-specific lock, which is used when the lookup
     # cache is mutated
     self._lock = threading.Lock()
     if package_name is CALLER_PACKAGE:
         package_name = caller_package().__name__
     Components.__init__(self, package_name, *args, **kw)
Пример #5
0
 def __init__(self, *arg, **kw):
     # add a registry-instance-specific lock, which is used when the lookup
     # cache is mutated
     self._lock = threading.Lock()
     # add a view lookup cache
     self._clear_view_lookup_cache()
     Components.__init__(self, *arg, **kw)
Пример #6
0
 def test_hit_via_sm(self):
     from zope.interface import Interface
     from zope.interface import implementer
     from zope.interface.registry import Components
     from zope.component import getGlobalSiteManager
     from zope.component.tests.examples import ConformsToIComponentLookup
     class IFoo(Interface):
         pass
     class IBar(Interface):
         pass
     @implementer(IFoo)
     class Global(object):
         __init__ = fails_if_called(self)
     @implementer(IFoo)
     class Local(object):
         def __init__(self, context):
             self.context = context
     @implementer(IBar)
     class Bar(object):
         pass
     class Context(ConformsToIComponentLookup):
         def __init__(self, sm):
             self.sitemanager = sm
     gsm = getGlobalSiteManager()
     gsm.registerAdapter(Global, (IBar,), IFoo, '')
     sm1 = Components('sm1', bases=(gsm, ))
     sm1.registerAdapter(Local, (IBar,), IFoo, '')
     bar = Bar()
     adapted = self._callFUT(bar, IFoo, context=Context(sm1))
     self.assertTrue(adapted.__class__ is Local)
     self.assertTrue(adapted.context is bar)
Пример #7
0
 def __init__(self, *arg, **kw):
     # add a registry-instance-specific lock, which is used when the lookup
     # cache is mutated
     self._lock = threading.Lock()
     # add a view lookup cache
     self._clear_view_lookup_cache()
     Components.__init__(self, *arg, **kw)
    def test_hit_in_current_site(self):
        from zope.component._api import getSiteManager
        from zope.component.globalregistry import getGlobalSiteManager
        from zope.interface.registry import Components
        from zope.interface import Interface
        from zope.interface.interfaces import IInterface

        class ILocal(Interface):
            pass

        class IGlobal(Interface):
            pass

        gsm = getGlobalSiteManager()
        site_man = Components(bases=(gsm,))
        def get(_context=None):
            return site_man
        getSiteManager.sethook(get)
        self.addCleanup(getSiteManager.reset)


        gsm.registerUtility(IGlobal, IInterface, 'foo')
        site_man.registerUtility(ILocal, IInterface, 'bar')

        result = self._callFUT(None)
        self.assertEqual(len(result), 2)
        self.assertIn(ILocal, result)
        self.assertIn(IGlobal, result)

        getSiteManager.reset()

        result = self._callFUT(None)
        self.assertEqual(len(result), 1)
        self.assertIn(IGlobal, result)
Пример #9
0
 def test_init_forwards_kw(self):
     from zope.interface import Interface
     from zope.interface.registry import Components
     dummy = object()
     c = Components()
     c.registerUtility(dummy, Interface)
     registry = self._makeOne(bases=(c,))
     self.assertEqual(registry.getUtility(Interface), dummy)
Пример #10
0
 def __init__(self, serializer=json.dumps, adapters=(), **kw):
     """ Any keyword arguments will be passed to the ``serializer``
     function."""
     self.serializer = serializer
     self.kw = kw
     self.components = Components()
     for type, adapter in adapters:
         self.add_adapter(type, adapter)
Пример #11
0
 def test_init_forwards_kw(self):
     from zope.interface import Interface
     from zope.interface.registry import Components
     dummy = object()
     c = Components()
     c.registerUtility(dummy, Interface)
     registry = self._makeOne(bases=(c, ))
     self.assertEqual(registry.getUtility(Interface), dummy)
Пример #12
0
 def __init__(self, package_name=CALLER_PACKAGE, *args, **kw):
     # add a registry-instance-specific lock, which is used when the lookup
     # cache is mutated
     self._lock = threading.Lock()
     # add a view lookup cache
     self._clear_view_lookup_cache()
     if package_name is CALLER_PACKAGE:
         package_name = caller_package().__name__
     Components.__init__(self, package_name, *args, **kw)
     dict.__init__(self)
Пример #13
0
def populate_components():
    def factory(o):
        return 42

    pop_components = Components()
    for iface in ifaces:
        for other_iface in ifaces:
            pop_components.registerAdapter(factory, (iface, ),
                                           other_iface,
                                           event=False)

    return pop_components
Пример #14
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)
Пример #15
0
    def test_uses_configured_site_manager(self):
        from zope.interface.registry import Components
        from zope.component import getSiteManager
        from zope.component.testfiles.components import comp, IApp

        registry = Components()
        def dummy(context=None):
            return registry
        getSiteManager.sethook(dummy)

        try:
            self._callFUT('registerUtility', comp, IApp, u'')
            self.assertTrue(registry.getUtility(IApp) is comp)
        finally:
            getSiteManager.reset()
Пример #16
0
    def test_nested(self):
        from zope.interface import Interface
        from zope.interface import implementer
        from zope.interface.registry import Components
        from zope.component import getGlobalSiteManager
        from zope.component.tests.examples import ConformsToIComponentLookup

        class IFoo(Interface):
            pass

        class IBar(Interface):
            pass

        class IBaz(Interface):
            pass

        @implementer(IBar)
        class Bar(object):
            pass

        @implementer(IBaz)
        class Baz(object):
            pass

        @implementer(IFoo)
        class Global(object):
            def __init__(self, first, second):
                self.first, self.second = first, second

        @implementer(IFoo)
        class Local(object):
            def __init__(self, first, second):
                self.first, self.second = first, second

        class Context(ConformsToIComponentLookup):
            def __init__(self, sm):
                self.sitemanager = sm

        gsm = getGlobalSiteManager()
        gsm.registerAdapter(Global, (IBar, IBaz), IFoo, '')
        sm1 = Components('sm1', bases=(gsm, ))
        sm1.registerAdapter(Local, (IBar, IBaz), IFoo, '')
        bar = Bar()
        baz = Baz()
        adapted = self._callFUT((bar, baz), IFoo, '', context=Context(sm1))
        self.assertTrue(adapted.__class__ is Local)
        self.assertTrue(adapted.first is bar)
        self.assertTrue(adapted.second is baz)
Пример #17
0
 def __init__(self):
     self.registry = Components('Testing')
     self.old = getSiteManager.sethook(lambda: self.registry)
     self.instances.add(self)
     if not self.__class__.atexit_setup:
         atexit.register(self.atexit)
         self.__class__.atexit_setup = True
Пример #18
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)
Пример #19
0
    def test_uses_configured_site_manager(self):
        from zope.interface.registry import Components
        from zope.component import getSiteManager
        from zope.component.testfiles.components import comp, IApp
        from zope.component._compat import _BLANK

        registry = Components()

        def dummy(context=None):
            return registry

        getSiteManager.sethook(dummy)

        try:
            self._callFUT('registerUtility', comp, IApp, _BLANK)
            self.assertTrue(registry.getUtility(IApp) is comp)
        finally:
            getSiteManager.reset()
Пример #20
0
def main():
    registry = Components()
    bootstrap(registry)

    session_factory = registry.queryUtility(IDBSessionFactory, "master")
    session = session_factory()
    a = MainTable()
    a.name = "test"
    session.add(a)
    print(session.get_bind())
    session.commit()

    session_factory = registry.queryUtility(IDBSessionFactory, "other")
    session = session_factory()
    a = OtherTable()
    a.name_other = "test"
    session.add(a)
    print(session.get_bind())
    session.commit()
Пример #21
0
 def test_nested(self):
     from zope.component import getGlobalSiteManager
     from zope.interface.registry import Components
     gsm = getGlobalSiteManager()
     gutil = _makeMyUtility('global', gsm)
     gsm.registerUtility(gutil, IMyUtility, 'myutil')
     sm1 = Components('sm1', bases=(gsm, ))
     sm1_1 = Components('sm1_1', bases=(sm1, ))
     util1 = _makeMyUtility('one', sm1)
     sm1.registerUtility(util1, IMyUtility, 'myutil')
     util1_1 = _makeMyUtility('one-one', sm1_1)
     sm1_1.registerUtility(util1_1, IMyUtility, 'myutil')
     myregistry = Components()
     custom_util = _makeMyUtility('my_custom_util', myregistry)
     myregistry.registerUtility(custom_util, IMyUtility, 'my_custom_util')
     sm1.__bases__ = (myregistry,) + sm1.__bases__
     # Both the ``myregistry`` and global utilities should be available:
     self.assertTrue(self._callFUT(sm1, IMyUtility, 'my_custom_util')
                                         is custom_util)
     self.assertTrue(self._callFUT(sm1, IMyUtility, 'myutil') is gutil)
Пример #22
0
 def test_passwords(self):
     from zope.interface.registry import Components
     from alpaca.common.domain.user import User
     from alpaca.common.utilities.interfaces import IPasswordProcessor
     from alpaca.common.utilities.pbkdf2_password_processor import (
         PBKDF2PasswordProcessor
     )
     processor = PBKDF2PasswordProcessor()
     registry = Components()
     registry.registerUtility(
         processor,
         IPasswordProcessor,
         'pbkdf2'
     )
     user = User()
     user.set_password('łąki łan 123', 'pbkdf2', processor)
     self.assertEqual(user.password_processor, 'pbkdf2')
     self.assertTrue(bool(user.password_hash))
     self.assertLessEqual(len(user.password_hash), 100)
     self.assertFalse(user.password_equals('łąki łany 123', registry))
     self.assertTrue(user.password_equals('łąki łan 123', registry))
Пример #23
0
def main(argv=sys.argv[1:]):
    reg = Components()
    reg.registerUtility(GoogleVisionAPIFaceDetection(), IDetection, 'gcp')
    reg.registerUtility(MSProjectoxfordDetection(get_ms_param()['API_TOKEN']),
                        IDetection, 'ms')
    reg.registerUtility(AkamaiCrop(), ICrop, 'akamai')

    parser = argparse.ArgumentParser()
    parser.add_argument('mode', help='gcp or ms')
    parser.add_argument('target', help='url or path')
    parser.add_argument('--crop', default='akamai')
    args = parser.parse_args(argv)

    detect = reg.queryUtility(IDetection, args.mode)
    result = detect(args.target)
    crop = AkamaiCrop()
    url = crop(result)
    print(url)
Пример #24
0
 def test_nested(self):
     from zope.interface import Interface
     from zope.interface import implementer
     from zope.interface.registry import Components
     from zope.component import getGlobalSiteManager
     from zope.component.tests.examples import ConformsToIComponentLookup
     class IFoo(Interface):
         pass
     class IBar(Interface):
         pass
     class IBaz(Interface):
         pass
     @implementer(IBar)
     class Bar(object):
         pass
     @implementer(IBaz)
     class Baz(object):
         pass
     @implementer(IFoo)
     class Global(object):
         def __init__(self, first, second):
             self.first, self.second = first, second
     @implementer(IFoo)
     class Local(object):
         def __init__(self, first, second):
             self.first, self.second = first, second
     class Context(ConformsToIComponentLookup):
         def __init__(self, sm):
             self.sitemanager = sm
     gsm = getGlobalSiteManager()
     gsm.registerAdapter(Global, (IBar, IBaz), IFoo, '')
     sm1 = Components('sm1', bases=(gsm, ))
     sm1.registerAdapter(Local, (IBar, IBaz), IFoo, '')
     bar = Bar()
     baz = Baz()
     adapted = self._callFUT((bar, baz), IFoo, '', context=Context(sm1))
     self.assertTrue(adapted.__class__ is Local)
     self.assertTrue(adapted.first is bar)
     self.assertTrue(adapted.second is baz)
    def test_register_in_current_site(self):
        from zope.component._api import getSiteManager
        from zope.component.globalregistry import getGlobalSiteManager
        from zope.interface.registry import Components
        from zope.interface import Interface
        from zope.interface.interfaces import IInterface

        class IFoo(Interface):
            pass

        site_man = Components()
        def get(_context=None):
            return site_man
        getSiteManager.sethook(get)
        self.addCleanup(getSiteManager.reset)

        self._callFUT('foo', IFoo)

        self.assertIs(site_man.getUtility(IInterface, name='foo'),
                      IFoo)
        self.assertIsNone(
            getGlobalSiteManager().queryUtility(IInterface, name='foo')
        )
Пример #26
0
 def test_nested(self):
     from zope.component import getGlobalSiteManager
     from zope.component.interfaces import IComponentLookup
     from zope.interface.registry import Components
     gsm = getGlobalSiteManager()
     gutil = _makeMyUtility('global', gsm)
     gsm.registerUtility(gutil, IMyUtility, 'myutil')
     sm1 = Components('sm1', bases=(gsm, ))
     sm1_1 = Components('sm1_1', bases=(sm1, ))
     util1 = _makeMyUtility('one', sm1)
     sm1.registerUtility(util1, IMyUtility, 'myutil')
     self.assertTrue(IComponentLookup(util1) is sm1)
     self.assertTrue(self._callFUT(util1, IMyUtility, 'myutil') is gutil)
     util1_1 = _makeMyUtility('one-one', sm1_1)
     sm1_1.registerUtility(util1_1, IMyUtility, 'myutil')
     self.assertTrue(IComponentLookup(util1_1) is sm1_1)
     self.assertTrue(self._callFUT(util1_1, IMyUtility, 'myutil') is util1)
Пример #27
0
def main(argv=sys.argv[1:]):
    reg = Components()
    reg.registerUtility(GoogleVisionAPIFaceDetection(),
                        IDetection, 'gcp')
    reg.registerUtility(MSProjectoxfordDetection(get_ms_param()['API_TOKEN']),
                        IDetection, 'ms')
    reg.registerUtility(AkamaiCrop(),
                        ICrop, 'akamai')

    parser = argparse.ArgumentParser()
    parser.add_argument('mode', help='gcp or ms')
    parser.add_argument('target', help='url or path')
    parser.add_argument('--crop', default='akamai')
    args = parser.parse_args(argv)

    detect = reg.queryUtility(IDetection, args.mode)
    result = detect(args.target)
    crop = AkamaiCrop()
    url = crop(result)
    print(url)
Пример #28
0
def test_registration_with_custom_registry():
    from pseud.utils import (get_rpc_callable,
                             registry,
                             register_rpc,
                             )

    local_registry = Components(name='local',
                                bases=(registry,))

    @register_rpc(name='try_to_call_me')
    def callme(*args, **kw):
        return 'global'

    @register_rpc(name='try_to_call_me',
                  registry=local_registry)
    def callme2(*args, **kw):
        return 'local'

    assert get_rpc_callable('try_to_call_me')() == 'global'
    assert get_rpc_callable('try_to_call_me',
                            registry=local_registry)() == 'local'
Пример #29
0
    def __init__(self, configuration=None):
        """
        Use configuration and dbConfiguration objects to setup your application.
        
        Events:
        - init(configuration)
        """
        self.registry = Components()
        self.configuration = configuration
        self.dbConfiguration = None
        # set id for logging
        if configuration:
            self.id = configuration.id
        else:
            self.id = __name__

        self.__name__ = u""
        self.__parent__ = None
        self.__acl__ = []

        # development
        self.debug = False
        self.reloadExtensions = False

        # v0.9.12: moved _meta to configuration.meta
        # meta fields are now handled by the application configuration
        # self._meta = copy.deepcopy(SystemFlds)

        # default root name if multiple
        self._defaultRoot = ""
        # cache database structure
        self._structure = PoolStructure()
        self._dbpool = None

        self.log = logging.getLogger(self.id)
        self.log.debug("Initialize %s", repr(configuration))
        self.Signal("init", configuration=configuration)

        self.starttime = 0
Пример #30
0
 def test_nested(self):
     from zope.component import getGlobalSiteManager
     from zope.interface.interfaces import IComponentLookup
     from zope.interface.registry import Components
     gsm = getGlobalSiteManager()
     gutil = _makeMyUtility('global', gsm)
     gsm.registerUtility(gutil, IMyUtility, 'myutil')
     sm1 = Components('sm1', bases=(gsm, ))
     sm1_1 = Components('sm1_1', bases=(sm1, ))
     util1 = _makeMyUtility('one', sm1)
     sm1.registerUtility(util1, IMyUtility, 'myutil')
     self.assertTrue(IComponentLookup(util1) is sm1)
     self.assertTrue(self._callFUT(util1, IMyUtility, 'myutil') is gutil)
     util1_1 = _makeMyUtility('one-one', sm1_1)
     sm1_1.registerUtility(util1_1, IMyUtility, 'myutil')
     self.assertTrue(IComponentLookup(util1_1) is sm1_1)
     self.assertTrue(self._callFUT(util1_1, IMyUtility, 'myutil') is util1)
Пример #31
0
class Registry:
    """A service registry for dependency management.
    """

    def __init__(self):
        self._component = Components()

    def find_service(self, iface, context=None, name=''):
        """Finds a service registered with the provided interface.

        This can be used to locate services registered either as a utility or
        factory service. If no service exists for either of the categories an
        error is thrown.
        """
        service = self._component.queryUtility(iface, name=name)
        if not service:
            service = self._component.queryAdapter(context, iface, name=name)

        if not service:
            msgfmt = "No utility or factory service found for {}"
            iface_name = getattr(iface, '__name__', str(iface))
            raise ServiceError(msgfmt.format(iface_name))
        return service

    def register_service(self, service, iface, name=''):
        """Registers a singleton utility service.

        A callable serving as a factory to lazily create the utility service
        can be provided in place of the service instance.
        """
        key = 'component' if not callable(service) else 'factory'
        kwargs = {'provided': iface, key: service, 'name': name}
        self._component.registerUtility(**kwargs)

    def register_factory(self, factory, iface, required=None, name=''):
        """Registers a service factory.
        """
        required = required or Interface
        if not isinstance(required, (list, tuple)):
            required = (required,)

        self._component.registerAdapter(
            factory=factory, provided=iface, required=required, name=name
        )
Пример #32
0
 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()
Пример #33
0
import zope.interface
import zope.interface.verify
from zope.interface.adapter import AdapterRegistry
from zope.interface.registry import Components
registry = Components()


class IFoo(zope.interface.Interface):
    """Foo blah blah"""
    x = zope.interface.Attribute("""X blah blah""")


class IBaz(IFoo):
    """Baz blah"""
    def eek(a=1):
        """eek in baz blah"""


@zope.interface.implementer(IBaz)
class Bazz:
    def __init__(self, x=None):
        self.x = x

    def eek(self, a=1):
        return a


assert IFoo.implementedBy(Bazz)
assert IBaz.implementedBy(Bazz)

bazz = Bazz()
Пример #34
0
class TestHandler(unittest.TestCase):

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

    def test_register_handler(self):
        test_object1 = U1(1)
        test_object2 = U12(2)

        @adapter(I1)
        def handle1(x):
            self.assertEqual(x, test_object1)

        self.components.registerHandler(handle1, info=u'First handler')
        self.components.handle(test_object1)

        @adapter(I1, I2)
        def handle12(x, y):
            self.assertEqual(x, test_object1)
            self.assertEqual(y, test_object2)

        self.components.registerHandler(handle12)
        self.components.handle(test_object1, test_object2)

    def test_register_noncompliant_handler(self):
        handle_calls = []
        def handle(*objects):
            handle_calls.append(objects)

        self.assertRaises(TypeError, self.components.registerHandler, handle)
        self.components.registerHandler(
            handle, required=[I1], info=u'a comment')
        self.components.registerHandler(
            handle, required=[U], info=u'handle a class')

        test_object = U1(1)
        self.components.handle(test_object)
        self.assertEqual(len(handle_calls), 2)
        map(self.assertEqual, handle_calls, [(test_object,), (test_object,)])

    def test_list_handlers(self):
        test_object1 = U1(1)
        test_object2 = U12(2)

        @adapter(I1)
        def handle1(x):
            self.assertEqual(x, test_object1)

        @adapter(I1, I2)
        def handle12(x, y):
            self.assertEqual(x, test_object1)
            self.assertEqual(y, test_object2)

        handle_calls = []
        def handle(*objects):
            handle_calls.append(objects)

        self.components.registerHandler(handle1, info=u'First handler')
        self.components.registerHandler(handle12)
        self.components.registerHandler(
            handle, required=[I1], info=u'a comment')
        self.components.registerHandler(
            handle, required=[U], info=u'handle a class')

        handlers = list(self.components.registeredHandlers())
        handlers_required = map(lambda x: getattr(x, 'required'), handlers)
        handlers_handler = map(lambda x: getattr(x, 'handler'), handlers)
        handlers_info = map(lambda x: getattr(x, 'info'), handlers)

        self.assertEqual(len(handlers), 4)
        self.assertEqual(handlers_required,
                         [(I1,), (I1, I2), (I1,), (implementedBy(U),)])
        self.assertEqual(handlers_handler,
                         [handle1, handle12, handle, handle])
        self.assertEqual(
            handlers_info,
            [u'First handler', u'', u'a comment', u'handle a class'])

    def test_unregister_handler(self):
        test_object1 = U1(1)
        test_object2 = U12(2)

        @adapter(I1)
        def handle1(x):
            self.assertEqual(x, test_object1)

        @adapter(I1, I2)
        def handle12(x, y):
            self.assertEqual(x, test_object1)
            self.assertEqual(y, test_object2)

        handle_calls = []
        def handle(*objects):
            handle_calls.append(objects)

        self.components.registerHandler(handle1, info=u'First handler')
        self.components.registerHandler(handle12)
        self.components.registerHandler(
            handle, required=[I1], info=u'a comment')
        self.components.registerHandler(
            handle, required=[U], info=u'handle a class')

        self.assertEqual(len(list(self.components.registeredHandlers())), 4)
        self.assertTrue(self.components.unregisterHandler(handle12))
        self.assertEqual(len(list(self.components.registeredHandlers())), 3)
        self.assertFalse(self.components.unregisterHandler(handle12))
        self.assertEqual(len(list(self.components.registeredHandlers())), 3)
        self.assertRaises(TypeError, self.components.unregisterHandler)
        self.assertEqual(len(list(self.components.registeredHandlers())), 3)
        self.assertTrue(
            self.components.unregisterHandler(handle, required=[I1]))
        self.assertEqual(len(list(self.components.registeredHandlers())), 2)
        self.assertTrue(self.components.unregisterHandler(handle, required=[U]))
        self.assertEqual(len(list(self.components.registeredHandlers())), 1)

    def test_multi_handler_unregistration(self):
        """
        There was a bug where multiple handlers for the same required
        specification would all be removed when one of them was
        unregistered.

        """
        from zope import interface

        calls = []

        class I(interface.Interface):
            pass

        def factory1(event):
            calls.append(2)

        def factory2(event):
            calls.append(3)

        class Event(object):
            interface.implements(I)

        self.components.registerHandler(factory1, [I,])
        self.components.registerHandler(factory2, [I,])
        self.components.handle(Event())
        self.assertEqual(sum(calls), 5)
        self.assertTrue(self.components.unregisterHandler(factory1, [I,]))
        calls = []
        self.components.handle(Event())
        self.assertEqual(sum(calls), 3)
Пример #35
0
 def __init__(self):
     self._component = Components()
Пример #36
0
def global_registry():
    return _global_registry or Components()
Пример #37
0
class JSON(object):
    """ Renderer that returns a JSON-encoded string.

    Configure a custom JSON renderer using the
    :meth:`~pyramid.config.Configurator.add_renderer` API at application
    startup time:

    .. code-block:: python

       from pyramid.config import Configurator

       config = Configurator()
       config.add_renderer('myjson', JSON(indent=4))

    Once this renderer is registered as above, you can use
    ``myjson`` as the ``renderer=`` parameter to ``@view_config`` or
    :meth:`~pyramid.config.Configurator.add_view``:

    .. code-block:: python

       from pyramid.view import view_config

       @view_config(renderer='myjson')
       def myview(request):
           return {'greeting':'Hello world'}

    Custom objects can be serialized using the renderer by either
    implementing the ``__json__`` magic method, or by registering
    adapters with the renderer.  See
    :ref:`json_serializing_custom_objects` for more information.

    .. note::

        The default serializer uses ``json.JSONEncoder``. A different
        serializer can be specified via the ``serializer`` argument.  Custom
        serializers should accept the object, a callback ``default``, and any
        extra ``kw`` keyword arguments passed during renderer construction.
        This feature isn't widely used but it can be used to replace the
        stock JSON serializer with, say, simplejson.  If all you want to
        do, however, is serialize custom objects, you should use the method
        explained in :ref:`json_serializing_custom_objects` instead
        of replacing the serializer.

    .. versionadded:: 1.4
       Prior to this version, there was no public API for supplying options
       to the underlying serializer without defining a custom renderer.
    """

    def __init__(self, serializer=json.dumps, adapters=(), **kw):
        """ Any keyword arguments will be passed to the ``serializer``
        function."""
        self.serializer = serializer
        self.kw = kw
        self.components = Components()
        for type, adapter in adapters:
            self.add_adapter(type, adapter)

    def add_adapter(self, type_or_iface, adapter):
        """ When an object of the type (or interface) ``type_or_iface`` fails
        to automatically encode using the serializer, the renderer will use
        the adapter ``adapter`` to convert it into a JSON-serializable
        object.  The adapter must accept two arguments: the object and the
        currently active request.

        .. code-block:: python

           class Foo(object):
               x = 5

           def foo_adapter(obj, request):
               return obj.x

           renderer = JSON(indent=4)
           renderer.add_adapter(Foo, foo_adapter)

        When you've done this, the JSON renderer will be able to serialize
        instances of the ``Foo`` class when they're encountered in your view
        results."""
        
        self.components.registerAdapter(adapter, (type_or_iface,),
                                        IJSONAdapter)

    def __call__(self, info):
        """ Returns a plain JSON-encoded string with content-type
        ``application/json``. The content-type may be overridden by
        setting ``request.response.content_type``."""
        def _render(value, system):
            request = system.get('request')
            if request is not None:
                response = request.response
                ct = response.content_type
                if ct == response.default_content_type:
                    response.content_type = 'application/json'
            default = self._make_default(request)
            return self.serializer(value, default=default, **self.kw)
        
        return _render

    def _make_default(self, request):
        def default(obj):
            if hasattr(obj, '__json__'):
                return obj.__json__(request)
            obj_iface = providedBy(obj)
            adapters = self.components.adapters
            result = adapters.lookup((obj_iface,), IJSONAdapter,
                                     default=_marker)
            if result is _marker:
                raise TypeError('%r is not JSON serializable' % (obj,))
            return result(obj, request)
        return default
Пример #38
0
'''
JSON Adapters

Created on May 30, 2013

@author: Edward Easton
'''
import json
import datetime
import logging

from zope.interface.registry import Components
from zope.interface import Interface, providedBy

# Singleton type registry
_TYPE_REGISTRY = Components()
_marker = object()


def get_log():
    return logging.getLogger('pp.utils.json')


class IJSONAdapter(Interface):
    """
    Marker interface for objects that can convert an arbitrary object
    into a JSON-serializable primitive.
    """


def get_adapters():
Пример #39
0
class TestSubscriber(unittest.TestCase):

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

    def test_register_subscriber(self):
        self.components.registerSubscriptionAdapter(A1_2)
        self.components.registerSubscriptionAdapter(A1_12, provided=IA2)
        self.components.registerSubscriptionAdapter(
            A, [I1], IA2, info='a sample comment')
        subscribers = self.components.subscribers((U1(1),), IA2)
        self.assertEqual(len(subscribers), 3)
        self.assertEqual(repr(subscribers[0]), 'A1_2(U1(1))')
        self.assertEqual(repr(subscribers[1]), 'A1_12(U1(1))')
        self.assertEqual(repr(subscribers[2]), 'A(U1(1),)') 

    def test_register_noncompliant_subscriber(self):
        self.assertRaises(TypeError,
                          self.components.registerSubscriptionAdapter, A1_12)
        self.assertRaises(TypeError,
                          self.components.registerSubscriptionAdapter, A)
        self.assertRaises(
            TypeError,
            self.components.registerSubscriptionAdapter, A, required=[IA1])

    def test_register_named_subscriber(self):
        self.components.registerSubscriptionAdapter(
            A, [I1], IA2, u'', u'a sample comment')
        self.assertRaises(TypeError,
                          self.components.registerSubscriptionAdapter, 
                          A, [I1], IA2, u'oops', u'a sample comment')
        subscribers = self.components.subscribers((U1(1),), IA2)
        self.assertEqual(len(subscribers), 1)
        self.assertEqual(repr(subscribers[0]), 'A(U1(1),)')

    def test_register_no_factory(self):
        self.components.registerSubscriptionAdapter(noop, [I1], IA2)
        subscribers = self.components.subscribers((U1(1),), IA2)
        self.assertEqual(len(subscribers), 0)

    def test_sorting_registered_subscription_adapters(self):
        self.components.registerSubscriptionAdapter(A1_2)
        self.components.registerSubscriptionAdapter(A1_12, provided=IA2)
        self.components.registerSubscriptionAdapter(
            A, [I1], IA2, info=u'a sample comment')
        self.components.registerSubscriptionAdapter(
            A, [I1], IA2, u'', u'a sample comment')
        self.components.registerSubscriptionAdapter(noop, [I1], IA2)

        sorted_subscribers = sorted(
            self.components.registeredSubscriptionAdapters())
        sorted_subscribers_name = map(lambda x: getattr(x, 'name'),
                                      sorted_subscribers)
        sorted_subscribers_provided = map(lambda x: getattr(x, 'provided'),
                                          sorted_subscribers) 
        sorted_subscribers_required = map(lambda x: getattr(x, 'required'),
                                          sorted_subscribers)
        sorted_subscribers_factory = map(lambda x: getattr(x, 'factory'),
                                         sorted_subscribers)
        sorted_subscribers_info = map(lambda x: getattr(x, 'info'),
                                      sorted_subscribers)

        self.assertEqual(len(sorted_subscribers), 5)
        self.assertEqual(sorted_subscribers_name, [u'', u'', u'', u'', u''])
        self.assertEqual(sorted_subscribers_provided,
                         [IA2, IA2, IA2, IA2, IA2])
        self.assertEqual(sorted_subscribers_required,
                         [(I1,), (I1,), (I1,),(I1,), (I1,)])
        self.assertEqual(sorted_subscribers_factory,
                         [A, A, A1_12, A1_2, noop])
        self.assertEqual(
            sorted_subscribers_info,
            [u'a sample comment', u'a sample comment', u'', u'', u''])

    def test_unregister(self):
        self.components.registerSubscriptionAdapter(A1_2)
        self.assertEqual(len(self.components.subscribers((U1(1),), IA2)), 1)
        self.assertTrue(self.components.unregisterSubscriptionAdapter(A1_2))
        self.assertEqual(len(self.components.subscribers((U1(1),), IA2)), 0)

    def test_unregister_multiple(self):
        self.components.registerSubscriptionAdapter(A1_2)
        self.components.registerSubscriptionAdapter(A1_12, provided=IA2)
        self.components.registerSubscriptionAdapter(
            A, [I1], IA2, info=u'a sample comment')
        self.components.registerSubscriptionAdapter(
            A, [I1], IA2, u'', u'a sample comment')
        self.components.registerSubscriptionAdapter(noop, [I1], IA2)
        self.assertEqual(len(self.components.subscribers((U1(1),), IA2)), 4)
        self.assertEqual(
            len(list(self.components.registeredSubscriptionAdapters())), 5)

        self.assertTrue(
            self.components.unregisterSubscriptionAdapter(A, [I1], IA2))
        self.assertEqual(len(self.components.subscribers((U1(1),), IA2)), 2)
        self.assertEqual(
            len(list(self.components.registeredSubscriptionAdapters())), 3)

    def test_unregister_no_factory(self):
        self.components.registerSubscriptionAdapter(A1_2)
        self.components.registerSubscriptionAdapter(A1_12, provided=IA2)
        self.components.registerSubscriptionAdapter(noop, [I1], IA2)
        self.assertEqual(len(self.components.subscribers((U1(1),), IA2)), 2)
        self.assertEqual(
            len(list(self.components.registeredSubscriptionAdapters())), 3)

        self.assertRaises(
            TypeError,
            self.components.unregisterSubscriptionAdapter, required=[I1])
        self.assertRaises(
            TypeError,
            self.components.unregisterSubscriptionAdapter, provided=IA2)
        self.assertTrue(
            self.components.unregisterSubscriptionAdapter(
                required=[I1], provided=IA2))
        self.assertEqual(len(self.components.subscribers((U1(1),), IA2)), 0)
        self.assertEqual(
            len(list(self.components.registeredSubscriptionAdapters())), 0)

    def test_unregister_noncompliant_subscriber(self):
        self.assertRaises(
            TypeError,
            self.components.unregisterSubscriptionAdapter, A1_12)
        self.assertRaises(
            TypeError,
            self.components.unregisterSubscriptionAdapter, A)
        self.assertRaises(
            TypeError,
            self.components.unregisterSubscriptionAdapter, A, required=[IA1])

    def test_unregister_nonexistent_subscriber(self):
        self.assertFalse(
            self.components.unregisterSubscriptionAdapter(required=[I1],
                                                          provided=IA2))
Пример #40
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)
Пример #41
0
    def test_extendning(self):
        c1 = Components('1')
        self.assertEqual(c1.__bases__, ())

        c2 = Components('2', (c1, ))
        self.assertTrue(c2.__bases__ == (c1, ))

        test_object1 = U1(1)
        test_object2 = U1(2)
        test_object3 = U12(1)
        test_object4 = U12(3)

        self.assertEqual(len(list(c1.registeredUtilities())), 0)
        self.assertEqual(len(list(c2.registeredUtilities())), 0)

        c1.registerUtility(test_object1)
        self.assertEqual(len(list(c1.registeredUtilities())), 1)
        self.assertEqual(len(list(c2.registeredUtilities())), 0)
        self.assertEqual(c1.queryUtility(I1), test_object1)
        self.assertEqual(c2.queryUtility(I1), test_object1)

        c1.registerUtility(test_object2)
        self.assertEqual(len(list(c1.registeredUtilities())), 1)
        self.assertEqual(len(list(c2.registeredUtilities())), 0)
        self.assertEqual(c1.queryUtility(I1), test_object2)
        self.assertEqual(c2.queryUtility(I1), test_object2)


        c3 = Components('3', (c1, ))
        c4 = Components('4', (c2, c3))
        self.assertEqual(c4.queryUtility(I1), test_object2)
    
        c1.registerUtility(test_object3, I2)
        self.assertEqual(c4.queryUtility(I2), test_object3)

        c3.registerUtility(test_object4, I2)
        self.assertEqual(c4.queryUtility(I2), test_object4)

        @adapter(I1)
        def handle1(x):
            self.assertEqual(x, test_object1)

        def handle(*objects):
            self.assertEqual(objects, (test_object1,))

        @adapter(I1)
        def handle3(x):
            self.assertEqual(x, test_object1)

        @adapter(I1)
        def handle4(x):
            self.assertEqual(x, test_object1)

        c1.registerHandler(handle1, info=u'First handler')
        c2.registerHandler(handle, required=[U])
        c3.registerHandler(handle3)
        c4.registerHandler(handle4)

        c4.handle(test_object1)
Пример #42
0
runner.bench_time_func(
    'read __doc__',  # stored in Python instance dictionary directly
    bench_getattr,
    '__doc__',
    inner_loops=INNER * 10)

runner.bench_time_func(
    'read providedBy',  # from the class, wrapped into a method object.
    bench_getattr,
    'providedBy',
    inner_loops=INNER * 10)

runner.bench_time_func('query adapter (no registrations)',
                       bench_query_adapter,
                       Components(),
                       inner_loops=1)


def populate_components():
    def factory(o):
        return 42

    pop_components = Components()
    for iface in ifaces:
        for other_iface in ifaces:
            pop_components.registerAdapter(factory, (iface, ),
                                           other_iface,
                                           event=False)

    return pop_components
Пример #43
0
def get_registry():
    global _registry
    if _registry is None:
        _registry = Components()
    return _registry
Пример #44
0
 def setUp(self):
     self.components = Components('comps')
Пример #45
0
 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()
Пример #46
0
 def registerHandler(self, *arg, **kw):
     result = Components.registerHandler(self, *arg, **kw)
     self.has_listeners = True
     return result
Пример #47
0
def app_registry():
    """
    See also app_registry_mock.
    :return:
    """
    return Components()
Пример #48
0
 def registerSubscriptionAdapter(self, *arg, **kw):
     result = Components.registerSubscriptionAdapter(self, *arg, **kw)
     self.has_listeners = True
     return result
Пример #49
0
 def test_nested(self):
     from zope.component import getGlobalSiteManager
     from zope.interface.registry import Components
     gsm = getGlobalSiteManager()
     gutil = _makeMyUtility('global', gsm)
     gsm.registerUtility(gutil, IMyUtility, 'myutil')
     sm1 = Components('sm1', bases=(gsm, ))
     sm1_1 = Components('sm1_1', bases=(sm1, ))
     util1 = _makeMyUtility('one', sm1)
     sm1.registerUtility(util1, IMyUtility, 'myutil')
     util1_1 = _makeMyUtility('one-one', sm1_1)
     sm1_1.registerUtility(util1_1, IMyUtility, 'myutil')
     myregistry = Components()
     custom_util = _makeMyUtility('my_custom_util', myregistry)
     myregistry.registerUtility(custom_util, IMyUtility, 'my_custom_util')
     sm1.__bases__ = (myregistry, ) + sm1.__bases__
     # Both the ``myregistry`` and global utilities should be available:
     self.assertTrue(
         self._callFUT(sm1, IMyUtility, 'my_custom_util') is custom_util)
     self.assertTrue(self._callFUT(sm1, IMyUtility, 'myutil') is gutil)
Пример #50
0
class TestAdapter(unittest.TestCase):

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

    def test_register_and_unregister_adapter(self):
        self.components.registerAdapter(A12_1)

        multi_adapter = self.components.getMultiAdapter(
            (U1(1), U12(2)), IA1)
        self.assertEqual(multi_adapter.__class__, A12_1)
        self.assertEqual(repr(multi_adapter), 'A12_1(U1(1), U12(2))')

        self.assertTrue(self.components.unregisterAdapter(A12_1))
        self.assertRaises(
            ComponentLookupError,
            self.components.getMultiAdapter,
            (U1(1), U12(2)),
            IA1
            )

    def test_register_and_unregister_adapter_with_two_interfaces(self):
        self.assertRaises(TypeError, self.components.registerAdapter,
                          A1_12)
        self.components.registerAdapter(A1_12,
                                        provided=IA2)

        multi_adapter = self.components.getMultiAdapter((U1(1),), IA2)
        self.assertEqual(multi_adapter.__class__, A1_12)
        self.assertEqual(repr(multi_adapter), 'A1_12(U1(1))')

        self.assertRaises(TypeError, self.components.unregisterAdapter, A1_12)
        self.assertTrue(self.components.unregisterAdapter(A1_12, provided=IA2))
        self.assertRaises(ComponentLookupError,
                          self.components.getMultiAdapter, (U1(1),), IA2)

    def test_register_and_unregister_adapter_with_no_interfaces(self):
        self.assertRaises(TypeError, self.components.registerAdapter, A12_)

        self.components.registerAdapter(A12_, provided=IA2)
        multi_adapter = self.components.getMultiAdapter((U1(1), U12(2)), IA2)
        self.assertEqual(multi_adapter.__class__, A12_)
        self.assertEqual(repr(multi_adapter), 'A12_(U1(1), U12(2))')

        self.assertRaises(TypeError, self.components.unregisterAdapter, A12_)
        self.assertTrue(self.components.unregisterAdapter(A12_, provided=IA2))
        self.assertRaises(ComponentLookupError,
                          self.components.getMultiAdapter, (U1(1), U12(2)), IA2)

    def test_reg_and_unreg_adp_with_no___component_adapts___attribute(self):
        self.assertRaises(TypeError, self.components.registerAdapter, A_2)
        self.components.registerAdapter(A_2, required=[I3])
        self.assertTrue(self.components.unregisterAdapter(A_2, required=[I3]))

    def test_register_and_unregister_class_specific(self):
        self.components.registerAdapter(A_3, required=[U],
                                        info=u'Really class specific')
        self.assertTrue(self.components.unregisterAdapter(required=[U],
                                                          provided=IA3))
      
    def test_registered_adapters_and_sorting(self):
        self.components.registerAdapter(A12_1)
        self.components.registerAdapter(A1_12, provided=IA2)
        self.components.registerAdapter(A12_, provided=IA2)
        self.components.registerAdapter(A_2, required=[I3])
        self.components.registerAdapter(A_3, required=[U],
                                        info=u'Really class specific')

        sorted_adapters = sorted(self.components.registeredAdapters())
        sorted_adapters_name = map(lambda x: getattr(x, 'name'),
                                   sorted_adapters)
        sorted_adapters_provided = map(lambda x: getattr(x, 'provided'),
                                       sorted_adapters) 
        sorted_adapters_required = map(lambda x: getattr(x, 'required'),
                                       sorted_adapters)
        sorted_adapters_info = map(lambda x: getattr(x, 'info'),
                                   sorted_adapters)

        self.assertEqual(len(sorted_adapters), 5)
        self.assertEqual(sorted_adapters_name, [u'', u'', u'', u'', u''])
        self.assertEqual(sorted_adapters_provided, [IA1,
                                                    IA2,
                                                    IA2,
                                                    IA2,
                                                    IA3])

        self.assertEqual(sorted_adapters_required, [(I1, I2),
                                                    (I1, I2),
                                                    (I1,),
                                                    (I3,),
                                                    (implementedBy(U),)])
        self.assertEqual(sorted_adapters_info,
                         [u'', u'', u'', u'', u'Really class specific'])

    def test_get_none_existing_adapter(self):
        self.assertRaises(ComponentLookupError,
                          self.components.getMultiAdapter, (U(1),), IA1)

    def test_query_none_existing_adapter(self):
        self.assertTrue(self.components.queryMultiAdapter((U(1),), IA1) is None)
        self.assertEqual(self.components.queryMultiAdapter((U(1),), IA1,
                                                           default=42), 42)

    def test_unregister_none_existing_adapter(self):
        self.assertFalse(self.components.unregisterAdapter(A_2, required=[I3]))
        self.assertFalse(self.components.unregisterAdapter(A12_1, required=[U]))

    def test_unregister_adapter(self):
        self.components.registerAdapter(A12_1)
        self.components.registerAdapter(A1_12, provided=IA2)
        self.components.registerAdapter(A12_, provided=IA2)
        self.components.registerAdapter(A_2, required=[I3])
        self.components.registerAdapter(A_3, required=[U],
                                        info=u'Really class specific')

        self.assertTrue(self.components.unregisterAdapter(A12_1))
        self.assertTrue(self.components.unregisterAdapter(
            required=[U], provided=IA3))

        sorted_adapters = sorted(self.components.registeredAdapters())
        sorted_adapters_name = map(lambda x: getattr(x, 'name'),
                                   sorted_adapters)
        sorted_adapters_provided = map(lambda x: getattr(x, 'provided'),
                                       sorted_adapters) 
        sorted_adapters_required = map(lambda x: getattr(x, 'required'),
                                       sorted_adapters)
        sorted_adapters_info = map(lambda x: getattr(x, 'info'),
                                   sorted_adapters)

        self.assertEqual(len(sorted_adapters), 3)
        self.assertEqual(sorted_adapters_name, [u'', u'', u''])
        self.assertEqual(sorted_adapters_provided, [IA2,
                                                    IA2,
                                                    IA2])
        self.assertEqual(sorted_adapters_required, [(I1, I2),
                                                    (I1,),
                                                    (I3,)])
        self.assertEqual(sorted_adapters_info, [u'', u'', u''])

    def test_register_named_adapter(self):
        self.components.registerAdapter(A1_12, provided=IA2, name=u'test')
        self.assertTrue(
            self.components.queryMultiAdapter((U1(1),), IA2) is None)
        self.assertEqual(
            repr(self.components.queryMultiAdapter((U1(1),),IA2,name=u'test')),
            'A1_12(U1(1))')

        self.assertTrue(self.components.queryAdapter(U1(1), IA2) is None)
        self.assertEqual(
            repr(self.components.queryAdapter(U1(1), IA2, name=u'test')),
            'A1_12(U1(1))')
        self.assertEqual(
            repr(self.components.getAdapter(U1(1), IA2, name=u'test')),
            'A1_12(U1(1))')

    def test_get_adapters(self):
        self.components.registerAdapter(A1_12, provided=IA1, name=u'test 1')
        self.components.registerAdapter(A1_23, provided=IA2, name=u'test 2')
        self.components.registerAdapter(A1_12, provided=IA2)
        self.components.registerAdapter(A1_12, provided=IA2)

        adapters = list(self.components.getAdapters((U1(1),), IA2))
        self.assertEqual(len(adapters), 2)
        self.assertEqual(adapters[0][0], u'test 2')
        self.assertEqual(adapters[1][0], u'')
        self.assertEqual(repr(adapters[0][1]), 'A1_23(U1(1))')
        self.assertEqual(repr(adapters[1][1]), 'A1_12(U1(1))')

    def test_register_no_factory(self):
        self.components.registerAdapter(A1_12, provided=IA2)
        self.components.registerAdapter(noop, 
                                        required=[IA1], provided=IA2, 
                                        name=u'test noop')

        self.assertTrue(
            self.components.queryAdapter(U1(9), IA2, name=u'test noop') is None)
        adapters = list(self.components.getAdapters((U1(1),), IA2))
        self.assertEqual(len(adapters), 1)
        self.assertEqual(adapters[0][0], u'')
        self.assertEqual(repr(adapters[0][1]), 'A1_12(U1(1))')

        self.assertTrue(self.components.unregisterAdapter(A1_12, provided=IA2))

        sorted_adapters = sorted(self.components.registeredAdapters())
        sorted_adapters_name = map(lambda x: getattr(x, 'name'),
                                   sorted_adapters)
        sorted_adapters_provided = map(lambda x: getattr(x, 'provided'),
                                       sorted_adapters) 
        sorted_adapters_required = map(lambda x: getattr(x, 'required'),
                                       sorted_adapters)
        sorted_adapters_info = map(lambda x: getattr(x, 'info'),
                                   sorted_adapters)

        self.assertEqual(len(sorted_adapters), 1)
        self.assertEqual(sorted_adapters_name, [u'test noop'])
        self.assertEqual(sorted_adapters_provided, [IA2])
        self.assertEqual(sorted_adapters_required, [(IA1,)])
        self.assertEqual(sorted_adapters_info, [u''])
Пример #51
0
def register_components(components: Components):
    components.registerAdapter(Template, [ITemplateSource], ITemplate)
    components.registerAdapter(VariableCollector, [ITemplateVariable],
                               ICollector)