Python zope.interface.implements() Examples

The following are 30 code examples of zope.interface.implements(). 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_declarations.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_classImplement_on_deeply_nested_classes():
    """This test is in response to a bug found, which is why it's a bit
    contrived

    >>> from zope.interface import *
    >>> class B1(object):
    ...     pass
    >>> class B2(B1):
    ...     pass
    >>> class B3(B2):
    ...     pass
    >>> class D(object):
    ...     implements()
    >>> class S(B3, D):
    ...     implements()

    This failed due to a bug in the code for finding __providedBy__
    descriptors for old-style classes.

    """ 
Example #2
Source File: test_declarations.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def test_classProvides_before_implements():
    """Special descriptor for class __provides__

    The descriptor caches the implementedBy info, so that
    we can get declarations for objects without instance-specific
    interfaces a bit quicker.

        For example::

          >>> from zope.interface import Interface, classProvides
          >>> class IFooFactory(Interface):
          ...     pass
          >>> class IFoo(Interface):
          ...     pass
          >>> class C(object):
          ...     classProvides(IFooFactory)
          ...     implements(IFoo)
          >>> [i.getName() for i in C.__provides__]
          ['IFooFactory']

          >>> [i.getName() for i in C().__provides__]
          ['IFoo']
    """ 
Example #3
Source File: checkers.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def requestAvatarId(credentials):
        """
        @param credentials: something which implements one of the interfaces in
        self.credentialInterfaces.

        @return: a Deferred which will fire a string which identifies an
        avatar, an empty tuple to specify an authenticated anonymous user
        (provided as checkers.ANONYMOUS) or fire a Failure(UnauthorizedLogin).
        Alternatively, return the result itself.

        @see: L{twisted.cred.credentials}
        """



# A note on anonymity - We do not want None as the value for anonymous
# because it is too easy to accidentally return it.  We do not want the
# empty string, because it is too easy to mistype a password file.  For
# example, an .htpasswd file may contain the lines: ['hello:asdf',
# 'world:asdf', 'goodbye', ':world'].  This misconfiguration will have an
# ill effect in any case, but accidentally granting anonymous access is a
# worse failure mode than simply granting access to an untypeable
# username.  We do not want an instance of 'object', because that would
# create potential problems with persistence. 
Example #4
Source File: http.py    From python-for-android with Apache License 2.0 6 votes vote down vote up
def isSecure(self):
        """
        Return True if this request is using a secure transport.

        Normally this method returns True if this request's HTTPChannel
        instance is using a transport that implements ISSLTransport.

        This will also return True if setHost() has been called
        with ssl=True.

        @returns: True if this request is secure
        @rtype: C{bool}
        """
        if self._forceSSL:
            return True
        transport = getattr(getattr(self, 'channel', None), 'transport', None)
        if interfaces.ISSLTransport(transport, None) is not None:
            return True
        return False 
Example #5
Source File: imap4.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def messageFile(self, octets):
        """Create a file to which an incoming message may be written.

        @type octets: C{int}
        @param octets: The number of octets which will be written to the file

        @rtype: Any object which implements C{write(string)} and
        C{seek(int, int)}
        @return: A file-like object
        """
        if octets > self._memoryFileLimit:
            return tempfile.TemporaryFile()
        else:
            return StringIO.StringIO() 
Example #6
Source File: test_policies.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_transportInterfaces(self):
        """
        The transport wrapper passed to the wrapped protocol's
        C{makeConnection} provides the same interfaces as are provided by the
        original transport.
        """
        class IStubTransport(Interface):
            pass

        class StubTransport:
            implements(IStubTransport)

        # Looking up what ProtocolWrapper implements also mutates the class.
        # It adds __implemented__ and __providedBy__ attributes to it.  These
        # prevent __getattr__ from causing the IStubTransport.providedBy call
        # below from returning True.  If, by accident, nothing else causes
        # these attributes to be added to ProtocolWrapper, the test will pass,
        # but the interface will only be provided until something does trigger
        # their addition.  So we just trigger it right now to be sure.
        implementedBy(policies.ProtocolWrapper)

        proto = protocol.Protocol()
        wrapper = policies.ProtocolWrapper(policies.WrappingFactory(None), proto)

        wrapper.makeConnection(StubTransport())
        self.assertTrue(IStubTransport.providedBy(proto.transport)) 
Example #7
Source File: test_ftp.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_interface(self):
        """
        L{ftp.BaseFTPRealm} implements L{IRealm}.
        """
        self.assertTrue(verifyClass(IRealm, ftp.BaseFTPRealm)) 
Example #8
Source File: controller.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def registerControllerForModel(controller, model):
    """
    Registers `controller' as an adapter of `model' for IController, and
    optionally registers it for IResource, if it implements it.

    @param controller: A class that implements L{interfaces.IController}, usually a
           L{Controller} subclass. Optionally it can implement
           L{resource.IResource}.
    @param model: Any class, but probably a L{twisted.web.woven.model.Model}
           subclass.
    """
    components.registerAdapter(controller, model, interfaces.IController)
    if resource.IResource.implementedBy(controller):
        components.registerAdapter(controller, model, resource.IResource) 
Example #9
Source File: app.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def listenWith(self, portType, *args, **kw):
        """
        Start an instance of the given C{portType} listening.

        @type portType: type which implements C{IListeningPort}
        """
        self.extraPorts.append((portType, args, kw))
        if self.running:
            from twisted.internet import reactor
            p = reactor.listenWith(portType, *args, **kw)
            self._extraListeners[(portType, args, kw)] = p
            return p 
Example #10
Source File: app.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def connectWith(self, connectorType, *args, **kw):
        """
        Start an instance of the given C{connectorType} connecting.

        @type connectorType: type which implements C{IConnector}
        """
        self.extraConnectors.append((connectorType, args, kw))
        if self.running:
            from twisted.internet import reactor
            return reactor.connectWith(connectorType, *args, **kw) 
Example #11
Source File: compat.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def listenWith(self, portType, *args, **kw):
        """Add a service that starts an instance of C{portType} listening.

        @type portType: type which implements C{IListeningPort}
        @param portType: The object given by C{portType(*args, **kw)}
        will be started listening.
        """ 
Example #12
Source File: compat.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def connectWith(self, connectorType, *args, **kw):
        """Add a service that starts an instance of C{connectorType} connecting.

        @type connectorType: type which implements C{IConnector}
        @param connectorType: The object given by C{connectorType(*args, **kw)}
        will be started connecting.
        """ 
Example #13
Source File: htb.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, protoClass, bucketFilter):
        """Tell me what to wrap and where to get buckets.

        @param protoClass: The class of Protocol I will generate
          wrapped instances of.
        @type protoClass: L{Protocol<twisted.internet.interfaces.IProtocol>}
          class
        @param bucketFilter: The filter which will determine how
          traffic is shaped.
        @type bucketFilter: L{HierarchicalBucketFilter}.
        """
        # More precisely, protoClass can be any callable that will return
        # instances of something that implements IProtocol.
        self.protocol = protoClass
        self.bucketFilter = bucketFilter 
Example #14
Source File: test_smtp.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_portalRejectedSenderAddress(self):
        """
        Test that a C{MAIL FROM} command with an address rejected by an
        L{smtp.SMTP} instance's portal is responded to with the correct error
        code.
        """
        class DisallowAnonymousAccess(object):
            """
            Checker for L{IAnonymous} which rejects authentication attempts.
            """
            implements(ICredentialsChecker)

            credentialInterfaces = (IAnonymous,)

            def requestAvatarId(self, credentials):
                return defer.fail(UnauthorizedLogin())

        realm = SingletonRealm(smtp.IMessageDelivery, NotImplementedDelivery())
        portal = Portal(realm, [DisallowAnonymousAccess()])
        proto = smtp.SMTP()
        proto.portal = portal
        trans = StringTransport()
        proto.makeConnection(trans)

        # Deal with the necessary preliminaries
        proto.dataReceived('HELO example.com\r\n')
        trans.clear()

        # Try to specify our sender address
        proto.dataReceived('MAIL FROM:<alice@example.com>\r\n')

        # Clean up the protocol before doing anything that might raise an
        # exception.
        proto.connectionLost(error.ConnectionLost())

        # Make sure that we received exactly the correct response
        self.assertEqual(
            trans.value(),
            '550 Cannot receive from specified address '
            '<alice@example.com>: Sender not acceptable\r\n') 
Example #15
Source File: imap4.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def addListener(self, listener):
        """Add a mailbox change listener

        @type listener: Any object which implements C{IMailboxListener}
        @param listener: An object to add to the set of those which will
        be notified when the contents of this mailbox change.
        """ 
Example #16
Source File: test_components.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def testMultipleInterfaceRegistration(self):
        class IMIFoo(components.Interface):
            pass
        class IMIBar(components.Interface):
            pass
        class MIFooer(components.Adapter):
            zinterface.implements(IMIFoo, IMIBar)
        class Blegh:
            pass
        components.registerAdapter(MIFooer, Blegh, IMIFoo, IMIBar)
        self.assert_(isinstance(IMIFoo(Blegh()), MIFooer))
        self.assert_(isinstance(IMIBar(Blegh()), MIFooer)) 
Example #17
Source File: test_components.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def testClassIsGCd(self):
        import weakref, gc
        class Test(object):
            zinterface.implements(IZope)
        # Do some stuff with it
        components.backwardsCompatImplements(Test)
        IZope(Test())

        # Make a weakref to it, then ensure the weakref goes away
        r = weakref.ref(Test)
        del Test
        gc.collect()
        self.assertEquals(r(), None) 
Example #18
Source File: idea.py    From imaginary with MIT License 5 votes vote down vote up
def _doObtain(self, retriever, path, reasonsWhyNot):
        """
        A generator that implements the logic for obtain()
        """
        if path is None:
            # Special case: we only get a self->self link if we are the
            # beginning _and_ the end.
            path = Path(links=[])
            selfLink = Link(source=self, target=self)
            self._annotateOneLink(selfLink)
            finalPath = path.to(selfLink)
        else:
            finalPath = Path(links=path.links[:])
            self._annotateOneLink(finalPath.links[-1])

        result = retriever.retrieve(finalPath)
        objections = set(retriever.objectionsTo(finalPath, result))
        reasonsWhyNot |= objections
        if result is not None:
            if not objections:
                yield result

        for link in self._applyAnnotators(self._allLinks()):
            subpath = path.to(link)
            if subpath.isCyclic():
                continue
            if retriever.shouldKeepGoing(subpath):
                for obtained in link.target._doObtain(retriever, subpath, reasonsWhyNot):
                    yield obtained 
Example #19
Source File: test_userbase.py    From axiom with MIT License 5 votes vote down vote up
def test_install(self):
        """
        Create a database, install userbase and check that the store
        implements L{IRealm} and L{ICredentialsChecker}. i.e. that userbase
        has been installed. This is an integration test.
        """
        self.userbase('install')
        self.assertImplements(self.store, IRealm)
        self.assertImplements(self.store, ICredentialsChecker) 
Example #20
Source File: test_userbase.py    From axiom with MIT License 5 votes vote down vote up
def test_usernamepassword(self):
        """
        L{Preauthenticated} implements L{IUsernamePassword} and succeeds all
        authentication checks.
        """
        creds = userbase.Preauthenticated(u'foo@bar')
        self.assertTrue(
            verifyObject(IUsernamePassword, creds),
            "Preauthenticated does not implement IUsernamePassword")
        self.assertTrue(
            creds.checkPassword('random string'),
            "Preauthenticated did not accept an arbitrary password.") 
Example #21
Source File: test_userbase.py    From axiom with MIT License 5 votes vote down vote up
def test_usernamehashedpassword(self):
        """
        L{Preauthenticated} implements L{IUsernameHashedPassword} and succeeds
        all authentication checks.
        """
        creds = userbase.Preauthenticated(u'foo@bar')
        self.assertTrue(
            verifyObject(IUsernameHashedPassword, creds),
            "Preauthenticated does not implement IUsernameHashedPassword")
        self.assertTrue(
            creds.checkPassword('arbitrary bytes'),
            "Preauthenticated did not accept an arbitrary password.") 
Example #22
Source File: test_declarations.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_picklability_of_implements_specifications():
    """

    Sometimes, we need to pickle implements specs.  We should be able
    to do so as long as the class is picklable.

    >>> import pickle
    >>> pickle.loads(pickle.dumps(implementedBy(C))) is implementedBy(C)
    True


    """ 
Example #23
Source File: mailbox.py    From bitmask-dev with GNU General Public License v3.0 5 votes vote down vote up
def removeListener(self, listener):
        """
        Remove a listener from the listeners queue.

        :param listener: listener to remove
        :type listener: an object that implements IMailboxListener
        """
        self.listeners.remove(listener) 
Example #24
Source File: wireprotocol.py    From OpenBazaar-Server with MIT License 5 votes vote down vote up
def register_processor(self, processor):
        """Add a new class which implements the `MessageProcessor` interface."""
        if verifyObject(MessageProcessor, processor):
            self.processors.append(processor) 
Example #25
Source File: twisted_test.py    From honeything with GNU General Public License v3.0 5 votes vote down vote up
def implements(f):
        pass 
Example #26
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 #27
Source File: test_declarations.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_builtins(self):
        # Setup

        intspec = implementedBy(int)
        olddeclared = intspec.declared

        classImplements(int, I1)
        class myint(int):
            implements(I2)

        x = 42
        self.assertEqual([i.getName() for i in providedBy(x)],
                         ['I1'])

        x = myint(42)
        directlyProvides(x, I3)
        self.assertEqual([i.getName() for i in providedBy(x)],
                         ['I3', 'I2', 'I1'])

        # cleanup
        intspec.declared = olddeclared
        classImplements(int)

        x = 42
        self.assertEqual([i.getName() for i in providedBy(x)],
                         []) 
Example #28
Source File: test_declarations.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_classImplements_after_classImplementsOnly_issue_402():
    """http://www.zope.org/Collectors/Zope3-dev/402

>>> from zope.interface import *
>>> class I1(Interface):
...     pass
>>> class I2(Interface):
...     pass
>>> class C:
...     implements(I1)
>>> class C2:
...     implementsOnly(I2)
>>> class I3(Interface):
...     pass

>>> [i.__name__ for i in providedBy(C2()).__iro__]
['I2', 'Interface']

>>> classImplements(C2, I3)
>>> [i.__name__ for i in providedBy(C2()).__iro__]
['I2', 'I3', 'Interface']

>>> class I4(Interface):
...     pass
>>> classImplements(C2, I4)
>>> [i.__name__ for i in providedBy(C2()).__iro__]
['I2', 'I3', 'I4', 'Interface']


""" 
Example #29
Source File: dns.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def lookupRecordType(self, type):
        """
        Retrieve the L{IRecord} implementation for the given record type.

        @param type: A record type, such as L{A} or L{NS}.
        @type type: C{int}

        @return: An object which implements L{IRecord} or C{None} if none
            can be found for the given type.
        @rtype: L{types.ClassType}
        """
        return self._recordTypes.get(type, None) 
Example #30
Source File: test_httpauth.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def test_interface(self):
        """
        L{BasicCredentialFactory} implements L{ICredentialFactory}.
        """
        self.assertTrue(
            verifyObject(ICredentialFactory, self.credentialFactory))