def __init__(self): wx.Frame.__init__(self , None, -1, "Testing Menu Engine", size = ( 500,400 )) menuengine.frame = self menuengine.prebind = self.Logger c = menubar[ menu[ "File", menuitem( bind = "OnNotReady" )["Open"], menuitem( prebind = "True", bind = "OnNotReady" )["Save"] , menusep[""], menuitem( bind = "OnExit" )["Exit"] ] ] flatten( c )
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
def __init__(self): wx.Frame.__init__(self, None, -1, "Testing Menu Engine", size=(500, 400)) menuengine.frame = self menuengine.prebind = self.Logger c = menubar[menu["File", menuitem(bind="OnNotReady")["Open"], menuitem(prebind="True", bind="OnNotReady")["Save"], menusep[""], menuitem(bind="OnExit")["Exit"]]] flatten(c)
def test_macros ( self ): '''test 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 ( 'test_macro', lambda url, label: T.a ( href = url ) [ label ] ), T.html [ T.head [ T.title [ my_name ( ) ] ], T.body [ T.ul [ [ T.li [ test_macro ( **_item ) ] for _item in url_data ] ] ] ] ) output = flatten ( template ) self.assertEqual ( output, ( u'<html><head><title>test_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>' ) )
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>' ))
def render_partial(T, template, fragments=None, vars=None, loader=None, **kw): try: result = T._evaluate(template, fragments, vars, loader, **kw) output = flatten(result) except: if T.debug: return T.debug_out(sys.exc_info()[:-1], template) else: # print "Error in template ( %s )" % template raise if T.tidy and tidylib: options = dict(input_xml=True, output_xhtml=True, add_xml_decl=False, doctype='omit', indent='auto', tidy_mark=False, input_encoding='utf8') return unicode( tidylib.parseString(output.encode('utf-8'), **options)) else: # p = PrettyPrinter ( ) # return p.parse ( output ) return output
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>') )
def test_dom_traversal_from_macro(self): '''macro abuse: self-traversing template''' 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/breve-logo.png', alt='breve logo'), T.br, T.span(class_='bold')['''Hello from Breve!''']]), css_results(selectors)]]) 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/breve-logo.png" alt="breve 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>'))
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>' ))
def test_custom_tags(self): """custom tags""" from breve.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>') )
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>') )
def handleGetLootRequest(self, request): """ :type request: werkzeug.wrappers.Request """ html = flatten(self.renderSignatureLoot(request.args['key'])) return JsonResponse( dict(status='getLoot', metadata=dict( levels=dict( trivial=dict( label='Debris', image='http://image.eveonline.com/Type/33254_64.png', ), easy=dict( label='Rubble', image='http://image.eveonline.com/Type/33255_64.png', ), medium=dict( label='Remains', image='http://image.eveonline.com/Type/33256_64.png', ), hard=dict( label='Ruins', image='http://image.eveonline.com/Type/33257_64.png', ), ), ), html=html) )
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>') )
def doPost(self, request): """ :type request: werkzeug.wrappers.Request """ operation = request.args.get('call', None) helper = IGBRequest(request) if operation == 'saveSignatures': newSignatures = request.data.decode('utf8') parsed = parseSignatures(newSignatures) currentSignatures = self._updateSignatures(self.getDA().getSignaturesDA(), helper, parsed) html = flatten(self.getKnownSignaturesTable(currentSignatures)) return JsonResponse(dict(status='save sig', html=html)) elif operation == 'getSystem': return JsonResponse(dict(systemName=helper.systemName)) elif operation == 'getLoot': return self.handleGetLootRequest(request) elif operation == 'addContainer': return self.handleAddContainerRequest(request) else: return JsonResponse(dict(error='invalid operation'))
def test_macros(): """test macros""" 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('test_macro', lambda url, label: T.a(href=url)[label] ), T.html[ T.head[T.title[my_name()]], T.body[ T.ul[ [T.li[test_macro(**_item)] # @UndefinedVariable for _item in url_data] ] ] ] ) output = flatten(template) assert output == ('<html><head><title>test_macros</title></head>' '<body><ul><li><a href="http://www.google.com">Google</a></li>' '<li><a href="http://www.yahoo.com">Yahoo!</a></li>' '<li><a href="http://www.amazon.com">Amazon</a></li></ul></body></html>')
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 ) 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>' ) )
def test_tag_serialization(): """basic tag flattening""" template = T.html[ T.head[T.title[my_name()]], T.body[T.div['okay']] ] output = flatten(template) assert output == ('<html><head><title>test_tag_serialization</title></head>' '<body><div>okay</div></body></html>')
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''
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>'))
def test_auto_tags(self): '''test AutoTag class''' 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>' )
def test_auto_tags(): """test AutoTag class""" T = AutoTag() template = ( T.foo(attr='foo')[ T.bar(attr='bar'), T.baz(attr='baz') ] ) actual = flatten(template) assert actual == '<foo attr="foo"><bar attr="bar"></bar><baz attr="baz"></baz></foo>'
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>' )
def test_assign(): """assign directive""" template = ( assign('msg', 'okay1'), T.html[ T.head[T.title[my_name()]], T.body[T.div[msg]] # @UndefinedVariable ] ) output = flatten(template) assert output == ('<html><head><title>test_assign</title></head>' '<body><div>okay1</div></body></html>')
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>'))
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>' )
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>'))
def render(self, request, url): """ :type url: werkzeug.routing.MapAdapter :type request: werkzeug.wrappers.Request """ # ifLogged = lambda fun: fun if self.isLogged else '' isTrusted = IGBRequest(request).isTrusted layout = ( T.html(lang='en')[ T.head[ T.meta(charset='utf-8'), T.meta(content='IE=Edge', **{'http-equiv': "X-UA-Compatible"}), T.meta(name='viewport', content='width=device-width, initial-scale=1'), T.title['PyEve IGB'], T.link(href='/static/css/bootstrap-black.min.css', rel='stylesheet'), T.link(href='/static/css/igb.css', rel='stylesheet'), T.script(src='https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js'), T.script(src='/static/js/bootstrap.js'), T.script(src='/static/js/igbCore.js'), self.getAdditionalJs() ], T.body[ # 'HOWDY', # request.headers.get('EVE_TRUSTED', 'alo'), T.div(class_='container-fluid')[ C.switch(isTrusted)[ C.case(True)[self.content], C.case(False)[self.renderRequestTrust()] ], T.div(class_='text-center')[ T.small[ 'PyEVE. Created by ', T.a(href="#", onclick="CCPEVE.showInfo(1377, 93747896); return false")[ 'Rudykocur Maxwell' ] ] ] ], ] ] ) return Response(flatten(layout), mimetype='text/html')
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>' ))
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>') )
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>'))
def test_dynamic_tags(): """test dynamic creation of tags""" template = ( assign('mytag', Tag('mytag')), mytag(feature='foo')[ # @UndefinedVariable 'hello, from mytag', Tag('explicit')(feature='bar')[ 'hello from explicit tag' ] ] ) actual = flatten(template) assert actual == ('<mytag feature="foo">hello, from mytag' '<explicit feature="bar">hello from explicit tag</explicit></mytag>')
def test_unicode_attributes(): """unicode and string coercion in attributes""" 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) assert output == ('<html><head><title>test_unicode_attributes</title></head><body>' '<span id="удерживать">Coerce byte string to Unicode</span>' '<span id="не оставляющий сомнений">Explicit Unicode object</span>' '</body></html>')
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/breve-logo.png', alt='breve 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/breve-logo.png" alt="breve 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>') )
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>' )
def test_flatten_callable(): """test flattening of callables""" def my_callable(): return "Hello, World" template = ( T.html[ T.head[T.title[my_name()]], T.body[ T.div[my_callable] ] ] ) actual = flatten(template) assert actual == ('<html><head><title>test_flatten_callable</title></head>' '<body><div>Hello, World</div></body></html>')
def test_assign_with_macro(): """assign directive with macro""" template = ( assign('msg', 'okay2'), macro('display_msg', lambda _m: T.span[_m] ), T.html[ T.head[T.title[my_name()]], T.body[T.div[display_msg(msg)]] # @UndefinedVariable ] ) output = flatten(template) assert output == ('<html><head><title>test_assign_with_macro</title></head>' '<body><div><span>okay2</span></div></body></html>')
def test_minJS(): """inline minified Javascript flattening""" js = """ if (x=1) { y=2; } """ template = T.html[ T.body[ T.minJS(js) ] ] output = flatten(template) assert output == ('<html><body>\n<script type="text/javascript">\n//<![CDATA[\n' 'if(x=1){y=2;}\n//]]></script>\n</body></html>')
def test_unicode(): """unicode and string coercion""" template = T.html[ T.head[T.title[my_name()]], T.body[ b'Brev\xc3\xa9 converts plain strings', T.br, 'Brev\xe9 handles unicode strings', T.br, T.div["äåå? ▸ ", T.em["я не понимаю"], "▸ 3 km²"] ] ] output = flatten(template) assert output == ('<html><head><title>test_unicode</title></head>' '<body>Brevé converts plain strings<br />' 'Brevé handles unicode strings<br />' '<div>äåå? ▸ <em>я не понимаю</em>▸ 3 km²</div></body></html>')
def test_auto_tags ( self ): '''test AutoTag class''' 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>' )
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>' ) )
def test_check(): """check() function""" template = T.html[ T.head[T.title[my_name()]], T.body[ check(1 == 1) and ( T.span['This is displayed'] ), check(1 == 0) and ( T.span['This is not displayed'] ) ] ] output = flatten(template) assert output == ('<html><head><title>test_check</title></head>' '<body><span>This is displayed</span></body></html>')
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>' )
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>' )
def test_let ( self ): '''let directive''' T = tags template = ( let ( 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_let</title></head><body><div>okay</div></body></html>' )
def test_unicode(self): '''unicode and string coercion''' T = tags template = T.html[T.head[T.title[my_name()]], T.body['Brev\xc3\xa9 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>'))
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> & unaltered.</div>''' )]]] output = flatten(template) self.assertEqual(output, ( u'<html><head><title>test_escaping</title></head>' u'<body><div style="width: 400px;<should be &escaped&>">' u'<p class="foo">&&&</p><p>Coffee & cream</p>' u'<div>this should be <u>unescaped</u> & unaltered.</div></div></body></html>' ))
def build_tree(facet, root_url, category_path): ul_by_path = {} root = T.ul() ul_by_path[''] = root cats = list(facet['category']) cats.sort( lambda x, y: cmp(len(x['path'].split('.')), len(y['path'].split('.')))) for c in cats: u = T.ul() ul_by_path[c['path']] = u if c['path'] == category_path: class_ = 'selected' else: class_ = '' link = T.a(href=root_url.child(c['path']))[c['data']['label']] link.attrs['class'] = class_ li_link = T.li()[link] parent = get_parent(c['path']) ul_by_path[parent][li_link, u] return flatten(root)
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>' ))
def test_soup2breve(self): ''' round-trip some html ''' breve_source = ''.join( convert_file(os.path.join(test_root(), 'html/index.html'), dict(meta=meta_handler))) code_object = compile(breve_source, 'soup2breve', 'eval') _globals = dict(E=entities) _globals.update(tags) actual = flatten(eval(code_object, _globals)) expected = file(os.path.join(test_root(), 'html/index.html')).read() try: # we can't actually round trip because attributes never come out in # the same order twice =( self.assertEqual(len(actual), len(expected)) except AssertionError: diff(actual, expected) raise
def test_custom_tags(self): '''custom tags''' from breve.tests.sitemap import tags, xmlns 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>' ))
def __str__ ( self ): return flatten ( self )
def flatten_callable ( o ): return flatten ( o ( ) )
def flatten_sequence ( o ): return u''.join ( [ flatten ( i ) for i in o ] )
def __str__(self): if self.name in T.fragments: return xml(flatten(T.fragments[self.name])) if self.children: return u''.join([flatten(c) for c in self.children]) return u''
def __str__(self): if self.children: return u''.join([flatten(c) for c in self.children]) return u''