Ejemplo n.º 1
0
    def test_fromZ2Interface_methods(self):

        from Products.Five.bridge import fromZ2Interface

        class IMethods(Z2_Interface):

            def one():
                """One method."""

            def another(arg1, arg2):
                """Another method, taking arguments."""

        converted = fromZ2Interface(IMethods)

        self.failUnless(Z3_Interface.isEqualOrExtendedBy(converted))
        self.assertEqual(len(converted.names()), 2)
        self.failUnless('one' in converted.names())
        self.failUnless('another' in converted.names())

        one = converted.getDescriptionFor('one')
        self.failUnless(isinstance(one, Z3_Method))
        self.assertEqual(one.getName(), 'one')
        self.assertEqual(one.getDoc(), 'One method.')

        another = converted.getDescriptionFor('another')
        self.failUnless(isinstance(another, Z3_Method))
        self.assertEqual(another.getName(), 'another')
        self.assertEqual(another.getDoc(), 'Another method, taking arguments.')
Ejemplo n.º 2
0
 def __call__(self,*args,**kw):
     # sadly doesn't get called
     raise NotImplementedError
     r = Interface.__call__(*args,**kw)
     if r is empty:
         return None
     return r
Ejemplo n.º 3
0
 def testVerifyImplementation(self):
     from zope.interface.verify import verifyClass
     from zope.interface import Interface
     from zope.interface.tests.unitfixtures import Foo
     from zope.interface.tests.unitfixtures import FooInterface
     from zope.interface.tests.unitfixtures import I1
     self.assert_(verifyClass(FooInterface, Foo))
     self.assert_(Interface.providedBy(I1))
Ejemplo n.º 4
0
    def test_fromZ2Interface_empty(self):

        from Products.Five.bridge import fromZ2Interface

        class IEmpty(Z2_Interface):
            pass

        converted = fromZ2Interface(IEmpty)

        self.failUnless(Z3_Interface.isEqualOrExtendedBy(converted))
        self.assertEqual(len(converted.names()), 0)
Ejemplo n.º 5
0
def SimpleInterface(name, bases, attrs):
    modname = attrs.get('__module__')
    if modname:
        modname += '.autogenerated_interfaces'
    namespace = {'__module__': modname,
                 '__qualname__': attrs.get('qualname')}
    zinterface = _ZInterface.__class__(name, (_ZInterface,), namespace)
    # TODO: actually do the interface description here

    created = _InterfaceBase(name, bases, attrs, __zope_interface__=zinterface)
    return created
Ejemplo n.º 6
0
 def after(self):
     schema = Interface.__class__(
         self.name,
         (Interface, ),
         self.fields
         )
     schema.__doc__ = self.info.text.strip()
     self.action(
         discriminator=('schema', self.id),
         callable=schema_registry.__setitem__,
         args=(self.id, schema),
         )
Ejemplo n.º 7
0
def load_cached_schema():
    for x in getUtilitiesFor(IResourceFactory):
        factory = x[1]
        if factory.portal_type not in SCHEMA_CACHE:
            behaviors_registrations = []
            for iface in factory.behaviors or ():
                if Interface.providedBy(iface):
                    name = iface.__identifier__
                else:
                    name = iface
                behaviors_registrations.append(getUtility(IBehavior, name=name))
            SCHEMA_CACHE[factory.portal_type] = {
                'behaviors': behaviors_registrations,
                'schema': factory.schema
            }
    for iface, utility in getUtilitiesFor(IBehavior):
        if isinstance(iface, str):
            name = iface
        elif Interface.providedBy(iface):
            name = iface.__identifier__
        if name not in BEHAVIOR_CACHE:
            BEHAVIOR_CACHE[name] = utility.interface
Ejemplo n.º 8
0
def load_cached_schema():
    for x in get_utilities_for(IResourceFactory):
        factory = x[1]
        if factory.type_name not in SCHEMA_CACHE:
            FACTORY_CACHE[factory.type_name] = factory
            behaviors_registrations = []
            for iface in factory.behaviors or ():
                if Interface.providedBy(iface):
                    name = iface.__identifier__
                else:
                    name = iface
                behaviors_registrations.append(
                    get_utility(IBehavior, name=name))
            SCHEMA_CACHE[factory.type_name] = {
                'behaviors': behaviors_registrations,
                'schema': factory.schema
            }
    for iface, utility in get_utilities_for(IBehavior):
        if isinstance(iface, str):
            name = iface
        elif Interface.providedBy(iface):
            name = iface.__identifier__
        if name not in BEHAVIOR_CACHE:
            BEHAVIOR_CACHE[name] = utility.interface
Ejemplo n.º 9
0
    def remove_behavior(self, iface):
        """We need to apply the marker interface.

        value: Interface to add
        """
        if isinstance(iface, str):
            name = iface
        elif Interface.providedBy(iface):
            name = iface.__identifier__
        behavior_registration = getUtility(IBehavior, name=name)
        if behavior_registration is not None and\
                behavior_registration.marker is not None:
            noLongerProvides(self, behavior_registration.marker)
        if iface in self.__behaviors__:
            self.__behaviors__ -= {name}
Ejemplo n.º 10
0
    def remove_behavior(self, iface):
        """We need to apply the marker interface.

        value: Interface to add
        """
        if isinstance(iface, str):
            name = iface
        elif Interface.providedBy(iface):
            name = iface.__identifier__
        behavior_registration = getUtility(IBehavior, name=name)
        if behavior_registration is not None and\
                behavior_registration.marker is not None:
            noLongerProvides(self, behavior_registration.marker)
        if iface in self.__behaviors__:
            self.__behaviors__ -= {name}
Ejemplo n.º 11
0
def export_fields_to_dict(obj, fields=None, parentname=None):
    export_dict = {'name': obj.name, 'title': obj.title, 'ref': obj.paco_ref_parts}
    if schemas.IDeployable.providedBy(obj):
        export_dict['enabled'] = obj.is_enabled()
    if fields != None:
        for fieldname in fields:
            value = getattr(obj, fieldname, None)
            if value == None or value == '':
                continue
            if Interface.providedBy(value):
                if not isinstance(value, (str, int, float, list)):
                    value = auto_export_obj_to_dict(value)
            export_dict[fieldname] = value
    if parentname != None:
        export_dict[parentname] = obj.__parent__.name
    return export_dict
Ejemplo n.º 12
0
    def add_behavior(self, iface):
        """We need to apply the marker interface.

        value: Interface to add
        """
        if isinstance(iface, str):
            name = iface
        elif Interface.providedBy(iface):
            name = iface.__identifier__
        else:
            raise AttributeError('Cant identify Interface')
        behavior_registration = getUtility(IBehavior, name=name)
        if behavior_registration is not None and\
                behavior_registration.interface(self) is not None:
            # We can adapt so we can apply this dynamic behavior
            self.__behaviors__ |= {name}
            if behavior_registration.marker is not None:
                alsoProvides(self, behavior_registration.marker)
Ejemplo n.º 13
0
    def add_behavior(self, iface):
        """We need to apply the marker interface.

        value: Interface to add
        """
        if isinstance(iface, str):
            name = iface
        elif Interface.providedBy(iface):
            name = iface.__identifier__
        else:
            raise AttributeError('Cant identify Interface')
        behavior_registration = getUtility(IBehavior, name=name)
        if behavior_registration is not None and\
                behavior_registration.interface(self) is not None:
            # We can adapt so we can apply this dynamic behavior
            self.__behaviors__ |= {name}
            if behavior_registration.marker is not None:
                alsoProvides(self, behavior_registration.marker)
Ejemplo n.º 14
0
    def remove_behavior(self, iface: Union[str, Interface]) -> None:
        """We need to apply the marker interface.

        value: Interface to add
        """
        if isinstance(iface, str):
            name = iface
        elif Interface.providedBy(iface):
            name = iface.__identifier__  # type: ignore
        behavior_registration = get_utility(IBehavior, name=name)
        if behavior_registration is not None and behavior_registration.marker is not None:
            try:
                noLongerProvides(self, behavior_registration.marker)
            except ValueError:
                # could not remove interface
                pass
        if iface in self.__behaviors__:
            self.__behaviors__ -= {name}
        self.register()  # make sure we resave this obj
Ejemplo n.º 15
0
    def add_behavior(self, iface: Union[str, Interface]) -> None:
        """We need to apply the marker interface.

        value: Interface to add
        """
        if isinstance(iface, str):
            name = iface
        elif Interface.providedBy(iface):
            name = iface.__identifier__  # type: ignore
        else:
            raise AttributeError("Cant identify Interface")
        behavior_registration = get_utility(IBehavior, name=name)
        if behavior_registration is not None and behavior_registration.interface(self) is not None:
            # We can adapt so we can apply this dynamic behavior
            if name not in self.__behaviors__:
                self.__behaviors__ |= {name}
                if behavior_registration.marker is not None:
                    alsoProvides(self, behavior_registration.marker)
                self.register()  # make sure we resave this obj
Ejemplo n.º 16
0
    def test_fromZ2Interface_attributes(self):

        from Products.Five.bridge import fromZ2Interface

        class IAttributes(Z2_Interface):
            one = Z2_Attribute('one', 'One attribute')
            another = Z2_Attribute('another', 'Another attribute')

        converted = fromZ2Interface(IAttributes)

        self.failUnless(Z3_Interface.isEqualOrExtendedBy(converted))
        self.assertEqual(len(converted.names()), 2)
        self.failUnless('one' in converted.names())
        self.failUnless('another' in converted.names())

        one = converted.getDescriptionFor('one')
        self.failUnless(isinstance(one, Z3_Attribute))
        self.assertEqual(one.getName(), 'one')
        self.assertEqual(one.getDoc(), 'One attribute')

        another = converted.getDescriptionFor('another')
        self.failUnless(isinstance(another, Z3_Attribute))
        self.assertEqual(another.getName(), 'another')
        self.assertEqual(another.getDoc(), 'Another attribute')
Ejemplo n.º 17
0
    def test_fromZ2Interface_attributes(self):

        from Products.Five.bridge import fromZ2Interface

        class IAttributes(Z2_Interface):
            one = Z2_Attribute('one', 'One attribute')
            another = Z2_Attribute('another', 'Another attribute')

        converted = fromZ2Interface(IAttributes)

        self.failUnless(Z3_Interface.isEqualOrExtendedBy(converted))
        self.assertEqual(len(converted.names()), 2)
        self.failUnless('one' in converted.names())
        self.failUnless('another' in converted.names())

        one = converted.getDescriptionFor('one')
        self.failUnless(isinstance(one, Z3_Attribute))
        self.assertEqual(one.getName(), 'one')
        self.assertEqual(one.getDoc(), 'One attribute')

        another = converted.getDescriptionFor('another')
        self.failUnless(isinstance(another, Z3_Attribute))
        self.assertEqual(another.getName(), 'another')
        self.assertEqual(another.getDoc(), 'Another attribute')
Ejemplo n.º 18
0
def test_persistent_registry():
    db = DB(DemoStorage())
    tm = transaction.TransactionManager()

    registry = PersistentRegistry()
    siteobj = Site()

    with Connection(db, transaction_manager=tm) as conn:
        with tm:
            conn.root()['site'] = siteobj
            siteobj.setLocalRegistry(registry)
            registry.register((Interface,), Interface, 'dummy2', dummy2)

    with Connection(db) as conn:
        site = conn.root()['site']
        reg = site.getLocalRegistry()
        assert reg is registry
        assert reg.lookup((Interface,), Interface, 'dummy2') == dummy2

    with Connection(db) as conn:
        site = conn.root()['site']
        reg = site.getLocalRegistry()

        assert Interface.component((Interface,), name='dummy') == dummy
        with pytest.raises(ComponentLookupError):
            Interface.component((Interface,), name='dummy2')

        with LookupContext(reg):
            assert Interface.component((Interface,), name='dummy2') == dummy2
            with pytest.raises(ComponentLookupError):
                Interface.component((Interface,), name='dummy')

        with pytest.raises(ComponentLookupError):
            Interface.component((Interface,), name='dummy2')

    chain = ChainedLookup()
    chain.add(implicit.lookup)
    implicit.lookup = chain

    with Connection(db) as conn:
        site = conn.root()['site']
        reg = site.getLocalRegistry()

        with LookupChainLink(reg):
            assert Interface.component((Interface,), name='dummy2') == dummy2
            assert Interface.component((Interface,), name='dummy') == dummy

        with pytest.raises(ComponentLookupError):
            Interface.component((Interface,), name='dummy2')

    link = Registry()
    link.register((Interface,), Interface, 'dummy', dummy3)

    with Connection(db) as conn:
        site = conn.root()['site']
        reg = site.getLocalRegistry()

        with LookupChainLink(reg):
            with LookupChainLink(link):
                assert Interface.component((Interface,), name='dummy2') == dummy2
                assert Interface.component((Interface,), name='dummy') == dummy3

                with LookupContext(link):
                    with pytest.raises(ComponentLookupError):
                        assert Interface.component((Interface,), name='dummy2') == dummy2
                    assert Interface.component((Interface,), name='dummy') == dummy3

                with pytest.raises(KeyError):
                    with LookupChainLink(link):
                        pass

                assert Interface.component((Interface,), name='dummy2') == dummy2
                assert Interface.component((Interface,), name='dummy') == dummy3
                    
            assert Interface.component((Interface,), name='dummy2') == dummy2
            assert Interface.component((Interface,), name='dummy') == dummy
Ejemplo n.º 19
0
def _create_dynamic_interface(name=None, cache=None):
    if not name in cache:
        cache[name] = Interface.__class__(name=name)
    return cache[name]
Ejemplo n.º 20
0
 def testVerifyImplementation(self):
     from zope.interface.verify import verifyClass
     self.assert_(verifyClass(FooInterface, Foo))
     self.assert_(Interface.providedBy(I1))
Ejemplo n.º 21
0
def dispatch(*events):
    for sub in Interface.subscription(*events):
        sub(*events)
Ejemplo n.º 22
0
def objectEventNotify(event):
    """Dispatch ObjectEvents to interested adapters.
    """
    for handler in Interface.subscription(event.object, event):
        handler(event.object, event)
Ejemplo n.º 23
0
                input("Ingrese la posicion en la que se va a insertar: "))
            try:
                coleccion.insertarElemento(numero, pos)
            except ErrorPosicion as e:
                print(
                    "El numero {} no pudo ser insertado debido al siguiente error:"
                    .format(e.getElemento()))
                print(e.getMensaje())
        elif op == 2:
            numero = int(input("Ingrese un numero a agregar al final: "))
            coleccion.agregarElemento(numero)
        elif op == 3:
            pos = int(input("Ingrese la posicion del numero a mostrar: "))
            try:
                print(coleccion.mostrarElemento(pos))
            except ErrorPosicion as e:
                print(
                    "El numero {} no pudo ser mostrado debido al siguiente error:"
                    .format(e.getElemento()))
                print(e.getMensaje())
        elif op == 0:
            flag = True
        else:
            print("Opcion no valida")


if __name__ == "__main__":
    c = Coleccion()

    Interface(IColeccion(c))
Ejemplo n.º 24
0
 def testVerifyImplementation(self):
     from zope.interface.verify import verifyClass
     self.assert_(verifyClass(FooInterface, Foo))
     self.assert_(Interface.providedBy(I1))
Ejemplo n.º 25
0
 def __call__(self, req):
     context = Location()
     directlyProvides(context, IPublicationRoot)
     form = Interface(context, req, name=self.formname)
     return form()