def renderHTTP(self, ctx): # The URL may have deferred parts so flatten it u = flatten(self.original, ctx) # It might also be relative so resolve it against the current URL # and flatten it again. u = flatten(URL.fromContext(ctx).click(u), ctx) return redirectTo(u, inevow.IRequest(ctx))
def test_normal(self): """No quoting at all happens when we are in a JavascriptContext which is not in a single quoted string or a double quoted string. """ ctx = makeCtx() self.assertEquals(flat.flatten("foo", ctx), "'foo'") self.assertEquals(flat.flatten(livepage.js("1 < 2 & 3"), ctx), "1 < 2 & 3")
def renderHTTP(self, ctx): # The URL may have deferred parts so flatten it u = flatten(self.original, ctx) # It might also be relative so resolve it against the current URL # and flatten it again. u = flatten(URL.fromContext(ctx).click(u), ctx) return redirectTo(u, inevow.IRequest(ctx))
def testXML(self): t = '<a xmlns:n="http://nevow.com/ns/nevow/0.1" href="#"><n:attr name="href">href</n:attr>label</a>' result = flat.flatten(loaders.xmlstr(t).load()) self.assertEqual(result, '<a href="href">label</a>') t = '<a xmlns:n="http://nevow.com/ns/nevow/0.1" href="#"><n:attr name="href"><n:slot name="href"/></n:attr>label</a>' ctx = context.WovenContext() ctx.fillSlots('href', 'href') result = flat.flatten(flat.precompile(loaders.xmlstr(t).load()), ctx) self.assertEqual(result, '<a href="href">label</a>')
def testXML(self): t = '<a xmlns:n="http://nevow.com/ns/nevow/0.1" href="#"><n:attr name="href">href</n:attr>label</a>' result = flat.flatten(loaders.xmlstr(t).load()) self.assertEqual(result, '<a href="href">label</a>') t = '<a xmlns:n="http://nevow.com/ns/nevow/0.1" href="#"><n:attr name="href"><n:slot name="href"/></n:attr>label</a>' ctx = context.WovenContext() ctx.fillSlots('href', 'href') result = flat.flatten(flat.precompile(loaders.xmlstr(t).load()), ctx) self.assertEqual(result, '<a href="href">label</a>')
def testHTML(self): t = '<a href="#"><nevow:attr name="href">href</nevow:attr>label</a>' doc = flat.flatten(loaders.htmlstr(t).load()) self.assertEqual(doc, '<a href="href">label</a>') t = '<a href="#"><nevow:attr name="href"><nevow:slot name="href"/></nevow:attr>label</a>' precompiled = loaders.htmlstr(t).load() ctx = context.WovenContext(tag=tags.invisible[precompiled]) ctx.fillSlots('href', 'href') result = flat.flatten(precompiled, ctx) self.assertEqual(result, '<a href="href">label</a>')
def testHTML(self): t = '<a href="#"><nevow:attr name="href">href</nevow:attr>label</a>' doc = flat.flatten(loaders.htmlstr(t).load()) self.assertEqual(doc, '<a href="href">label</a>') t = '<a href="#"><nevow:attr name="href"><nevow:slot name="href"/></nevow:attr>label</a>' ctx = context.WovenContext() ctx.fillSlots('href', 'href') precompiled = flat.precompile(loaders.htmlstr(t).load()) result = flat.flatten(precompiled, ctx) self.assertEqual(result, '<a href="href">label</a>')
def test_title(self): """ The I{title} renderer should add the wrapped fragment's title attribute, if any, or the default "Divmod". """ page = self.createPage(self.username) titleTag = title() tag = page.render_title(context.WebContext(tag=titleTag), None) self.assertIdentical(tag, titleTag) flattened = flatten(tag) self.assertSubstring(flatten(getattr(page.fragment, "title", "Divmod")), flattened)
def test_title(self): """ The I{title} renderer should add the wrapped fragment's title attribute, if any, or the default "Divmod". """ page = self.createPage(self.username) titleTag = title() tag = page.render_title(context.WebContext(tag=titleTag), None) self.assertIdentical(tag, titleTag) flattened = flatten(tag) self.assertSubstring( flatten(getattr(page.fragment, 'title', 'Divmod')), flattened)
def test_inAttribute(self): """When inside an attribute, we must make sure to quote double quotes. """ ctx = makeCtx(inAttribute=True) self.assertEquals(flat.flatten('foo', ctx), "'foo'") self.assertEquals( flat.flatten(livepage.js.foo('hello"world'), ctx), "foo('hello"world')") self.assertEquals( flat.flatten(livepage.js.foo("1 < 2 & 3"), ctx), "foo('1 < 2 & 3')")
def test_urlintagwithmultipleamps(self): """ Test the serialization of an URL with an ampersand in it as an attribute value. The ampersand must be quoted for the attribute to be valid. """ tag = tags.invisible[tags.a(href=url.URL.fromString('http://localhost/').add('foo', 'bar').add('baz', 'spam'))] self.assertEqual(flatten(tag), '<a href="http://localhost/?foo=bar&baz=spam"></a>') tag = tags.invisible[loaders.xmlstr('<a xmlns:n="http://nevow.com/ns/nevow/0.1" href="#"><n:attr name="href"><n:slot name="href"/></n:attr></a>')] tag.fillSlots('href', url.URL.fromString('http://localhost/').add('foo', 'bar').add('baz', 'spam')) self.assertEqual(flatten(tag), '<a href="http://localhost/?foo=bar&baz=spam"></a>')
def test_urlintagwithmultipleamps(self): """ Test the serialization of an URL with an ampersand in it as an attribute value. The ampersand must be quoted for the attribute to be valid. """ tag = tags.invisible[tags.a(href=url.URL.fromString('http://localhost/').add('foo', 'bar').add('baz', 'spam'))] self.assertEquals(flatten(tag), '<a href="http://localhost/?foo=bar&baz=spam"></a>') tag = tags.invisible[loaders.xmlstr('<a xmlns:n="http://nevow.com/ns/nevow/0.1" href="#"><n:attr name="href"><n:slot name="href"/></n:attr></a>')] tag.fillSlots('href', url.URL.fromString('http://localhost/').add('foo', 'bar').add('baz', 'spam')) self.assertEquals(flatten(tag), '<a href="http://localhost/?foo=bar&baz=spam"></a>')
def test_data(self): ctx = context.WovenContext() ctx.remember('foo', inevow.IData) tag = p(render=rend.data) self.assertEquals(flat.flatten(tag, ctx), '<p>foo</p>') ctx.remember('\xc2\xa3'.decode('utf-8'), inevow.IData) tag = p(render=rend.data) self.assertEquals(flat.flatten(tag, ctx), '<p>\xc2\xa3</p>') ctx.remember([1,2,3,4,5], inevow.IData) tag = p(render=rend.data) self.assertEquals(flat.flatten(tag, ctx), '<p>12345</p>') ctx.remember({'foo':'bar'}, inevow.IData) tag = p(data=directive('foo'), render=rend.data) self.assertEquals(flat.flatten(tag, ctx), '<p>bar</p>')
def test_dontQuoteJS(self): """We must not put js objects in single quotes, even if they are inside another js.__call__ """ self.assertEquals( flat.flatten(livepage.js.foo(livepage.js.bar()), makeCtx()), "foo(bar())")
def test_blogsRenderer(self): """ Test that L{hyperbola_view.BlogListFragment.blogs} renders a list of blogs. """ site = self.siteStore.findUnique(SiteConfiguration) site.hostname = u'blogs.renderer' blog1 = self._shareAndGetProxy(self._makeBlurb(FLAVOR.BLOG)) blog2 = self._shareAndGetProxy(self._makeBlurb(FLAVOR.BLOG)) blf = hyperbola_view.BlogListFragment( athena.LivePage(), self.publicPresence) blf.docFactory = loaders.stan( tags.div(pattern='blog')[ tags.span[tags.slot('title')], tags.span[tags.slot('link')], tags.span[tags.slot('post-url')]]) tag = tags.invisible markup = flat.flatten(tags.div[blf.blogs(None, tag)]) doc = minidom.parseString(markup) blogNodes = doc.firstChild.getElementsByTagName('div') self.assertEqual(len(blogNodes), 2) for (blogNode, blog) in zip(blogNodes, (blog1, blog2)): (title, blogURL, postURL) = blogNode.getElementsByTagName('span') blogURL = blogURL.firstChild.nodeValue expectedBlogURL = str(websharing.linkTo(blog)) self.assertEqual(blogURL, expectedBlogURL) postURL = postURL.firstChild.nodeValue self.assertEqual( postURL, 'https://blogs.renderer' + expectedBlogURL + '/post')
def test_transportRoot(self): """ The transport root should always point at the '/live' transport root provided to avoid database interaction while invoking the transport. """ livePage = self.makeLivePage() self.assertEquals(flatten(livePage.transportRoot), 'http://localhost/live')
def flattened(spam): # Join the bits to make a complete URL. u = ''.join(bits) # It might also be relative so resolve it against the current URL # and flatten it again. u = flat.flatten(URL.fromContext(ctx).click(u), ctx) return redirectTo(u, inevow.IRequest(ctx))
def flattened(spam): # Join the bits to make a complete URL. u = ''.join(bits) # It might also be relative so resolve it against the current URL # and flatten it again. u = flat.flatten(URL.fromContext(ctx).click(u), ctx) return redirectTo(u, inevow.IRequest(ctx))
def formatHeader(self, columns: [str]) -> bytes: self.columns = columns tr = tags.tr()[ [tags.th()[i] for i in self.columns] ] self.header.children.append(tr) return flat.flatten(tr)
def handleWsFailure(self,failureInst,handler,callbackURI): """ called in case of failure condition. """ failureInst.trap(error.Error) # handle the various status codes scode = int(failureInst.value.status) #print 'failureInst.value is',failureInst.value,failureInst.value.status,type(failureInst.value.status) if scode == 503: # mark the state as retry for req in handler.requests: self.recentTxns[req['id']].setretry() # try again - service is temporarily unavailable. d = defer.Deferred() donecb = d.addCallback(self.proxyHandler.doRemoteRequest,handler,callbackURI) donecb.addCallback(self.clearTxn,handler) donecb.addErrback(self.handleWsFailure,handler,callbackURI) reactor.callLater(2,d.callback,None) else: # return the error code back resp = ProxyResponse([{'id':req['id'],'status':scode} for req in handler.requests],[]) fireCallbackURI(callbackURI,flat.flatten(resp.generateResponse())) # trap all the errors here. return None
def test_invisiblens(self): """ Test that invisible tags do not get output with a namespace. """ xml = ('<p xmlns:n="http://nevow.com/ns/nevow/0.1">' '<n:invisible>123</n:invisible></p>') self.failUnlessEqual('<p>123</p>', flatten(parseString(xml)))
def renderHTTP_exception(self, ctx, reason): conf = confparse.Config() now = time.time() hash = sha.sha("%s%s" % (conf.CompanyName, now)).hexdigest() refNo = sum([ord(i) for i in hash+hash]) log.err(reason) request = inevow.IRequest(ctx) request.setResponseCode(http.INTERNAL_SERVER_ERROR) request.write('<html><head><title>Vulani Error</title><link rel="stylesheet" type="text/css" href="/css/style.css"/></head><body>') request.write('<div id="pageTitle"><img id="pageTitleLogo" src="/images/vulani-tums.png" alt=""/>') request.write('</div>') request.write('<div id="sideContainer"><div id="pageNote">Error</div>') request.write('<div id="pageSide"> </div></div>') request.write('<div id="pageContent">') request.write("<h3>An error has occured</h3><p>An error has occurred. We apologise for this inconvenience.</p>") request.write('<div style="height:25em; width:50em; overflow: auto;">') from nevow import failure st = flat.flatten(failure.formatFailure(reason)) print type(st), "ERROR" result = ''.join(st) resHead = result.split('<a href="#tracebackEnd">')[0].replace('font-size: large;', '') realError = result.split('<div class="frame">')[-1] print realError result = resHead + '<div><div class="frame">' + realError if not 'stfu' in dir(Settings): Utils.sendMail("%s <*****@*****.**>" % Settings.LDAPOrganisation, ["*****@*****.**"], "[REF: %s] TUMS Error" % refNo, result, html=True) request.write(result) request.write('</div></div>') request.write("</body></html>") request.finishRequest( False )
def test_urlSlot(self): u = url.URL.fromString('http://localhost/').child(r'<c:\foo\bar&>') tag = tags.img(src=tags.slot('src')) tag.fillSlots('src', u) self.assertEquals( flatten(tag), '<img src="http://localhost/%3Cc%3A%5Cfoo%5Cbar%26%3E" />')
def visit_cmsimage_node(self, node): maxwidth=node.attributes['maxwidth'] maxheight=node.attributes['maxheight'] if maxwidth is None or maxheight is None: tag = T.img(src=self.systemURL.child('assets').child( node.attributes['id'] )) else: tag = T.img(src=self.systemURL.child('assets').child( node.attributes['id'] ).add('size','%sx%s'%(maxwidth,maxheight))) if node.attributes['alt']: tag = tag(alt=node.attributes['alt']) if node.attributes['title']: tag = tag(title=node.attributes['title']) if node.attributes['cssclass']: tag = tag(class_=node.attributes['cssclass']) if node.attributes['href']: tag = T.a(href=node.attributes['href'])[ tag ] if node.attributes['caption']: tag = T.div(class_='cmsimage')[tag,T.p[node.attributes['caption']]] else: tag = T.div(class_='cmsimage')[tag] html = flat.flatten(tag) self.body.append(html)
def test_otherns(self): xml = ( '<html xmlns="http://www.w3.org/1999/xhtml" ' 'xmlns:xf="http://www.w3.org/2002/xforms"><p>' 'in default namespace</p><xf:input><xf:label>' 'in another namespace</xf:label></xf:input></html>') self.assertEqual(xml, flatten(parseString(xml)))
def renderHTTP_exception(self, ctx, reason): log.err(reason) request = inevow.IRequest(ctx) request.setResponseCode(http.INTERNAL_SERVER_ERROR) request.write('<html><head><title>TUMS Error</title><link rel="stylesheet" type="text/css" href="/css/style.css"/></head><body>') request.write('<div id="pageTitle"><img src="/images/thusa.png" alt=""/><ul>') request.write('<li><h1><a href="/auth/Status/">Dashboard</a></h1>View system status</li>') request.write('<li><h1><a href="/auth/Users/">Users</a></h1>Manage user accounts</li>') request.write('<li><h1><a href="/auth/Reports/">Reports</a></h1>View system reports</li>') request.write('<li><h1><a href="/auth/Tools/">Tools</a></h1>Configure system settings</li></ul></div>') request.write('<div id="pageNote"><h2>Error</h2></div><div id="pageSide"></div>') request.write('<div id="pageContent">') request.write("<h3>An error has occured</h3><p>An error has occurred. We apologise for this inconvenience.</p>") request.write("<p><strong>Please don't panic!</strong> The explanation in the box below may contain a simple reason for the problem. ") request.write("<br/>This error has been automaticaly emailed to Thusa for analysis.") request.write('<div style="height:25em; width:50em; overflow: scroll;">') from nevow import failure result = ''.join(flat.flatten(failure.formatFailure(reason))) #Utils.sendMail("%s <*****@*****.**>" % Settings.LDAPOrganisation, ["*****@*****.**"], "TUMS Error", result, html=True) request.write(result) request.write('</div></div>') request.write("</body></html>") request.finishRequest( False )
def test_switchns(self): xml = ( '<html xmlns="http://www.w3.org/1999/xhtml">' '<p>in default namespace</p>' '<foo:div xmlns:foo="http://www.w3.org/1999/xhtml">' '<foo:p>in foo namespace</foo:p></foo:div></html>') self.assertEqual(xml, flatten(parseString(xml)))
def photoRss(self, ctx): request = inevow.IRequest(ctx) # this should be making atom! # it needs to return the most recent pics, with a link to the next set! # copied from what flickr emits request.setHeader("Content-Type", "text/xml; charset=utf-8") items = [T.Tag('title')["bigasterisk %s photos" % self.desc.determineLabel(self.desc.graph, self.desc.topicDict)]] for pic in self.desc.photos()[-50:]: # no plan yet for the range. use paging i guess items.append(T.Tag('item')[ T.Tag('title')[self.graph.label(pic, default=pic.split('/')[-1])], T.Tag('link')[absoluteSite(pic) + '?size=screen'], T.Tag('description')[ '<a href="%s"><img src="%s" /></a>' % (absoluteSite(pic) + '?size=large', absoluteSite(pic) + '?size=thumb')], T.Tag('media:thumbnail')(url=absoluteSite(pic) + '?size=small'), T.Tag('media:content')(url=absoluteSite(pic) + '?size=screen'), ]) return """<?xml version="1.0" encoding="utf-8" standalone="yes"?> <rss version="2.0" xmlns:media="http://search.yahoo.com/mrss" xmlns:atom="http://www.w3.org/2005/Atom"> <channel> """ + flat.flatten(items) + """
def test_rfc1808(self): """Test the relative link resolving stuff I found in rfc1808 section 5. """ base = url.URL.fromString(rfc1808_relative_link_base) for link, result in rfc1808_relative_link_tests: #print link self.assertEqual(result, flatten(base.click(link)))
def xmlCountResults(count): """a made-up format for count query results""" return '<?xml version="1.0"?>\n' + flat.flatten( Tag("sparql")(xmlns=RESULTS_NS, **{'xmlns:ext':EXTENDED_NS})[ Tag("results")[ Tag("ext:count")[count], ]])
def getEditGrabberForm(self, targetID): if self.wt is None: self.wt = self.original.privateApplication grabber = self.wt.fromWebID(targetID) f = liveform.LiveForm( lambda **kwargs: self.editGrabber(grabber, **kwargs), (liveform.Parameter('password1', liveform.PASSWORD_INPUT, unicode, u'New Password'), liveform.Parameter('password2', liveform.PASSWORD_INPUT, unicode, u'Repeat Password'), liveform.Parameter('ssl', liveform.CHECKBOX_INPUT, bool, 'Use SSL', default=grabber.ssl)), description='Edit Grabber') grabber.grab() f.setFragmentParent(self) return unicode(flatten(f), 'utf-8')
def test_dataContextCreation(self): data = {'foo': 'oof', 'bar': 'rab'} doc = tags.p(data=data)[tags.slot('foo'), tags.slot('bar')] doc.fillSlots('foo', tags.invisible(data=tags.directive('foo'), render=str)) doc.fillSlots('bar', lambda ctx, data: data['bar']) self.assertEquals(flat.flatten(doc), '<p>oofrab</p>')
def xmlResults(resultRows): """xml text for a list of sparql results. These rows are a list of dicts with variable names as keys, rdflib objects as values. Values of None, as rdflib returns if your selection variable doesn't appear in your query, are omitted. For example, running this: SELECT ?x ?unused { ?x :y :z} will return bindings for ?x only, just as if you never included ?unused. The sparql engine should probably error on that case, in which case this handler will stop getting used. But note that if there was an OPTIONAL { ?unused ... } in the query, then there's no error but some rows won't get a <binding>. See _addOptionalVars in remotegraph.py. This is the inverse of parseSparqlResults. """ # this is redundant with a version in rdflib already, although # mine uses a default xml namespace that saves quite a few bytes # in one test, getQuery spends 27% in queryd and 71% in this function! return '<?xml version="1.0"?>\n' + flat.flatten( Tag("sparql")(xmlns=RESULTS_NS) [Tag("head")[Tag("variable")(name="notimplemented")], Tag("results")(ordered="notimplemented", distinct="notimplemented")[ (Tag("result")[(Tag("binding")(name=k)[term(v)] for k, v in row.items() if v is not None)] for row in resultRows)]])
def test_reloadAfterPrecompile(self): """ """ # Get a filename temp = self.mktemp() # Write some content f = file(temp, 'w') f.write('<p>foo</p>') f.close() # Precompile the doc ctx = context.WovenContext() doc = loaders.htmlfile(temp) pc = flat.precompile(flat.flatten(doc), ctx) before = ''.join(flat.serialize(pc, ctx)) # Write the file with different content and make sure the # timestamp changes f = file(temp, 'w') f.write('<p>bar</p>') f.close() os.utime(temp, (os.path.getatime(temp), os.path.getmtime(temp)+5)) after = ''.join(flat.serialize(pc, ctx)) self.assertIn('foo', before) self.assertIn('bar', after) self.failIfEqual(before, after)
def photoRss(self, ctx): request = inevow.IRequest(ctx) # this should be making atom! # it needs to return the most recent pics, with a link to the next set! # copied from what flickr emits request.setHeader("Content-Type", "text/xml; charset=utf-8") items = [ T.Tag('title')["bigasterisk %s photos" % self.desc.determineLabel( self.desc.graph, self.desc.topicDict)] ] for pic in self.desc.photos( )[-50:]: # no plan yet for the range. use paging i guess items.append( T.Tag('item')[ T.Tag('title')[self.graph. label(pic, default=pic.split('/')[-1])], T.Tag('link')[absoluteSite(pic) + '?size=screen'], T.Tag('description')['<a href="%s"><img src="%s" /></a>' % (absoluteSite(pic) + '?size=large', absoluteSite(pic) + '?size=thumb')], T.Tag('media:thumbnail')(url=absoluteSite(pic) + '?size=small'), T.Tag('media:content')(url=absoluteSite(pic) + '?size=screen'), ]) return """<?xml version="1.0" encoding="utf-8" standalone="yes"?> <rss version="2.0" xmlns:media="http://search.yahoo.com/mrss" xmlns:atom="http://www.w3.org/2005/Atom"> <channel> """ + flat.flatten(items) + """
def test_rfc1808(self): """Test the relative link resolving stuff I found in rfc1808 section 5. """ base = url.URL.fromString(rfc1808_relative_link_base) for link, result in rfc1808_relative_link_tests: #print link self.failUnlessEqual(result, flatten(base.click(link)))
def test_transportRoot(self): """ The transport root should always point at the '/live' transport root provided to avoid database interaction while invoking the transport. """ livePage = self.makeLivePage() self.assertEquals(flatten(livePage.transportRoot), 'http://localhost/live')
def maketag(context, tag, default, kwargs, content=None): default.update(kwargs) if content is not None: t = tag(**default)[content] else: t = tag(**default) context.write(flat.flatten(t)) return ""
def test_invisiblens(self): """ Test that invisible tags do not get output with a namespace. """ xml = ( '<p xmlns:n="http://nevow.com/ns/nevow/0.1">' '<n:invisible>123</n:invisible></p>') self.assertEqual('<p>123</p>', flatten(parseString(xml)))
def create_advert(): s = ('This page was automatically generated and ' 'uploaded using ') return trac_html( flat.flatten( T.div(class_='last-modified') [s, T.a(href='/projects/pida/wiki/TracDumbUpload')['TracDumbUpload'], T.br, T.br]))
def test_inSingleQuoteString(self): """When inside a single-quote string, we must quote single- quoted strings. """ ctx = makeCtx() self.assertEquals( flat.flatten(livepage.js.foo(tags.div["single'quote"]), ctx), "foo('<div>single\\'quote</div>')")
def test_unicode(self): """ L{URLSerializer} should provide basic IRI (RFC 3987) support by encoding Unicode to UTF-8 before percent-encoding. """ iri = u'http://localhost/expos\xe9?doppelg\xe4nger=Bryan O\u2019Sullivan#r\xe9sum\xe9' uri = b'http://localhost/expos%C3%A9?doppelg%C3%A4nger=Bryan%20O%E2%80%99Sullivan#r%C3%A9sum%C3%A9' self.assertEqual(flatten(url.URL.fromString(iri)), uri)
def test_unicode(self): """ L{URLSerializer} should provide basic IRI (RFC 3987) support by encoding Unicode to UTF-8 before percent-encoding. """ iri = u'http://localhost/expos\xe9?doppelg\xe4nger=Bryan O\u2019Sullivan#r\xe9sum\xe9' uri = 'http://localhost/expos%C3%A9?doppelg%C3%A4nger=Bryan%20O%E2%80%99Sullivan#r%C3%A9sum%C3%A9' self.assertEquals(flatten(url.URL.fromString(iri)), uri)
def test_publicPage(self): """ Test that L{publicpage.PublicAthenaLivePage} supports themeing of Athena's unsupported-browser page. """ stp = StubThemeProvider(store=self.siteStore) installOn(stp, self.siteStore) p = PublicAthenaLivePage(self.siteStore, None) self.assertEqual(p.renderUnsupported(None), flatten(CUSTOM_MSG))
def test_data(self): ctx = context.WovenContext() ctx.remember('foo', inevow.IData) tag = p(render=rend.data) self.assertEqual(flat.flatten(tag, ctx), '<p>foo</p>') ctx.remember('\xc2\xa3'.decode('utf-8'), inevow.IData) tag = p(render=rend.data) self.assertEqual(flat.flatten(tag, ctx), '<p>\xc2\xa3</p>') ctx.remember([1, 2, 3, 4, 5], inevow.IData) tag = p(render=rend.data) self.assertEqual(flat.flatten(tag, ctx), '<p>12345</p>') ctx.remember({'foo': 'bar'}, inevow.IData) tag = p(data=directive('foo'), render=rend.data) self.assertEqual(flat.flatten(tag, ctx), '<p>bar</p>')
def renderHTTP_exception(self, ctx, reason): request = inevow.IRequest(ctx) request.setResponseCode(http.INTERNAL_SERVER_ERROR) request.write("<html><head><title>Exception</title></head><body>") from nevow import failure result = failure.formatFailure(reason) request.write(''.join(flat.flatten(result))) request.write("</body></html>") server.Request.finish(request)
def renderHTTP_exception(self, ctx, reason): request = inevow.IRequest(ctx) request.setResponseCode(http.INTERNAL_SERVER_ERROR) request.write("<html><head><title>Exception</title></head><body>") from nevow import failure result = failure.formatFailure(reason) request.write(''.join(flat.flatten(result))) request.write("</body></html>") server.Request.finish(request)
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)
def test_bodyRendererEmptyBody(self): """ L{BlurbViewer.body} should be able to render Blurbs with empty bodies. """ body = u'' view = BlurbViewer(self._makeBlurb(hyperblurb.FLAVOR.BLOG, None, body)) result = flatten(view.body(None, None)) self.assertEqual(result, body)
def test_urlXmlAttrSlot(self): u = url.URL.fromString("http://localhost/").child(r"<c:\foo\bar&>") tag = tags.invisible[ loaders.xmlstr( '<img xmlns:n="http://nevow.com/ns/nevow/0.1" src="#"><n:attr name="src"><n:slot name="src"/></n:attr></img>' ) ] tag.fillSlots("src", u) self.assertEqual(flatten(tag), '<img src="http://localhost/%3Cc%3A%5Cfoo%5Cbar%26%3E" />')
def call(self, method, *args): """Call a client-side method with the given arguments. Arguments will be converted to strings. You should probably use the other higher-level apis instead. """ flatcall = flatten( m(n=method, t=self.groupName)[[squish(x) for x in args if x is not None]]) self.socket.write(flatcall + '\0')
def call(self, method, *args): """Call a client-side method with the given arguments. Arguments will be converted to strings. You should probably use the other higher-level apis instead. """ flatcall = flatten( m(n=method, t=self.groupName)[[ squish(x) for x in args if x is not None]]) self.socket.write(flatcall + '\0')
def test_urlXmlAttrSlot(self): u = url.URL.fromString('http://localhost/').child(r'<c:\foo\bar&>') tag = tags.invisible[loaders.xmlstr( '<img xmlns:n="http://nevow.com/ns/nevow/0.1" src="#"><n:attr name="src"><n:slot name="src"/></n:attr></img>' )] tag.fillSlots('src', u) self.assertEquals( flatten(tag), '<img src="http://localhost/%3Cc%3A%5Cfoo%5Cbar%26%3E" />')