Exemplo n.º 1
0
class TestFileChooser(testcase.TestCase):
    jsClass = u'WebbyVellum.Tests.TestFileChooser'

    def newFileChooser(self, labels=None):
        """
        Return a new Signup widget
        @param labels: create ChooserIcons with the given labels as well
        """
        # if labels was given, create some test files.  FileChooser
        # will make ChooserIcons out of these during rendering
        self.store = cleanStore()
        self.user = testUser(self.store)
        if labels is not None:
            for label in labels:
                fileitem = data.FileMeta(store=self.store,
                                         user=self.user,
                                         filename=label,
                                         mimeType=u'text/plain')

        self.fc = gmtools.FileChooser(self.user)
        self.fc.setFragmentParent(self)

        return self.fc

    athena.expose(newFileChooser)

    def addNewIcon(self, label):
        fileitem = data.FileMeta(store=self.store,
                                 user=self.user,
                                 filename=label,
                                 mimeType=u'text/plain')
        return self.fc.user.fileAdded(fileitem)

    athena.expose(addNewIcon)
Exemplo n.º 2
0
class TestIRCContainer(testcase.TestCase):
    jsClass = u'WebbyVellum.Tests.TestIRCContainer'

    def generateConversation(self, id):
        """
        Hook up a new (fake) conversation so tests can play with the tab.
        """
        convwin = iwebby.IChatConversations(self.irc)
        nullconv = NullConversation(convwin, id)
        return convwin.showConversation(nullconv, id)

    athena.expose(generateConversation)

    def newContainer(self, ):
        """
        Return a new IRC Container with mock conversations for the ids given
        """
        user = testUser(cleanStore())
        # XXX warning - livetrial does not provide test isolation!
        # setting instance variables can bite you in the ass.  If this
        # method is called first from every test, life is fine, but if
        # generateConversation is called without calling this first,
        # behavior is UNDEFINED.
        self.irc = ircweb.IRCContainer(MockMinAccountManager(), user)
        self.irc.setFragmentParent(self)

        return self.irc

    athena.expose(newContainer)
Exemplo n.º 3
0
class TableWidget(athena.LiveFragment):
    jsClass = u"tableWidget"

    docFactory = loaders.xmlfile('tableWidget.xml', templateDir = '/usr/local/tcs/tums/templates')

    tableName = "dragTable"

    def __init__(self, *a, **kw):
        athena.LiveFragment.__init__(self, *a, **kw)
        self.sysconf = confparse.Config()

    def getData(self):
        # Returns 2D array of table data, and the headers
        return [[u"<a href='/'>Foo!</a>",2], [3,4]], [u"Number 1", u"Number 2"]
    athena.expose(getData)

    def tableChanged(self, rowOrder):
        print "New row order", rowOrder
        pass
    athena.expose(tableChanged)

    def getTableName(self):
        return unicode(self.tableName)

    athena.expose(getTableName)

    def render_tableSlot(self, ctx, tag):
        return ctx.tag[tags.div(id=self.tableName)[""]]
Exemplo n.º 4
0
class ScrollTableWidgetTestCase(TestCase):
    """
    Tests for the scrolltable's view class.
    """
    jsClass = u'Mantissa.Test.ScrollTableViewTestCase'

    def __init__(self):
        TestCase.__init__(self)
        self.perTestData = {}

    def getScrollingWidget(self, key, rowCount=10):
        store = Store()
        installOn(PrivateApplication(store=store), store)
        elements = [
            ScrollElement(store=store, column=i) for i in range(rowCount)
        ]
        columns = [ScrollElement.column]
        f = SequenceScrollingFragment(store, elements, columns)
        f.docFactory = getLoader(f.fragmentName)
        f.setFragmentParent(self)
        self.perTestData[key] = (store, elements, f)
        return f

    expose(getScrollingWidget)

    def changeRowCount(self, key, n):
        store, elements, fragment = self.perTestData[key]
        elements[:] = [ScrollElement(store=store, column=i) for i in range(n)]

    expose(changeRowCount)
Exemplo n.º 5
0
class AdminStatsTestBase(webadmin.AdminStatsFragment):
    docFactory = loaders.stan(tags.div(render=tags.directive('liveElement')))

    def _initializeObserver(self):
        pass

    def getGraphNames(self):
        return [(u"graph1", u"graph 1"), (u"graph2", u"graph 2")]

    athena.expose(getGraphNames)

    def fetchLastHour(self, name):
        t = extime.Time()
        return ([
            unicode((t + datetime.timedelta(minutes=i)).asHumanly())
            for i in range(60)
        ], [
            24, 28, 41, 37, 39, 25, 44, 32, 41, 45, 44, 47, 24, 28, 29, 49, 43,
            56, 28, 35, 66, 43, 72, 65, 62, 56, 84, 52, 74, 73, 74, 77, 71, 46,
            70, 55, 65, 51, 42, 55, 19, 30, 25, 24, 20, 16, 39, 22, 39, 29, 29,
            18, 39, 19, 21, 12, 25, 25, 25, 29
        ])

    def buildPie(self):
        self.queryStats = {
            u'beans': 10,
            u'enchiladas': 27,
            u'salsa': 3,
            u'fajitas': 48
        }
        self.pieSlices()

    athena.expose(buildPie)
Exemplo n.º 6
0
class NodeLocationSubElement2(LiveElement):
    docFactory = loaders.stan(
        tags.div(render=tags.directive('liveElement'))[
            tags.label(_class='bar', _for="username"),
            tags.input(_class='bar', id='username')])

    def getDynamicWidget(self):
        """
        Return a widget dynamically for us to have more fun with.
        """
        e = NodeLocationSubElement1()
        e.setFragmentParent(self)
        return e

    expose(getDynamicWidget)

    def getNodeInsertedHelper(self):
        """
        Return a dynamically instantiated NodeInsertedHelper to play with.
        """
        e = NodeInsertedHelper()
        e.setFragmentParent(self)
        return e

    expose(getNodeInsertedHelper)
Exemplo n.º 7
0
class ChatterElement(LiveElement):

    docFactory = xmlfile(sibpath(__file__, 'template.html'))
    jsClass = u'ChatThing.ChatterWidget'

    def __init__(self, room):
        self.room = room

    def setUsername(self, username):
        self.username = username
        message = ' * user ' + username + ' has joined the room'
        self.room.wall(message)

    setUsername = expose(setUsername)

    def say(self, message):
        self.room.tellEverybody(self, message)

    say = expose(say)

    def wall(self, message):
        self.callRemote('displayMessage', message)

    def hear(self, username, what):
        self.callRemote('displayUserMessage', username, what)
Exemplo n.º 8
0
Arquivo: HA.py Projeto: calston/tums
class ClusterFragment(athena.LiveFragment):
    jsClass = u'cluster.PS'

    docFactory = loaders.xmlfile('cluster.xml', templateDir = Settings.BaseDir + '/templates')

    def __init__(self, *a, **kw):
        super(ClusterFragment, self).__init__(*a, **kw)
        self.sysconf = confparse.Config()

    def initialTable(self):
        ha = self.sysconf.General.get('ha', {})
        
        servers = [ map(unicode, [v['name'], v['topology'], '?', k]) for k,v in ha.items() ]
        servers.sort()

        if not servers:
            servers = [[u'Searching...', u'', u'', u'']]

        return servers
    athena.expose(initialTable)

    def lanTest(self):
        ha = self.sysconf.General.get('ha', {})

        flan = Utils.getLans(self.sysconf)[0]
        lanIP = self.sysconf.EthernetDevices[flan].get('network', '192.168.0.0/24')
        myIP = self.sysconf.EthernetDevices[flan].get('ip', '192.168.0.0/24').split('/')[0]
        print lanIP, myIP
        def lanScan(res):
            print res
            for i in res.split('\n'):
                if i[:5] != "Host:":
                    continue
                
                n = i.split()
                ip = n[1]
                host = n[2][1:-1]
                
                if ip in ha.keys():
                    ha[ip]['status'] = 'Online'
                else:
                    ha[ip] = {
                        'status': 'Online',
                        'topology': "Not Configured",
                        'name': host or ip,
                    }
                if ip == myIP:
                    ha[ip]['status'] = "Me"
                    ha[ip]['name'] = ""

            servers = [ map(unicode, [v['name'], v['topology'], v.get('status', 'Offline'), k]) for k,v in ha.items() ]

            return servers

        loc = 'nmap -sS -p 9682,54322 -oG - %s 2>&1 | grep "9682/open/tcp" | grep "54322/open/tcp"' % (lanIP.encode())
        print loc
        return WebUtils.system(loc).addBoth(lanScan)
    athena.expose(lanTest)
Exemplo n.º 9
0
class NotebookWidget(athena.LiveElement):
    jsClass = u'ControllerModule.NotebookWidget'
    docFactory = loaders.stan(
        tags.div(render=tags.directive('liveElement'))
        [classTag(tags.div, 'pageHeader')["IPython Notebook"],
         classTag(tags.div, 'controlCol')[
             classTag(
                 tags.div(onclick="Nevow.Athena.Widget.get(this).addIOCell();"
                          ), 'controlLink')["Add IO Cell"],
             classTag(
                 tags.div(
                     onclick="Nevow.Athena.Widget.get(this).addTextCell();"
                 ), 'controlLink')["Add Text Cell"],
             classTag(
                 tags.div(
                     onclick="Nevow.Athena.Widget.get(this).createGroup();"
                 ), 'controlLink')["Create Group"],
             tags.hr(size="1"), "Move", tags.br, "Delete", ],
         classTag(tags.div(id='nb'), 'notebook')])

    def __init__(self, controller):
        self.controller = controller
        reactor.callLater(.1, self.callRemote, 'getIDs')
        reactor.callLater(.1, self.callRemote, 'addIOCell')

    def setIDs(self, ids):
        self.ids = parseTargets(ids)

    athena.expose(setIDs)

    def execute(self, cmd_id, line):
        d = self.controller.execute(self.ids, str(line))
        d.addCallback(self.returnResult, cmd_id)

    athena.expose(execute)

    def returnResult(self, result, cmd_id):
        n = len(result)
        if n is 1:
            id = unicode(result[0][1])
            out = htmlString(result[0][3])
            if result[0][4]:
                out += '<br><b>ERR:</b><br>' + htmlString(result[0][4])
        else:
            id = u'*'
            result = map(list, result)
            out = ''
            for i in range(n):
                node = result[i][0]
                # out
                if result[i][3]:
                    out += '%i:%s<br/>' % (node, htmlString(result[i][3]))
                # err
                if result[i][4]:
                    out += '%i:%s<br/>' % (node, htmlString(result[i][4]))
        self.callRemote('handleOutput', cmd_id, id, unicode(out))
Exemplo n.º 10
0
class MainPage(athena.LiveElement):
    jsClass = u"WebInterface.PLC"
    docFactory = loaders.stan(
        tags.invisible[tags.div(render=tags.directive('liveElement'))[tags.div(
            id='content')[tags.div(render=tags.directive('PLCElement'))]],
                       tags.a(href='settings')['Settings']])

    def __init__(self, *a, **kw):
        athena.LiveElement.__init__(self, *a, **kw)
        self.pcl_state = False
        self.HMI = None
        self.resetPLCStartedHMI()

    def setPLCState(self, state):
        self.pcl_state = state
        if self.HMI is not None:
            self.callRemote('updateHMI')

    def setPLCStartedHMI(self, hmi):
        self.PLCStartedHMIClass = hmi

    def resetPLCStartedHMI(self):
        self.PLCStartedHMIClass = DefaultPLCStartedHMI

    def getHMI(self):
        return self.HMI

    def HMIexec(self, function, *args, **kwargs):
        if self.HMI is not None:
            getattr(self.HMI, function, lambda: None)(*args, **kwargs)

    athena.expose(HMIexec)

    def resetHMI(self):
        self.HMI = None

    def PLCElement(self, ctx, data):
        return self.getPLCElement()

    renderer(PLCElement)

    def getPLCElement(self):
        self.detachFragmentChildren()
        if self.pcl_state:
            f = self.PLCStartedHMIClass()
        else:
            f = PLCStoppedHMI()
        f.setFragmentParent(self)
        self.HMI = f
        return f

    athena.expose(getPLCElement)

    def detachFragmentChildren(self):
        for child in self.liveFragmentChildren[:]:
            child.detach()
Exemplo n.º 11
0
class TestMapWidget(testcase.TestCase):
    jsClass = u'SVGMap.Tests.TestMapWidget'

    def newMapWidgetInContainer(self):
        """
        Return a new SVGMap
        """
        enc = ircweb.IRCContainer(None, testUser(cleanStore()))
        enc.setFragmentParent(self)
        return enc

    athena.expose(newMapWidgetInContainer)

    def newMapWidget(self):
        """
        Return a new SVGMap
        """
        st = cleanStore()
        chan = data.Channel(store=st, name=u'#foo')
        mapw = svgmap.MapWidget(chan, MockChatEntry())
        mapw.setFragmentParent(self)
        return mapw

    athena.expose(newMapWidget)

    def requestSetMapBackground(self):
        """
        Return a new BackgroundImage object 
        """
        st = cleanStore()
        chan = data.Channel(store=st, name=u'#foo')
        fileitem = testFileMeta(st)
        odata = data.FileData(store=st,
                              data=obscurement.newBlackImage(100, 100))
        obsc = data.FileMeta(
            store=st,
            data=odata,
            filename=u'#foo_obscurement.png',
            mimeType=u'image/png',
            md5=u'316ca7b4c921a204797dfbb70becfef9',
            width=100,
            height=100,
        )
        chan.background = fileitem
        chan.obscurement = obsc
        bgi = svgmap.BackgroundImage(chan)
        bgi.setFragmentParent(self)
        return bgi

    athena.expose(requestSetMapBackground)
Exemplo n.º 12
0
class BlurbTestCase(TestCase, HyperbolaTestMixin):
    """
    Tests for blurb rendering/behaviour
    """
    jsClass = u'Hyperbola.Test.BlurbTestCase'

    def _getBlurb(self, flavor):
        self._setUpStore()
        share = self._shareAndGetProxy(self._makeBlurb(flavor))

        f = hyperbola_view.blurbViewDispatcher(share)
        f.setFragmentParent(self)
        f.docFactory = getLoader(f.fragmentName)

        return f

    def getBlogPost(self, tags):
        """
        Make a L{FLAVOR.BLOG_POST}, wrap it in the appropriate fragment and
        return it

        @param tags: tags to apply to the blog post
        @type tags: iterable of C{unicode}

        @rtype: L{hyperbola_view.BlurbViewer}
        """
        f = self._getBlurb(FLAVOR.BLOG_POST)
        for tag in tags:
            f.original.tag(tag)
        return f
    expose(getBlogPost)

    def getBlog(self, tags):
        """
        Make a L{FLAVOR.BLOG}, wrap it in the appropriate fragment and
        return it

        @param tags: tags to insert in the store
        @type tags: iterable of C{unicode}

        @rtype: L{hyperbola_view.BlurbViewer}
        """
        f = self._getBlurb(FLAVOR.BLOG)
        catalog = self.store.findOrCreate(Catalog)
        for tag in tags:
            catalog.tag(self.store, tag)
        return f
    expose(getBlog)
Exemplo n.º 13
0
class Widget(athena.LiveFragment):


    docFactory = loaders.xmlstr('''\
<div xmlns:nevow="http://nevow.com/ns/nevow/0.1"
     xmlns:athena="http://divmod.org/ns/athena/0.7"
     nevow:render="liveFragment">
     <div nevow:render="label" />
     <div nevow:render="widget">
     </div>
</div>
''')

    def set_model_attr(self, attr):
        self._model_attr = attr

    def set_changed_callback(self, cb):
        self._changed_callback = cb

    def set_value(self, value):
        self.callRemote('setValue', value).addErrback(self._oops)

    def value_changed(self, value):
        self._changed_callback(self._model_attr, value)
    athena.expose(value_changed)

    def render_label(self, ctx, data):
        if self.label:
            return T.div(class_="model-widget-label")[self.label]
        else:
            return ctx.tag

    def _oops(self, err):
        log.err(err)
Exemplo n.º 14
0
class LiveStatusFragment(athena.LiveFragment):
    docFactory = loaders.stan(tags.span(render=tags.directive('liveFragment')))
    jsClass = u'Quotient.Grabber.StatusWidget'
    _pending = False
    _pendingStatus = None

    def __init__(self, status):
        self.status = status

    def statusChanged(self, newStatus):
        if self._pending:
            self._pendingStatus = newStatus
        else:
            self._pending = True
            self.callRemote('setStatus', newStatus).addCallback(self._unpend)

    def _unpend(self, ign):
        pendingStatus = self._pendingStatus
        self._pendingStatus = None
        self._pending = False
        if pendingStatus is not None:
            self.statusChanged(pendingStatus)

    def startObserving(self):
        self.removeObserver = self.status.addChangeObserver(self.statusChanged)
        return self.status.message

    expose(startObserving)
Exemplo n.º 15
0
class LoggingFragment(athena.LiveElement, log.Loggable):
    logCategory = 'webui_logging_fragment'
    jsClass = u'Coherence.Logging'
    fragmentName = 'coherence-logging'

    docFactory = loaders.stan(
        tags.div(render=tags.directive('liveElement'))
        [tags.div(id="Logging-container", class_="coherence_container")[""], ])

    def __init__(self, page, active):
        super(LoggingFragment, self).__init__()
        self.setFragmentParent(page)
        self.page = page
        self.coherence = page.coherence
        self.active = active

    def going_live(self):
        self.info("add a view to the LoggingFragment", self._athenaID)
        self.page.menu.add_tab('Logging', self.active, self._athenaID)
        d = self.page.notifyOnDisconnect()
        d.addCallback(self.remove_me)
        d.addErrback(self.remove_me)
        return {}

    athena.expose(going_live)

    def remove_me(self, result):
        self.info("remove view from the LoggingFragment")
Exemplo n.º 16
0
class ReconnectableElement(LiveElement):
    """
    I am a live element that can disconnect and be reconnected.
    """
    docFactory = loaders.stan(
        tags.div(render=tags.directive("liveElement"))[tags.button(
            onclick=
            "Nevow.Athena.page.deliveryChannel.sendCloseMessage(); return true;"
        )["Disconnect"],
                                                       tags.button(onclick="""
            Nevow.Athena.Widget.get(this).callRemote('getID').addCallback(function (result) {
                var e = document.createElement('div');
                e.appendChild(document.createTextNode('ID: '+result));
                document.body.appendChild(e);
            })
            """)["Show ID"]])

    def __init__(self):
        """
        Create a ReconnectableElement with a unique ID
        """
        LiveElement.__init__(self)
        self.currentID = counter()

    def getID(self):
        """
        Retrieve my current ID.
        """
        return self.currentID

    expose(getID)
Exemplo n.º 17
0
class FullControllerTestCase(testcase.TestCase, _ControllerMixin):
    jsClass = u'Quotient.Test.FullControllerTestCase'

    def getFullControllerWidget(self):
        """
        Retrieve the Controller widget for a mailbox with twenty messages in
        it.
        """
        inbox = self.getInbox()
        inbox.uiComplexity = 3
        catalog = inbox.store.findUnique(Catalog)

        impl = _Part(store=inbox.store)
        messages = [
            testMessageFactory(store=inbox.store,
                               sender=self.aliceEmail,
                               subject=u'message %d' % (i, ),
                               receivedWhen=self.sent,
                               sentWhen=self.sent2,
                               spam=False,
                               archived=False,
                               read=False,
                               impl=impl) for i in range(20)
        ]

        catalog.tag(messages[1], u'foo')

        return self.widgetFor(inbox)

    expose(getFullControllerWidget)
class GrabberListTestCase(TestCase):
    """
    Tests for the grabber list/scrolltable
    """

    jsClass = u'Quotient.Test.GrabberListTestCase'

    def getWidgetDocument(self):
        s = Store()

        grabberConfig = grabber.GrabberConfiguration(store=s)
        installOn(grabberConfig, s)

        self.grabber = grabber.POP3Grabber(store=s,
                                           config=grabberConfig,
                                           username=u'foo',
                                           domain=u'bar',
                                           password=u'baz')

        f = grabber.GrabberConfigFragment(grabberConfig)
        f.setFragmentParent(self)
        f.docFactory = getLoader(f.fragmentName)
        return f

    def deleteGrabber(self):
        self.grabber.deleteFromStore()

    expose(deleteGrabber)
Exemplo n.º 19
0
class RemoteMethodErrorShowsDialog(testcase.TestCase):
    jsClass = u'Nevow.Athena.Tests.RemoteMethodErrorShowsDialog'

    def raiseValueError(self):
        raise ValueError('hi')

    athena.expose(raiseValueError)
Exemplo n.º 20
0
class MapWidget(athena.LiveElement):
    implements(iwebby.IMapWidget)
    jsClass = u'SVGMap.MapWidget'
    docFactory = loaders.xmlfile(RESOURCE('elements/MapWidget'))

    def __init__(self, channel, chatEntry, *a, **kw):
        super(MapWidget, self).__init__(*a, **kw)
        self.channel = channel
        self.chatEntry = chatEntry

    def setMapBackgroundFromChannel(self):
        """
        Create a new BackgroundImage widget and send it to the channel.
        """
        image = BackgroundImage(self.channel)
        image.setFragmentParent(self)
        return self.callRemote("setMapBackground", image)

    def updateObscurementFromChannel(self):
        """
        Just send a new md5key for the obscurement, which the client-side
        widget will use to reset the background.
        """
        return self.callRemote("updateObscurement",
                               self.channel.obscurement.md5)

    def sendCommand(self, command):
        return self.chatEntry.chatMessage(command)

    athena.expose(sendCommand)
Exemplo n.º 21
0
class ValidatingSignupForm(liveform.LiveForm):
    jsClass = u'Mantissa.Validate.SignupForm'

    _parameterNames = [
        'realName', 'username', 'domain', 'password', 'emailAddress'
    ]

    docFactory = ThemedDocumentFactory("user-info-signup", "templateResolver")

    def __init__(self, uis):
        self.userInfoSignup = uis
        self.templateResolver = ITemplateNameResolver(uis.store)
        super(ValidatingSignupForm, self).__init__(uis.createUser, [
            liveform.Parameter(pname, liveform.TEXT_INPUT, unicode)
            for pname in self._parameterNames
        ])

    def getInitialArguments(self):
        """
        Retrieve a domain name from the user info signup item and return it so
        the client will know what domain it can sign up in.
        """
        return (self.userInfoSignup.getAvailableDomains()[0], )

    def usernameAvailable(self, username, domain):
        return self.userInfoSignup.usernameAvailable(username, domain)

    athena.expose(usernameAvailable)
Exemplo n.º 22
0
class StatusWidget(athena.LiveElement):
    jsClass = u'ControllerModule.StatusWidget'

    docFactory = loaders.stan(
        tags.div(render=tags.directive('liveElement'))[tags.div(
            id="statusWidget"
        )[tags.form(id="statusidform",
                    action="""javascript:
                var statusidform = document.getElementById('statusidform');
                var w = Nevow.Athena.Widget.get(statusidform);
                w.refreshStatus();
                """)
          [tags.input(id="statusidfield", type="text"), tags.br,
           tags.input(type="checkbox",
                      id="pending",
                      checked="true",
                      onChange="this.form.submit()")["pending"],
           tags.input(type="checkbox",
                      id="queue",
                      checked="true",
                      onChange="this.form.submit()")["queue"],
           tags.
           input(type="checkbox", id="history", onChange="this.form.submit()"
                 )["history"],
           tags.
           input(type="checkbox", id="locals", onChange="this.form.submit()"
                 )["locals"], tags.br,
           tags.input(type="submit", value="refresh status")],
          tags.div(id="statusOut")]])

    def __init__(self, controller):
        self.controller = controller
        reactor.callLater(.1, self.callRemote, 'getIDs')

    def status(self,
               targets,
               pending=True,
               queue=True,
               history=True,
               locals=True):
        args = (pending, queue, history, locals)
        idlist = parseTargets(targets)
        if idlist is False:
            return self.fail()
        d = self.controller.status(idlist)
        return d.addCallbacks(self.statusOK, self.fail, callbackArgs=args)

    athena.expose(status)

    def statusOK(self, resultList, *args):
        return self.finish(statusListToHTML(resultList, *args))

    def refreshStatus(self, *args):
        return self.callRemote('refreshStatus')

    def finish(self, s):
        return self.callRemote('updateStatus', unicode(s))

    def fail(self, f=None):
        return self.finish('Failure')
Exemplo n.º 23
0
class ReconnectableElementRenderingLivePage(OriginalPage):
    """
    A version of the ElementRenderingLivePage from the plugin which also has
    methods suitable for reconnection.

    XXX: this class unfortunately uncovers some nasty corners of the LivePage
    API.  Don't be too surprised if this ends up broken by some future fixes to
    that API.  We should not attempt to keep this working as-is; if you do find
    it in a broken state, just update it to use newer, better documented APIs.
    """
    jsClass = u'Nevow.Test.ReconnectAcceptanceTest.ReconnectingPage'

    def __init__(self, *a, **k):
        """
        Make sure our interface allows the particular method we want to expose.
        """
        super(ReconnectableElementRenderingLivePage, self).__init__(*a, **k)
        self.iface = ['giveElementID']
        self.rootObject = self

    def giveElementID(self, newID):
        """
        Assign an ID to the widget.
        """
        self.element.setFragmentParent(self)
        self._localObjects[newID] = self.element

    expose(giveElementID)
Exemplo n.º 24
0
class DynamicStylesheetFetching(testcase.TestCase, CSSModuleTestMixin):
    """
    Tests for stylesheet fetching when dynamic widget instantiation is
    involved.
    """
    jsClass = 'Nevow.Athena.Tests.DynamicStylesheetFetching'
    # lala we want to use TestCase.mktemp
    _testMethodName = 'DynamicStylesheetFetching'

    def getWidgetWithCSSDependencies(self):
        """
        Return a widget which depends on some CSS.
        """
        self.page.cssModules = self._makeCSSRegistry()

        element = athena.LiveElement()
        element.cssModule = 'TestCSSModuleDependencies.Dependor'
        element.setFragmentParent(self)
        element.docFactory = loaders.stan(
            tags.div(render=tags.directive('liveElement')))

        return (element, [
            str(self.page.getCSSModuleURL(n))
            for n in ('TestCSSModuleDependencies',
                      'TestCSSModuleDependencies.Dependee',
                      'TestCSSModuleDependencies.Dependor')
        ])

    expose(getWidgetWithCSSDependencies)
Exemplo n.º 25
0
class FromAddressScrollTableTestCase(testcase.TestCase):
    """
    Tests for L{xquotient.smtpout.FromAddressScrollTable}
    """

    jsClass = u'Quotient.Test.FromAddressScrollTableTestCase'

    def getFromAddressScrollTable(self):
        s = Store()

        LoginMethod(store=s,
                    internal=False,
                    protocol=u'email',
                    localpart=u'default',
                    domain=u'host',
                    verified=True,
                    account=s)

        installOn(compose.Composer(store=s), s)

        smtpout.FromAddress(store=s,
                            address=u'notdefault@host',
                            smtpHost=u'host',
                            smtpUsername=u'notdefault')

        f = smtpout.FromAddressScrollTable(s)
        f.setFragmentParent(self)
        f.docFactory = getLoader(f.fragmentName)
        return f

    expose(getFromAddressScrollTable)
Exemplo n.º 26
0
class Clock(athena.LiveFragment):
    jsClass = u"WidgetDemo.Clock"

    docFactory = loaders.xmlstr('''\
<div xmlns:nevow="http://nevow.com/ns/nevow/0.1"
     xmlns:athena="http://divmod.org/ns/athena/0.7"
     nevow:render="liveFragment">
    <div>
        <a href="#"><athena:handler event="onclick" handler="start" />
            Start
        </a>
        <a href="#"><athena:handler event="onclick" handler="stop" />
            Stop
        </a>
    </div>
    <div class="clock-time" />
</div>
''')

    running = False

    def start(self):
        if self.running:
            return
        self.loop = task.LoopingCall(self.updateTime)
        self.loop.start(1)
        self.running = True

    athena.expose(start)

    def stop(self):
        if not self.running:
            return
        self.loop.stop()
        self.running = False

    athena.expose(stop)

    def _oops(self, err):
        log.err(err)
        if self.running:
            self.loop.stop()
            self.running = False

    def updateTime(self):
        self.callRemote('setTime', str(time.ctime(),
                                       'ascii')).addErrback(self._oops)
Exemplo n.º 27
0
        class DynamicFragment(athena.LiveFragment):
            docFactory = loaders.stan(
                tags.div(render=tags.directive('liveFragment')))
            jsClass = u'Nevow.Athena.Tests.DynamicWidgetClass'

            def someMethod(self):
                return u'foo'

            expose(someMethod)
Exemplo n.º 28
0
class TestSignupValidationInformation(testcase.TestCase):
    jsClass = u'Mantissa.Test.SignupValidationInformation'

    def makeWidget(self):
        uis = FakeUserInfoSignup()
        vsf = ValidatingSignupForm(uis)
        vsf.setFragmentParent(self)
        return vsf
    expose(makeWidget)
Exemplo n.º 29
0
class AccountManager(athena.LiveElement):
    """
    UI element that handles changing of the nick and processing a login to the
    IRC server.
    """
    jsClass = u"WebbyVellum.AccountManager"
    docFactory = loaders.xmlfile(RESOURCE('elements/AccountManager'))
    implements(iwebby.IChatAccountManager)

    def __init__(self, accountManager, conversationTabs, user, *a, **kw):
        super(AccountManager, self).__init__(*a, **kw)
        self.accountManager = accountManager
        self.conversationTabs = conversationTabs
        self.user = user

    def getInitialArguments(self):
        nick = self.user.nick
        channels = self.user.recentChannels
        if nick and channels:
            # when both nick and channels are already set, log the irc user
            # straight in.
            self.onLogOnSubmit(nick, channels)
            # set autoHide = True on the widget because login will be
            # automatic
            return (nick, channels, True)
        return (nick, channels)

    def onLogOnSubmit(self, nick, channels):
        """
        Process by looking up the password for that nick and starting
        a login process on the IRC protocol.
        """
        host = 'localhost'.encode('utf8')
        password = self.user.password.encode('utf8')
        username = nick.encode('utf8')

        # SET the permanent nick to the nick we were provided, trust it.
        # We can trust the nick because use of AccountManager 
        # implies that the user is *already* authenticated, through
        # the web.  Users visiting using a regular IRC client will 
        # naturally have to supply their passwords the normal way.
        self.user.nick = unicode(nick)

        channels = channels.encode('utf8')
        d = self.accountManager.doConnection(host, username, password, channels)

        def _gotAccount(acct):
            # set up disconnection callback for browser close etc.
            def logOff(_ignored, acct):
                self.accountManager.disconnectAsNeeded(acct)
            self.page.notifyOnDisconnect().addBoth(logOff, acct)

            return u'connected %s@%s and joined %s' % (username, host, channels)

        d.addCallback(_gotAccount)
        return d
    athena.expose(onLogOnSubmit)
Exemplo n.º 30
0
class EchoElement(LiveElement):

    docFactory = xmlfile(sibpath(__file__, 'template.html'))
    jsClass = 'EchoThing.EchoWidget'

    def say(self, message):
        self.callRemote('addText', message)

    say = expose(say)
Exemplo n.º 31
0
    def getStore(self, name, domain):
        """Convenience method for the REPL. I got tired of typing this string every time I logged in."""
        return IRealm(self.original.store.parent).accountByAddress(name, domain).avatars.open()

    def head(self):
        return ()


    def addOutput(self, output, async=False):
        self.callRemote('addOutputLine', unicode(output, 'ascii'))


    def evaluateInputLine(self, inputLine):
        return self.interpreter.push(inputLine)
    expose(evaluateInputLine)



registerAdapter(REPL, DeveloperApplication, INavigableFragment)

class Traceback(Item):
    typeName = 'mantissa_traceback'
    schemaVersion = 1

    when = timestamp()
    traceback = bytes()
    collector = reference()

    def __init__(self, store, collector, failure):
        when = extime.Time()