Example #1
0
 def test_match_multiple_times3(self):
     # See http://genshi.edgewall.org/ticket/370#comment:12
     tmpl = MarkupTemplate(
         """<?xml version="1.0"?>
       <root xmlns:py="http://genshi.edgewall.org/">
         <py:match path="foo/bar">
           <zzzzz/>
         </py:match>
         <foo>
           <bar/>
           <bar/>
         </foo>
         <bar/>
       </root>"""
     )
     self.assertEqual(
         """<?xml version="1.0"?>\n<root>
         <foo>
           <zzzzz/>
           <zzzzz/>
         </foo>
         <bar/>
       </root>""",
         tmpl.generate().render(),
     )
Example #2
0
    def test_triple_match_produces_no_duplicate_items(self):
        tmpl = MarkupTemplate(
            """<doc xmlns:py="http://genshi.edgewall.org/">
          <div py:match="div[@id='content']" py:attrs="select('@*')" once="true">
            <ul id="tabbed_pane" />
            ${select('*')}
          </div>

          <body py:match="body" once="true" buffer="false">
            ${select('*|text()')}
          </body>
          <body py:match="body" once="true" buffer="false">
              ${select('*|text()')}
          </body>

          <body>
            <div id="content">
              <h1>Ticket X</h1>
            </div>
          </body>
        </doc>"""
        )
        output = tmpl.generate().render("xhtml", doctype="xhtml")
        matches = re.findall("tabbed_pane", output)
        self.assertNotEqual(None, matches)
        self.assertEqual(1, len(matches))
Example #3
0
 def test_as_element(self):
     tmpl = MarkupTemplate("""<div xmlns:py="http://genshi.edgewall.org/">
       <py:with vars="x = x * 2">${x}</py:with>
     </div>""")
     self.assertEqual("""<div>
       84
     </div>""", tmpl.generate(x=42).render(encoding=None))
Example #4
0
    def emitHTML(self, _htmlpath, _templateFn, **kwds):
        """
        read the specified template, perform template
        instantantiation and write the result to _htmlpath.

        Any keyword arguments are used to fill in the blanks
        in the template.
        """
        while _htmlpath.startswith(os.sep):
            _htmlpath = _htmlpath[1:]

        outfn = os.path.join(self.siteRoot, _htmlpath)
        infn = os.path.join(gTemplateDir, _templateFn)

        outdn = os.path.dirname(outfn)
        if not os.path.exists(outdn):
            os.makedirs(outdn)

        tmpl = MarkupTemplate(open(infn, 'r').read(), loader=self._makeLoader(infn), lookup='strict')
        variables = self._makeGlobals(_htmlpath)
        variables.update(kwds)
        stream = tmpl.generate(**variables)
        fp = open(outfn, "w")
        fp.write(stream.render('html'))
        fp.close()
Example #5
0
 def test_multiple_matches(self):
     tmpl = MarkupTemplate("""<html xmlns:py="http://genshi.edgewall.org/">
       <input py:match="form//input" py:attrs="select('@*')"
              value="${values[str(select('@name'))]}" />
       <form><p py:for="field in fields">
         <label>${field.capitalize()}</label>
         <input type="text" name="${field}" />
       </p></form>
     </html>""")
     fields = ['hello_%s' % i for i in range(5)]
     values = dict([('hello_%s' % i, i) for i in range(5)])
     self.assertEqual("""<html>
       <form><p>
         <label>Hello_0</label>
         <input value="0" type="text" name="hello_0"/>
       </p><p>
         <label>Hello_1</label>
         <input value="1" type="text" name="hello_1"/>
       </p><p>
         <label>Hello_2</label>
         <input value="2" type="text" name="hello_2"/>
       </p><p>
         <label>Hello_3</label>
         <input value="3" type="text" name="hello_3"/>
       </p><p>
         <label>Hello_4</label>
         <input value="4" type="text" name="hello_4"/>
       </p></form>
     </html>""", tmpl.generate(fields=fields, values=values)
                     .render(encoding=None))
Example #6
0
 def test_select_text_in_element(self):
     """
     See http://genshi.edgewall.org/ticket/77#comment:1
     """
     tmpl = MarkupTemplate("""<html xmlns="http://www.w3.org/1999/xhtml"
           xmlns:py="http://genshi.edgewall.org/">
       <body py:match="body" py:content="select('*')" />
       <h1 py:match="h1">
         <text>
           ${select('text()')}
         </text>
         Goodbye!
       </h1>
       <body>
         <h1>Hello!</h1>
       </body>
     </html>""")
     self.assertEqual("""<html xmlns="http://www.w3.org/1999/xhtml">
       <body><h1>
         <text>
           Hello!
         </text>
         Goodbye!
       </h1></body>
     </html>""", tmpl.generate().render(encoding=None))
def application(environ, start_response):
    output = api.mongoApi(environ)
    records = json.loads(output)["result"]
    items = []
    if type(records) in seqTypes:
        if len(records):
            items.append(str(len(records)) + " records")
            buildHeader(records[0], items)
            for rec in records:
                buildRecord(rec, items)
        else:
            items.append("no records found")
    else:
        items.append("<i>count:</i> " + str(records))
    print >>sys.stderr, "DEBUG VIEW items:", items

    template = "/template/record_tab.html"
    f = open(DOCROOT + template)
    tmpl = MarkupTemplate(f)
    f.close()
    stream = tmpl.generate(DOCROOT=DOCROOT, items=items)

    output = stream.render("xhtml")

    status = "200 OK"
    response_headers = [("Content-type", "text/html"), ("Content-Length", str(len(output)))]
    start_response(status, response_headers)
    return [output]
Example #8
0
    def test_recursive_match_3(self):
        tmpl = MarkupTemplate("""<test xmlns:py="http://genshi.edgewall.org/">
          <py:match path="b[@type='bullet']">
            <bullet>${select('*|text()')}</bullet>
          </py:match>
          <py:match path="group[@type='bullet']">
            <ul>${select('*')}</ul>
          </py:match>
          <py:match path="b">
            <generic>${select('*|text()')}</generic>
          </py:match>

          <b>
            <group type="bullet">
              <b type="bullet">1</b>
              <b type="bullet">2</b>
            </group>
          </b>
        </test>
        """)
        self.assertEqual("""<test>
            <generic>
            <ul><bullet>1</bullet><bullet>2</bullet></ul>
          </generic>
        </test>""", tmpl.generate().render(encoding=None))
Example #9
0
 def test_multiple_vars_trailing_semicolon(self):
     tmpl = MarkupTemplate("""<div xmlns:py="http://genshi.edgewall.org/">
       <py:with vars="x = x * 2; y = x / 2;">${x} ${y}</py:with>
     </div>""")
     self.assertEqual("""<div>
       84 42
     </div>""", str(tmpl.generate(x=42)))
Example #10
0
 def test_recursive_match_2(self):
     """
     When two or more match templates match the same element and also
     themselves output the element they match, avoiding recursion is even
     more complex, but should work.
     """
     tmpl = MarkupTemplate("""<html xmlns:py="http://genshi.edgewall.org/">
       <body py:match="body">
         <div id="header"/>
         ${select('*')}
       </body>
       <body py:match="body">
         ${select('*')}
         <div id="footer"/>
       </body>
       <body>
         <h1>Foo</h1>
       </body>
     </html>""")
     self.assertEqual("""<html>
       <body>
         <div id="header"/><h1>Foo</h1>
         <div id="footer"/>
       </body>
     </html>""", tmpl.generate().render(encoding=None))
Example #11
0
 def test_match_with_once_attribute(self):
     tmpl = MarkupTemplate("""<html xmlns:py="http://genshi.edgewall.org/">
       <py:match path="body" once="true"><body>
         <div id="wrap">
           ${select("*")}
         </div>
       </body></py:match>
       <body>
         <p>Foo</p>
       </body>
       <body>
         <p>Bar</p>
       </body>
     </html>""")
     self.assertEqual(
         """<html>
       <body>
         <div id="wrap">
           <p>Foo</p>
         </div>
       </body>
       <body>
         <p>Bar</p>
       </body>
     </html>""",
         tmpl.generate().render(encoding=None))
Example #12
0
 def test_strip_false(self):
     tmpl = MarkupTemplate("""<div xmlns:py="http://genshi.edgewall.org/">
       <div py:strip="False"><b>foo</b></div>
     </div>""")
     self.assertEqual("""<div>
       <div><b>foo</b></div>
     </div>""", str(tmpl.generate()))
Example #13
0
 def test_not_iterable(self):
     """
     Verify that assignment to nested tuples works correctly.
     """
     tmpl = MarkupTemplate("""<doc xmlns:py="http://genshi.edgewall.org/">
       <py:for each="item in foo">
         $item
       </py:for>
     </doc>""", filename='test.html')
     try:
         list(tmpl.generate(foo=12))
         self.fail('Expected TemplateRuntimeError')
     except TypeError, e:
         assert (str(e) == "iteration over non-sequence" or
                 str(e) == "'int' object is not iterable")
         exc_type, exc_value, exc_traceback = sys.exc_info()
         frame = exc_traceback.tb_next
         frames = []
         while frame.tb_next:
             frame = frame.tb_next
             frames.append(frame)
         self.assertEqual("<Expression u'iter(foo)'>",
                          frames[-1].tb_frame.f_code.co_name)
         self.assertEqual('test.html',
                          frames[-1].tb_frame.f_code.co_filename)
         self.assertEqual(2, frames[-1].tb_lineno)
Example #14
0
def application(environ, start_response):
    output = api.mongoApi(environ)
    records = json.loads(output)['result']
    items = []
    if type(records) in seqTypes:
        if len(records):
            if len(records) > MAX_RECORDS:
                records = records[:MAX_RECORDS]
                items.append("<b>Exceeded max records for pretty output; showing first %s</b>" % MAX_RECORDS)
            for rec in records:
                if type(rec) in stringTypes:
                    items.append(rec)
                elif type(rec) in hashTypes:
                    buildRecord(rec, items)
                else:
                    print >> sys.stderr, "ERROR: unknown type for buildRecord:", type(rec)
        else:
            items.append("no records found")
    else:
        items.append("<i>count:</i> " + str(records))
##    print >> sys.stderr, "DEBUG VIEW records:", records[:10]

    template = "/template/record.html"
    f = open(DOCROOT + template)
    tmpl = MarkupTemplate(f)
    f.close()
    stream = tmpl.generate(DOCROOT=DOCROOT, items=items, seqTypes=seqTypes)
    output = stream.render('xhtml')

    status = '200 OK'
    response_headers = [('Content-type', 'text/html'),
                        ('Content-Length', str(len(output)))]
    start_response(status, response_headers)
    return [output]
Example #15
0
 def test_recursive_match_1(self):
     """
     Match directives are applied recursively, meaning that they are also
     applied to any content they may have produced themselves:
     """
     tmpl = MarkupTemplate("""<doc xmlns:py="http://genshi.edgewall.org/">
       <elem py:match="elem">
         <div class="elem">
           ${select('*')}
         </div>
       </elem>
       <elem>
         <subelem>
           <elem/>
         </subelem>
       </elem>
     </doc>""")
     self.assertEqual("""<doc>
       <elem>
         <div class="elem">
           <subelem>
           <elem>
         <div class="elem">
         </div>
       </elem>
         </subelem>
         </div>
       </elem>
     </doc>""", tmpl.generate().render(encoding=None))
Example #16
0
 def test_multiple_vars_single_assignment(self):
     tmpl = MarkupTemplate("""<div xmlns:py="http://genshi.edgewall.org/">
       <py:with vars="x = y = z = 1">${x} ${y} ${z}</py:with>
     </div>""")
     self.assertEqual("""<div>
       1 1 1
     </div>""", tmpl.generate(x=42).render(encoding=None))
Example #17
0
 def test_multiple_vars_trailing_semicolon(self):
     tmpl = MarkupTemplate("""<div xmlns:py="http://genshi.edgewall.org/">
       <py:with vars="x = x * 2; y = x / 2;">${x} ${y}</py:with>
     </div>""")
     self.assertEqual("""<div>
       84 %s
     </div>""" % (84 / 2), tmpl.generate(x=42).render(encoding=None))
Example #18
0
 def test_strip_empty(self):
     tmpl = MarkupTemplate("""<div xmlns:py="http://genshi.edgewall.org/">
       <div py:strip=""><b>foo</b></div>
     </div>""")
     self.assertEqual("""<div>
       <b>foo</b>
     </div>""", tmpl.generate().render(encoding=None))
Example #19
0
 def test_match_with_recursive_attribute(self):
     tmpl = MarkupTemplate(
         """<doc xmlns:py="http://genshi.edgewall.org/">
       <py:match path="elem" recursive="false"><elem>
         <div class="elem">
           ${select('*')}
         </div>
       </elem></py:match>
       <elem>
         <subelem>
           <elem/>
         </subelem>
       </elem>
     </doc>"""
     )
     self.assertEqual(
         """<doc>
       <elem>
         <div class="elem">
           <subelem>
           <elem/>
         </subelem>
         </div>
       </elem>
     </doc>""",
         tmpl.generate().render(encoding=None),
     )
Example #20
0
    def __addHtmlSection(self, section, id, depth):
        if depth > 0:
	    content = ''
	    for text in section.text:
	 	content = content + text
            urls = self.impl.downloadHtmlImages(content)
            content = self.impl.remoteToLocalImageUrls(urls, content)
            stream = MarkupTemplate("""<html xmlns="http://www.w3.org/1999/xhtml"
    					xmlns:py="http://genshi.edgewall.org/">
					<head>
					  <title>${section.title}</title>
					  <style type="text/css">
						h1 { text-align: center; }
						${section.css}
					  </style>
					</head>
					<body>
					  <h1>${section.title}</h1>
					  """ + content + """
					</body>
					</html>""").generate(section = section)
            html = stream.render('xhtml', doctype = 'xhtml11', drop_xml_decl = False)
            item = self.impl.addHtml('', '%s.html' % id, html)
            self.impl.addSpineItem(item)
            self.impl.addTocMapNode(item.destPath, section.title, depth)
            id += '.'
        if len(section.subsections) > 0:
            for i, subsection in enumerate(section.subsections):
                 self.__addHtmlSection(subsection, id + str(i + 1), depth + 1)
Example #21
0
 def test_nested_vars_single_assignment(self):
     tmpl = MarkupTemplate("""<div xmlns:py="http://genshi.edgewall.org/">
       <py:with vars="x, (y, z) = (1, (2, 3))">${x} ${y} ${z}</py:with>
     </div>""")
     self.assertEqual("""<div>
       1 2 3
     </div>""", tmpl.generate(x=42).render(encoding=None))
Example #22
0
 def test_as_element(self):
     tmpl = MarkupTemplate("""<div xmlns:py="http://genshi.edgewall.org/">
       <py:replace value="title" />
     </div>""", filename='test.html')
     self.assertEqual("""<div>
       Test
     </div>""", tmpl.generate(title='Test').render(encoding=None))
Example #23
0
 def test_invocation_in_attribute(self):
     tmpl = MarkupTemplate("""<doc xmlns:py="http://genshi.edgewall.org/">
       <py:def function="echo(what)">${what or 'something'}</py:def>
       <p class="${echo('foo')}">bar</p>
     </doc>""")
     self.assertEqual("""<doc>
       <p class="foo">bar</p>
     </doc>""", str(tmpl.generate()))
Example #24
0
def make_index(test_filenames, inner_html_files):
    template = MarkupTemplate(open(os.path.join(file_base, 'index.xml')))
    stream = template.generate(file_names=serialize_filenames(test_filenames),
                               inner_html_file_names=serialize_filenames(inner_html_files));

    out_f = open("index.html", "w")
    out_f.write(stream.render('html', doctype='html5', 
                              encoding="utf-8"))
Example #25
0
 def test_content_directive_in_match(self):
     tmpl = MarkupTemplate("""<html xmlns:py="http://genshi.edgewall.org/">
       <div py:match="foo">I said <q py:content="select('text()')">something</q>.</div>
       <foo>bar</foo>
     </html>""")
     self.assertEqual("""<html>
       <div>I said <q>bar</q>.</div>
     </html>""", tmpl.generate().render(encoding=None))
Example #26
0
 def test_invocation_in_attribute_none(self):
     tmpl = MarkupTemplate("""<doc xmlns:py="http://genshi.edgewall.org/">
       <py:def function="echo()">${None}</py:def>
       <p class="${echo()}">bar</p>
     </doc>""")
     self.assertEqual("""<doc>
       <p>bar</p>
     </doc>""", tmpl.generate().render(encoding=None))
Example #27
0
 def test_otherwise(self):
     tmpl = MarkupTemplate("""<div xmlns:py="http://genshi.edgewall.org/" py:choose="">
       <span py:when="False">hidden</span>
       <span py:otherwise="">hello</span>
     </div>""")
     self.assertEqual("""<div>
       <span>hello</span>
     </div>""", tmpl.generate().render(encoding=None))
Example #28
0
    def body(self, environ, full_path):
        """Pass environ and **self.variables into the template."""

        template = MarkupTemplate(full_path.read())
        variables = self.variables.copy()
        variables["environ"] = environ
        return [template.generate(**variables)
                .render('html', doctype='html')]
Example #29
0
 def test_def_in_match(self):
     tmpl = MarkupTemplate("""<doc xmlns:py="http://genshi.edgewall.org/">
       <py:def function="maketitle(test)"><b py:replace="test" /></py:def>
       <head py:match="head">${select('*')}</head>
       <head><title>${maketitle(True)}</title></head>
     </doc>""")
     self.assertEqual("""<doc>
       <head><title>True</title></head>
     </doc>""", tmpl.generate().render(encoding=None))
Example #30
0
 def test_otherwise_outside_choose(self):
     """
     Verify that an `otherwise` directive outside of a `choose` directive is
     reported as an error.
     """
     tmpl = MarkupTemplate("""<doc xmlns:py="http://genshi.edgewall.org/">
       <div py:otherwise="" />
     </doc>""")
     self.assertRaises(TemplateRuntimeError, str, tmpl.generate())
Example #31
0
 def test_translate_i18n_msg_with_attr(self):
     tmpl = MarkupTemplate("""<html xmlns:py="http://genshi.edgewall.org/"
         xmlns:i18n="http://genshi.edgewall.org/i18n">
       <p i18n:msg="" title="Foo bar">Foo</p>
     </html>""")
     gettext = lambda s: u"Voh"
     translator = Translator(DummyTranslations({
         'Foo': u'Voh',
         'Foo bar': u'Voh bär'
     }))
     tmpl.filters.insert(0, translator)
     tmpl.add_directives(Translator.NAMESPACE, translator)
     self.assertEqual("""<html>
       <p title="Voh bär">Voh</p>
     </html>""", tmpl.generate().render())
Example #32
0
 def test_with_strip(self):
     """
     Verify that a match template can produce the same kind of element that
     it matched without entering an infinite recursion.
     """
     tmpl = MarkupTemplate("""<doc xmlns:py="http://genshi.edgewall.org/">
       <elem py:match="elem" py:strip="">
         <div class="elem">${select('text()')}</div>
       </elem>
       <elem>Hey Joe</elem>
     </doc>""")
     self.assertEqual(
         """<doc>
         <div class="elem">Hey Joe</div>
     </doc>""", str(tmpl.generate()))
Example #33
0
 def test_match_with_position_predicate(self):
     tmpl = MarkupTemplate("""<html xmlns:py="http://genshi.edgewall.org/">
       <p py:match="body/p[1]" class="first">${select('*|text()')}</p>
       <body>
         <p>Foo</p>
         <p>Bar</p>
       </body>
     </html>""")
     self.assertEqual(
         """<html>
       <body>
         <p class="first">Foo</p>
         <p>Bar</p>
       </body>
     </html>""", str(tmpl.generate()))
Example #34
0
 def test_match_without_closure(self):
     tmpl = MarkupTemplate("""<html xmlns:py="http://genshi.edgewall.org/">
       <p py:match="body/p" class="para">${select('*|text()')}</p>
       <body>
         <p>Foo</p>
         <div><p>Bar</p></div>
       </body>
     </html>""")
     self.assertEqual(
         """<html>
       <body>
         <p class="para">Foo</p>
         <div><p>Bar</p></div>
       </body>
     </html>""", str(tmpl.generate()))
Example #35
0
 def test_function_with_strip(self):
     """
     Verify that a named template function with a strip directive actually
     strips of the outer element.
     """
     tmpl = MarkupTemplate("""<doc xmlns:py="http://genshi.edgewall.org/">
       <div py:def="echo(what)" py:strip="">
         <b>${what}</b>
       </div>
       ${echo('foo')}
     </doc>""")
     self.assertEqual("""<doc>
         <b>foo</b>
     </doc>""",
                      tmpl.generate().render(encoding=None))
Example #36
0
 def test_multi_assignment(self):
     """
     Verify that assignment to tuples works correctly.
     """
     tmpl = MarkupTemplate("""<doc xmlns:py="http://genshi.edgewall.org/">
       <py:for each="k, v in items">
         <p>key=$k, value=$v</p>
       </py:for>
     </doc>""")
     self.assertEqual(
         """<doc>
         <p>key=a, value=1</p>
         <p>key=b, value=2</p>
     </doc>""",
         tmpl.generate(items=(('a', 1), ('b', 2))).render(encoding=None))
Example #37
0
 def test_multiple_true_whens(self):
     """
     Verify that, if multiple `py:when` bodies match, only the first is
     output.
     """
     tmpl = MarkupTemplate(
         """<div xmlns:py="http://genshi.edgewall.org/" py:choose="">
       <span py:when="1 == 1">1</span>
       <span py:when="2 == 2">2</span>
       <span py:when="3 == 3">3</span>
     </div>""")
     self.assertEqual("""<div>
       <span>1</span>
     </div>""",
                      tmpl.generate().render(encoding=None))
Example #38
0
 def test_as_element(self):
     """
     Verify that the directive can also be used as an element.
     """
     tmpl = MarkupTemplate("""<doc xmlns:py="http://genshi.edgewall.org/">
       <py:match path="elem">
         <div class="elem">${select('text()')}</div>
       </py:match>
       <elem>Hey Joe</elem>
     </doc>""")
     self.assertEqual(
         """<doc>
         <div class="elem">Hey Joe</div>
     </doc>""",
         tmpl.generate().render(encoding=None))
def write_test_file(script_dir, out_dir, tests, file_name, template_file_name):
    file_name = os.path.join(out_dir, file_name + ".html")
    short_name = os.path.split(file_name)[1]

    with open(os.path.join(script_dir, template_file_name)) as f:
        template = MarkupTemplate(f)

    stream = template.generate(file_name=short_name,
                               tests=tests,
                               file_timeout=min(1000 * len(tests), 60 * 1000),
                               test_timeout=1000)

    with open(file_name, "w") as f:
        f.write(stream.render('html', doctype='html5', encoding="utf8"))
    return file_name
Example #40
0
 def test_when_with_strip(self):
     """
     Verify that a when directive with a strip directive actually strips of
     the outer element.
     """
     tmpl = MarkupTemplate("""<doc xmlns:py="http://genshi.edgewall.org/">
       <div py:choose="" py:strip="">
         <span py:otherwise="">foo</span>
       </div>
     </doc>""")
     self.assertEqual(
         """<doc>
         <span>foo</span>
     </doc>""",
         tmpl.generate().render(encoding=None))
Example #41
0
 def test_when_without_test_but_with_choose_value(self):
     """
     Verify that an `when` directive that doesn't have a `test` attribute
     works as expected as long as the parent `choose` directive has a test
     expression.
     """
     tmpl = MarkupTemplate("""<doc xmlns:py="http://genshi.edgewall.org/">
       <div py:choose="foo" py:strip="">
         <py:when>foo</py:when>
       </div>
     </doc>""")
     self.assertEqual("""<doc>
         foo
     </doc>""",
                      tmpl.generate(foo='Yeah').render(encoding=None))
Example #42
0
 def test_as_element(self):
     """
     Verify that the directive can also be used as an element.
     """
     tmpl = MarkupTemplate("""<doc xmlns:py="http://genshi.edgewall.org/">
       <py:choose>
         <py:when test="1 == 1">1</py:when>
         <py:when test="2 == 2">2</py:when>
         <py:when test="3 == 3">3</py:when>
       </py:choose>
     </doc>""")
     self.assertEqual("""<doc>
         1
     </doc>""",
                      tmpl.generate().render(encoding=None))
Example #43
0
 def test_match_multiple_times1(self):
     # See http://genshi.edgewall.org/ticket/370
     tmpl = MarkupTemplate("""<html xmlns:py="http://genshi.edgewall.org/">
       <py:match path="body[@id='content']/h2" />
       <head py:match="head" />
       <head py:match="head" />
       <head />
       <body />
     </html>""")
     self.assertEqual(
         """<html>
       <head/>
       <body/>
     </html>""",
         tmpl.generate().render())
Example #44
0
 def test_ignore_tag_with_fixed_xml_lang(self):
     tmpl = MarkupTemplate("""<html xmlns:py="http://genshi.edgewall.org/">
       <p xml:lang="en">(c) 2007 Edgewall Software</p>
     </html>""")
     translator = Translator()
     messages = list(translator.extract(tmpl.stream))
     self.assertEqual(0, len(messages))
Example #45
0
 def test_ignore_attribute_with_expression(self):
     tmpl = MarkupTemplate("""<html xmlns:py="http://genshi.edgewall.org/">
       <input type="submit" value="Reply" title="Reply to comment $num" />
     </html>""")
     translator = Translator()
     messages = list(translator.extract(tmpl.stream))
     self.assertEqual(0, len(messages))
def render_genshi_tmpl(tmplstr, context, tmplpath=None):
    '''
    Render a Genshi template. A method should be passed in as part of the
    context. If no method is passed in, xml is assumed. Valid methods are:

    .. code-block:

        - xml
        - xhtml
        - html
        - text
        - newtext
        - oldtext

    Note that the ``text`` method will call ``NewTextTemplate``. If ``oldtext``
    is desired, it must be called explicitly
    '''
    method = context.get('method', 'xml')
    if method == 'text' or method == 'newtext':
        from genshi.template import NewTextTemplate
        tmpl = NewTextTemplate(tmplstr)
    elif method == 'oldtext':
        from genshi.template import OldTextTemplate
        tmpl = OldTextTemplate(tmplstr)
    else:
        from genshi.template import MarkupTemplate
        tmpl = MarkupTemplate(tmplstr)

    return tmpl.generate(**context).render(method)
Example #47
0
def render_genshi_tmpl(tmplstr, context, tmplpath=None):
    """
    Render a Genshi template. A method should be passed in as part of the
    context. If no method is passed in, xml is assumed. Valid methods are:

    .. code-block:

        - xml
        - xhtml
        - html
        - text
        - newtext
        - oldtext

    Note that the ``text`` method will call ``NewTextTemplate``. If ``oldtext``
    is desired, it must be called explicitly
    """
    method = context.get("method", "xml")
    if method == "text" or method == "newtext":
        from genshi.template import NewTextTemplate  # pylint: disable=no-name-in-module

        tmpl = NewTextTemplate(tmplstr)
    elif method == "oldtext":
        from genshi.template import OldTextTemplate  # pylint: disable=no-name-in-module

        tmpl = OldTextTemplate(tmplstr)
    else:
        from genshi.template import MarkupTemplate  # pylint: disable=no-name-in-module

        tmpl = MarkupTemplate(tmplstr)

    return tmpl.generate(**context).render(method)
Example #48
0
 def test_ast_transformation(self):
     """
     Verify that the usual template expression AST transformations are
     applied despite the code being compiled to a `Suite` object.
     """
     tmpl = MarkupTemplate("""<div xmlns:py="http://genshi.edgewall.org/">
       <span py:with="bar=foo.bar">
         $bar
       </span>
     </div>""")
     self.assertEqual(
         """<div>
       <span>
         42
       </span>
     </div>""", str(tmpl.generate(foo={'bar': 42})))
Example #49
0
    def _generate_resource(self, res, isclass=False):
        template_file = "class.html" if isclass else "module.html"

        templatedir_path = join(self._theme_dir, template_file)
        with open(templatedir_path, 'r') as content_file:
            content = content_file.read()
        tmpl = MarkupTemplate(content)
        stream = tmpl.generate(resource=res,
                               module_tree=self._resource.module_tree,
                               project_name=self._resource.name)

        resource_path = join(self._destination, self._resource.docsdir,
                             res.name + '.html')
        f = open(resource_path, 'w+')
        f.write(stream.render('xhtml'))
        f.close()
Example #50
0
 def test_nested_assignment(self):
     """
     Verify that assignment to nested tuples works correctly.
     """
     tmpl = MarkupTemplate("""<doc xmlns:py="http://genshi.edgewall.org/">
       <py:for each="idx, (k, v) in items">
         <p>$idx: key=$k, value=$v</p>
       </py:for>
     </doc>""")
     self.assertEqual(
         """<doc>
         <p>0: key=a, value=1</p>
         <p>1: key=b, value=2</p>
     </doc>""",
         tmpl.generate(items=enumerate(dict(a=1, b=2).items())).render(
             encoding=None))
Example #51
0
    def filter_stream(self, req, method, filename, stream, data):
        if filename != 'ticket.html':
            return stream

        # if specify disable, not execute.
        enable = True
        if 'ticketext' in req.args:
            enable = req.args['ticketext']
            enable = enable.lower() in _TRUE_VALUES
            enable = bool(enable)
        if not enable:
            return stream

        readyDescription = False
        if req.path_info == '/newticket' and 'preview' not in req.args:
            readyDescription = True

        script = '\n<script type="text/javascript">\n'\
               + 'var tikectTemplate = new ticketext.TicketTemplate(\'' + req.base_path + '\');\n'\
               + 'tikectTemplate.setElementId(\'field-type\', \'field-description\');\n'\
               + 'tikectTemplate.setReadyDescription(' + str(readyDescription).lower() + ');\n'\
               + 'tikectTemplate.initialize();\n'\
               + '</script>\n'

        return stream | Transformer('//div[@id="footer"]').before(
            MarkupTemplate(script).generate())
Example #52
0
 def test_match_with_xpath_variable(self):
     tmpl = MarkupTemplate("""<div xmlns:py="http://genshi.edgewall.org/">
       <span py:match="*[name()=$tagname]">
         Hello ${select('@name')}
       </span>
       <greeting name="Dude"/>
     </div>""")
     self.assertEqual(
         """<div>
       <span>
         Hello Dude
       </span>
     </div>""", str(tmpl.generate(tagname='greeting')))
     self.assertEqual(
         """<div>
       <greeting name="Dude"/>
     </div>""", str(tmpl.generate(tagname='sayhello')))
Example #53
0
 def test_extract_included_attribute_text(self):
     tmpl = MarkupTemplate("""<html xmlns:py="http://genshi.edgewall.org/">
       <span title="Foo"></span>
     </html>""")
     translator = Translator()
     messages = list(translator.extract(tmpl.stream))
     self.assertEqual(1, len(messages))
     self.assertEqual((2, None, u'Foo', []), messages[0])
Example #54
0
 def test_extract_gettext_with_unicode_string(self):
     tmpl = MarkupTemplate("""<html xmlns:py="http://genshi.edgewall.org/">
       ${gettext("Grüße")}
     </html>""")
     translator = Translator()
     messages = list(translator.extract(tmpl.stream))
     self.assertEqual(1, len(messages))
     self.assertEqual((2, 'gettext', u'Gr\xfc\xdfe', []), messages[0])
Example #55
0
 def test_extract_funky_plural_form(self):
     tmpl = MarkupTemplate("""<html xmlns:py="http://genshi.edgewall.org/">
       ${ngettext(len(items), *widget.display_names)}
     </html>""")
     translator = Translator()
     messages = list(translator.extract(tmpl.stream))
     self.assertEqual(1, len(messages))
     self.assertEqual((2, 'ngettext', (None, None), []), messages[0])
Example #56
0
 def test_extract_text_from_sub(self):
     tmpl = MarkupTemplate("""<html xmlns:py="http://genshi.edgewall.org/">
       <py:if test="foo">Foo</py:if>
     </html>""")
     translator = Translator()
     messages = list(translator.extract(tmpl.stream))
     self.assertEqual(1, len(messages))
     self.assertEqual((2, None, u'Foo', []), messages[0])
Example #57
0
 def test_as_element(self):
     """
     Verify that the directive can also be used as an element.
     """
     tmpl = MarkupTemplate("""<doc xmlns:py="http://genshi.edgewall.org/">
       <py:for each="item in items">
         <b>${item}</b>
       </py:for>
     </doc>""")
     self.assertEqual(
         """<doc>
         <b>1</b>
         <b>2</b>
         <b>3</b>
         <b>4</b>
         <b>5</b>
     </doc>""", str(tmpl.generate(items=range(1, 6))))
Example #58
0
 def test_not_iterable(self):
     """
     Verify that assignment to nested tuples works correctly.
     """
     tmpl = MarkupTemplate("""<doc xmlns:py="http://genshi.edgewall.org/">
       <py:for each="item in foo">
         $item
       </py:for>
     </doc>""",
                           filename='test.html')
     try:
         list(tmpl.generate(foo=12))
         self.fail('Expected TemplateRuntimeError')
     except TemplateRuntimeError, e:
         self.assertEqual('test.html', e.filename)
         if sys.version_info[:2] >= (2, 4):
             self.assertEqual(2, e.lineno)
Example #59
0
 def test_extract_attribute_expr(self):
     tmpl = MarkupTemplate("""<html xmlns:py="http://genshi.edgewall.org/">
       <input type="submit" value="${_('Save')}" />
     </html>""")
     translator = Translator()
     messages = list(translator.extract(tmpl.stream))
     self.assertEqual(1, len(messages))
     self.assertEqual((2, '_', u'Save', []), messages[0])
Example #60
0
 def test_extract_non_included_attribute_interpolated(self):
     tmpl = MarkupTemplate("""<html xmlns:py="http://genshi.edgewall.org/">
       <a href="#anchor_${num}">Foo</a>
     </html>""")
     translator = Translator()
     messages = list(translator.extract(tmpl.stream))
     self.assertEqual(1, len(messages))
     self.assertEqual((2, None, u'Foo', []), messages[0])