def testMakeTemplateGroup(self): child_template = jsontemplate.Template('- {@}') top = jsontemplate.Template( B(""" Directory listing for {root} {.repeated section children} {@|template child} {.end} """)) data = { 'root': '/home', 'children': [ 'bin', 'work', ], } self.verify.Raises(jsontemplate.EvaluationError, top.expand, data) jsontemplate.MakeTemplateGroup({'child': child_template, 'top': top}) self.verify.LongStringsEqual( top.expand(data), B(""" Directory listing for /home - bin - work """))
def testSelfRecursion(self): data = { 'name': '/home', 'files': ['a.txt', 'b.txt'], 'dirs': [ { 'name': 'andy', 'files': ['1.txt', '2.txt'] }, ], } t = jsontemplate.Template( B(""" {name} {.repeated section dirs} {@|template SELF} {.end} {.repeated section files} {@} {.end} """)) # TODO: A nicer job with whitespace self.verify.LongStringsEqual(t.expand(data), B(""" /home andy 1.txt 2.txt a.txt b.txt """), ignore_all_whitespace=True) # Now CHAIN a regular formatter with a template-formatter t = jsontemplate.Template( B(""" {name} {.repeated section dirs} {@|template SELF|upper} {.end} {.repeated section files} {@} {.end} """)) # TODO: A nicer job with whitespace self.verify.LongStringsEqual(t.expand(data), B(""" /home ANDY 1.TXT 2.TXT a.txt b.txt """), ignore_all_whitespace=True)
def testMutualRecursion(self): class NodePredicates(jsontemplate.FunctionRegistry): def Lookup(self, user_str): """The node type is also a predicate.""" func = lambda v, context, args: (v['type'] == user_str) return func, None # No arguments expr = jsontemplate.Template(B(""" {.if PLUS} {a} + {b} {.or MINUS} {a} - {b} {.or MULT} {a} * {b} {.or DIV} {a} / {b} {.or FUNC} {@|template func} {.end} """), more_predicates=NodePredicates()) func = jsontemplate.Template( B(""" function ({.repeated section params}{@} {.end}) { {.repeated section exprs} {@|template expr} {.end} } """)) jsontemplate.MakeTemplateGroup({'func': func, 'expr': expr}) self.verify.LongStringsEqual( expr.expand({ 'type': 'PLUS', 'a': 1, 'b': 2 }), '1 + 2\n') self.verify.LongStringsEqual(expr.expand({ 'type': 'FUNC', 'params': ['x'], 'exprs': [{ 'type': 'PLUS', 'a': 3, 'b': 4 }] }), B(""" function (x ) { 3 + 4 } """), ignore_all_whitespace=True)
def testMultipleTemplateGroups(self): style = jsontemplate.Template('') body = jsontemplate.Template('') jsontemplate.MakeTemplateGroup({'style': style, 'body': body}) # Can't do it twice self.verify.Raises(jsontemplate.UsageError, jsontemplate.MakeTemplateGroup, { 'style': style, 'body': body })
def testByteTemplateMixed(self): # (Latin-1) Byte string template t = jsontemplate.Template('Hello \xb5 {name}') # Byte string OK self.verify.Equal(t.expand({u'name': '\xb5'}), 'Hello \xb5 \xb5') self.verify.Raises(UnicodeDecodeError, t.expand, {u'name': u'\u00b5'}) # Byte string template without any special chars t = jsontemplate.Template('Hello {name}') # Unicode data is OK self.verify.Equal(t.expand({u'name': u'\u00b5'}), u'Hello \u00B5')
def testRepeatedSectionFormatter(self): def _Columns(x): n = len(x) i = 0 columns = [] while True: columns.append(x[i:i + 3]) i += 3 if i >= len(x): break return columns t = jsontemplate.Template(B(""" {.repeated section dirs | columns} {.repeated section @}{@} {.end} {.end} """), more_formatters={'columns': _Columns}) d = {'dirs': ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']} self.verify.LongStringsEqual( B(""" a b c d e f g h i j """), t.expand(d))
def testTemplateReference(self): # TITLE is referenced body_template = jsontemplate.Template( B(""" {.define TITLE} Definition of '{word}' {.end} {.define BODY} <h3>{.template TITLE}</h3> {definition} {.end} """)) s = body_template.expand(self.DATA, style=self.STYLE) self.verify.LongStringsEqual( B(""" <title>Definition of 'hello' </title> <body> <h3>Definition of 'hello' </h3> greeting </body> """), s)
def testOption(self): # Now do it with "strip-line" body_template = jsontemplate.Template( B(""" {.OPTION strip-line} {.define TITLE} Definition of '{word}' {.end} {.END} {.define BODY} <h3>{.template TITLE}</h3> {definition} {.end} """)) s = body_template.expand(self.DATA, style=self.STYLE) self.verify.LongStringsEqual( B(""" <title>Definition of 'hello'</title> <body> <h3>Definition of 'hello'</h3> greeting </body> """), s)
def testMoreFormattersAsDict(self): t = jsontemplate.Template('Hello {name|lower} {name|upper}', more_formatters={ 'lower': lambda v: v.lower(), 'upper': lambda v: v.upper(), }) self.verify.Equal(t.expand({'name': 'World'}), 'Hello world WORLD')
def testTemplateExpand(self): t = jsontemplate.Template('Hello {name}') self.verify.Equal(t.expand({'name': 'World'}), 'Hello World') # Test the kwarg syntax self.verify.Equal(t.expand(name='World'), 'Hello World') # Only accepts one argument self.verify.Raises(TypeError, t.expand, {'name': 'world'}, 'extra')
def testConflictingGroups(self): t = jsontemplate.Template( B(""" {.define TITLE} Definition of '{word}' {.end} {.define BODY} <h3>{.template TITLE}</h3> {definition} {.end} """))
def testUnicodeTemplateMixed(self): # Unicode template t = jsontemplate.Template(u'Hello {name}') # Encoded utf-8 data is OK self.verify.Equal(t.expand({u'name': '\xc2\xb5'}), u'Hello \xb5') # Latin-1 data is not OK self.verify.Raises(UnicodeDecodeError, t.expand, {u'name': '\xb5'}) # Byte string \0 turns into code point 0 self.verify.Equal(t.expand({u'name': '\0'}), u'Hello \u0000')
def testExecute(self): """Test the .execute() method.""" t = jsontemplate.Template('Hello {name}') tokens = [] t.execute({'name': 'World'}, tokens.append) self.verify.In('Hello ', tokens) tokens = [] # Legacy alias for execute() t.render({'name': 'World'}, tokens.append) self.verify.In('Hello ', tokens)
def testMoreFormattersAsFunction(self): def MyFormatters(user_str): if user_str == 'lower': return lambda v: v.lower() elif user_str == 'upper': return lambda v: v.upper() else: return None t = jsontemplate.Template('Hello {name|lower} {name|upper}', more_formatters=MyFormatters) self.verify.Equal(t.expand({'name': 'World'}), 'Hello world WORLD')
def testStyleWithTemplateGroup(self): body_template = jsontemplate.Template( B(""" {.define TITLE} Definition of '{word}' {.end} {.define BODY} <h3>{.template TITLE}</h3> {definition} {.template t1} {@|template t1} {word|template t2} {.end} """)) t1 = jsontemplate.Template('T1') t2 = jsontemplate.Template('{@}') # Create a template group, and make sure it doesn't mess up how .template # TITLE is referenced. jsontemplate.MakeTemplateGroup({ 'body': body_template, 't1': t1, 't2': t2, }) s = body_template.expand(self.DATA, style=self.STYLE) self.verify.LongStringsEqual( B(""" <title>Definition of 'hello' </title> <body> <h3>Definition of 'hello' </h3> greeting T1T1 hello </body> """), s)
def testMoreFormattersAsClass(self): class MyFormatters(jsontemplate.FunctionRegistry): def Lookup(self, user_str): """Returns func, args, type.""" if user_str == 'lower': func = lambda v, context, args: v.lower() elif user_str == 'upper': func = lambda v, context, args: v.upper() else: func = None return func, None t = jsontemplate.Template('Hello {name|lower} {name|upper}', more_formatters=MyFormatters()) self.verify.Equal(t.expand({'name': 'World'}), 'Hello world WORLD')
def testScope(self): # From the wiki t = jsontemplate.Template(""" {internal_link_prefix|htmltag} <p> <b>HTML Source</b> <ul> {.repeated section html-source-links} <p> <a href="{internal_link_prefix|htmltag}raw-html/data/wiki/columns-{num-cols}/{url-name}"> {anchor|html} </a> <p> {.end} </ul> </p> """) d = { 'internal_link_prefix': 'http://', 'url-name': 'Wiki', 'html-source-links': [ { 'num-cols': 1, 'anchor': '1' }, { 'num-cols': 2, 'anchor': '2' }, ], } # Bug fix t.expand(d)
def testTemplateTrace(self): trace = jsontemplate.Trace() t = jsontemplate.Template('Hello {name}') t.expand({'name': 'World'}, trace=trace) self.verify.Equal(trace.exec_depth, 1)
def testSimpleUnicodeSubstitution(self): t = jsontemplate.Template(u'Hello {name}') self.verify.Equal(t.expand({u'name': u'World'}), u'Hello World')
class StylesTest(taste.Test): # Used in multiple tests STYLE = jsontemplate.Template( B(""" <title>{.template TITLE}</title> <body> {.template BODY} </body> """)) DATA = { 'word': 'hello', 'definition': 'greeting', } def testTemplateReference(self): # TITLE is referenced body_template = jsontemplate.Template( B(""" {.define TITLE} Definition of '{word}' {.end} {.define BODY} <h3>{.template TITLE}</h3> {definition} {.end} """)) s = body_template.expand(self.DATA, style=self.STYLE) self.verify.LongStringsEqual( B(""" <title>Definition of 'hello' </title> <body> <h3>Definition of 'hello' </h3> greeting </body> """), s) def testOption(self): # Now do it with "strip-line" body_template = jsontemplate.Template( B(""" {.OPTION strip-line} {.define TITLE} Definition of '{word}' {.end} {.END} {.define BODY} <h3>{.template TITLE}</h3> {definition} {.end} """)) s = body_template.expand(self.DATA, style=self.STYLE) self.verify.LongStringsEqual( B(""" <title>Definition of 'hello'</title> <body> <h3>Definition of 'hello'</h3> greeting </body> """), s) def testStyleWithTemplateGroup(self): body_template = jsontemplate.Template( B(""" {.define TITLE} Definition of '{word}' {.end} {.define BODY} <h3>{.template TITLE}</h3> {definition} {.template t1} {@|template t1} {word|template t2} {.end} """)) t1 = jsontemplate.Template('T1') t2 = jsontemplate.Template('{@}') # Create a template group, and make sure it doesn't mess up how .template # TITLE is referenced. jsontemplate.MakeTemplateGroup({ 'body': body_template, 't1': t1, 't2': t2, }) s = body_template.expand(self.DATA, style=self.STYLE) self.verify.LongStringsEqual( B(""" <title>Definition of 'hello' </title> <body> <h3>Definition of 'hello' </h3> greeting T1T1 hello </body> """), s)
def testExpandWithStyle(self): # TODO: REMOVE with expand_with_style and execute_with_style_LEGACY data = { 'title': 'Greetings!', 'body': { 'names': ['andy', 'bob'] }, } body_template = jsontemplate.Template( B(""" {.repeated section names} Hello {@} {.end} """)) style = jsontemplate.Template( B(""" {title} {.section body}{@|raw}{.end} """)) result = jsontemplate.expand_with_style(body_template, style, data) self.verify.LongStringsEqual( B(""" Greetings! Hello andy Hello bob """), result) self.verify.Raises(jsontemplate.EvaluationError, jsontemplate.expand_with_style, body_template, style, data, 'foo') # New style with old API body_template = jsontemplate.Template( B(""" {.define TITLE} Definition of '{word}' {.end} {.define BODY} <h3>{.template TITLE}</h3> {definition} {.end} """)) style = jsontemplate.Template( B(""" <title>{.template TITLE}</title> <body> {.template BODY} </body> """)) data = { 'word': 'hello', 'definition': 'greeting', } s = jsontemplate.expand_with_style(body_template, style, data) self.verify.LongStringsEqual( B(""" <title>Definition of 'hello' </title> <body> <h3>Definition of 'hello' </h3> greeting </body> """), s)