Python zope.interface.providedBy() Examples

The following are 30 code examples of zope.interface.providedBy(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module zope.interface , or try the search function .
Example #1
Source File: test_interface.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def testObjectImplements(self):
        from zope.interface.tests.unitfixtures import A
        from zope.interface.tests.unitfixtures import B
        from zope.interface.tests.unitfixtures import C
        from zope.interface.tests.unitfixtures import D
        from zope.interface.tests.unitfixtures import E
        from zope.interface.tests.unitfixtures import I1
        from zope.interface.tests.unitfixtures import I2
        from zope.interface.tests.unitfixtures import IC
        self.assert_(IC.providedBy(C()))

        self.assert_(I1.providedBy(A()))
        self.assert_(I1.providedBy(B()))
        self.assert_(not I1.providedBy(C()))
        self.assert_(I1.providedBy(D()))
        self.assert_(I1.providedBy(E()))

        self.assert_(not I2.providedBy(A()))
        self.assert_(I2.providedBy(B()))
        self.assert_(not I2.providedBy(C()))

        # Not after interface geddon
        # self.assert_(not I2.providedBy(D()))

        self.assert_(not I2.providedBy(E())) 
Example #2
Source File: test_declarations.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_provided_by_with_slots():
    """

    This is an edge case: if the __slots__ of a class contain '__provides__',
    using providedBy() on that class should still work (this occurs, for
    example, when providing an adapter for a concrete class.)

    >>> import zope.interface
    >>> class Slotted(object):
    ...     __slots__ = ('__provides__')
    >>> class IFoo(zope.interface.Interface):
    ...     pass
    >>> IFoo.providedBy(Slotted)
    False

    """ 
Example #3
Source File: test_interface.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def test_classImplements_base_not_derived(self):
        from zope.interface import Interface
        from zope.interface import implementedBy
        from zope.interface import providedBy
        class IBase(Interface):
            def method():
                pass
        class IDerived(IBase):
            pass
        class Current():
            __implemented__ = IBase
            def method(self):
                pass
        current = Current()

        self.assertTrue(IBase.implementedBy(Current))
        self.assertFalse(IDerived.implementedBy(Current))
        self.assertTrue(IBase in implementedBy(Current))
        self.assertFalse(IDerived in implementedBy(Current))
        self.assertTrue(IBase in providedBy(current))
        self.assertFalse(IDerived in providedBy(current)) 
Example #4
Source File: test_interface.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def testUtil(self):
        from zope.interface import implementedBy
        from zope.interface import providedBy
        from zope.interface.tests.unitfixtures import A
        from zope.interface.tests.unitfixtures import B
        from zope.interface.tests.unitfixtures import C
        from zope.interface.tests.unitfixtures import I1
        from zope.interface.tests.unitfixtures import I2
        from zope.interface.tests.unitfixtures import IC
        self.assert_(IC in implementedBy(C))
        self.assert_(I1 in implementedBy(A))
        self.assert_(not I1 in implementedBy(C))
        self.assert_(I2 in implementedBy(B))
        self.assert_(not I2 in implementedBy(C))

        self.assert_(IC in providedBy(C()))
        self.assert_(I1 in providedBy(A()))
        self.assert_(not I1 in providedBy(C()))
        self.assert_(I2 in providedBy(B()))
        self.assert_(not I2 in providedBy(C())) 
Example #5
Source File: tls.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def makeConnection(self, transport):
        """
        Connect this wrapper to the given transport and initialize the
        necessary L{OpenSSL.SSL.Connection} with a memory BIO.
        """
        self._tlsConnection = self.factory._createConnection(self)
        self._appSendBuffer = []

        # Add interfaces provided by the transport we are wrapping:
        for interface in providedBy(transport):
            directlyProvides(self, interface)

        # Intentionally skip ProtocolWrapper.makeConnection - it might call
        # wrappedProtocol.makeConnection, which we want to make conditional.
        Protocol.makeConnection(self, transport)
        self.factory.registerProtocol(self)
        if self._connectWrapped:
            # Now that the TLS layer is initialized, notify the application of
            # the connection.
            ProtocolWrapper.makeConnection(self, transport)

        # Now that we ourselves have a transport (initialized by the
        # ProtocolWrapper.makeConnection call above), kick off the TLS
        # handshake.
        self._checkHandshakeStatus() 
Example #6
Source File: tls.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def _checkHandshakeStatus(self):
        """
        Ask OpenSSL to proceed with a handshake in progress.

        Initially, this just sends the ClientHello; after some bytes have been
        stuffed in to the C{Connection} object by C{dataReceived}, it will then
        respond to any C{Certificate} or C{KeyExchange} messages.
        """
        # The connection might already be aborted (eg. by a callback during
        # connection setup), so don't even bother trying to handshake in that
        # case.
        if self._aborted:
            return
        try:
            self._tlsConnection.do_handshake()
        except WantReadError:
            self._flushSendBIO()
        except Error:
            self._tlsShutdownFinished(Failure())
        else:
            self._handshakeDone = True
            if IHandshakeListener.providedBy(self.wrappedProtocol):
                self.wrappedProtocol.handshakeCompleted() 
Example #7
Source File: checkers.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def requestAvatarId(self, credentials):
        """
        Part of the L{ICredentialsChecker} interface.  Called by a portal with
        some credentials to check if they'll authenticate a user.  We check the
        interfaces that the credentials provide against our list of acceptable
        checkers.  If one of them matches, we ask that checker to verify the
        credentials.  If they're valid, we call our L{_cbGoodAuthentication}
        method to continue.

        @param credentials: the credentials the L{Portal} wants us to verify
        """
        ifac = providedBy(credentials)
        for i in ifac:
            c = self.checkers.get(i)
            if c is not None:
                d = defer.maybeDeferred(c.requestAvatarId, credentials)
                return d.addCallback(self._cbGoodAuthentication,
                        credentials)
        return defer.fail(UnhandledCredentials("No checker for %s" % \
            ', '.join(map(reflect.qual, ifac)))) 
Example #8
Source File: checkers.py    From Safejumper-for-Desktop with GNU General Public License v2.0 6 votes vote down vote up
def requestAvatarId(self, credentials):
        """
        Part of the L{ICredentialsChecker} interface.  Called by a portal with
        some credentials to check if they'll authenticate a user.  We check the
        interfaces that the credentials provide against our list of acceptable
        checkers.  If one of them matches, we ask that checker to verify the
        credentials.  If they're valid, we call our L{_cbGoodAuthentication}
        method to continue.

        @param credentials: the credentials the L{Portal} wants us to verify
        """
        ifac = providedBy(credentials)
        for i in ifac:
            c = self.checkers.get(i)
            if c is not None:
                d = defer.maybeDeferred(c.requestAvatarId, credentials)
                return d.addCallback(self._cbGoodAuthentication,
                        credentials)
        return defer.fail(UnhandledCredentials("No checker for %s" % \
            ', '.join(map(reflect.qual, ifac)))) 
Example #9
Source File: tls.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def _applyProtocolNegotiation(self, connection):
        """
        Applies ALPN/NPN protocol neogitation to the connection, if the factory
        supports it.

        @param connection: The OpenSSL connection object to have ALPN/NPN added
            to it.
        @type connection: L{OpenSSL.SSL.Connection}

        @return: Nothing
        @rtype: L{None}
        """
        if IProtocolNegotiationFactory.providedBy(self.wrappedFactory):
            protocols = self.wrappedFactory.acceptableProtocols()
            context = connection.get_context()
            _setAcceptableProtocols(context, protocols)

        return 
Example #10
Source File: tls.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def _checkHandshakeStatus(self):
        """
        Ask OpenSSL to proceed with a handshake in progress.

        Initially, this just sends the ClientHello; after some bytes have been
        stuffed in to the C{Connection} object by C{dataReceived}, it will then
        respond to any C{Certificate} or C{KeyExchange} messages.
        """
        # The connection might already be aborted (eg. by a callback during
        # connection setup), so don't even bother trying to handshake in that
        # case.
        if self._aborted:
            return
        try:
            self._tlsConnection.do_handshake()
        except WantReadError:
            self._flushSendBIO()
        except Error:
            self._tlsShutdownFinished(Failure())
        else:
            self._handshakeDone = True
            if IHandshakeListener.providedBy(self.wrappedProtocol):
                self.wrappedProtocol.handshakeCompleted() 
Example #11
Source File: test_interface.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def test_classImplements_base_not_derived(self):
        from zope.interface import Interface
        from zope.interface import implementedBy
        from zope.interface import providedBy
        class IBase(Interface):
            def method():
                pass
        class IDerived(IBase):
            pass
        class Current():
            __implemented__ = IBase
            def method(self):
                raise NotImplementedError()
        current = Current()

        self.assertTrue(IBase.implementedBy(Current))
        self.assertFalse(IDerived.implementedBy(Current))
        self.assertTrue(IBase in implementedBy(Current))
        self.assertFalse(IDerived in implementedBy(Current))
        self.assertTrue(IBase in providedBy(current))
        self.assertFalse(IDerived in providedBy(current)) 
Example #12
Source File: tls.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def makeConnection(self, transport):
        """
        Connect this wrapper to the given transport and initialize the
        necessary L{OpenSSL.SSL.Connection} with a memory BIO.
        """
        self._tlsConnection = self.factory._createConnection(self)
        self._appSendBuffer = []

        # Add interfaces provided by the transport we are wrapping:
        for interface in providedBy(transport):
            directlyProvides(self, interface)

        # Intentionally skip ProtocolWrapper.makeConnection - it might call
        # wrappedProtocol.makeConnection, which we want to make conditional.
        Protocol.makeConnection(self, transport)
        self.factory.registerProtocol(self)
        if self._connectWrapped:
            # Now that the TLS layer is initialized, notify the application of
            # the connection.
            ProtocolWrapper.makeConnection(self, transport)

        # Now that we ourselves have a transport (initialized by the
        # ProtocolWrapper.makeConnection call above), kick off the TLS
        # handshake.
        self._checkHandshakeStatus() 
Example #13
Source File: test_http.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def _makeRequestProxyFactory(clsToWrap):
    """
    Return a callable that proxies instances of C{clsToWrap} via
        L{_IDeprecatedHTTPChannelToRequestInterface}.

    @param clsToWrap: The class whose instances will be proxied.
    @type cls: L{_IDeprecatedHTTPChannelToRequestInterface}
        implementer.

    @return: A factory that returns
        L{_IDeprecatedHTTPChannelToRequestInterface} proxies.
    @rtype: L{callable} whose interface matches C{clsToWrap}'s constructor.
    """

    def _makeRequestProxy(*args, **kwargs):
        instance = clsToWrap(*args, **kwargs)
        return _IDeprecatedHTTPChannelToRequestInterfaceProxy(instance)

    # For INonQueuedRequestFactory
    directlyProvides(_makeRequestProxy, providedBy(clsToWrap))
    return _makeRequestProxy 
Example #14
Source File: test_declarations.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_backward_compat(self):

        class C1(object): __implemented__ = I1
        class C2(C1): __implemented__ = I2, I5
        class C3(C2): __implemented__ = I3, C2.__implemented__

        self.assert_(C3.__implemented__.__class__ is tuple)

        self.assertEqual(
            [i.getName() for i in providedBy(C3())],
            ['I3', 'I2', 'I5'],
            )

        class C4(C3):
            implements(I4)

        self.assertEqual(
            [i.getName() for i in providedBy(C4())],
            ['I4', 'I3', 'I2', 'I5'],
            )

        self.assertEqual(
            [i.getName() for i in C4.__implemented__],
            ['I4', 'I3', 'I2', 'I5'],
            )

        # Note that C3.__implemented__ should now be a sequence of interfaces
        self.assertEqual(
            [i.getName() for i in C3.__implemented__],
            ['I3', 'I2', 'I5'],
            )
        self.failIf(C3.__implemented__.__class__ is tuple) 
Example #15
Source File: test_declarations.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_ObjectSpecification_Simple_old_style():
    """
    >>> c = COnly_old()
    >>> directlyProvides(c, I4)
    >>> [i.__name__ for i in providedBy(c)]
    ['I4', 'I3']
    """ 
Example #16
Source File: test_declarations.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_ObjectSpecification_Simple():
    """
    >>> c = C()
    >>> directlyProvides(c, I4)
    >>> [i.__name__ for i in providedBy(c)]
    ['I4', 'I3', 'I1', 'I2']
    """ 
Example #17
Source File: plugin.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def _generateCacheEntry(provider):
    dropin = CachedDropin(provider.__name__,
                          provider.__doc__)
    for k, v in iteritems(provider.__dict__):
        plugin = IPlugin(v, None)
        if plugin is not None:
            # Instantiated for its side-effects.
            CachedPlugin(dropin, k, v.__doc__, list(providedBy(plugin)))
    return dropin 
Example #18
Source File: policies.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def makeConnection(self, transport):
        """
        When a connection is made, register this wrapper with its factory,
        save the real transport, and connect the wrapped protocol to this
        L{ProtocolWrapper} to intercept any transport calls it makes.
        """
        directlyProvides(self, providedBy(transport))
        Protocol.makeConnection(self, transport)
        self.factory.registerProtocol(self)
        self.wrappedProtocol.makeConnection(self)

    # Transport relaying 
Example #19
Source File: tls.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def logPrefix(self):
        """
        Annotate the wrapped factory's log prefix with some text indicating TLS
        is in use.

        @rtype: C{str}
        """
        if ILoggingContext.providedBy(self.wrappedFactory):
            logPrefix = self.wrappedFactory.logPrefix()
        else:
            logPrefix = self.wrappedFactory.__class__.__name__
        return "%s (TLS)" % (logPrefix,) 
Example #20
Source File: plugin.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def _generateCacheEntry(provider):
    dropin = CachedDropin(provider.__name__,
                          provider.__doc__)
    for k, v in provider.__dict__.iteritems():
        plugin = IPlugin(v, None)
        if plugin is not None:
            cachedPlugin = CachedPlugin(dropin, k, v.__doc__, list(providedBy(plugin)))
    return dropin 
Example #21
Source File: data_manager.py    From nova-ideo with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_obj_value(obj, fields={}):
    interfaces = [i for i in providedBy(obj).interfaces()]
    if not interfaces:
        return {}

    result = {}
    objects_to_add = []
    if fields:
        for interface in interfaces:
            attributes = [a for a in interface if a in fields and
                          isinstance(interface[a], Attribute)]
            for attr in attributes:
                result[attr], to_add = get_attr_value(
                    interface[attr], obj, fields.get(attr, {}))
                objects_to_add.extend(to_add)

    else:
        for interface in interfaces:
            attributes = [a for a in interface
                          if isinstance(interface[a], Attribute)]
            for attr in attributes:
                result[attr], to_add = get_attr_value(interface[attr], obj)
                objects_to_add.extend(to_add)

    result = normalize_value(result)
    result['@id'] = '_:' + str(get_oid(obj, 'None'))
    result['@type'] = getattr(
        obj, 'type_title', obj.__class__.__name__)
    contributors = getattr(obj, 'contributors', None)
    if contributors:
        result['creator_email'] = contributors[0].email
    return result, objects_to_add 
Example #22
Source File: policies.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def makeConnection(self, transport):
        """
        When a connection is made, register this wrapper with its factory,
        save the real transport, and connect the wrapped protocol to this
        L{ProtocolWrapper} to intercept any transport calls it makes.
        """
        directlyProvides(self, providedBy(transport))
        Protocol.makeConnection(self, transport)
        self.factory.registerProtocol(self)
        self.wrappedProtocol.makeConnection(self)


    # Transport relaying 
Example #23
Source File: policies.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def _wrappedLogPrefix(wrapper, wrapped):
    """
    Compute a log prefix for a wrapper and the object it wraps.

    @rtype: C{str}
    """
    if ILoggingContext.providedBy(wrapped):
        logPrefix = wrapped.logPrefix()
    else:
        logPrefix = wrapped.__class__.__name__
    return "%s (%s)" % (logPrefix, wrapper.__class__.__name__) 
Example #24
Source File: test_endpoints.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_wrappingProtocolNotHandshakeListener(self):
        """
        Our L{_WrappingProtocol} should not provide L{IHandshakeListener}
        if the C{wrappedProtocol} doesn't.
        """
        tp = TestProtocol()
        p = endpoints._WrappingProtocol(None, tp)
        self.assertFalse(interfaces.IHandshakeListener.providedBy(p)) 
Example #25
Source File: test_endpoints.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_wrappingProtocolHandshakeListener(self):
        """
        Our L{_WrappingProtocol} should be an L{IHandshakeListener} if
        the C{wrappedProtocol} is.
        """
        handshakeListener = TestHandshakeListener()
        wrapped = endpoints._WrappingProtocol(None, handshakeListener)
        self.assertTrue(interfaces.IHandshakeListener.providedBy(wrapped)) 
Example #26
Source File: test_endpoints.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_wrappingProtocolNotHalfCloseable(self):
        """
        Our L{_WrappingProtocol} should not provide L{IHalfCloseableProtocol}
        if the C{WrappedProtocol} doesn't.
        """
        tp = TestProtocol()
        p = endpoints._WrappingProtocol(None, tp)
        self.assertEqual(
            interfaces.IHalfCloseableProtocol.providedBy(p), False) 
Example #27
Source File: test_endpoints.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_wrappingProtocolHalfCloseable(self):
        """
        Our L{_WrappingProtocol} should be an L{IHalfCloseableProtocol} if the
        C{wrappedProtocol} is.
        """
        cd = object()
        hcp = TestHalfCloseableProtocol()
        p = endpoints._WrappingProtocol(cd, hcp)
        self.assertEqual(
            interfaces.IHalfCloseableProtocol.providedBy(p), True) 
Example #28
Source File: test_endpoints.py    From learn_python3_spider with MIT License 5 votes vote down vote up
def test_wrappingProtocolNotFileDescriptorReceiver(self):
        """
        Our L{_WrappingProtocol} does not provide L{IHalfCloseableProtocol} if
        the wrapped protocol doesn't.
        """
        tp = TestProtocol()
        p = endpoints._WrappingProtocol(None, tp)
        self.assertFalse(interfaces.IFileDescriptorReceiver.providedBy(p)) 
Example #29
Source File: portal.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def login(self, credentials, mind, *interfaces):
        """
        @param credentials: an implementor of
        twisted.cred.credentials.ICredentials

        @param mind: an object which implements a client-side interface for
        your particular realm.  In many cases, this may be None, so if the word
        'mind' confuses you, just ignore it.

        @param interfaces: list of interfaces for the perspective that the mind
        wishes to attach to.  Usually, this will be only one interface, for
        example IMailAccount.  For highly dynamic protocols, however, this may
        be a list like (IMailAccount, IUserChooser, IServiceInfo).  To expand:
        if we are speaking to the system over IMAP, any information that will
        be relayed to the user MUST be returned as an IMailAccount implementor;
        IMAP clients would not be able to understand anything else.  Any
        information about unusual status would have to be relayed as a single
        mail message in an otherwise-empty mailbox.  However, in a web-based
        mail system, or a PB-based client, the ``mind'' object inside the web
        server (implemented with a dynamic page-viewing mechanism such as
        woven) or on the user's client program may be intelligent enough to
        respond to several ``server''-side interfaces.

        @return: A deferred which will fire a tuple of (interface,
        avatarAspect, logout).  The interface will be one of the interfaces
        passed in the 'interfaces' argument.  The 'avatarAspect' will implement
        that interface.  The 'logout' object is a callable which will detach
        the mind from the avatar.  It must be called when the user has
        conceptually disconnected from the service.  Although in some cases
        this will not be in connectionLost (such as in a web-based session), it
        will always be at the end of a user's interactive session.
        """
        ifac = interface.providedBy(credentials)
        for i in ifac:
            c = self.checkers.get(i)
            if c is not None:
                return maybeDeferred(c.requestAvatarId, credentials
                    ).addCallback(self.realm.requestAvatar, mind, *interfaces
                    )
        return defer.fail(failure.Failure(error.UnhandledCredentials(
            "No checker for %s" % ', '.join(map(reflect.qual, ifac))))) 
Example #30
Source File: adapter.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def subscribers(self, objects, provided):
        subscriptions = self.subscriptions(map(providedBy, objects), provided)
        if provided is None:
            result = ()
            for subscription in subscriptions:
                subscription(*objects)
        else:
            result = []
            for subscription in subscriptions:
                subscriber = subscription(*objects)
                if subscriber is not None:
                    result.append(subscriber)
        return result