Exemple #1
0
    def process(self, context, boundTo, data, autoConfigure = True):
        """Knows how to process a dictionary of lists
        where the dictionary may contain a key with the same
        name as some of the arguments to the MethodBinding
        instance.
        """
        typedValue = self.original.typedValue
        results = {}
        failures = {}
        if '----' in data:
            ## ---- is the "direct object", the one argument you can specify using the command line without saying what the argument name is
            data[typedValue.arguments[0].name] = data['----']
            del data['----']
        for binding in typedValue.arguments:
            name = binding.name
            try:
                context = WovenContext(context, faketag)
                context.remember(binding, iformless.IBinding)
                results[name] = iformless.IInputProcessor(binding.typedValue).process(context, boundTo, data.get(name, ['']))
            except formless.InputError as e:
                results[name] = data.get(name, [''])[0]
                failures[name] = e.reason

        if failures:
            #print "There were validation errors. The errors were: ", failures
            raise formless.ValidateError(failures, "Error:", results)

        if autoConfigure:
            def _except(e):
                failures[''] = e.reason # self.original.name
                raise formless.ValidateError(failures, e.reason, results)
            return exceptblock(self.original.configure, _except, formless.InputError,
                               boundTo, results)
        return results
Exemple #2
0
    def doRendering(self, fragmentClass):
        """
        Verify that the given fragment class will render without raising an
        exception.
        """
        siteStore = Store()

        loginSystem = LoginSystem(store=siteStore)
        installOn(loginSystem, siteStore)
        p = Product(store=siteStore, types=["xmantissa.webadmin.LocalUserBrowser",
                                            "xmantissa.signup.SignupConfiguration"])
        account = loginSystem.addAccount(u'testuser', u'localhost', None)
        p.installProductOn(account.avatars.open())
        f = fragmentClass(None, u'testuser', account)

        p = LivePage(
            docFactory=stan(
                html[
                    head(render=directive('liveglue')),
                    body(render=lambda ctx, data: f)]))
        f.setFragmentParent(p)

        ctx = WovenContext()
        req = FakeRequest()
        ctx.remember(req, IRequest)

        d = p.renderHTTP(ctx)
        def rendered(ign):
            p.action_close(None)
        d.addCallback(rendered)
        return d
Exemple #3
0
    def test_oldFlattenableOverriddenRend(self):
        """
        Flattening L{Element} instances with an overridden C{rend} method
        flattened with the old flatten function results in the flattened
        version of whatever their C{rend} method returns.
        """
        renders = []
        class OldStyleElement(Element):
            docFactory = stan("Hello, world")
            def rend(self, ctx, data):
                return invisible(render=directive("foo"))[Element.rend(self, ctx, data)]

            def foo(self, request, tag):
                renders.append((self, request))
                return p[tag]
            renderer(foo)

        result = []
        element = OldStyleElement()
        request = FakeRequest()
        context = WovenContext()
        context.remember(request)
        finished = oldFlatten(element, context, result.append, lambda ign: ign)
        def cbFinished(ignored):
            self.assertEqual("".join(result), "<p>Hello, world</p>")
            self.assertEqual(renders, [(element, request)])
        finished.addCallback(cbFinished)
        return finished
    def test_oldFlattenableOverriddenRend(self):
        """
        Flattening L{Element} instances with an overridden C{rend} method
        flattened with the old flatten function results in the flattened
        version of whatever their C{rend} method returns.
        """
        renders = []

        class OldStyleElement(Element):
            docFactory = stan("Hello, world")

            def rend(self, ctx, data):
                return invisible(render=directive("foo"))[Element.rend(
                    self, ctx, data)]

            def foo(self, request, tag):
                renders.append((self, request))
                return p[tag]

            renderer(foo)

        result = []
        element = OldStyleElement()
        request = FakeRequest()
        context = WovenContext()
        context.remember(request)
        finished = oldFlatten(element, context, result.append, lambda ign: ign)

        def cbFinished(ignored):
            self.assertEqual("".join(result), "<p>Hello, world</p>")
            self.assertEqual(renders, [(element, request)])

        finished.addCallback(cbFinished)
        return finished
Exemple #5
0
    def doRendering(self, fragmentClass):
        """
        Verify that the given fragment class will render without raising an
        exception.
        """
        siteStore = Store()

        loginSystem = LoginSystem(store=siteStore)
        installOn(loginSystem, siteStore)
        p = Product(
            store=siteStore, types=["xmantissa.webadmin.LocalUserBrowser", "xmantissa.signup.SignupConfiguration"]
        )
        account = loginSystem.addAccount(u"testuser", u"localhost", None)
        p.installProductOn(account.avatars.open())
        f = fragmentClass(None, u"testuser", account)

        p = LivePage(docFactory=stan(html[head(render=directive("liveglue")), body(render=lambda ctx, data: f)]))
        f.setFragmentParent(p)

        ctx = WovenContext()
        req = FakeRequest()
        ctx.remember(req, IRequest)

        d = p.renderHTTP(ctx)

        def rendered(ign):
            p.action_close(None)

        d.addCallback(rendered)
        return d
Exemple #6
0
    def process(self, context, boundTo, data, autoConfigure = True):
        """Knows how to process a dictionary of lists
        where the dictionary may contain a key with the same
        name as some of the arguments to the MethodBinding
        instance.
        """
        typedValue = self.original.typedValue
        results = {}
        failures = {}
        if '----' in data:
            ## ---- is the "direct object", the one argument you can specify using the command line without saying what the argument name is
            data[typedValue.arguments[0].name] = data['----']
            del data['----']
        for binding in typedValue.arguments:
            name = binding.name
            try:
                context = WovenContext(context, faketag)
                context.remember(binding, iformless.IBinding)
                results[name] = iformless.IInputProcessor(binding.typedValue).process(context, boundTo, data.get(name, ['']))
            except formless.InputError as e:
                results[name] = data.get(name, [''])[0]
                failures[name] = e.reason

        if failures:
            #print "There were validation errors. The errors were: ", failures
            raise formless.ValidateError(failures, "Error:", results)

        if autoConfigure:
            def _except(e):
                failures[''] = e.reason # self.original.name
                raise formless.ValidateError(failures, e.reason, results)
            return exceptblock(self.original.configure, _except, formless.InputError,
                               boundTo, results)
        return results
Exemple #7
0
    def test_bootstraps(self):
        """
        L{LivePage._bootstraps} should return a list of 2-tuples of
        (initialization method, arguments) of methods to call in JavaScript.

        Specifically, it should invoke Divmod.bootstrap with the page's own
        URL, and Nevow.Athena.bootstrap with the name of the client-side Page
        class to instantiate and the URL to instantiate it with.
        """
        SEG = "'" + '"'
        URI = "http://localhost/" + SEG
        req = FakeRequest(uri='/' + SEG, currentSegments=[SEG])
        ctx = WovenContext()
        ctx.remember(req, IRequest)
        self.page.clientID = 'asdf'
        self.assertEqual(
            self.page._bootstraps(ctx),
            [
                (
                    "Divmod.bootstrap",
                    # Nevow's URL quoting rules are weird, but this is the URL
                    # flattener's fault, not mine.  Adjust to taste if that changes
                    # (it won't) -glyph
                    [u"http://localhost/'%22"]),
                ("Nevow.Athena.bootstrap",
                 [u'Nevow.Athena.PageWidget', u'asdf'])
            ])
Exemple #8
0
 def _render(self, page):
     """
     Test helper which tries to render the given page.
     """
     ctx = WovenContext()
     req = FakeRequest()
     ctx.remember(req, IRequest)
     return page.renderHTTP(ctx).addCallback(lambda ign: req.v)
Exemple #9
0
 def _render(self, fragment):
     """
     Test helper which tries to render the given fragment.
     """
     ctx = WovenContext()
     req = FakeRequest()
     ctx.remember(req, IRequest)
     return Page(docFactory=stan(fragment)).renderString(ctx)
Exemple #10
0
 def _render(self, resource):
     """
     Test helper which tries to render the given resource.
     """
     ctx = WovenContext()
     req = FakeRequest(headers={'host': self.hostname})
     ctx.remember(req, IRequest)
     return req, resource.renderHTTP(ctx)
Exemple #11
0
 def _render(self, resource):
     """
     Test helper which tries to render the given resource.
     """
     ctx = WovenContext()
     req = FakeRequest(headers={'host': self.hostname})
     ctx.remember(req, IRequest)
     return req, resource.renderHTTP(ctx)
Exemple #12
0
 def _render(self, fragment, request=None):
     """
     Test helper which tries to render the given fragment.
     """
     ctx = WovenContext()
     if request is None:
         request = FakeRequest()
     ctx.remember(request, IRequest)
     return Page(docFactory=stan(fragment)).renderString(ctx)
Exemple #13
0
def _makeContext():
    """
    Create the request and context objects necessary for rendering a page.

    @return: A two-tuple of the created L{FakeRequest} and L{WovenContext},
    with the former remembered in the latter.
    """
    request = FakeRequest()
    context = WovenContext()
    context.remember(request, IRequest)
    return (request, context)
Exemple #14
0
def _makeContext():
    """
    Create the request and context objects necessary for rendering a page.

    @return: A two-tuple of the created L{FakeRequest} and L{WovenContext},
    with the former remembered in the latter.
    """
    request = FakeRequest()
    context = WovenContext()
    context.remember(request, IRequest)
    return (request, context)
Exemple #15
0
 def test_renderReconnect(self):
     """
     L{LivePage.renderHTTP} should render a JSON-encoded version of its
     clientID rather than a rendered version of its template when provided
     with a special __athena_reconnect__ parameter.
     """
     req = FakeRequest(args={athena.ATHENA_RECONNECT: ["1"]})
     ctx = WovenContext()
     ctx.remember(req, IRequest)
     string = self.page.renderHTTP(ctx)
     jsonifiedID = '"%s"' % (self.page.clientID, )
     self.assertEqual(string, jsonifiedID)
Exemple #16
0
 def _renderHead(self, result):
     """
     Go through all the gyrations necessary to get the head contents
     produced by the page rendering process.
     """
     site = ISiteURLGenerator(self.siteStore)
     t = tags.invisible()
     ctx = WovenContext(tag=t)
     req = FakeRequest()
     ctx.remember(req, IRequest)
     expected = [th.head(req, site)
                 for th in self.pageFactory._preferredThemes()]
     head = result.render_head(ctx, None)
     return t, expected
Exemple #17
0
 def test_unsupportedBrowserPage(self):
     """
     Test that unsupported browsers get told they're unsupported.
     """
     ctx = WovenContext()
     page = athena.LivePage()
     req = FakeRequest()
     req.received_headers[
         'user-agent'] = "Mozilla/4.0 (compatible; MSIE 2.0; Windows NT 5.1)"
     ctx.remember(req, IRequest)
     d = renderPage(page, reqFactory=lambda: req)
     d.addCallback(self.assertEqual,
                   flat.flatten(page.unsupportedBrowserLoader))
     return d
Exemple #18
0
 def test_oldFlattenableInAttribute(self):
     """
     Flattening a L{Element} as the value of an attribute of a L{Tag} XML
     attribute escapes the element's flattened document.
     """
     result = []
     element = Element()
     element.docFactory = stan(['"&<>'])
     request = FakeRequest()
     context = WovenContext()
     context.remember(request)
     finished = oldFlatten(p(foo=element), context, result.append, lambda ign: ign)
     finished.addCallback(lambda ign: "".join(result))
     finished.addCallback(self.assertEqual, '<p foo="&quot;&amp;&lt;&gt;"></p>')
     return finished
Exemple #19
0
 def _renderHead(self, result):
     """
     Go through all the gyrations necessary to get the head contents
     produced by the page rendering process.
     """
     site = ISiteURLGenerator(self.siteStore)
     t = tags.invisible()
     ctx = WovenContext(tag=t)
     req = FakeRequest()
     ctx.remember(req, IRequest)
     expected = [
         th.head(req, site) for th in self.pageFactory._preferredThemes()
     ]
     head = result.render_head(ctx, None)
     return t, expected
Exemple #20
0
 def test_oldFlattenable(self):
     """
     Flattening L{Element} instances with the old flatten function results in
     the flattened version of whatever their C{render} method returns.
     """
     result = []
     element = Element()
     element.docFactory = stan(['"&<>'])
     request = FakeRequest()
     context = WovenContext()
     context.remember(request)
     finished = oldFlatten(element, context, result.append, lambda ign: ign)
     finished.addCallback(lambda ign: "".join(result))
     finished.addCallback(self.assertEqual, '"&amp;&lt;&gt;')
     return finished
 def test_oldFlattenable(self):
     """
     Flattening L{Element} instances with the old flatten function results in
     the flattened version of whatever their C{render} method returns.
     """
     result = []
     element = Element()
     element.docFactory = stan(['"&<>'])
     request = FakeRequest()
     context = WovenContext()
     context.remember(request)
     finished = oldFlatten(element, context, result.append, lambda ign: ign)
     finished.addCallback(lambda ign: "".join(result))
     finished.addCallback(self.assertEqual, '"&amp;&lt;&gt;')
     return finished
Exemple #22
0
def precompile(stan, ctx=None):
    """Given the stan and the optional context, return a list of strings and
    Context instances, optimizing as much static content as possible into contiguous
    string runs.
    The Context instances will have Tag instances whose .children have also been
    precompiled.
    """
    from nevow.context import WovenContext
    newctx = WovenContext(precompile=True)
    if ctx is not None:
        macroFactory = inevow.IMacroFactory(ctx, default=None)
        if macroFactory is not None:
            newctx.remember(macroFactory, inevow.IMacroFactory)
    doc = []
    list(iterflatten(stan, newctx, doc.append))
    return doc
Exemple #23
0
def precompile(stan, ctx=None):
    """Given the stan and the optional context, return a list of strings and
    Context instances, optimizing as much static content as possible into contiguous
    string runs.

    The Context instances will have Tag instances whose .children have also been
    precompiled.
    """
    from nevow.context import WovenContext
    newctx = WovenContext(precompile=True)
    if ctx is not None:
        macroFactory = inevow.IMacroFactory(ctx, None)
        if macroFactory is not None:
            newctx.remember(macroFactory, inevow.IMacroFactory)
    doc = []
    list(iterflatten(stan, newctx, doc.append))
    return doc
Exemple #24
0
 def test_pageJsClassDependencies(self):
     """
     L{LivePage.render_liveglue} should include modules that the
     L{LivePage}'s jsClass depends on.
     """
     self.page.jsClass = u'PythonTestSupport.Dependor.PageTest'
     freq = FakeRequest()
     self.page._becomeLive(url.URL.fromRequest(freq))
     ctx = WovenContext(tag=tags.div())
     ctx.remember(freq, IRequest)
     self.assertEqual(self.page.render_liveglue(ctx, None), ctx.tag)
     expectDependor = flat.flatten(
         self.page.getImportStan(u'PythonTestSupport.Dependor'))
     expectDependee = flat.flatten(
         self.page.getImportStan(u'PythonTestSupport.Dependee'))
     result = flat.flatten(ctx.tag, ctx)
     self.assertIn(expectDependor, result)
     self.assertIn(expectDependee, result)
Exemple #25
0
    def test_oldFlattenableError(self):
        """
        If the old flattener encounters an asynchronous Failure while
        flattening an L{IRenderable}, the returned L{Deferred} fires with the
        failure.
        """
        result = Deferred()
        element = Element()
        element.docFactory = stan(result)

        request = FakeRequest()
        context = WovenContext()
        context.remember(request)

        accumulator = []
        finished = oldFlatten(element, context, accumulator.append, lambda ign: ign)
        result.addErrback(lambda err: err.trap(RuntimeError))
        finished = self.assertFailure(finished, RuntimeError)
        result.errback(RuntimeError("test error"))
        return finished
Exemple #26
0
    def test_rendering(self):
        """
        Test that L{webadmin.UserInteractionFragment} renders without raising
        any exceptions.
        """
        f = UserInteractionFragment(self.browser)

        p = LivePage(docFactory=stan(html[head(render=directive("liveglue")), body(render=lambda ctx, data: f)]))
        f.setFragmentParent(p)

        ctx = WovenContext()
        req = FakeRequest()
        ctx.remember(req, IRequest)

        d = p.renderHTTP(ctx)

        def rendered(ign):
            p.action_close(None)

        d.addCallback(rendered)
        return d
 def process(self, context, boundTo, data, autoConfigure = True):
     """Knows how to process a dictionary of lists
     where the dictionary may contain a key with the same
     name as some of the arguments to the MethodBinding
     instance.
     """
     typedValue = self.original.typedValue
     results = {}
     failures = {}
     if data.has_key('----'):
         ## ---- is the "direct object", the one argument you can specify using the command line without saying what the argument name is
         data[typedValue.arguments[0].name] = data['----']
         del data['----']
     for binding in typedValue.arguments:
         name = binding.name
         try:
             context = WovenContext(context, faketag)
             context.remember(binding, iformless.IBinding)
             results[name] = iformless.IInputProcessor(binding.typedValue).process(context, boundTo, data.get(name, ['']))
         except formless.InputError, e:
             results[name] = data.get(name, [''])[0]
             failures[name] = e.reason
Exemple #28
0
    def test_rendering(self):
        """
        Test that L{webadmin.UserInteractionFragment} renders without raising
        any exceptions.
        """
        f = UserInteractionFragment(self.browser)

        p = LivePage(
            docFactory=stan(
                html[
                    head(render=directive('liveglue')),
                    body(render=lambda ctx, data: f)]))
        f.setFragmentParent(p)

        ctx = WovenContext()
        req = FakeRequest()
        ctx.remember(req, IRequest)

        d = p.renderHTTP(ctx)
        def rendered(ign):
            p.action_close(None)
        d.addCallback(rendered)
        return d
Exemple #29
0
    def _render(self, element):
        """
        Put the given L{IRenderer} provider into an L{athena.LivePage} and
        render it.  Return a Deferred which fires with the request object used
        which is an instance of L{nevow.testutil.FakeRequest}.
        """
        p = LivePage(docFactory=stan(html[head(
            render=directive('liveglue')), body[invisible(
                render=lambda ctx, data: element)]]))
        element.setFragmentParent(p)

        ctx = WovenContext()
        req = FakeRequest()
        ctx.remember(req, IRequest)

        d = p.renderHTTP(ctx)

        def rendered(ign):
            p.action_close(None)
            return req

        d.addCallback(rendered)
        return d
Exemple #30
0
 def process(self, context, boundTo, data, autoConfigure=True):
     """Knows how to process a dictionary of lists
     where the dictionary may contain a key with the same
     name as some of the arguments to the MethodBinding
     instance.
     """
     typedValue = self.original.typedValue
     results = {}
     failures = {}
     if data.has_key("----"):
         data[typedValue.arguments[0].name] = data["----"]
         del data["----"]
     for binding in typedValue.arguments:
         name = binding.name
         try:
             context = WovenContext(context, faketag)
             context.remember(binding, iformless.IBinding)
             results[name] = iformless.IInputProcessor(binding.typedValue).process(
                 context, boundTo, data.get(name, [""])
             )
         except formless.InputError, e:
             results[name] = data.get(name, [""])[0]
             failures[name] = e.reason
Exemple #31
0
    def postForm(self, ctx, bindingName, args):
        """Accept a form post to the given bindingName. The bindingName
        can be dotted to indicate an attribute of this Configurable, eg
        addresses.0.changeEmail. The post arguments are given in args.
        Return a Resource which will be rendered in response.
        """
        from formless import iformless
        from nevow.tags import invisible
        request = ctx.locate(inevow.IRequest)
        pathSegs = bindingName.split('.')
        configurable = self

        cf = ctx.locate(iformless.IConfigurableFactory)
        ## Get the first binding
        firstSeg = pathSegs.pop(0)
        binding = configurable.getBinding(ctx, firstSeg)
        ctx.remember(binding, IBinding)
        ctx.remember(configurable, IConfigurable)
        ## I don't think this works right now, it needs to be fixed.
        ## Most cases it won't be triggered, because we're just traversing a
        ## single binding name
        for seg in pathSegs:
            assert 1 == 0, "Sorry, this doesn't work right now"
            binding = configurable.getBinding(ctx, seg)
            child = self.boundTo
            if not isinstance(binding, GroupBinding):
                accessor = inevow.IContainer(configurable.boundTo, None)
                if accessor is None:
                    child = getattr(configurable.boundTo, binding.name)
                else:
                    child = accessor.child(ctx, binding.name)
            ## If it's a groupbinding, we don't do anything at all for this path segment
            
            ## This won't work right now. We need to push the previous configurable
            ## as the configurableFactory somehow and ask that for hte next binding
            ## we also need to support deferreds coming back from locateConfigurable
            assert 'black' is 'white', "Deferred support is pending"
            configurable = cf.locateConfigurable(ctx, child)
            ctx = WovenContext(ctx, invisible(key=seg))
            ctx.remember(binding, IBinding)
            ctx.remember(configurable, IConfigurable)

        bindingProcessor = iformless.IInputProcessor(binding)
        rv = bindingProcessor.process(ctx, binding.boundTo, args)
        ctx.remember(rv, inevow.IHand)
        ctx.remember('%r success.' % bindingName, inevow.IStatusMessage)
        return rv
Exemple #32
0
    def postForm(self, ctx, bindingName, args):
        """Accept a form post to the given bindingName. The bindingName
        can be dotted to indicate an attribute of this Configurable, eg
        addresses.0.changeEmail. The post arguments are given in args.
        Return a Resource which will be rendered in response.
        """
        from formless import iformless
        from nevow.tags import invisible
        request = ctx.locate(inevow.IRequest)
        pathSegs = bindingName.split('.')
        configurable = self

        cf = ctx.locate(iformless.IConfigurableFactory)
        ## Get the first binding
        firstSeg = pathSegs.pop(0)
        binding = configurable.getBinding(ctx, firstSeg)
        ctx.remember(binding, IBinding)
        ctx.remember(configurable, IConfigurable)
        ## I don't think this works right now, it needs to be fixed.
        ## Most cases it won't be triggered, because we're just traversing a
        ## single binding name
        for seg in pathSegs:
            assert 1 == 0, "Sorry, this doesn't work right now"
            binding = configurable.getBinding(ctx, seg)
            child = self.boundTo
            if not isinstance(binding, GroupBinding):
                accessor = inevow.IContainer(configurable.boundTo, None)
                if accessor is None:
                    child = getattr(configurable.boundTo, binding.name)
                else:
                    child = accessor.child(ctx, binding.name)
            ## If it's a groupbinding, we don't do anything at all for this path segment
            
            ## This won't work right now. We need to push the previous configurable
            ## as the configurableFactory somehow and ask that for hte next binding
            ## we also need to support deferreds coming back from locateConfigurable
            assert 'black' is 'white', "Deferred support is pending"
            configurable = cf.locateConfigurable(ctx, child)
            ctx = WovenContext(ctx, invisible(key=seg))
            ctx.remember(binding, IBinding)
            ctx.remember(configurable, IConfigurable)

        bindingProcessor = iformless.IInputProcessor(binding)
        rv = bindingProcessor.process(ctx, binding.boundTo, args)
        ctx.remember(rv, inevow.IHand)
        ctx.remember('%r success.' % bindingName, inevow.IStatusMessage)
        return rv
Exemple #33
0
    def _render(self, element):
        """
        Put the given L{IRenderer} provider into an L{athena.LivePage} and
        render it.  Return a Deferred which fires with the request object used
        which is an instance of L{nevow.testutil.FakeRequest}.
        """
        p = LivePage(
            docFactory=stan(
                html[
                    head(render=directive('liveglue')),
                    body[
                        invisible(render=lambda ctx, data: element)]]))
        element.setFragmentParent(p)

        ctx = WovenContext()
        req = FakeRequest()
        ctx.remember(req, IRequest)

        d = p.renderHTTP(ctx)
        def rendered(ign):
            p.action_close(None)
            return req
        d.addCallback(rendered)
        return d
Exemple #34
0
 def postForm(self, ctx, bindingName, args):
     """Accept a form post to the given bindingName. The bindingName
     can be dotted to indicate an attribute of this Configurable, eg
     addresses.0.changeEmail. The post arguments are given in args.
     Return a Resource which will be rendered in response.
     """
     from formless import iformless
     from nevow.tags import invisible
     request = ctx.locate(inevow.IRequest)
     pathSegs = bindingName.split('.')
     configurable = self
     cf = ctx.locate(iformless.IConfigurableFactory)
     firstSeg = pathSegs.pop(0)
     binding = configurable.getBinding(ctx, firstSeg)
     ctx.remember(binding, IBinding)
     ctx.remember(configurable, IConfigurable)
     for seg in pathSegs:
         assert 1 == 0, "Sorry, this doesn't work right now"
         binding = configurable.getBinding(ctx, seg)
         child = self.boundTo
         if not isinstance(binding, GroupBinding):
             accessor = inevow.IContainer(configurable.boundTo, None)
             if accessor is None:
                 child = getattr(configurable.boundTo, binding.name)
             else:
                 child = accessor.child(ctx, binding.name)
         assert 'black' is 'white', "Deferred support is pending"
         configurable = cf.locateConfigurable(ctx, child)
         ctx = WovenContext(ctx, invisible(key=seg))
         ctx.remember(binding, IBinding)
         ctx.remember(configurable, IConfigurable)
     bindingProcessor = iformless.IInputProcessor(binding)
     rv = bindingProcessor.process(ctx, binding.boundTo, args)
     ctx.remember(rv, inevow.IHand)
     ctx.remember('%r success.' % bindingName, inevow.IStatusMessage)
     return rv
Exemple #35
0
    def rend(self, ctx, data):
        # Unfortunately, we still need a context to make the rest of the
        # rendering process work.  A goal should be to elimate this completely.
        context = WovenContext()

        if self.docFactory is None:
            raise MissingDocumentFactory(self)

        preprocessors = _getPreprocessors(self)

        doc = self.docFactory.load(context, preprocessors)

        context.remember(self, IData)
        context.remember(self, IRenderer)
        context.remember(self, IRendererFactory)
        context.tag = invisible[doc]
        return context
Exemple #36
0
def _ctxForRequest(request, slotData, renderFactory, inAttribute):
    """
    Create a L{WovenContext} which can be used to by the
    backwards-compatibility support of L{IRenderer} and L{getFlattener} to
    continue rendering a response for the given request.
    """
    ctx = WovenContext()
    ctx.isAttrib = inAttribute
    ctx.remember(None, IData) # Even though IData(ctx) can never return None,
                              # remembering None here is somehow very important
                              # for preventing a TypeError from happening when
                              # ctx.locate(IData) is invoked, since it is
                              # sometimes invoked from a codepath other than
                              # __conform__. -exarkun
    ctx.remember(request, IRequest)
    for slotGroup in slotData:
        if slotGroup is not None:
            for k, v in slotGroup.items():
                ctx.fillSlots(k, v)
    if renderFactory is not None:
        ctx.remember(_OldRendererFactory(renderFactory), IRendererFactory)
    return ctx
Exemple #37
0
def TagSerializer(original, context, contextIsMine=False):
    """
    Original is the tag.
    Context is either:
      - the context of someone up the chain (if contextIsMine is False)
      - this tag's context (if contextIsMine is True)
    """
    #    print "TagSerializer:",original, "ContextIsMine",contextIsMine, "Context:",context
    visible = bool(original.tagName)

    if visible and context.isAttrib:
        raise RuntimeError, "Tried to render tag '%s' in an tag attribute context." % (
            original.tagName)

    if context.precompile and original.macro:
        toBeRenderedBy = original.macro
        ## Special case for directive; perhaps this could be handled some other way with an interface?
        if isinstance(toBeRenderedBy, directive):
            toBeRenderedBy = IMacroFactory(context).macro(
                context, toBeRenderedBy.name)
        original.macro = Unset
        newContext = WovenContext(context, original)
        yield serialize(toBeRenderedBy(newContext), newContext)
        return

    ## TODO: Do we really need to bypass precompiling for *all* specials?
    ## Perhaps just render?
    if context.precompile and ([
            x for x in original._specials.values()
            if x is not None and x is not Unset
    ] or original.slotData):
        ## The tags inside this one get a "fresh" parent chain, because
        ## when the context yielded here is serialized, the parent
        ## chain gets reconnected to the actual parents at that
        ## point, since the render function here could change
        ## the actual parentage hierarchy.
        nestedcontext = WovenContext(precompile=context.precompile,
                                     isAttrib=context.isAttrib)

        # If necessary, remember the MacroFactory onto the new context chain.
        macroFactory = IMacroFactory(context, None)
        if macroFactory is not None:
            nestedcontext.remember(macroFactory, IMacroFactory)

        original = original.clone(deep=False)
        if not contextIsMine:
            context = WovenContext(context, original)
        context.tag.children = precompile(context.tag.children, nestedcontext)

        yield context
        return

    ## Don't render patterns
    if original.pattern is not Unset and original.pattern is not None:
        return

    if not contextIsMine:
        if original.render:
            ### We must clone our tag before passing to a render function
            original = original.clone(deep=False)
        context = WovenContext(context, original)

    if original.data is not Unset:
        newdata = convertToData(original.data, context)
        if isinstance(newdata, util.Deferred):
            yield newdata.addCallback(
                lambda newdata: _datacallback(newdata, context))
        else:
            _datacallback(newdata, context)

    if original.render:
        ## If we have a render function we want to render what it returns,
        ## not our tag
        toBeRenderedBy = original.render
        # erase special attribs so if the renderer returns the tag,
        # the specials won't be on the context twice.
        original._clearSpecials()
        yield serialize(toBeRenderedBy, context)
        return

    if not visible:
        for child in original.children:
            yield serialize(child, context)
        return

    yield '<%s' % original.tagName
    if original.attributes:
        attribContext = WovenContext(parent=context,
                                     precompile=context.precompile,
                                     isAttrib=True)
        for (k, v) in original.attributes.iteritems():
            if v is None:
                continue
            yield ' %s="' % k
            yield serialize(v, attribContext)
            yield '"'
    if not original.children:
        if original.tagName in allowSingleton:
            yield ' />'
        else:
            yield '></%s>' % original.tagName
    else:
        yield '>'
        for child in original.children:
            yield serialize(child, context)
        yield '</%s>' % original.tagName
Exemple #38
0
def TagSerializer(original, context, contextIsMine=False):
    """
    Original is the tag.
    Context is either:
      - the context of someone up the chain (if contextIsMine is False)
      - this tag's context (if contextIsMine is True)
    """
    #    print "TagSerializer:",original, "ContextIsMine",contextIsMine, "Context:",context
    visible = bool(original.tagName)

    if visible and context.isAttrib:
        raise RuntimeError("Tried to render tag '%s' in an tag attribute context." % (original.tagName))

    if context.precompile and original.macro:
        toBeRenderedBy = original.macro
        ## Special case for directive; perhaps this could be handled some other way with an interface?
        if isinstance(toBeRenderedBy, directive):
            toBeRenderedBy = IMacroFactory(context).macro(context, toBeRenderedBy.name)
        original.macro = Unset
        newContext = WovenContext(context, original)
        yield serialize(toBeRenderedBy(newContext), newContext)
        return

    ## TODO: Do we really need to bypass precompiling for *all* specials?
    ## Perhaps just render?
    if context.precompile and (
        [x for x in list(original._specials.values()) if x is not None and x is not Unset] or original.slotData
    ):
        ## The tags inside this one get a "fresh" parent chain, because
        ## when the context yielded here is serialized, the parent
        ## chain gets reconnected to the actual parents at that
        ## point, since the render function here could change
        ## the actual parentage hierarchy.
        nestedcontext = WovenContext(precompile=context.precompile, isAttrib=context.isAttrib)

        # If necessary, remember the MacroFactory onto the new context chain.
        macroFactory = IMacroFactory(context, None)
        if macroFactory is not None:
            nestedcontext.remember(macroFactory, IMacroFactory)

        original = original.clone(deep=False)
        if not contextIsMine:
            context = WovenContext(context, original)
        context.tag.children = precompile(context.tag.children, nestedcontext)

        yield context
        return

    ## Don't render patterns
    if original.pattern is not Unset and original.pattern is not None:
        return

    if not contextIsMine:
        if original.render:
            ### We must clone our tag before passing to a render function
            original = original.clone(deep=False)
        context = WovenContext(context, original)

    if original.data is not Unset:
        newdata = convertToData(original.data, context)
        if isinstance(newdata, util.Deferred):
            yield newdata.addCallback(lambda newdata: _datacallback(newdata, context))
        else:
            _datacallback(newdata, context)

    if original.render:
        ## If we have a render function we want to render what it returns,
        ## not our tag
        toBeRenderedBy = original.render
        # erase special attribs so if the renderer returns the tag,
        # the specials won't be on the context twice.
        original._clearSpecials()
        yield serialize(toBeRenderedBy, context)
        return

    if not visible:
        for child in original.children:
            yield serialize(child, context)
        return

    yield "<%s" % original.tagName
    if original.attributes:
        attribContext = WovenContext(parent=context, precompile=context.precompile, isAttrib=True)
        for (k, v) in sorted(original.attributes.items()):
            if v is None:
                continue
            yield ' %s="' % k
            yield serialize(v, attribContext)
            yield '"'
    if not original.children:
        if original.tagName in allowSingleton:
            yield " />"
        else:
            yield "></%s>" % original.tagName
    else:
        yield ">"
        for child in original.children:
            yield serialize(child, context)
        yield "</%s>" % original.tagName
Exemple #39
0
 def cbCheckPageByClientID(result):
     req = FakeRequest()
     ctx = WovenContext()
     ctx.remember(req, IRequest)
     page1prime, seg = w.locateChild(ctx, [page1.clientID])
     self.assertIdentical(page1prime, page1)