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 _xml2ReSTFragment(xml): XML_TEMPLATE = """<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <div xmlns:n="http://nevow.com/ns/nevow/0.1" >%(xml)s</div>""" xml = XML_TEMPLATE%{'xml':xml} return ReSTFragment(docFactory=loaders.xmlstr( xml, ignoreDocType=True))
def test_reusedDocFactory(self): """ Test that a docFactory which is used more than once behaves properly both times. """ class Page(rend.Page): docFactory = loaders.stan(div[invisible(render=directive('included'))]) def __init__(self, included): self.included = included rend.Page.__init__(self) def render_included(self, context, data): return self.included p1 = Page(loaders.stan('first')) p2 = Page(loaders.xmlstr('<p>second</p>')) d = deferredRender(p1) def rendered(result): self.assertEqual(result, '<div>first</div>') return deferredRender(p2) d.addCallback(rendered) def renderedAgain(result): self.assertEqual(result, '<div><p>second</p></div>') d.addCallback(renderedAgain) return d
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)
def test_docFactoryInStanTree(self): class Page(rend.Page): def __init__(self, included): self.included = included rend.Page.__init__(self) def render_included(self, context, data): return self.included docFactory = loaders.stan( div[invisible(render=directive('included'))]) doc = '<p>fum</p>' temp = self.mktemp() f = file(temp, 'w') f.write(doc) f.close() result = deferredRender(Page(loaders.stan(p['fee']))) self.assertEquals(result, '<div><p>fee</p></div>') result = deferredRender(Page(loaders.htmlstr('<p>fi</p>'))) self.assertEquals(result, '<div><p>fi</p></div>') result = deferredRender(Page(loaders.xmlstr('<p>fo</p>'))) self.assertEquals(result, '<div><p>fo</p></div>') result = deferredRender(Page(loaders.htmlfile(temp))) self.assertEquals(result, '<div><p>fum</p></div>') result = deferredRender(Page(loaders.xmlfile(temp))) self.assertEquals(result, '<div><p>fum</p></div>')
def test_docFactoryInStanTree(self): class Page(rend.Page): def __init__(self, included): self.included = included rend.Page.__init__(self) def render_included(self, context, data): return self.included docFactory = loaders.stan(div[invisible(render=directive('included'))]) doc = '<p>fum</p>' temp = self.mktemp() f = file(temp, 'w') f.write(doc) f.close() result = deferredRender(Page(loaders.stan(p['fee']))) self.assertEquals(result, '<div><p>fee</p></div>') result = deferredRender(Page(loaders.htmlstr('<p>fi</p>'))) self.assertEquals(result, '<div><p>fi</p></div>') result = deferredRender(Page(loaders.xmlstr('<p>fo</p>'))) self.assertEquals(result, '<div><p>fo</p></div>') result = deferredRender(Page(loaders.htmlfile(temp))) self.assertEquals(result, '<div><p>fum</p></div>') result = deferredRender(Page(loaders.xmlfile(temp))) self.assertEquals(result, '<div><p>fum</p></div>')
def test_xmlStringInStanTree(self): """ Like L{test_htmlStringInStanTree}, but for an xmlstr loader. """ return self._testDocFactoryInStanTree( loaders.xmlstr('<p>fo</p>'), '<p>fo</p>')
class Index(rend.Page): addSlash = True docFactory = loaders.xmlstr(index_html) child_css = static.File('.') def child_console_process_page(self, ctx): return ConsoleProcessPage()
class MainPage(rend.Page): docFactory = loaders.xmlstr(resource_string(__name__, "main.xhtml")) def __init__(self, config, dbpool, collector): self.config = config['web'] self.dbpool = dbpool self.collector = collector rend.Page.__init__(self) def render_logo(self, ctx, data): if 'logo' in self.config and os.path.exists(self.config['logo']): return T.img(src="customlogo") return "To place your logo here, see the documentation" def child_customlogo(self, ctx): return static.File(self.config['logo']) def child_static(self, ctx): return static.File(resource_filename(__name__, "static")) def child_api(self, ctx): return ApiResource(self.config, self.dbpool, self.collector) def childFactory(self, ctx, node): """Backward compatibility with previous API""" if node in ["equipment", "search", "complete", "past", "images"]: inevow.IRequest(ctx).rememberRootURL() return RedirectApi() return None
def test_reusedDocFactory(self): """ Test that a docFactory which is used more than once behaves properly both times. """ class Page(rend.Page): docFactory = loaders.stan( div[invisible(render=directive('included'))]) def __init__(self, included): self.included = included rend.Page.__init__(self) def render_included(self, context, data): return self.included p1 = Page(loaders.stan('first')) p2 = Page(loaders.xmlstr('<p>second</p>')) d = deferredRender(p1) def rendered(result): self.assertEqual(result, '<div>first</div>') return deferredRender(p2) d.addCallback(rendered) def renderedAgain(result): self.assertEqual(result, '<div><p>second</p></div>') d.addCallback(renderedAgain) return d
def test_simpleXHTMLRendering(self): """ Test that a Element with a simple, static xhtml document factory renders correctly. """ f = Element(docFactory=xmlstr("<p>Hello, world.</p>")) return self._render(f).addCallback( self.assertEqual, "<p>Hello, world.</p>")
def test_simpleXHTMLRendering(self): """ Test that a Element with a simple, static xhtml document factory renders correctly. """ f = Element(docFactory=xmlstr("<p>Hello, world.</p>")) return self._render(f).addCallback(self.assertEquals, "<p>Hello, world.</p>")
def test_xmlstrPreprocessors(self): """ Test that the xmlstr loader properly passes uncompiled documents to preprocessors it is given. """ factory = loaders.xmlstr( '<div><span>Hello</span><span>world</span></div>') return self._preprocessorTest(factory)
def test_missingSpace(self): doc = '<p xmlns:nevow="http://nevow.com/ns/nevow/0.1"><nevow:slot name="foo"/> <nevow:slot name="foo"/></p>' ## This used to say htmlstr, and this test failed because microdom ignores whitespace; ## This test passes fine using xmlstr. I am not going to fix this because microdom is too ## hard to fix. If you need this, switch to xmlstr. result = loaders.xmlstr(doc).load() # There should be a space between the two slots self.assertEquals(result[2], ' ')
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" />')
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" />')
class ZakAdmin(rend.Page): docFactory= loaders.xmlstr("""<html> <head> <style> #humanMsgLog, #humanMsgErr, #humanMsg, #tmplmadd { display:none; } .tablepricing { border: 1px solid black; border-radius: 4px; margin-top: 20px; } .tablepricing td { text-align: center; padding: 4px; } .tablepricing th { background-color: #bd0000; text-align: center; color: white; padding: 4px; } </style> <script src="/js/cm/j.jsgz"></script> <script src="/js/cm/pginit.jsgz"></script> </head> <body> <div> <img src="/imgs/zak.png"></img> </div> <br/> <div id="zakLoader" style="display:none"> <b>Welcome</b>:<br/> please wait, Zak is loading... <img src="/imgs/lgear.gif"></img> </div> </body> </html>""") def __init__(self): rend.Page.__init__(self) self.children= { 'dashboard': AdminProperties(), 'tableau': AdminTableau(), 'reservation': AdminReservation(), 'js': JsDispenser, 'css': CssDispenser, 'imgs': ImgDispenser, 'init': AdminInit(), 'pricing': AdminPricing(), 'invoice': AdminInvoice(), 'settings': AdminSettings(), 'notsupported': AdminNotSupported(), 'search': AdminSearch(), 'favicon.ico': Favicon, '': self, 'manifest': Manifest(), }
def __init__(self, album_info, template_info): self.album_info = album_info self.template_info = template_info self.image_count = album_info['per_page'] print "="*80 print "markup: \n%s" % self.template_info['markup'] print "="*80 self.markup = "" self.docFactory = loaders.xmlstr(self.template_info['markup']) self.data_images = []
def __init__(self, album_info, template_info): self.album_info = album_info self.template_info = template_info self.image_count = album_info['per_page'] print "=" * 80 print "markup: \n%s" % self.template_info['markup'] print "=" * 80 self.markup = "" self.docFactory = loaders.xmlstr(self.template_info['markup']) self.data_images = []
class TabbedPaneFragment(athena.LiveFragment): jsClass = u'Nevow.TagLibrary.TabbedPane.TabbedPane' cssModule = 'Nevow.TagLibrary.TabbedPane' docFactory = loaders.xmlstr(""" <div class="nevow-tabbedpane" xmlns:nevow="http://nevow.com/ns/nevow/0.1" xmlns:athena="http://divmod.org/ns/athena/0.7" nevow:render="liveFragment" style="opacity: .3"> <ul class="nevow-tabbedpane-tabs" id="tab-container"> <nevow:invisible nevow:render="tabs" /> </ul> <li nevow:pattern="tab" ><athena:handler event="onclick" handler="dom_tabClicked" /><nevow:attr name="class"><nevow:slot name="class" /></nevow:attr><nevow:slot name="tab-name" /></li> <div nevow:pattern="page"> <nevow:attr name="class"><nevow:slot name="class" /></nevow:attr> <nevow:slot name="page-content" /> </div> <div id="pane-container"><nevow:invisible nevow:render="pages" /></div> </div>""".replace('\n', '')) def __init__(self, pages, selected=0, name='default'): self.pages = pages self.selected = selected self.name = name super(TabbedPaneFragment, self).__init__() def getInitialArguments(self): return (str(self.pages[self.selected][0], 'utf-8'),) def render_tabs(self, ctx, data): tabPattern = inevow.IQ(self.docFactory).patternGenerator('tab') for (i, (name, content)) in enumerate(self.pages): if self.selected == i: cls = 'nevow-tabbedpane-selected-tab' else: cls = 'nevow-tabbedpane-tab' yield tabPattern.fillSlots( 'tab-name', name).fillSlots( 'class', cls) def render_pages(self, ctx, data): pagePattern = inevow.IQ(self.docFactory).patternGenerator('page') for (i, (name, content)) in enumerate(self.pages): if self.selected == i: cls = 'nevow-tabbedpane-selected-pane' else: cls = 'nevow-tabbedpane-pane' yield pagePattern.fillSlots( 'page-content', content).fillSlots( 'class', cls)
class VerySimpleWidget(athena.LiveElement): docFactory = loaders.xmlstr( '''<span xmlns:n="http://nevow.com/ns/nevow/0.1" n:render="liveElement"><b>Content</b></span>''') jsClass = u'Tabby.Tests.VerySimpleWidget' def serverToClient(self): """Call a method s->c""" return self.callRemote('something') athena.expose(serverToClient)
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>')
class NoReliability(rend.Page): docFactory = loaders.xmlstr('''\ <html xmlns:n="http://nevow.com/ns/nevow/0.1"> <head> <title>AllMyData - Tahoe</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body> <h2>"Reliability" page not available</h2> <p>Please install the python "NumPy" module to enable this page.</p> </body> </html> ''')
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>')
class TreeRenderer(rend.Page): addSlash = True docFactory = loaders.xmlstr(""" <html> <head><title>Tree Editor</title></head> <body><h1><span nevow:data="description" nevow:render="string">Tree Description</span></h1> <span nevow:render="descriptionForm"/> <ol nevow:data="children" nevow:render="sequence"> <li nevow:pattern="item"><span nevow:render="childLink"/> <span nevow:render="childDel"/> </li> </ol> <a href="..">Up</a> </body> </html> """) def setDescription(self, description): self.original.description = description def addChild(self, name, description): self.original.add(Tree(name, description)) def deleteChild(self, name): del self.original[name] def data_description(self, context, data): return self.original.description def data_children(self, context, data): return list(self.original.items()) def render_childLink(self, context, data): return T.a(href='subtree_%s/' % data[0])[data[1].description] def childFactory(self, ctx, name): if name.startswith('subtree_'): return self.original[name[len('subtree_'):]] def render_descriptionForm(self, context, data): return webform.renderForms() def render_childDel(self, context, xxx_todo_changeme): (name, _) = xxx_todo_changeme ret = T.form( action="./freeform_post!!deleteChild", enctype="multipart/form-data", method="POST")[T.input(type="hidden", name="name", value=name), T.input(type="submit", value="Delete")] return ret
class ConsoleProcessPage(athena.LivePage): addSlash = True docFactory = loaders.xmlstr(page_html) child_css = static.File(os.path.dirname(__file__)) def __init__(self, *a, **kw): super(ConsoleProcessPage, self).__init__(*a, **kw) self.jsModules.mapping['PyConsole'] = util.sibpath( __file__, 'pyconsole_nevow.js') self.initialized = False def render_console_process(self, ctx, data): self.console_process_nevow = ConsoleProcessNevow() self.console_process_nevow.page = self return ctx.tag[self.console_process_nevow]
def test_xmlSlotDefault(self): """ An I{nevow:slot} tag in an XML template may have a I{default} attribute specifying a value for the slot if it is not otherwise given one. """ slotsdoc = ''' <div xmlns:nevow="http://nevow.com/ns/nevow/0.1"> <nevow:slot name="1" /> <nevow:slot name="2" default="3" /> </div> ''' loader = loaders.xmlstr(slotsdoc) loaded = loader.load() self.assertEquals(loaded[1].default, None) self.assertEquals(loaded[3].default, "3")
class Root(rend.Page): docFactory = loaders.xmlstr('''\ <html xmlns:n="http://nevow.com/ns/nevow/0.1"> <head> <title>Tahoe-LAFS Provisioning/Reliability Calculator</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> </head> <body> <p><a href="reliability">Reliability Tool</a></p> <p><a href="provisioning">Provisioning Tool</a></p> </body> </html> ''') child_reliability = web_reliability.ReliabilityTool() child_provisioning = provisioning.ProvisioningTool()
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)
def test_xmlstr(self): loader = loaders.xmlstr(self.nsdoc) self.assertEquals( id(loader.load()), id(loader.load()) ) loader = loaders.xmlstr(self.nsdoc, pattern='1') self.assertEquals( id(loader.load()), id(loader.load()) ) l1 = loaders.xmlstr(self.nsdoc, pattern='1') l2 = loaders.xmlstr(self.nsdoc, pattern='1') self.assertNotEqual( id(l1.load()), id(l2.load()) ) l1 = loaders.xmlstr(self.nsdoc, pattern='1') l2 = loaders.xmlstr(self.nsdoc, pattern='2') self.assertNotEqual( id(l1.load()), id(l2.load()) )
class WidgetPage(athena.LivePage): docFactory = loaders.xmlstr("""\ <html xmlns:nevow="http://nevow.com/ns/nevow/0.1"> <head> <nevow:invisible nevow:render="liveglue" /> </head> <body> <div nevow:render="clock"> First Clock </div> <div nevow:render="clock"> Second Clock </div> <div nevow:render="debug" /> </body> </html> """) addSlash = True def __init__(self, *a, **kw): super(WidgetPage, self).__init__(*a, **kw) self.jsModules.mapping['WidgetDemo'] = util.sibpath( __file__, 'widgets.js') def childFactory(self, ctx, name): ch = super(WidgetPage, self).childFactory(ctx, name) if ch is None: p = util.sibpath(__file__, name) if os.path.exists(p): ch = static.File(file(p)) return ch def render_clock(self, ctx, data): c = Clock() c.page = self return ctx.tag[c] def render_debug(self, ctx, data): f = athena.IntrospectionFragment() f.setFragmentParent(self) return ctx.tag[f]
class Button(athena.LiveFragment): jsClass = u"SimpleWidget.Button" docFactory = loaders.xmlstr(""" <div xmlns:nevow="http://nevow.com/ns/nevow/0.1" nevow:render="liveFragment"> <form onSubmit="return false;"> <input type="submit" value="" onClick="SimpleWidget.Button.get(this).click()"/> </form> </div>""") allowedMethods = ['onClick', 'getLabel'] def __init__(self, label): athena.LiveFragment.__init__(self) self.label = label @athena.expose def getLabel(self): return unicode(self.label) @athena.expose def onClick(self): print "clicked %s" % self.label
class TabbedPaneFetcher(athena.LiveElement): jsClass = u'Nevow.Test.TestTabbedPane.TabbedPaneFetcher' docFactory = loaders.xmlstr(""" <div xmlns:athena="http://divmod.org/ns/athena/0.7" xmlns:nevow="http://nevow.com/ns/nevow/0.1" nevow:render="liveElement"> <a href="#"> <athena:handler event="onclick" handler="dom_getTabbedPane" /> Get a tabbed pane from the server </a> </div>""") def getTabbedPane(self): """ Return a L{TabbedPaneFragment}. """ f = tabbedPaneFragment() f.setFragmentParent(self) return f athena.expose(getTabbedPane)
FORM_LAYOUT = loaders.xmlstr( """<?xml version="1.0"?> <form xmlns:n="http://nevow.com/ns/nevow/0.1" n:pattern="freeform-form"> <!-- Replace/fill the form attributes --> <n:attr name="action"><n:slot name="form-action"/></n:attr> <n:attr name="id"><n:slot name="form-id"/></n:attr> <n:attr name="name"><n:slot name="form-name"/></n:attr> <!-- General form information --> <p><strong><n:slot name="form-label"/></strong></p> <p><em><n:slot name="form-description"/></em></p> <p><strong><em><n:slot name="form-error"/></em></strong></p> <!-- Start of the form layout table --> <table style="background: #eee; border: 1px solid #bbb; padding: 1em;" > <!-- Mark location arguments will be added --> <n:slot name="form-arguments"/> <!-- General argument layout pattern --> <n:invisible n:pattern="argument" n:render="remove"> <tr> <th><n:slot name="label"/>:</th> <td><n:slot name="input"/><span class="freeform-error"><n:slot name="error"/></span></td> </tr> <tr> <th></th> <td><n:slot name="description"/></td> </tr> </n:invisible> <!-- Argument layout, just for fum --> <n:invisible n:pattern="argument!!fo" n:render="remove"> <tr> <th><n:slot name="label"/>:</th> <td> <textarea cols="40" rows="5"><n:attr name="id"><n:slot name="id"/></n:attr><n:attr name="name"><n:slot name="name"/></n:attr><n:slot name="value"/></textarea> <span class="freeform-error"><n:slot name="error"/></span></td> </tr> <tr> <th></th> <td><n:slot name="description"/></td> </tr> </n:invisible> <!-- Button row --> <tr> <td colspan="2"> <n:slot name="form-button"/> </td> </tr> </table> </form> """).load()
def test_xmlstr(self): doc = '<p>hello</p>' self._withAndWithout(loaders.xmlstr(doc))
def asDOM( text, source_path=None, template=None, flavor=None, s5_theme_url=None, navigation=None, operation=None, ): if flavor is None: flavor = 'html' settings = dict( input_encoding='utf-8', output_encoding='utf-8', embed_stylesheet=False, stylesheet_path=htmlutil.KLUDGE_KILL_CSS, generator=False, # TODO file insertion should really be disabled # but can't do that now, as that would make the # original include directive fail.. also can't # just temporarily enable it to kludge, as that # would mean the included file sees it as fully # enabled.. will have to reimplement include. # file_insertion_enabled=0, # TODO ponder disabling raw; it allows content creators to # attack the site # raw_enabled=0, _disable_config=1, roast_operation=operation, ) if flavor == 's5': writer = s5_html.Writer() assert template is None assert s5_theme_url is not None settings.update(dict( theme=None, theme_url=s5_theme_url, current_slide=True, )) elif flavor == 'html': writer = html4css1.Writer() else: raise 'Unknown RST flavor: %r' % flavor # Docutils stores default `foo` role in global state that persists # from one parser to another. Parsing directive "default-role" # sets that, usually from s5defs.txt. To avoid infecting all # latter runs (`foo` will create <span # class="incremental">foo</span> instead of <cite>foo</cite>), we # try to contain the damage, and restore the default role to # original settings before every run. try: del roles._roles[''] except KeyError: pass html, publisher = publish_programmatically( source_class=io.StringInput, source=text, source_path=source_path, destination_class=io.StringOutput, destination=None, destination_path=None, reader=None, reader_name='standalone', parser=None, parser_name='restructuredtext', writer=writer, writer_name=None, settings=None, settings_spec=None, settings_overrides=settings, config_section=None, enable_exit_status=None) tree = minidom.parseString(html) title = htmlutil.getTitle(tree) title = htmlutil.getNodeContentsAsText(title) # kill generator meta tag htmlutil.killGeneratorMetaTags(tree) # kill stylesheet htmlutil.killLinkedStylesheet(tree) if flavor == 'html': body = htmlutil.getOnlyElementByTagName(tree, 'body') docs = htmlutil.getElementsByClass(body, 'document') if len(docs) == 1: body = docs[0] # remove the headings rst promoted to top level, # the template will take care of that for h1 in body.getElementsByTagName('h1'): if htmlutil.elementHasClass(h1, 'title'): h1.parentNode.removeChild(h1) break if template is not None: template = Template(original=body, docFactory=loaders.xmlstr(template), title=title, navigation=navigation, ) html = flat.flatten(template) tree = minidom.parseString(html) htmlutil.fixXMLTags(tree) return tree
def test_ignoreComment(self): doc = '<!-- skip this --><p>Hello.</p>' df = loaders.xmlstr(doc, ignoreComment=True) self.assertEquals(flat.flatten(df), '<p>Hello.</p>')
def test_ignoreDocType(self): doc = '''<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n<html><body><p>Hello.</p></body></html>''' df = loaders.xmlstr(doc, ignoreDocType=True) self.assertEquals(flat.flatten(df), '<html><body><p>Hello.</p></body></html>')
def test_xmlstr(self): doc = '<ul id="nav"><li>a</li><li>b</li><li>c</li></ul>' df = loaders.xmlstr(doc) self.assertEquals(df.load()[0], doc)
def test_missingSpace(self): doc = '<p xmlns:nevow="http://nevow.com/ns/nevow/0.1"><nevow:slot name="foo"/> <nevow:slot name="foo"/></p>' result = loaders.xmlstr(doc).load() self.assertEquals(result[2], ' ')
""" return self._defaultThemedRendering(ThemedElement) class MantissaThemeTests(XHTMLDirectoryThemeTestsMixin, TestCase): """ Stock L{XHTMLDirectoryTheme} tests applied to L{baseOffering} and its theme. """ offering = baseOffering theme = offering.themes[0] CUSTOM_MSG = xmlstr('<div>Athena unsupported here</div>') BASE_MSG = file(sibpath(__file__, "../themes/base/athena-unsupported.html") ).read().strip() class StubThemeProvider(Item): """ Trivial implementation of a theme provider, for testing that custom Athena-unsupported pages can be used. """ _attribute = integer(doc="exists to pacify Axiom's hunger for attributes") implements(ITemplateNameResolver) powerupInterfaces = (ITemplateNameResolver,) def getDocFactory(self, name):
def test_slotWithCharacterData(self): """Test that xml templates with slots that contain content can be loaded""" template = '<p xmlns:nevow="http://nevow.com/ns/nevow/0.1"><nevow:slot name="foo">stuff</nevow:slot></p>' doc = loaders.xmlstr(template).load()
def __init__(self,xml): rend.Fragment.__init__(self, docFactory=loaders.xmlstr(self.XML_TEMPLATE%xml, ignoreDocType=True))