예제 #1
0
파일: web.py 프로젝트: fxia22/ASM_xf
    def makeConfigurable(self, cfgInfo, container, name):
        """Create a new configurable to a container, based on input from web form."""
        cmd, args = string.split(cfgInfo, ' ', 1)
        if cmd == "new": # create
            obj = coil.createConfigurable(reflect.namedClass(args), container, name)
        elif cmd == "dis": # dispense
            methodHash = int(args)
            if components.implements(container, coil.IConfigurator) and container.getType(name):
                interface = container.getType(name)
            elif components.implements(container, coil.IConfigCollection):
                interface = container.entityType
            else:
                interface = None
            for t in self.dispensers.getDispensers(interface):
                obj, methodName, desc = t
                if hash(t) == methodHash:
                    cfg = coil.getConfigurator(obj)
                    obj = getattr(cfg, methodName)()
                    print "created %s from dispenser" % obj
                    break
        else:
            raise ValueError, "Unrecognized command %r in cfgInfo %r" % (cmd, cfgInfo)

        self.dispensers.addObject(obj)
        return obj
예제 #2
0
 def testInstances(self):
     o = MultiplyAndAdd()
     self.assert_( components.implements(o, IMultiply) )
     self.assert_( components.implements(o, IMultiply) )
     o = Sub()
     self.assert_( components.implements(o, IAdder) )
     self.assert_( components.implements(o, ISub) )
예제 #3
0
파일: wizard.py 프로젝트: braams/shtoom
 def _displayNext(self, next):
     if next is None:
         # we're done
         self.destroy()
     elif tpc.implements(next, IPage):
         self._displayPage(next)
     elif tpc.implements(next, IWizard):
         self.startWizard(next)
예제 #4
0
 def testOldSubclass(self):
     class IFoo(components.Interface):
         pass
     class ThirdParty(Zoper):
         __implements__ = Zoper.__implements__, IFoo
     self.assert_(components.implements(ThirdParty(), IAdder))
     self.assert_(components.implements(ThirdParty(), IFoo))
     self.assert_(components.implements(ThirdParty(), IZope))
예제 #5
0
    def testInstances(self):
        o = MultiplyAndAdd()
        self.assert_( components.implements(o, IMultiply) )
        self.assert_( components.implements(o, IMultiply) )

        o = Sub()
        self.assert_( components.implements(o, IAdder) )
        self.assert_( components.implements(o, ISub) )
예제 #6
0
파일: wizard.py 프로젝트: xregist/shtoom
 def _displayNext(self, next):
     if next is None:
         # we're done
         self.destroy()
     elif tpc.implements(next, IPage):
         self._displayPage(next)
     elif tpc.implements(next, IWizard):
         self.startWizard(next)
예제 #7
0
 def testOldSubclass(self):
     # someone has third party class that subclasses Zoper,
     # and expects Zoper to have __implements__ since Zoper
     # was originally written for twisted 1.3, pre zope.interface
     class IFoo(components.Interface):
         pass
     class ThirdParty(Zoper):
         __implements__ = Zoper.__implements__, IFoo
     self.assert_(components.implements(ThirdParty(), IAdder))
     self.assert_(components.implements(ThirdParty(), IFoo))
     self.assert_(components.implements(ThirdParty(), IZope))
예제 #8
0
 def __init__(self, interface, proto, maxPacketSize=8192, reactor=None):
     if components.implements(proto, ethernet.IEthernetProtocol):
         self.ethernet = 1
     else:
         self.ethernet = 0
         assert components.implements(proto, ip.IIPProtocol) # XXX: fix me
     base.BasePort.__init__(self, reactor)
     self.interface = interface
     self.protocol = proto
     self.maxPacketSize = maxPacketSize
     self.setLogStr()
 def __init__(self, interface, proto, maxPacketSize=8192, reactor=None):
     if components.implements(proto, ethernet.IEthernetProtocol):
         self.ethernet = 1
     else:
         self.ethernet = 0
         assert components.implements(proto, ip.IIPProtocol)  # XXX: fix me
     base.BasePort.__init__(self, reactor)
     self.interface = interface
     self.protocol = proto
     self.maxPacketSize = maxPacketSize
     self.setLogStr()
예제 #10
0
 def testOldSubclass(self):
     # someone has third party class that subclasses Zoper,
     # and expects Zoper to have __implements__ since Zoper
     # was originally written for twisted 1.3, pre zope.interface
     class IFoo(components.Interface):
         pass
     class ThirdParty(Zoper):
         __implements__ = Zoper.__implements__, IFoo
     self.assert_(components.implements(ThirdParty(), IAdder))
     self.assert_(components.implements(ThirdParty(), IFoo))
     self.assert_(components.implements(ThirdParty(), IZope))
예제 #11
0
파일: mail.py 프로젝트: galaxysd/BitTorrent
 def addDomain(self, name, domain):
     portal = cred.portal.Portal(domain)
     map(portal.registerChecker, domain.getCredentialsCheckers())
     self.domains[name] = domain
     self.portals[name] = portal
     if self.aliases and components.implements(domain, IAliasableDomain):
         domain.setAliasGroup(self.aliases)
예제 #12
0
파일: mail.py 프로젝트: fxia22/ASM_xf
def maildirDbmFactory(container, name):
    if components.implements(container, coil.IConfigurator):
        container = container.getInstance()
    path = os.path.join(container.storagePath, name)
    if not os.path.exists(path):
        os.makedirs(path)
    return maildir.MaildirDirdbmDomain(path)
예제 #13
0
파일: coil.py 프로젝트: fxia22/ASM_xf
    def configure(self, dict):
        """Set a list of configuration variables."""
        items = dict.items()

        for name, value in items:
            t = self.getType(name)
            if isinstance(t, types.TypeType):
                if not isinstance(value, t) or (value is None):
                    raise InvalidConfiguration("type mismatch")
            elif isinstance(t, types.ClassType) and issubclass(t, components.Interface):
                if not components.implements(value, t) or (value is None):
                    raise InvalidConfiguration("type mismatch")
            elif t == 'boolean':
                try:
                    if value: pass
                except:
                    raise InvalidConfiguration("non-boolean for boolean type")
            else:
                raise InvalidConfiguration("Configuration item '%s' has "
                                           "unknown type '%s'" % (name, t))

        for name, value in items:
            func = getattr(self, "config_%s" % name, None)
            if func:
                func(value)
            else:
                setattr(self.instance, name, value)
예제 #14
0
파일: coil.py 프로젝트: fxia22/ASM_xf
 def entityConstraint(self, entity):
     if isinstance(self.entityType, types.TypeType) and isinstance(entity, self.entityType):
         return 1
     elif components.implements(entity, self.entityType):
         return 1
     else:
         raise roots.ConstraintViolation("%s of incorrect type (%s)" %
                                   (entity, self.entityType))
예제 #15
0
    def _disconnected(self, _):
        self.xmlstream = None

        # Notify all child services which implement
        # the IService interface
        for c in self:
            if components.implements(c, IService):
                c.componentDisconnected()
예제 #16
0
    def _authd(self, xs):
        # Flush all pending packets
        for p in self._packetQueue:
            self.xmlstream.send(p)
        self._packetQueue = []

        # Notify all child services which implement
        # the IService interface
        for c in self:
            if components.implements(c, IService):
                c.componentConnected(xs)
예제 #17
0
파일: static.py 프로젝트: fxia22/ASM_xf
 def _grabService(self, svc, sclas):
     """
     Find an instance of a particular class in a service collection and all
     subcollections.
     """
     for s in svc.services.values():
         if isinstance(s, sclas):
             return s
         if components.implements(s, IServiceCollection):
             ss = self._grabService(s, sclas)
             if ss:
                 return ss
예제 #18
0
파일: controller.py 프로젝트: fxia22/ASM_xf
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 components.implements(controller, resource.IResource):
        components.registerAdapter(controller, model, resource.IResource)
예제 #19
0
파일: typemap.py 프로젝트: fxia22/ASM_xf
 def getMapper(self, x):
     if components.implements(x, ITypeMapper):
         if isinstance(x, (ClassType, type)):
             return x()
         return x
     if isinstance(x, Ref):
         x = x()
     if x in self._mapperCache:
         return self._mapperCache[x]
     else:
         if isinstance(x, tuple):
             ot = TupleTypeMapper(x)
         elif issubclass(x, Storable):
             ot = ObjectTypeMapper(x)
         else:
             raise NotImplementedError("You can't store that.")
         self._mapperCache[x] = ot
         return ot
예제 #20
0
파일: util.py 프로젝트: fxia22/ASM_xf
def reactorCleanUp():
    from twisted.internet import reactor
    reactor.iterate() # flush short-range timers
    pending = reactor.getDelayedCalls()
    if pending:
        msg = "\npendingTimedCalls still pending:\n"
        for p in pending:
            msg += " %s\n" % p
        from warnings import warn
        warn(msg)
        for p in pending: p.cancel() # delete the rest
        reactor.iterate() # flush them
        raise unittest.FailTest, msg
    if components.implements(reactor, interfaces.IReactorThreads):
        reactor.suggestThreadPoolSize(0)
        if hasattr(reactor, 'threadpool') and reactor.threadpool:
            reactor.threadpool.stop()
            reactor.threadpool = None
예제 #21
0
 def testBasicLogin(self):
     l = []; f = []
     self.portal.login(credentials.UsernamePassword("bob", "hello"),
                       self, ITestable).addCallback(
         l.append).addErrback(f.append)
     if f:
         raise f[0]
     # print l[0].getBriefTraceback()
     iface, impl, logout = l[0]
     # whitebox
     self.assertEquals(iface, ITestable)
     self.failUnless(components.implements(impl, iface),
                     "%s does not implement %s" % (impl, iface))
     # greybox
     self.failUnless(impl.original.loggedIn)
     self.failUnless(not impl.original.loggedOut)
     logout()
     self.failUnless(impl.original.loggedOut)
예제 #22
0
 def opt_aliases(self, filename):
     """Specify an aliases(5) file to use for this domain"""
     if self.last_domain:
         if components.implements(self.last_domain, mail.IAliasableDomain):
             aliases = alias.loadAliasFile(self.service.domains, filename)
             self.last_domain.setAliasGroup(aliases)
             self.service.monitor.monitorFile(
                 filename,
                 AliasUpdater(self.service.domains, self.last_domain)
             )
         else:
             raise usage.UsageError(
                 "%s does not support alias files" % (
                     self.last_domain.__class__.__name__,
                 )
             )
     else:
         raise usage.UsageError("Specify a domain before specifying aliases")
예제 #23
0
파일: web.py 프로젝트: fxia22/ASM_xf
 def process(self, write, request, submit, name="", type=None, items=()):
     # write(str(('YAY', name, type)))
     # TODO: validation on the name?
     if submit == 'Delete':
         for item in items:
             obj = self.coll.getStaticEntity(item)
             if components.implements(obj, coil.IConfigurator):
                 obj = obj.getInstance()
             self.configurator.dispensers.removeObject(obj)
             self.coll.delEntity(item)
         write("<b>Items Deleted.</b><br>(%s)<br>" % html.escape(repr(items)))
     elif submit == "Insert":
         obj = self.configurator.makeConfigurable(type, self.coll, name)
         self.coll.putEntity(name, obj)
         write("<b>%s created!</b>" % type)
     else:
         raise widgets.FormInputError("Don't know how to %s" % repr(submit))
     self.format(self.getFormFields(request), write, request)
예제 #24
0
파일: web.py 프로젝트: fxia22/ASM_xf
    def configWidget(self, request):
        """Render the config part of the widget."""
        path = request.postpath
        if path:
            obj = self.app
            for elem in path:
                if elem:                # '' doesn't count
                    collection = coil.getCollection(obj)
                    if collection is None:
                        obj = None
                    else:
                        obj = collection.getStaticEntity(elem)

                    if obj is None:
                        # no such subobject
                        request.redirect(request.prePathURL())
                        return ['Redirecting...']
        else:
            obj = self.app
        ret = []
        linkfrom = string.join(['config']+request.postpath, '/') + '/'
        cfg = coil.getConfigurator(obj)

        # add a form for configuration if available
        if cfg and cfg.configTypes:
            ret.extend(widgets.TitleBox("Configuration", ConfigForm(self, cfg, linkfrom)).display(request))

        # add a form for a collection of objects
        coll = coil.getCollection(obj)
        if components.implements(coll, coil.IConfigCollection):
            if coll.entityType in (types.StringType, types.IntType, types.FloatType):
                ret.extend(widgets.TitleBox("Delete Items", ImmutableCollectionDeleteForm(self, coll, linkfrom)).display(request))
                colClass = ImmutableCollectionForm
            else:
                colClass = CollectionForm
            ret.extend(widgets.TitleBox("Listing", colClass(self, coll, linkfrom)).display(request))

        ret.append(html.PRE(str(obj)))
        return ret
예제 #25
0
파일: pop3.py 프로젝트: fxia22/ASM_xf
    def _cbMailbox(self, ial, user):
        if isinstance(ial, Mailbox) or components.implements(ial, IMailbox):
            import warnings
            warnings.warn(
                "POP3.authenticateUser*() methods must now return a 3-tuple,"
                "not a Mailbox.  Please update your code.",
                DeprecationWarning, 1
            )
            interface = IMailbox
            avatar = ial
            logout = lambda: None
        else:
            interface, avatar, logout = ial

        if interface is not IMailbox:
            self.failResponse('Authentication failed')
            log.err("_cbMailbox() called with an interface other than IMailbox")
            return

        self.mbox = avatar
        self._onLogout = logout
        self.successResponse('Authentication succeeded')
        log.msg("Authenticated login for " + user)
예제 #26
0
 def testGetSubAdapter(self):
     o = MultiplyAndAdd()
     self.assert_( not components.implements(o, IFoo) )
     foo = components.getAdapter(o, IFoo, None)
     self.assert_( isinstance(foo, FooAdapterForMAA) )
예제 #27
0
 def testNewSubclass(self):
     # new-style implementing class subclasses backwardsCompatImplements class
     o = SubZoper()
     self.assert_(components.implements(o, IZope))
     self.assert_(components.implements(o, ISub))
예제 #28
0
 def testNewSubclassOfOld(self):
     o = NewSubOfOldStyle()
     self.assert_(components.implements(o, IZope))
     self.assert_(components.implements(o, IAdder))
예제 #29
0
 def testNewSubclassOfOld(self):
     o = NewSubOfOldStyle()
     self.assert_(components.implements(o, IZope))
     self.assert_(components.implements(o, IAdder))
예제 #30
0
파일: web.py 프로젝트: fxia22/ASM_xf
 def __init__(self, configurator, cfgr, linkfrom):
     if not components.implements(cfgr, coil.IConfigurator):
         raise TypeError
     self.configurator = configurator  # this is actually a AppConfiguratorPage
     self.cfgr = cfgr
     self.linkfrom = linkfrom
예제 #31
0
 def _connected(self, xs):
     self.xmlstream = xs
     for c in self:
         if components.implements(c, IService):
             c.transportConnected(xs)
예제 #32
0
 def testGetSubAdapter(self):
     o = MultiplyAndAdd()
     self.assert_( not components.implements(o, IFoo) )
     foo = components.getAdapter(o, IFoo, None)
     self.assert_( isinstance(foo, FooAdapterForMAA) )
예제 #33
0
 def testOther(self):
     self.assert_( not components.implements(3, ISub) )
     self.assert_( not components.implements("foo", ISub) )
예제 #34
0
파일: test_unix.py 프로젝트: fxia22/ASM_xf
class Factory(protocol.Factory):
    def buildProtocol(self, addr):
        return protocol.Protocol()

class UnixSocketTestCase(test_smtp.LoopbackSMTPTestCase):
    """Test unix sockets."""
    
    def loopback(self, client, server):
        loopback.loopbackUNIX(client, server)

    def testDumber(self):
        filename = tempfile.mktemp()
        l = reactor.listenUNIX(filename, Factory())
        reactor.connectUNIX(filename, TestClientFactory())
        for i in xrange(100):
            reactor.iterate()
        l.stopListening()

    def testMode(self):
        filename = tempfile.mktemp()
        l = reactor.listenUNIX(filename, Factory(), mode = 0600)
        self.assertEquals(stat.S_IMODE(os.stat(filename)[0]), 0600)
        reactor.connectUNIX(filename, TestClientFactory())
        for i in xrange(100):
            reactor.iterate()
        l.stopListening()

if not components.implements(reactor, interfaces.IReactorUNIX):
    del UnixSocketTestCase
예제 #35
0
 def testNewSubclass(self):
     o = SubZoper()
     self.assert_(components.implements(o, IZope))
     self.assert_(components.implements(o, ISub))
예제 #36
0
파일: util.py 프로젝트: fxia22/ASM_xf
 def __init__(self, forwarded, interfaceClass, failWhenNotImplemented=0):
     assert implements(forwarded, interfaceClass)
     self.forwarded = forwarded
     self.interfaceClass = interfaceClass
     self.failWhenNotImplemented = failWhenNotImplemented
예제 #37
0
        pyExe = sys.executable
        scriptPath = util.sibpath(__file__, "process_stdinreader.py")
        p = Accumulator()
        reactor.spawnProcess(p, pyExe, [pyExe, "-u", scriptPath], env=None,
                             path=None)
        p.transport.write("hello, world")
        p.transport.closeStdin()

        while not p.closed:
            reactor.iterate()
        self.assertEquals(p.errF.getvalue(), "err\nerr\n")
        self.assertEquals(p.outF.getvalue(), "out\nhello, world\nout\n")


skipMessage = "wrong platform or reactor doesn't support IReactorProcess"
if (runtime.platform.getType() != 'posix') or (not components.implements(reactor, interfaces.IReactorProcess)):
    PosixProcessTestCase.skip = skipMessage
    PosixProcessTestCasePTY.skip = skipMessage
    TestTwoProcessesPosix.skip = skipMessage
else:
    # do this before running the tests: it uses SIGCHLD and stuff internally
    lsOut = popen2.popen3("/bin/ls ZZXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX")[2].read()
    # make sure SIGCHLD handler is installed, as it should be on reactor.run().
    # problem is reactor may not have been run when this test runs.
    if hasattr(reactor, "_handleSigchld"):
        import signal
        from twisted.internet import process
        signal.signal(signal.SIGCHLD, reactor._handleSigchld)

if (runtime.platform.getType() != 'win32') or (not components.implements(reactor, interfaces.IReactorProcess)):
    Win32ProcessTestCase.skip = skipMessage
예제 #38
0
 def testOther(self):
     self.assert_( not components.implements(3, ISub) )
     self.assert_( not components.implements("foo", ISub) )
예제 #39
0
 def testInstanceOnlyImplements(self):
     class Blah: pass
     o = Blah()
     o.__implements__ = IAdder
     self.assert_( components.implements(o, IAdder) )
예제 #40
0
파일: coil.py 프로젝트: fxia22/ASM_xf
def getCollection(obj):
    """Get an object implementing ICollection for obj."""
    if components.implements(obj, IConfigurator):
        obj = obj.getInstance()
    return components.getAdapter(obj, ICollection, None)
예제 #41
0
 def testNewSubclass(self):
     # new-style implementing class subclasses backwardsCompatImplements class
     o = SubZoper()
     self.assert_(components.implements(o, IZope))
     self.assert_(components.implements(o, ISub))