Exemplo n.º 1
0
    def flattened(o):
        if o.render:
            o = o.render(o, o.data)
            if not isinstance(o, Tag):
                yield flatten(o)
                raise StopIteration

        yield u'<%s%s>' % (o.name, u''.join(quoteattrs(o.attrs)))
        for c in o.children:
            yield flatten(c)
        yield u'</%s>' % o.name
        raise StopIteration
Exemplo n.º 2
0
    def test_nested_macros(self):
        """test nested macros"""

        T = tags
        url_data = [{
            'url': 'http://www.google.com',
            'label': 'Google'
        }, {
            'url': 'http://www.yahoo.com',
            'label': 'Yahoo!'
        }, {
            'url': 'http://www.amazon.com',
            'label': 'Amazon'
        }]

        template = (
            macro(
                'list_macro', lambda url, label:
                (macro('link_macro', lambda _u, _l: T.a(href=_u)[_l]), T.li[
                    link_macro(url, label)])),
            T.html[T.head[T.title[my_name()]],
                   T.body[T.ul[[list_macro(**_item) for _item in url_data]]]])
        output = flatten(template)
        self.assertEqual(output, (
            u'<html><head><title>test_nested_macros</title></head>'
            u'<body><ul><li><a href="http://www.google.com">Google</a></li>'
            u'<li><a href="http://www.yahoo.com">Yahoo!</a></li>'
            u'<li><a href="http://www.amazon.com">Amazon</a></li></ul></body></html>'
        ))
Exemplo n.º 3
0
    def test_dom_traversal_from_macro(self):
        T = tags
        template = (
            assign('selectors', []),
            macro('css_sep', lambda attr: attr == 'class' and '.' or '#'),
            macro(
                'get_selectors', lambda tag, is_tag: selectors.extend([
                    "%s%s%s { }" % (tag.name, css_sep(_k.strip('_')), _v)
                    for _k, _v in tag.attrs.items()
                    if _k.strip('_') in ('id', 'class')
                ])),
            macro('extract_css',
                  lambda tag: tag.walk(get_selectors, True) and tag),
            macro('css_results',
                  lambda selectors: T.pre['\n'.join(selectors)]),
            T.html[T.head[T.title['macro madness']], T.body[extract_css(
                T.div(class_='text', id='main-content')[
                    T.img(src='/images/liphtePy-logo.png', alt='liphtePy logo'
                          ), T.br,
                    T.span(class_='bold')['''Hello from Breve!''']]),
                                                            css_results(
                                                                selectors)]])
        """macro abuse: self-traversing template"""

        T = tags
        output = flatten(template)

        self.assertEqual(
            output,
            (u'<html><head><title>macro madness</title></head>'
             u'<body><div class="text" id="main-content">'
             u'<img src="/images/liphtePy-logo.png" alt="liphtePy logo"></img>'
             u'<br /><span class="bold">Hello from Breve!</span></div>'
             u'<pre>div.text { }\ndiv#main-content { }\nspan.bold { }</pre>'
             u'</body></html>'))
Exemplo n.º 4
0
    def test_autolist_macro(self):
        """test autolist macro"""

        data = ["Item %s" % _i for _i in range(1, 9)]

        template = (
            macro(
                'AutoList',
                lambda data: data and (
                    T.ul(class_='autolist')[
                        [T.li[_i] for _i in data]
                    ]
                ) or ''
            ),
            T.html[
                T.head[T.title[my_name()]],
                T.body[AutoList(data)]
            ]
        )
        output = flatten(template)

        # print('OMG OMG OMG OUT', output)

        self.assertEqual(
            output,
            (u'<html><head><title>test_autolist_macro</title></head>'
             u'<body><ul class="autolist"><li>Item 1</li><li>Item 2</li>'
             u'<li>Item 3</li><li>Item 4</li><li>Item 5</li><li>Item 6</li>'
             u'<li>Item 7</li><li>Item 8</li></ul></body></html>')
        )
Exemplo n.º 5
0
    def test_tag_multiplication_with_macro(self):
        """tag multiplication including macro"""

        T = tags
        url_data = [{
            'url': 'http://www.google.com',
            'label': 'Google',
            'class': 'link'
        }, {
            'url': 'http://www.yahoo.com',
            'label': 'Yahoo!',
            'class': 'link'
        }, {
            'url': 'http://www.amazon.com',
            'label': 'Amazon',
            'class': 'link'
        }]

        template = (
            macro('test_macro', lambda url: T.a(href=url)["$label"]),
            T.html[T.head[T.title[my_name()]],
                   T.body[T.ul[T.li(class_="$class")[test_macro("$url")] *
                               url_data]]])
        output = flatten(template)
        self.assertEqual(output, (
            u'<html><head><title>test_tag_multiplication_with_macro</title></head>'
            u'<body><ul><li class="link"><a href="http://www.google.com">Google</a></li>'
            u'<li class="link"><a href="http://www.yahoo.com">Yahoo!</a></li>'
            u'<li class="link"><a href="http://www.amazon.com">Amazon</a></li></ul></body></html>'
        ))
Exemplo n.º 6
0
def flatten_invisible(o):
    if o.render:
        # o.children = [ ]
        t = o.render(o, o.data)
    else:
        t = o
    if t.children:
        return u''.join([flatten(c) for c in t.children])
    return u''
Exemplo n.º 7
0
    def test_tag_serialization(self):
        """basic tag flattening"""

        T = tags
        template = T.html[T.head[T.title[my_name()]], T.body[T.div['okay']]]
        output = flatten(template)
        self.assertEqual(
            output,
            (u'<html><head><title>test_tag_serialization</title></head>'
             u'<body><div>okay</div></body></html>'))
Exemplo n.º 8
0
    def test_auto_tags(self):
        """test AutoTag class"""

        # noinspection PyPep8Naming
        T = AutoTag()
        template = (T.foo(attr='foo')[T.bar(attr='bar'), T.baz(attr='baz')])
        actual = flatten(template)
        self.assertEqual(
            actual,
            u'<foo attr="foo"><bar attr="bar"></bar><baz attr="baz"></baz></foo>'
        )
Exemplo n.º 9
0
    def test_assign(self):
        """assign directive"""

        T = tags
        template = (assign('msg', 'okay'), T.html[T.head[T.title[my_name()]],
                                                  T.body[T.div[msg]]])
        output = flatten(template)
        self.assertEqual(
            output,
            u'<html><head><title>test_assign</title></head><body><div>okay</div></body></html>'
        )
Exemplo n.º 10
0
    def test_dynamic_tags(self):
        """test dynamic creation of tags"""

        template = (assign('mytag', Tag('mytag')), mytag(
            feature='foo')['hello, from mytag',
                           Tag('explicit')(
                               feature='bar')['hello from explicit tag']])
        actual = flatten(template)
        self.assertEqual(
            actual,
            u'<mytag feature="foo">hello, from mytag<explicit feature="bar">hello from explicit tag</explicit></mytag>'
        )
Exemplo n.º 11
0
    def test_flatten_callable(self):
        """test flattening of callables"""
        def my_callable():
            return "Hello, World"

        T = tags
        template = (T.html[T.head[T.title[my_name()]],
                           T.body[T.div[my_callable]]])
        actual = flatten(template)
        self.assertEqual(
            actual, (u'<html><head><title>test_flatten_callable</title></head>'
                     u'<body><div>Hello, World</div></body></html>'))
Exemplo n.º 12
0
    def test_test(self):
        """test() function"""

        T = tags
        template = T.html[T.head[T.title[my_name()]],
                          T.body[test(1 == 1) and
                                 (T.span['This is displayed']),
                                 test(1 == 0) and
                                 (T.span['This is not displayed'])]]
        output = flatten(template)
        self.assertEqual(
            output, (u'<html><head><title>test_test</title></head>'
                     u'<body><span>This is displayed</span></body></html>'))
Exemplo n.º 13
0
    def test_unicode_attributes(self):
        """unicode and string coercion in attributes"""

        T = tags
        template = T.html[T.head[T.title[my_name()]], T.body[
            T.span(id='удерживать')["Coerce byte string to Unicode"],
            T.span(id='не оставляющий сомнений')["Explicit Unicode object"]]]
        output = flatten(template)

        self.assertEqual(output, (
            u'<html><head><title>test_unicode_attributes</title></head><body>'
            u'<span id="удерживать">Coerce byte string to Unicode</span>'
            u'<span id="не оставляющий сомнений">Explicit Unicode object</span></body></html>'
        ))
Exemplo n.º 14
0
    def test_assign_with_macro(self):
        """assign directive with macro"""

        T = tags
        template = (assign('msg',
                           'okay'), macro('display_msg',
                                          lambda _m: T.span[_m]),
                    T.html[T.head[T.title[my_name()]],
                           T.body[T.div[display_msg(msg)]]])
        output = flatten(template)
        self.assertEqual(
            output,
            (u'<html><head><title>test_assign_with_macro</title></head>'
             u'<body><div><span>okay</span></div></body></html>'))
Exemplo n.º 15
0
    def test_minJS(self):
        """inline minified Javascript flattening"""

        js = '''
            if (x=1) {
                y=2;
            }
        '''
        T = tags
        template = T.html[T.body[T.minJS(js)]]
        output = flatten(template)
        self.assertEqual(
            output,
            u'<html><body>\n<script type="text/javascript">\n//<![CDATA[\nif(x=1){y=2;}\n//]]></script>\n</body></html>'
        )
Exemplo n.º 16
0
    def test_autotable_macro(self):
        """test autotable macro"""

        data = [
            ['One', 'Two', 'Three', 'Four'],
            range(0, 4),
            range(4, 8),
            range(8, 12)
        ]

        template = (
            macro('AutoTable', lambda data, header=False: (
                assign('alts', ['even', 'odd']),
                data and (
                    T.table(class_='autotable')[
                        header and (
                            T.thead[[T.th[_col] for _col in data[0]]]
                        ),
                        T.tbody[
                            [T.tr(class_='row-%s' % alts[_rx % 2])[
                                 [T.td(class_='col-%s' % alts[_cx % 2])[_col]
                                  for _cx, _col in enumerate(_row)]
                             ] for _rx, _row in enumerate(data[int(header):])]
                        ]
                    ]
                ) or ''
            )),

            T.html[
                T.head[T.title[my_name()]],
                T.body[
                    AutoTable(data, header=True)
                ]
            ]
        )
        output = flatten(template)
        self.assertEqual(
            output,
            (u'<html><head><title>test_autotable_macro</title></head>'
             u'<body><table class="autotable"><thead><th>One</th><th>Two</th><th>Three</th><th>Four</th></thead>'
             u'<tbody><tr class="row-even"><td class="col-even">0</td><td class="col-odd">1</td>'
             u'<td class="col-even">2</td><td class="col-odd">3</td></tr>'
             u'<tr class="row-odd"><td class="col-even">4</td><td class="col-odd">5</td><td class="col-even">6</td>'
             u'<td class="col-odd">7</td></tr>'
             u'<tr class="row-even"><td class="col-even">8</td><td class="col-odd">9</td>'
             u'<td class="col-even">10</td><td class="col-odd">11</td></tr></tbody>'
             u'</table></body></html>')
        )
Exemplo n.º 17
0
    def test_unicode(self):
        """unicode and string coercion"""

        T = tags
        template = T.html[T.head[T.title[my_name()]],
                          T.body[u'Brev\xe9 converts plain strings', T.br,
                                 u'Brev\xe9 handles unicode strings', T.br,
                                 T.div["äåå? ▸ ", T.em["я не понимаю"],
                                       "▸ 3 km²"]]]
        output = flatten(template)
        self.assertEqual(
            output,
            (u'<html><head><title>test_unicode</title></head>'
             u'<body>Brevé converts plain strings<br />'
             u'Brevé handles unicode strings<br />'
             u'<div>äåå? ▸ <em>я не понимаю</em>▸ 3 km²</div></body></html>'))
Exemplo n.º 18
0
    def test_escaping(self):
        """escaping, xml() directive"""

        T = tags
        template = T.html[T.head[T.title[my_name()]], T.body[T.div(
            style='width: 400px;<should be &escaped&>'
        )[T.p(class_='foo')['&&&'], T.p['Coffee', E.nbsp, E.amp, E.nbsp,
                                        'cream'],
          xml('''<div>this should be <u>unescaped</u> &amp; unaltered.</div>'''
              )]]]
        output = flatten(template)
        self.assertEqual(output, (
            u'<html><head><title>test_escaping</title></head>'
            u'<body><div style="width: 400px;&lt;should be &amp;escaped&amp;&gt;">'
            u'<p class="foo">&amp;&amp;&amp;</p><p>Coffee&#160;&#38;&#160;cream</p>'
            u'<div>this should be <u>unescaped</u> &amp; unaltered.</div></div></body></html>'
        ))
Exemplo n.º 19
0
    def test_autolist_macro2(self):
        """test autolist macro"""

        sublist1 = ["List 1:%s" % _i for _i in range(3)]
        sublist2 = ["List 2:%s" % _i for _i in range(3, 6)]
        sublist3 = ["List 3:%s" % _i for _i in range(6, 9)]
        sublist3.append(sublist2)

        data = [
            'Item A', 'Item B', 'Item C',
            sublist1,
            'Item D', 'Item E', 'Item F',
            sublist3,
        ]
        template = (
            macro('AutoList', lambda data, level=0:
            data and (
                T.ul(class_='autolist level-%s' % level)[
                    [T.li[
                         [lambda _i, _j: _i, AutoList]
                         [isinstance(_i, list)](_i, level + 1)
                     ]
                     for _i in data]
                ]
            ) or ''
                  ),

            T.html[
                T.head[T.title[my_name()]],
                T.body[AutoList(data)]
            ]
        )
        output = flatten(template)
        self.assertEqual(
            output,
            (u'<html><head><title>test_autolist_macro2</title></head>'
             u'<body><ul class="autolist level-0"><li>Item A</li>'
             u'<li>Item B</li><li>Item C</li><li><ul class="autolist level-1">'
             u'<li>List 1:0</li><li>List 1:1</li><li>List 1:2</li></ul></li>'
             u'<li>Item D</li><li>Item E</li><li>Item F</li><li>'
             u'<ul class="autolist level-1"><li>List 3:6</li>'
             u'<li>List 3:7</li><li>List 3:8</li><li><ul class="autolist level-2">'
             u'<li>List 2:3</li><li>List 2:4</li><li>List 2:5</li></ul>'
             u'</li></ul></li></ul></body></html>')
        )
Exemplo n.º 20
0
    def test_tag_multiplication(self):
        """tag multiplication"""

        T = tags
        url_data = [
            dict(url='http://www.google.com', label='Google'),
            dict(url='http://www.yahoo.com', label='Yahoo!'),
            dict(url='http://www.amazon.com', label='Amazon')
        ]

        template = T.html[T.head[T.title[my_name()]],
                          T.body[T.ul[T.li[T.a(href="$url")["$label"]] *
                                      url_data]]]
        output = flatten(template)
        self.assertEqual(output, (
            u'<html><head><title>test_tag_multiplication</title></head>'
            u'<body><ul><li><a href="http://www.google.com">Google</a></li>'
            u'<li><a href="http://www.yahoo.com">Yahoo!</a></li>'
            u'<li><a href="http://www.amazon.com">Amazon</a></li></ul></body></html>'
        ))
Exemplo n.º 21
0
    def test_toc_macro(self):
        """test table-of-contents macro"""

        template = (
            assign('TOC', []),
            macro('TableOfContents', lambda matchtags, tag: (
                macro('toc_search', lambda tag, is_tag:
                tag.name in matchtags and (
                    TOC.append(T.a(href='#toc-%s' % tag.children[0])[tag.children[0]]),
                    tag.attrs.update({'class': 'chapter-%s' % tag.name}),
                    tag.children.insert(0, T.a(name='toc-%s' % tag.children[0])[tag.name])
                ) or True
                      ),
                tag.walk(toc_search, True)
            )),

            T.html[
                T.head[T.title[my_name()]],
                T.body[
                    T.div(id='TableOfContents')[
                        'Table of Contents',
                        lambda: T.ul[[T.li[_t] for _t in TOC]]
                    ],
                    TableOfContents(('h1', 'h2', 'h3'), T.div[
                        T.h1['Chapter 1'],
                        T.div['chapter 1 content'],
                        T.h1['Chapter 2'],
                        T.div[
                            'chapter 2 content',
                            T.h2['Chapter 2 subsection'],
                            T.div[
                                'chapter 2 subsection content'
                            ]
                        ]
                    ])
                ]
            ]
        )

        actual = flatten(template)
Exemplo n.º 22
0
    def test_custom_tags(self):
        """custom tags"""

        from liphtePy.tests.sitemap import tags, xmlns

        # noinspection PyPep8Naming
        T = Namespace(tags)

        # test data
        loc = 'http://www.example.com/',
        lastmod = '2008-01-01',
        changefreq = 'monthly',
        priority = 0.8

        template = T.urlset(xmlns=xmlns)[T.url[T.loc[loc], T.lastmod[lastmod],
                                               T.changefreq[changefreq],
                                               T.priority[priority]]]
        output = flatten(template)

        self.assertEqual(output, (
            u'<urlset xmlns="http://www.google.com/schemas/sitemap/0.84/sitemap.xsd">'
            u'<url><loc>http://www.example.com/</loc><lastmod>2008-01-01</lastmod>'
            u'<changefreq>monthly</changefreq><priority>0.8</priority></url></urlset>'
        ))
Exemplo n.º 23
0
 def __str__(self):
     return flatten(self)
Exemplo n.º 24
0
def flatten_callable(o):
    return flatten(o())
Exemplo n.º 25
0
def flatten_sequence(o):
    return u''.join([flatten(i) for i in o])