def test_textarea_indentation(): """Check for extra indentation to textarea (ticket #83).""" widgetsrc = """ <textarea xmlns:py="http://purl.org/kid/ns#" py:content="value" /> """ template = """ <div xmlns:py="http://purl.org/kid/ns#"> ${widget} </div> """ t = kid.Template(widgetsrc, value='') tmpl = kid.Template(template, widget=t.transform()) rslt = tmpl.serialize(output='xhtml', fragment=True) expected = """<div> <textarea></textarea> </div>""" assert rslt == expected template = """ <div xmlns:py="http://purl.org/kid/ns#">${widget}</div> """ t = kid.Template(widgetsrc, value='') tmpl = kid.Template(template, widget=t.transform()) rslt = tmpl.serialize(output='xhtml', fragment=True) expected = """<div><textarea></textarea></div>""" assert rslt == expected template = """ <div xmlns:py="http://purl.org/kid/ns#"> ${widget}</div> """ assert rslt == expected
def test_attr_error(): """Check that erroneous py:attrs expressions are reported.""" page = """\ <html xmlns:py="http://purl.org/kid/ns#"> <p py:attrs="%s" /> </html>""" t = kid.Template(source=page % "abc=123, def=789") s = t.serialize() assert 'abc="123"' in s and 'def="789"' in s from kid.template_util import TemplateAttrsError t = kid.Template(source=page % "abc=123, 456=789") e = str(raises(TemplateAttrsError, t.serialize)) assert 'invalid' in e assert 'while processing attrs=' in e assert 'abc=123, 456=789' in e t = kid.Template(source=page % "{'mickey':'mouse'}") s = t.serialize() assert 'mickey="mouse"' in s t = kid.Template(source=page % "mickey mouse") e = str(raises(TemplateAttrsError, t.serialize)) assert 'while processing attrs=' in e assert 'mickey mouse' in e t = kid.Template(source=page % "{mickey:mouse}") e = str(raises(TemplateAttrsError, t.serialize)) assert 'not defined' in e assert 'mickey' in e and 'mouse' in e
def index(): #default template template = kid.Template( name=os.path.basename(__file__)[:-3], title=get_text('sitename') + '-' + get_text(os.path.basename(__file__)[:-3]), projects=[], techs=[], headline=get_text(os.path.basename(__file__)[:-3]), project_not_found=get_text('database_not_available'), **common_language[DEFAULT_LANGUAGE]) data.init() techniques = data.retrieve_technique_stats() if techniques[0] == 0: template = kid.Template(name=os.path.basename(__file__)[:-3], title=get_text('sitename') + ' - ' + get_text('techniques'), headline=get_text('techniques'), techs=techniques[1], project_not_found='', **common_language[DEFAULT_LANGUAGE]) template.cache = False return template.serialize(output='xhtml-strict')
def test_remove_null_attributes(): """Expressions evaluating to None should remove the attribute.""" source = '<div a="$a" b="$b" c="$c" />' s = kid.Template(source, a=0, b=False, c=None).serialize() assert s.endswith('<div a="0" b="False" />') source = '<div a="$c$a" b="$c$b" c="$c$c" />' s = kid.Template(source, a=0, b=False, c=None).serialize() assert s.endswith('<div a="0" b="False" />')
def index(id=None): data.init() #default template template = kid.Template(name=os.path.basename(__file__)[:-3], title=get_text('sitename') + '-' + get_text(os.path.basename(__file__)[:-3]), projects=[], headline=get_text(os.path.basename(__file__)[:-3]), project_not_found=u'Databasen är inte tillgänglig', **common_language[DEFAULT_LANGUAGE]) if id == None: projects = data.retrieve_projects(sort_order='desc') if projects[0] == 0: template = kid.Template(name=os.path.basename(__file__)[:-3], title=get_text('sitename') + '-' + get_text(os.path.basename(__file__)[:-3]), projects=projects[1], headline=get_text( os.path.basename(__file__)[:-3]), project_not_found='', **common_language[DEFAULT_LANGUAGE]) # Find project by id else: project = data.lookup_project(id) # Project not found if project[0] == 2: projects = data.retrieve_projects(sort_order='desc') if projects[0] == 0: template = kid.Template( name=os.path.basename(__file__)[:-3], title=get_text('sitename') + '-' + get_text('project_not_found'), projects=projects[1], headline=get_text(os.path.basename(__file__)[:-3]), project_not_found=get_text('project_not_found'), **common_language[DEFAULT_LANGUAGE]) # Show project by id else: project = data.retrieve_projects(search=id, search_fields=['project_no']) project[1][0]['techniques_used'] = ", ".join( project[1][0]['techniques_used']) template = kid.Template( name='projectsbyid', title=get_text('sitename') + '-' + get_text('projects') + ": " + project[1][0]['project_name'], headline=project[1][0]['project_name'], **dict(project[1][0], **common_language[DEFAULT_LANGUAGE])) template.cache = False return template.serialize(output='xhtml-strict')
def Test(): template = kid.Template(file="simpletemplate.xml") print str(template) template = kid.Template(source='<p>$foo</p>', foo='Hello World!') print template.serialize() out = {'section': u'<span onClick="ReplaceChildrenWithUri(\'center\',\'section_classes.html\')" onMouseout="this.setAttribute(\'style\',\'\');" onMouseover="this.setAttribute(\'style\',\'color:Blue;\');">classes</span>', 'ClassFile': u'<span onClick="ReplaceChildrenWithUri(\'center\',\'file_lightuino.h.html\')" onMouseout="this.setAttribute(\'style\',\'\');" onMouseover="this.setAttribute(\'style\',\'color:Blue;\');">/me/hw/arduino/arduino-m5451-current-driver/latest/apps/lightuino_lib_dev/applet/lightuino.h</span>', 'subSection': ["hi"], 'className': u'Lightuinop'} template = kid.Template(file="yadogskin/classdetails.xml",**out) print str(template)
def test_XML_func_fragment(): text = u"""some plain "text" with & entities.""" t = kid.Template(source="<p>${XML(text)}</p>", text=text) rslt = t.serialize(fragment=True) assert rslt == '''<p>some plain "text" with & entities.</p>''' # another one text = """something <p>something else</p>""" t = kid.Template(source="<p>${XML(text)}</p>", text=text) actual = t.serialize(fragment=True) expected = '''<p>something <p>something else</p></p>''' assert actual == expected, '%r != %r' % (actual, expected)
def test_comment_whitespace(): """Comments should not add an additional newline (ticket #107).""" expected = '<?xml version="1.0" encoding="utf-8"?>\n<html>\n' \ '<!-- a comment -->\n<element />\n</html>' assert kid.Template(expected).serialize(output='xml') == expected expected = serialize_doctype(doctypes['html']) + '\n<HTML>\n' \ '<!-- a comment -->\n<ELEMENT>\n</ELEMENT>\n</HTML>' assert kid.Template(expected).serialize(output='HTML') == expected expected = serialize_doctype(doctypes['xhtml']) + '\n<html>\n' \ '<!-- a comment -->\n<element>\n</element>\n</html>' assert kid.Template(expected).serialize(output='xhtml') == expected
def test_no_repeated_namespaces(): """Check that namespaces are not repeated (ticket #144).""" div1 = """ <div xmlns="http://www.w3.org/1999/xhtml"/>""" div2 = """ <div xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://purl.org/kid/ns#" py:content="div1"/>""" t = kid.Template(div2, div1=kid.Template(div1).transform()) s = t.serialize(output='xhtml', fragment=True) assert s == '<div xmlns="http://www.w3.org/1999/xhtml"><div></div></div>'
def test_br_namespace_issues(): """Check problem with handling of br in XHTML (ticket #83).""" widgetsrc = '<div><br/></div>' template = """<div xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://purl.org/kid/ns#"> ${widget}<br/> </div>""" t = kid.Template(widgetsrc, value='') tmpl = kid.Template(template, widget=t.transform()) rslt = tmpl.serialize(output='xhtml', fragment=True) expected = """<div xmlns="http://www.w3.org/1999/xhtml"> <div><br /></div><br /> </div>""" assert rslt == expected
def test_dynamic_layout(): layout = kid.Template(""" <html xmlns:py="http://purl.org/kid/ns#"> ${body_content()} </html> """) child = kid.Template(""" <html py:layout="dynamic_layout" xmlns:py="http://purl.org/kid/ns#"> <body py:def="body_content()">body content</body> </html> """, dynamic_layout=type(layout)) output = child.serialize() assert output.find("body content") > -1, \ "body_content function was not executed"
def index(sort_by='start_date', sort_order='asc', techniques=None, search=None, search_fields=None): #default template template = kid.Template( name=os.path.basename(__file__)[:-3], title=get_text('sitename') + '-' + get_text(os.path.basename(__file__)[:-3]), results=[], techs=[], search_fields=[], translate_field=[], headline=get_text(os.path.basename(__file__)[:-3]), project_not_found=get_text('database_not_available'), **common_language[DEFAULT_LANGUAGE]) if techniques == '': techniques = None if search_fields == '': search_fields = None if type(search_fields) != type([]) and search_fields != None: search_fields = [search_fields] data.init() # search projects results = data.retrieve_projects(sort_by, sort_order, techniques, search, search_fields) # Projects found if results[0] == 0: techniques = data.retrieve_techniques() template = kid.Template( name=os.path.basename(__file__)[:-3], title=get_text('sitename') + ' - ' + get_text('search'), headline=get_text(os.path.basename(__file__)[:-3]), results=results[1], techs=techniques[1], search_fields=data.data[0].keys(), translate_field=field_language[DEFAULT_LANGUAGE], project_not_found='', **common_language[DEFAULT_LANGUAGE]) template.cache = False return template.serialize(output='xhtml-strict')
def test_reserved_names(): """Check for reserved keyword arguments (ticket #181).""" from kid.template_util import TemplateAttrsError try: t = kid.Template('<div />', content=None) except TemplateAttrsError, e: e = str(e)
def test_dont_modify_trees(): t = kid.Template(source="<a>$xml</a>") t.xml = ElementTree.fromstring("<b>some<c>nested</c>elements</b>") expected = "<a><b>some<c>nested</c>elements</b></a>" assert t.serialize(fragment=True) == expected print ElementTree.dump(t.xml) assert t.serialize(fragment=True) == expected
def render(): template = kid.Template( file='template.kid', title='Just a test', user='******', items=['Number %d' % num for num in range(1, 15)]) return template.serialize(output='xhtml')
def serialize(source, format=None, output='html', encoding='utf-8'): """Compile source template and serialize with given format.""" t = kid.Template(source=source) return t.serialize(encoding=encoding, format=format, output=output, fragment=True) # so that output will not be stripped
def test_nested_comments(): """Nested comments.""" t = kid.Template('<!--1--><html><!--2--><div><!--3-->' '<p><!--4--></p><!--5--></div><!--7--></html><!--8-->') assert (t.serialize(output='HTML') == serialize_doctype(doctypes['html']) + '\n<!--1--><HTML><!--2--><DIV><!--3-->' '<P><!--4--></P><!--5--></DIV><!--7--></HTML><!--8-->')
def generate(obj,cfg): sec = Tainer() sec.name = "all" sec.variables = obj.getElementsByTagName(TagField) + obj.getElementsByTagName(TagVariable) sec.methods = obj.getElementsByTagName(TagFunction) + obj.getElementsByTagName(TagMethod) out = {} out["g"] = globals() out["replace"] = PageLocCenter out["subSection"] = [sec] out["XESC"] = escape out["className"] = obj.name # Figure out the upwards links fileobj = obj.findParent(TagFile) if fileobj: out["ClassFile"] = obj2tlink(fileobj[0],PageLocCenter) else: out["ClassFile"] = "" sectionobj = obj.findParent("section") if sectionobj: out["section"] = obj2tlink(sectionobj[0],PageLocCenter) else: out["section"]= "" out["this"] = obj out["R"] = render #out["flatSections"] = obj.filterByAttr(AttrTag,"section") template = kid.Template(file=cfg["html"]["skin"] + os.sep + "filedetails.xml",**out) print str(template) fname = obj2file(obj) f = open("html"+os.sep+fname, "wb") f.write(str(template)) f.close() return (fname,template)
def writeall(self): ''' Very different writeall: there is no tree of nodes; there is no grammar.structure/recorddefs; kid opens file by itself. ''' try: import kid except: txt=botslib.txtexc() raise ImportError(_(u'Dependency failure: editype "template" requires python library "kid". Error:\n%s'%txt)) #for template-grammar: only syntax is used. Section 'syntax' has to have 'template' self.outmessagegrammarread(self.ta_info['editype'],self.ta_info['messagetype']) templatefile = botslib.abspath(u'templates',self.ta_info['template']) try: botsglobal.logger.debug(u'Start writing to file "%s".',self.ta_info['filename']) ediprint = kid.Template(file=templatefile, data=self.data) except: txt=botslib.txtexc() raise botslib.OutMessageError(_(u'While templating "$editype.$messagetype", error:\n$txt'),editype=self.ta_info['editype'],messagetype=self.ta_info['messagetype'],txt=txt) try: f = botslib.opendata(self.ta_info['filename'],'wb') ediprint.write(f, #~ ediprint.write(botslib.abspathdata(self.ta_info['filename']), encoding=self.ta_info['charset'], output=self.ta_info['output'], #output is specific parameter for class; init from grammar.syntax fragment=self.ta_info['merge']) except: txt=botslib.txtexc() raise botslib.OutMessageError(_(u'While templating "$editype.$messagetype", error:\n$txt'),editype=self.ta_info['editype'],messagetype=self.ta_info['messagetype'],txt=txt) botsglobal.logger.debug(_(u'End writing to file "%s".'),self.ta_info['filename'])
def test_HTML_output_method(): t = kid.Template('<html><p>Test</p><br /></html>') for output in 'HTML', 'HTML-strict': rslt = t.serialize(output=output) expected = serialize_doctype(doctypes[output.lower()]) + \ '\n<HTML><P>Test</P><BR></HTML>' assert rslt == expected
def test_comment_interpolation(): """Comments starting with '[' or '<![' should be interpolated.""" for b in ('', ' '): for c in '! [ < <[ <! ![ <![ ${'.split(): for d in '/ // ! ]'.split(): before_comment = '<!--%s%s $before %s-->' % (b, c, d) if c.startswith('!'): after_comment = '' elif c == '[' or c == '<![' or d == '//': after_comment = '<!--%s%s after %s-->' % (b, c, d) else: after_comment = before_comment before = '<html>%s</html>' % before_comment t = kid.Template(before, before='after') for output in ('HTML', 'xhtml', 'xml'): if output == 'HTML': after = '<HTML>%s</HTML>' % after_comment elif output == 'xhtml' or after_comment: after = '<html>%s</html>' % after_comment else: after = '<html />' if output == 'xml': after = '<?xml version="1.0" encoding="utf-8"?>\n' + after else: doctype = serialize_doctype(doctypes[output.lower()]) after = doctype + '\n' + after assert t.serialize(output=output) == after
def generate(mdtree, cfg, args, tagDict): me = Dotter() title, sectionFilter, contentSkin = args out = {} out['me'] = me out['R'] = render out['title'] = title out['link'] = lambda x: linker(x) me.sections = mdtree.filterByAttr(sectionFilter) for m in me.sections: brief = m.find("brief") if brief: m.brief = brief[0][1] else: m.brief = "" if contentSkin: m.generatedTo = title + "_" + os.path.basename(filenameify( m.name)) + ".html" generateContent(cfg, m, contentSkin) template = kid.Template(file=cfg["html"]["skin"] + os.sep + "toc.xml", **out) #print str(template) fname = args[0] + ".html" f = open("html" + os.sep + fname, "wb") f.write(str(template)) f.close() for m in me.sections: pass return (fname, template)
def test_generate_func(): def run_test(o): for s in o.generate(encoding='ascii'): assert s is not None and len(s) > 0 run_test(kid.Template(name=template_package + 'test_if')) run_test(kid.load_template(joinpath(template_dir, 'test_if.kid')))
def test_html_output_method(): t = kid.Template('<html><p>Test</p><br /></html>') for output in 'html', 'html-strict': rslt = t.serialize(output=output) expected = serialize_doctype(doctypes[output]) + \ '\n<html><p>Test</p><br></html>' assert rslt == expected
def test(): base_path = os.path.dirname(os.path.abspath(__file__)) kid.path = kid.TemplatePath([base_path]) ctxt = dict(hello='<world>', hey='ZYX', bozz=None, items=['Number %d' % num for num in range(1, 15)], prefix='#') start = time.clock() template = kid.Template(file='test.kid', **ctxt) print(' --> parse stage: %.4f ms' % ((time.clock() - start) * 1000)) for output in template.generate(): sys.stdout.write(output) print() times = [] for i in range(1000): start = time.clock() list(template.generate()) times.append(time.clock() - start) sys.stdout.write('.') sys.stdout.flush() print() print(' --> render stage: %s ms (average)' % ((sum(times) / len(times) * 1000)))
def SubProcess(morph): """The CGI Script forks off this child function as a child process to perform the TLSMD calculations and write out results files. """ ## close all file descriptors for fd in xrange(0, 25): try: os.close(fd) except OSError: pass ## run TLSMD struct_basename, struct_path = morph.source_path() tlsmd = TLSMDHingePredictor(open(struct_path, "r")) ## output tabulated data files idx_filename, idx_path = morph.chain_datafile_index_path() idx_fobj = open(idx_path, "w") for chain in tlsmd.iter_chains(): filename, path = morph.chain_datafile_path(chain.chain_id) idx_fobj.write(filename + "\n") open(path, "w").write(str(chain.tbl)) idx_fobj.close() ## write out HTML file html_filename, html_path = morph.html_path() template = kid.Template(file = "molmovdb.kid") template.tlsmd = tlsmd template.stylesheet_url = STYLESHEET_URL open(html_path, "w").writelines(template.generate(output = "html"))
def download(self, data): if kid: data = """<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://purl.org/kid/ns#"> <head> <title>PDF Demo</title> </head> <body>%s</body> </html>""" % data test = kid.Template(source=data) data = test.serialize(output='xhtml') result = StringIO.StringIO() pdf = pisa.CreatePDF( StringIO.StringIO(data), result ) if pdf.err: return "We had some errors in HTML" else: cp.response.headers["content-type"] = "application/pdf" return result.getvalue()
def test_layout_error(): from kid.template_util import TemplateLayoutError try: kid.Template(""" <html xmlns:py="http://purl.org/kid/ns#" py:layout="no_layout" /> """).serialize() except TemplateLayoutError, e: e = str(e)
def index(): template = kid.Template(name='home', headline=get_text('startpage'), title=get_text('sitename'), **common_language[DEFAULT_LANGUAGE]) template.cache = False return template.serialize(output='xhtml-strict')
def test_short_form(): # check that the serializer is outputting short-form elements when # no character data is present text = """<?xml version="1.0" encoding="utf-8"?> <test><short /></test>""" template = kid.Template(file=text) #mod.Template() actual = template.serialize().strip() assert actual == text, '%r != %r' % (actual, text)