def test_fast_buffer_encoded(self): s = u"drôl m’a rée « S’il" buf = util.FastEncodingBuffer(encoding='utf-8') buf.write(s[0:10]) buf.write(s[10:]) q = buf.getvalue() eq_(buf.getvalue(), s.encode('utf-8'))
def test_basic(self): t = self._file_template("modtest.html") t2 = self._file_template('subdir/modtest.html') eq_(t.module.__file__, os.path.join(module_base, 'modtest.html.py')) eq_(t2.module.__file__, os.path.join(module_base, 'subdir', 'modtest.html.py'))
def test_unicode_file_lookup(self): lookup = TemplateLookup(directories=[template_base], output_encoding="utf-8", default_filters=["decode.utf8"]) if compat.py3k: template = lookup.get_template("/chs_unicode_py3k.html") else: template = lookup.get_template("/chs_unicode.html") eq_(flatten_result(template.render_unicode(name="毛泽东")), u("毛泽东 是 新中国的主席<br/> Welcome 你 to 北京."))
def test_outer_scope(self): t = Template(""" <%def name="a()"> a: x is ${x} </%def> <%def name="b()"> <%def name="c()"> <% x = 10 %> c. x is ${x}. ${a()} </%def> b. ${c()} </%def> ${b()} x is ${x} """) eq_( flatten_result(t.render(x=5)), "b. c. x is 10. a: x is 5 x is 5" )
def test_stdin_success(self): with self._capture_output_fixture() as stdout: with mock.patch("sys.stdin", mock.Mock( read=mock.Mock(return_value="hello world ${x}"))): cmdline(["--var", "x=5", "-"]) eq_(stdout.write.mock_calls[0][1][0], "hello world 5")
def test_metadata_two(self): t = Template(""" Text Text % if bar: ${expression} % endif <%block name="foo"> hi block </%block> """, uri="/some/template") eq_( ModuleInfo.get_module_source_metadata(t.code, full_line_map=True), { 'full_line_map': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 4, 5, 5, 5, 7, 7, 7, 7, 7, 10, 10, 10, 10, 10, 10, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8], 'source_encoding': 'ascii', 'filename': None, 'line_map': {33: 10, 39: 8, 45: 8, 14: 0, 51: 45, 23: 1, 24: 4, 25: 5, 26: 5, 27: 5, 28: 7}, 'uri': '/some/template'} )
def test_fileargs_lookup(self): l = lookup.TemplateLookup(cache_dir=module_base, cache_type='file') l.put_string("test", """ <%! callcount = [0] %> <%def name="foo()" cached="True"> this is foo <% callcount[0] += 1 %> </%def> ${foo()} ${foo()} ${foo()} callcount: ${callcount} """) t = l.get_template('test') m = self._install_mock_cache(t) assert result_lines(l.get_template('test').render()) == [ 'this is foo', 'this is foo', 'this is foo', 'callcount: [1]', ] eq_(m.kwargs, {'dir': module_base, 'type': 'file'})
def test_args_complete(self): t = Template( """ <%%def name="foo()" cached="True" cache_timeout="30" cache_dir="%s" cache_type="file" cache_key='somekey'> this is foo </%%def> ${foo()} """ % module_base ) m = self._install_mock_cache(t) t.render() eq_(m.kwargs, {"dir": module_base, "type": "file", "timeout": 30}) t2 = Template( """ <%%page cached="True" cache_timeout="30" cache_dir="%s" cache_type="file" cache_key='somekey'/> hi """ % module_base ) m = self._install_mock_cache(t2) t2.render() eq_(m.kwargs, {"dir": module_base, "type": "file", "timeout": 30})
def test_fileargs_pagetag(self): t = Template(""" <%%page cache_dir='%s' cache_type='dbm'/> <%%! callcount = [0] %%> <%%def name="foo()" cached="True"> this is foo <%% callcount[0] += 1 %%> </%%def> ${foo()} ${foo()} ${foo()} callcount: ${callcount} """ % module_base) m = self._install_mock_cache(t) assert result_lines(t.render()) == [ 'this is foo', 'this is foo', 'this is foo', 'callcount: [1]', ] eq_(m.kwargs, {'dir': module_base, 'type': 'dbm'})
def test_locate_identifiers(self): """test the location of identifiers in a python code string""" code = """ a = 10 b = 5 c = x * 5 + a + b + q (g,h,i) = (1,2,3) [u,k,j] = [4,5,6] foo.hoho.lala.bar = 7 + gah.blah + u + blah for lar in (1,2,3): gh = 5 x = 12 ("hello world, ", a, b) ("Another expr", c) """ parsed = ast.PythonCode(code, **exception_kwargs) eq_( parsed.declared_identifiers, set( ["a", "b", "c", "g", "h", "i", "u", "k", "j", "gh", "lar", "x"] ), ) eq_( parsed.undeclared_identifiers, set(["x", "q", "foo", "gah", "blah"]), ) parsed = ast.PythonCode("x + 5 * (y-z)", **exception_kwargs) assert parsed.undeclared_identifiers == set(["x", "y", "z"]) assert parsed.declared_identifiers == set()
def test_interpret_expression_from_arg_two(self): """test that cache_key=${foo} gets its value from the 'foo' argument regardless of it being passed from the context. This is here testing that there's no change to existing behavior before and after #191. """ t = Template(""" <%def name="layout(foo)" cached="True" cache_key="${foo}"> foo: ${value} </%def> ${layout(3)} """, cache_impl="plain") eq_( result_lines(t.render(foo='foo', value=1)), ["foo: 1"] ) eq_( result_lines(t.render(foo='bar', value=2)), ["foo: 1"] )
def test_locate_identifiers(self): """test the location of identifiers in a python code string""" code = """ a = 10 b = 5 c = x * 5 + a + b + q (g,h,i) = (1,2,3) [u,k,j] = [4,5,6] foo.hoho.lala.bar = 7 + gah.blah + u + blah for lar in (1,2,3): gh = 5 x = 12 ("hello world, ", a, b) ("Another expr", c) """ parsed = ast.PythonCode(code, **exception_kwargs) eq_( parsed.declared_identifiers, set(['a', 'b', 'c', 'g', 'h', 'i', 'u', 'k', 'j', 'gh', 'lar', 'x']) ) eq_( parsed.undeclared_identifiers, set(['x', 'q', 'foo', 'gah', 'blah']) ) parsed = ast.PythonCode("x + 5 * (y-z)", **exception_kwargs) assert parsed.undeclared_identifiers == set(['x', 'y', 'z']) assert parsed.declared_identifiers == set()
def test_locate_identifiers_7(self): code = """ import foo.bar """ parsed = ast.PythonCode(code, **exception_kwargs) eq_(parsed.declared_identifiers, set(['foo'])) eq_(parsed.undeclared_identifiers, set())
def test_locate_identifiers_10(self): code = """ lambda q: q + 5 """ parsed = ast.PythonCode(code, **exception_kwargs) eq_(parsed.declared_identifiers, set()) eq_(parsed.undeclared_identifiers, set())
def test_fileargs_lookup(self): l = lookup.TemplateLookup(cache_dir=module_base, cache_type="file") l.put_string( "test", """ <%! callcount = [0] %> <%def name="foo()" cached="True"> this is foo <% callcount[0] += 1 %> </%def> ${foo()} ${foo()} ${foo()} callcount: ${callcount} """, ) t = l.get_template("test") m = self._install_mock_cache(t) assert result_lines(l.get_template("test").render()) == [ "this is foo", "this is foo", "this is foo", "callcount: [1]", ] eq_(m.kwargs, {"dir": module_base, "type": "file"})
def test_metadata(self): t = Template(""" Text Text % if bar: ${expression} % endif <%include file='bar'/> """, uri="/some/template") eq_( ModuleInfo.get_module_source_metadata(t.code, full_line_map=True), { 'full_line_map': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 1, 4, 5, 5, 5, 7, 8, 8, 8, 8, 8, 8, 8], 'source_encoding': 'ascii', 'filename': None, 'line_map': {34: 28, 14: 0, 21: 1, 22: 4, 23: 5, 24: 5, 25: 5, 26: 7, 27: 8, 28: 8}, 'uri': '/some/template' } )
def test_scope_eight(self): """test that the initial context counts as 'enclosing' scope, for nested defs""" t = Template(""" <%def name="enclosing()"> <%def name="a()"> a: x is ${x} </%def> <%def name="b()"> <% x = 10 %> b. x is ${x}. ${a()} </%def> ${b()} </%def> ${enclosing()} """) eq_( flatten_result(t.render(x=5)), "b. x is 10. a: x is 5" )
def test_fileargs_implicit(self): l = lookup.TemplateLookup(module_directory=module_base) l.put_string( "test", """ <%! callcount = [0] %> <%def name="foo()" cached="True" cache_type='dbm'> this is foo <% callcount[0] += 1 %> </%def> ${foo()} ${foo()} ${foo()} callcount: ${callcount} """) m = self._install_mock_cache(l.get_template('test')) assert result_lines(l.get_template('test').render()) == [ 'this is foo', 'this is foo', 'this is foo', 'callcount: [1]', ] eq_(m.kwargs, {'type': 'dbm'})
def test_locate_identifiers_6(self): code = """ def foo(): return bar() """ parsed = ast.PythonCode(code, **exception_kwargs) eq_(parsed.undeclared_identifiers, set(['bar'])) code = """ def lala(x, y): return x, y, z print(x) """ parsed = ast.PythonCode(code, **exception_kwargs) eq_(parsed.undeclared_identifiers, set(['z', 'x'])) eq_(parsed.declared_identifiers, set(['lala'])) code = """ def lala(x, y): def hoho(): def bar(): z = 7 print(z) """ parsed = ast.PythonCode(code, **exception_kwargs) eq_(parsed.undeclared_identifiers, set(['z'])) eq_(parsed.declared_identifiers, set(['lala']))
def test_function_decl_2(self): """test getting the arguments from a function""" code = "def foo(a, b, c=None, *args, **kwargs):pass" parsed = ast.FunctionDecl(code, **exception_kwargs) eq_(parsed.funcname, 'foo') eq_(parsed.argnames, ['a', 'b', 'c', 'args', 'kwargs'])
def test_fileargs_lookup(self): l = lookup.TemplateLookup(cache_dir=module_base, cache_type='file') l.put_string( "test", """ <%! callcount = [0] %> <%def name="foo()" cached="True"> this is foo <% callcount[0] += 1 %> </%def> ${foo()} ${foo()} ${foo()} callcount: ${callcount} """) t = l.get_template('test') m = self._install_mock_cache(t) assert result_lines(l.get_template('test').render()) == [ 'this is foo', 'this is foo', 'this is foo', 'callcount: [1]', ] eq_(m.kwargs, {'dir': module_base, 'type': 'file'})
def test_inter_def(self): """test defs calling each other""" template = Template(""" ${b()} <%def name="a()">\ im a </%def> <%def name="b()"> im b and heres a: ${a()} </%def> <%def name="c()"> im c </%def> """) # check that "a" is declared in "b", but not in "c" if compat.py3k: assert "a" not in template.module.render_c.__code__.co_varnames assert "a" in template.module.render_b.__code__.co_varnames else: assert "a" not in template.module.render_c.func_code.co_varnames assert "a" in template.module.render_b.func_code.co_varnames # then test output eq_( flatten_result(template.render()), "im b and heres a: im a" )
def test_url_escaping(self): t = Template(""" http://example.com/?bar=${bar | u}&v=1 """) eq_(flatten_result(t.render(bar=u"酒吧bar")), "http://example.com/?bar=%E9%85%92%E5%90%A7bar&v=1")
def test_scope_five(self): """test that variables are pulled from 'enclosing' scope before context.""" # same as test four, but adds a scope around it. t = Template(""" <%def name="enclosing()"> <% x = 5 %> <%def name="a()"> this is a. x is ${x}. </%def> <%def name="b()"> <% x = 9 %> this is b. x is ${x}. calling a. ${a()} </%def> ${b()} </%def> ${enclosing()} """) eq_( flatten_result(t.render()), "this is b. x is 9. calling a. this is a. x is 5." )
def test_scope_nine(self): """test that 'enclosing scope' doesnt get exported to other templates""" l = lookup.TemplateLookup() l.put_string( "main", """ <% x = 5 %> this is main. <%include file="secondary"/> """, ) l.put_string( "secondary", """ this is secondary. x is ${x} """, ) eq_( flatten_result(l.get_template("main").render(x=2)), "this is main. this is secondary. x is 2", )
def test_quoting(self): t = Template(""" foo ${bar | h} """) eq_(flatten_result(t.render(bar="<'some bar'>")), "foo <'some bar'>")
def test_function_decl(self): """test getting the arguments from a function""" code = "def foo(a, b, c=None, d='hi', e=x, f=y+7):pass" parsed = ast.FunctionDecl(code, **exception_kwargs) eq_(parsed.funcname, 'foo') eq_(parsed.argnames, ['a', 'b', 'c', 'd', 'e', 'f'])
def test_scope_ten(self): t = Template(""" <%def name="a()"> <%def name="b()"> <% y = 19 %> b/c: ${c()} b/y: ${y} </%def> <%def name="c()"> c/y: ${y} </%def> <% # we assign to "y". but the 'enclosing # scope' of "b" and "c" is from # the "y" on the outside y = 10 %> a/y: ${y} a/b: ${b()} </%def> <% y = 7 %> main/a: ${a()} main/y: ${y} """) eq_( flatten_result(t.render()), "main/a: a/y: 10 a/b: b/c: c/y: 10 b/y: 19 main/y: 7" )
def test_fileargs_implicit(self): l = lookup.TemplateLookup(module_directory=module_base) l.put_string( "test", """ <%! callcount = [0] %> <%def name="foo()" cached="True" cache_type='dbm'> this is foo <% callcount[0] += 1 %> </%def> ${foo()} ${foo()} ${foo()} callcount: ${callcount} """, ) m = self._install_mock_cache(l.get_template("test")) assert result_lines(l.get_template("test").render()) == [ "this is foo", "this is foo", "this is foo", "callcount: [1]", ] eq_(m.kwargs, {"type": "dbm"})
def test_fast_buffer_encoded(self): s = u("drôl m’a rée « S’il") buf = util.FastEncodingBuffer(encoding='utf-8') buf.write(s[0:10]) buf.write(s[10:]) q = buf.getvalue() eq_(buf.getvalue(), s.encode('utf-8'))
def test_locate_identifiers(self): """test the location of identifiers in a python code string""" code = """ a = 10 b = 5 c = x * 5 + a + b + q (g,h,i) = (1,2,3) [u,k,j] = [4,5,6] foo.hoho.lala.bar = 7 + gah.blah + u + blah for lar in (1,2,3): gh = 5 x = 12 ("hello world, ", a, b) ("Another expr", c) """ parsed = ast.PythonCode(code, **exception_kwargs) eq_( parsed.declared_identifiers, set([ 'a', 'b', 'c', 'g', 'h', 'i', 'u', 'k', 'j', 'gh', 'lar', 'x' ])) eq_(parsed.undeclared_identifiers, set(['x', 'q', 'foo', 'gah', 'blah'])) parsed = ast.PythonCode("x + 5 * (y-z)", **exception_kwargs) assert parsed.undeclared_identifiers == set(['x', 'y', 'z']) assert parsed.declared_identifiers == set()
def test_new_syntax(self): """test foo:bar syntax, including multiline args and expression eval.""" # note the trailing whitespace in the bottom ${} expr, need to strip # that off < python 2.7 t = Template(""" <%def name="foo(x, y, q, z)"> ${x} ${y} ${q} ${",".join("%s->%s" % (a, b) for a, b in z)} </%def> <%self:foo x="this is x" y="${'some ' + 'y'}" q=" this is q" z="${[ (1, 2), (3, 4), (5, 6) ] }"/> """) eq_( result_lines(t.render()), ['this is x', 'some y', 'this', 'is', 'q', '1->2,3->4,5->6'] )
def test_file_success(self): with self._capture_output_fixture() as stdout: cmdline( ["--var", "x=5", os.path.join(template_base, "cmd_good.mako")] ) eq_(stdout.write.mock_calls[0][1][0], "hello world 5")
def test_inter_def(self): """test defs calling each other""" template = Template(""" ${b()} <%def name="a()">\ im a </%def> <%def name="b()"> im b and heres a: ${a()} </%def> <%def name="c()"> im c </%def> """) # check that "a" is declared in "b", but not in "c" if compat.py3k: assert "a" not in template.module.render_c.__code__.co_varnames assert "a" in template.module.render_b.__code__.co_varnames else: assert "a" not in template.module.render_c.__code__.co_varnames assert "a" in template.module.render_b.__code__.co_varnames # then test output eq_(flatten_result(template.render()), "im b and heres a: im a")
def test_scope_ten(self): t = Template(""" <%def name="a()"> <%def name="b()"> <% y = 19 %> b/c: ${c()} b/y: ${y} </%def> <%def name="c()"> c/y: ${y} </%def> <% # we assign to "y". but the 'enclosing # scope' of "b" and "c" is from # the "y" on the outside y = 10 %> a/y: ${y} a/b: ${b()} </%def> <% y = 7 %> main/a: ${a()} main/y: ${y} """) eq_(flatten_result(t.render()), "main/a: a/y: 10 a/b: b/c: c/y: 10 b/y: 19 main/y: 7")
def test_scope_five(self): """test that variables are pulled from 'enclosing' scope before context.""" # same as test four, but adds a scope around it. t = Template(""" <%def name="enclosing()"> <% x = 5 %> <%def name="a()"> this is a. x is ${x}. </%def> <%def name="b()"> <% x = 9 %> this is b. x is ${x}. calling a. ${a()} </%def> ${b()} </%def> ${enclosing()} """) eq_(flatten_result(t.render()), "this is b. x is 9. calling a. this is a. x is 5.")
def test_locate_identifiers_11(self): code = """ def x(q): return q + 5 """ parsed = ast.PythonCode(code, **exception_kwargs) eq_(parsed.declared_identifiers, set(['x'])) eq_(parsed.undeclared_identifiers, set())
def test_def_blankargs(self): template = Template(""" <%def name="mycomp()"> hello mycomp ${variable} </%def> ${mycomp()}""") eq_(template.render(variable='hi').strip(), "hello mycomp hi")
def test_encode_filter(self): t = Template("""# coding: utf-8 some stuff.... ${x} """, default_filters=['decode.utf8']) eq_( t.render_unicode(x=u("voix m’a réveillé")).strip(), u("some stuff.... voix m’a réveillé"))
def test_encode_filter(self): t = Template("""# coding: utf-8 some stuff.... ${x} """, default_filters=['decode.utf8']) eq_( t.render_unicode(x=u("voix m’a réveillé")).strip(), u("some stuff.... voix m’a réveillé") )
def test_fast_buffer_truncate(self): buf = util.FastEncodingBuffer() buf.write("string a ") buf.write("string b") buf.truncate() buf.write("string c ") buf.write("string d") eq_(buf.getvalue(), "string c string d")
def test_encode_filter_non_str(self): t = Template("""# coding: utf-8 some stuff.... ${x} """, default_filters=['decode.utf8']) eq_( t.render_unicode(x=3).strip(), u("some stuff.... 3") )
def test_custom_args_page(self): t = Template(""" <%page cached="True" cache_region="myregion" cache_timeout="50" cache_foo="foob"/> """, cache_args={'use_beaker':False}) m = self._install_mock_cache(t) t.render() eq_(m.kwargs, {'use_beaker':False, 'region':'myregion', 'timeout':50, 'foo':'foob'})
def test_url_escaping(self): t = Template(""" http://example.com/?bar=${bar | u}&v=1 """) eq_( flatten_result(t.render(bar=u"酒吧bar")), "http://example.com/?bar=%E9%85%92%E5%90%A7bar&v=1" )
def test_quoting(self): t = Template(""" foo ${bar | h} """) eq_( flatten_result(t.render(bar="<'some bar'>")), "foo <'some bar'>" )