diff options
| author | Mike Bayer <mike_mp@zzzcomputing.com> | 2011-01-19 10:33:00 -0500 |
|---|---|---|
| committer | Mike Bayer <mike_mp@zzzcomputing.com> | 2011-01-19 10:33:00 -0500 |
| commit | 6779081b32cfb237062da8bc623a27d47301ce4c (patch) | |
| tree | fc3372c916cfc9efc61cccffde74528772532b37 /test | |
| parent | 76e622b46ef71eddfbcd1232ee08b4e55c88c363 (diff) | |
| download | external_python_mako-6779081b32cfb237062da8bc623a27d47301ce4c.tar.gz external_python_mako-6779081b32cfb237062da8bc623a27d47301ce4c.tar.bz2 external_python_mako-6779081b32cfb237062da8bc623a27d47301ce4c.zip | |
- now that trailing whitespace comes up in red, need to get rid of it
Diffstat (limited to 'test')
| -rw-r--r-- | test/__init__.py | 20 | ||||
| -rw-r--r-- | test/foo/test_ns.py | 2 | ||||
| -rw-r--r-- | test/sample_module_namespace.py | 2 | ||||
| -rw-r--r-- | test/templates/gettext.mako | 4 | ||||
| -rw-r--r-- | test/templates/internationalization.html | 4 | ||||
| -rw-r--r-- | test/test_ast.py | 46 | ||||
| -rw-r--r-- | test/test_babelplugin.py | 4 | ||||
| -rw-r--r-- | test/test_cache.py | 44 | ||||
| -rw-r--r-- | test/test_call.py | 54 | ||||
| -rw-r--r-- | test/test_decorators.py | 10 | ||||
| -rw-r--r-- | test/test_def.py | 80 | ||||
| -rw-r--r-- | test/test_exceptions.py | 26 | ||||
| -rw-r--r-- | test/test_filters.py | 46 | ||||
| -rw-r--r-- | test/test_inheritance.py | 26 | ||||
| -rw-r--r-- | test/test_lexer.py | 34 | ||||
| -rw-r--r-- | test/test_lookup.py | 14 | ||||
| -rw-r--r-- | test/test_lru.py | 34 | ||||
| -rw-r--r-- | test/test_namespace.py | 114 | ||||
| -rw-r--r-- | test/test_pygen.py | 6 | ||||
| -rw-r--r-- | test/test_template.py | 132 | ||||
| -rw-r--r-- | test/test_tgplugin.py | 2 |
21 files changed, 352 insertions, 352 deletions
diff --git a/test/__init__.py b/test/__init__.py index f9e3118..d2a1f25 100644 --- a/test/__init__.py +++ b/test/__init__.py @@ -10,34 +10,34 @@ template_base = os.path.join(os.path.dirname(__file__), 'templates') module_base = os.path.join(template_base, 'modules') class TemplateTest(unittest.TestCase): - + def _file_template(self, filename, **kw): filepath = self._file_path(filename) return Template(uri=filename, filename=filepath, module_directory=module_base, **kw) - + def _file_path(self, filename): name, ext = os.path.splitext(filename) - + if py3k: py3k_path = os.path.join(template_base, name + "_py3k" + ext) if os.path.exists(py3k_path): return py3k_path - + return os.path.join(template_base, filename) - + def _do_file_test(self, filename, expected, filters=None, unicode_=True, template_args=None, **kw): t1 = self._file_template(filename, **kw) self._do_test(t1, expected, filters=filters, unicode_=unicode_, template_args=template_args) - + def _do_memory_test(self, source, expected, filters=None, unicode_=True, template_args=None, **kw): t1 = Template(text=source, **kw) self._do_test(t1, expected, filters=filters, unicode_=unicode_, template_args=template_args) - + def _do_test(self, template, expected, filters=None, template_args=None, unicode_=True): if template_args is None: template_args = {} @@ -45,11 +45,11 @@ class TemplateTest(unittest.TestCase): output = template.render_unicode(**template_args) else: output = template.render(**template_args) - + if filters: output = filters(output) eq_(output, expected) - + def eq_(a, b, msg=None): """Assert a == b, with repr messaging on failure.""" assert a == b, msg or "%r != %r" % (a, b) @@ -64,7 +64,7 @@ def assert_raises(except_cls, callable_, *args, **kw): success = False except except_cls, e: success = True - + # assert outside the block so it works for AssertionError too ! assert success, "Callable did not raise an exception" diff --git a/test/foo/test_ns.py b/test/foo/test_ns.py index 084fe97..7a2425d 100644 --- a/test/foo/test_ns.py +++ b/test/foo/test_ns.py @@ -1,7 +1,7 @@ def foo1(context): context.write("this is foo1.") return '' - + def foo2(context, x): context.write("this is foo2, x is " + x) return ''
\ No newline at end of file diff --git a/test/sample_module_namespace.py b/test/sample_module_namespace.py index 084fe97..7a2425d 100644 --- a/test/sample_module_namespace.py +++ b/test/sample_module_namespace.py @@ -1,7 +1,7 @@ def foo1(context): context.write("this is foo1.") return '' - + def foo2(context, x): context.write("this is foo2, x is " + x) return ''
\ No newline at end of file diff --git a/test/templates/gettext.mako b/test/templates/gettext.mako index 8b7dfbb..df47d10 100644 --- a/test/templates/gettext.mako +++ b/test/templates/gettext.mako @@ -40,7 +40,7 @@ top = gettext('Begin') ## TRANSLATOR: Good bye ${_('Goodbye')} </div> - + <%def name="makerow(row=_('Babel'), count=1)"> <!-- ${ungettext('hella', 'hellas', count)} --> % for i in range(count): @@ -67,7 +67,7 @@ top = gettext('Begin') <div id="end"> <a href="#top"> ## TRANSLATOR: you won't see this either - + ${_('Top')} </a> </div> diff --git a/test/templates/internationalization.html b/test/templates/internationalization.html index 12ae25b..da5b61c 100644 --- a/test/templates/internationalization.html +++ b/test/templates/internationalization.html @@ -1,7 +1,7 @@ <div class="rst-docs"> - + <h1 class="pudge-member-page-heading">Internationalization, Localization and Unicode</h1> - + <table rules="none" frame="void" class="docinfo"> <col class="docinfo-name"></col> <col class="docinfo-content"></col> diff --git a/test/test_ast.py b/test/test_ast.py index b9fe948..adea08a 100644 --- a/test/test_ast.py +++ b/test/test_ast.py @@ -25,7 +25,7 @@ for lar in (1,2,3): parsed = ast.PythonCode(code, **exception_kwargs) assert parsed.declared_identifiers == set(['a','b','c', 'g', 'h', 'i', 'u', 'k', 'j', 'gh', 'lar', 'x']) assert 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() @@ -55,7 +55,7 @@ for y in range(1, y): """ parsed = ast.PythonCode(code, **exception_kwargs) assert parsed.undeclared_identifiers == set(['x', 'y', 'z', 'q', 'range']) - + def test_locate_identifiers_4(self): if util.py3k: code = """ @@ -63,18 +63,18 @@ x = 5 (y, ) def mydef(mydefarg): print("mda is", mydefarg) -""" +""" else: code = """ x = 5 (y, ) def mydef(mydefarg): print "mda is", mydefarg -""" +""" parsed = ast.PythonCode(code, **exception_kwargs) assert parsed.undeclared_identifiers == set(['y']) assert parsed.declared_identifiers == set(['mydef', 'x']) - + def test_locate_identifiers_5(self): if util.py3k: code = """ @@ -84,7 +84,7 @@ except: print(y) """ else: - + code = """ try: print x @@ -93,7 +93,7 @@ except: """ parsed = ast.PythonCode(code, **exception_kwargs) assert parsed.undeclared_identifiers == set(['x', 'y']) - + def test_locate_identifiers_6(self): code = """ def foo(): @@ -101,7 +101,7 @@ def foo(): """ parsed = ast.PythonCode(code, **exception_kwargs) assert parsed.undeclared_identifiers == set(['bar']) - + if util.py3k: code = """ def lala(x, y): @@ -117,7 +117,7 @@ print x parsed = ast.PythonCode(code, **exception_kwargs) assert parsed.undeclared_identifiers == set(['z', 'x']) assert parsed.declared_identifiers == set(['lala']) - + if util.py3k: code = """ def lala(x, y): @@ -137,7 +137,7 @@ print z parsed = ast.PythonCode(code, **exception_kwargs) assert parsed.undeclared_identifiers == set(['z']) assert parsed.declared_identifiers == set(['lala']) - + def test_locate_identifiers_7(self): code = """ import foo.bar @@ -156,7 +156,7 @@ class Hi(object): parsed = ast.PythonCode(code, **exception_kwargs) assert parsed.declared_identifiers == set(['Hi']) assert parsed.undeclared_identifiers == set() - + def test_locate_identifiers_9(self): code = """ ",".join([t for t in ("a", "b", "c")]) @@ -164,14 +164,14 @@ class Hi(object): parsed = ast.PythonCode(code, **exception_kwargs) assert parsed.declared_identifiers == set(['t']) assert parsed.undeclared_identifiers == set(['t']) - + code = """ [(val, name) for val, name in x] """ parsed = ast.PythonCode(code, **exception_kwargs) assert parsed.declared_identifiers == set(['val', 'name']) assert parsed.undeclared_identifiers == set(['val', 'name', 'x']) - + def test_locate_identifiers_10(self): code = """ lambda q: q + 5 @@ -179,7 +179,7 @@ lambda q: q + 5 parsed = ast.PythonCode(code, **exception_kwargs) eq_(parsed.declared_identifiers, set()) eq_(parsed.undeclared_identifiers, set()) - + def test_locate_identifiers_11(self): code = """ def x(q): @@ -195,12 +195,12 @@ from foo import * import x as bar """ self.assertRaises(exceptions.CompileException, ast.PythonCode, code, **exception_kwargs) - + def test_python_fragment(self): parsed = ast.PythonFragment("for x in foo:", **exception_kwargs) assert parsed.declared_identifiers == set(['x']) assert parsed.undeclared_identifiers == set(['foo']) - + parsed = ast.PythonFragment("try:", **exception_kwargs) if util.py3k: @@ -209,7 +209,7 @@ import x as bar parsed = ast.PythonFragment("except MyException, e:", **exception_kwargs) eq_(parsed.declared_identifiers, set(['e'])) eq_(parsed.undeclared_identifiers, set(['MyException'])) - + def test_argument_list(self): parsed = ast.ArgumentList("3, 5, 'hi', x+5, context.get('lala')", **exception_kwargs) assert parsed.undeclared_identifiers == set(['x', 'context']) @@ -231,7 +231,7 @@ import x as bar parsed = ast.FunctionDecl(code, **exception_kwargs) assert parsed.funcname=='foo' assert parsed.argnames==['a', 'b', 'c', 'args', 'kwargs'] - + def test_expr_generate(self): """test the round trip of expressions to AST back to python source""" x = 1 @@ -242,12 +242,12 @@ import x as bar def lala(arg): return "blah" + arg local_dict = dict(x=x, y=y, foo=F(), lala=lala) - + code = "str((x+7*y) / foo.bar(5,6)) + lala('ho')" astnode = pyparser.parse(code) newcode = pyparser.ExpressionGenerator(astnode).value() assert (eval(code, local_dict) == eval(newcode, local_dict)) - + a = ["one", "two", "three"] hoho = {'somevalue':"asdf"} g = [1,2,3,4,5] @@ -256,7 +256,7 @@ import x as bar astnode = pyparser.parse(code) newcode = pyparser.ExpressionGenerator(astnode).value() assert(eval(code, local_dict) == eval(newcode, local_dict)) - + local_dict={'f':lambda :9, 'x':7} code = "x+f()" astnode = pyparser.parse(code) @@ -269,5 +269,5 @@ import x as bar newcode = pyparser.ExpressionGenerator(astnode).value() assert(eval(code, local_dict)) == eval(newcode, local_dict), "%s != %s" % (code, newcode) - - + + diff --git a/test/test_babelplugin.py b/test/test_babelplugin.py index 2fea024..f6bbf01 100644 --- a/test/test_babelplugin.py +++ b/test/test_babelplugin.py @@ -6,13 +6,13 @@ try: from mako.ext.babelplugin import extract except: babel = None - + import os class ExtractMakoTestCase(TemplateTest): @skip_if(lambda: not babel, 'babel not installed: skipping babelplugin test') - + def test_extract(self): mako_tmpl = open(os.path.join(template_base, 'gettext.mako')) messages = list(extract(mako_tmpl, {'_': None, 'gettext': None, diff --git a/test/test_cache.py b/test/test_cache.py index 11469f5..b2198b5 100644 --- a/test/test_cache.py +++ b/test/test_cache.py @@ -10,7 +10,7 @@ try: except: from nose import SkipTest raise SkipTest("Beaker is required for these tests.") - + class MockCache(object): def __init__(self, realcache): self.realcache = realcache @@ -20,7 +20,7 @@ class MockCache(object): self.kwargs.pop('createfunc', None) self.kwargs.pop('defname', None) return self.realcache.get(key, **kwargs) - + class CacheTest(TemplateTest): def test_def(self): t = Template(""" @@ -33,7 +33,7 @@ class CacheTest(TemplateTest): callcount[0] += 1 %> </%def> - + ${foo()} ${foo()} ${foo()} @@ -63,7 +63,7 @@ class CacheTest(TemplateTest): m = self._install_mock_cache(t) assert t.render().strip() =="callcount: [2]" - + def test_nested_def(self): t = Template(""" <%! @@ -92,7 +92,7 @@ class CacheTest(TemplateTest): 'callcount: [1]', ] assert m.kwargs == {} - + def test_page(self): t = Template(""" <%! @@ -149,7 +149,7 @@ class CacheTest(TemplateTest): assert result_lines(t.render()) == ['hi'] assert m.key == "foo_hi" - + def test_dynamic_key_with_imports(self): lookup = TemplateLookup() lookup.put_string("foo.html", """ @@ -174,7 +174,7 @@ class CacheTest(TemplateTest): "callcount: [1]" ] assert m.kwargs == {} - + def test_fileargs_implicit(self): l = lookup.TemplateLookup(module_directory=module_base) l.put_string("test",""" @@ -193,7 +193,7 @@ class CacheTest(TemplateTest): ${foo()} callcount: ${callcount} """) - + m = self._install_mock_cache(l.get_template('test')) assert result_lines(l.get_template('test').render()) == [ 'this is foo', @@ -202,7 +202,7 @@ class CacheTest(TemplateTest): 'callcount: [1]', ] assert m.kwargs == {'type':'dbm', 'data_dir':module_base} - + def test_fileargs_deftag(self): t = Template(""" <%%! @@ -267,7 +267,7 @@ class CacheTest(TemplateTest): m = self._install_mock_cache(t) t.render() assert m.kwargs == {'data_dir':module_base, 'type':'file', 'expiretime':30} - + t2 = Template(""" <%%page cached="True" cache_timeout="30" cache_dir="%s" cache_type="file" cache_key='somekey'/> hi @@ -294,7 +294,7 @@ class CacheTest(TemplateTest): ${foo()} callcount: ${callcount} """) - + t = l.get_template('test') m = self._install_mock_cache(t) assert result_lines(l.get_template('test').render()) == [ @@ -304,7 +304,7 @@ class CacheTest(TemplateTest): 'callcount: [1]', ] assert m.kwargs == {'data_dir':module_base, 'type':'file'} - + def test_buffered(self): t = Template(""" <%! @@ -318,11 +318,11 @@ class CacheTest(TemplateTest): </%def> """, buffer_filters=["a"]) assert result_lines(t.render()) == ["this is a this is a test", "this is a this is a test"] - + def test_load_from_expired(self): """test that the cache callable can be called safely after the originating template has completed rendering. - + """ t = Template(""" ${foo()} @@ -330,13 +330,13 @@ class CacheTest(TemplateTest): foo </%def> """) - + import time x1 = t.render() time.sleep(3) x2 = t.render() assert x1.strip() == x2.strip() == "foo" - + def test_cache_uses_current_context(self): t = Template(""" ${foo()} @@ -344,7 +344,7 @@ class CacheTest(TemplateTest): foo: ${x} </%def> """) - + import time x1 = t.render(x=1) time.sleep(3) @@ -367,7 +367,7 @@ class CacheTest(TemplateTest): %> """) assert result_lines(t.render()) == ['foo: 1', 'foo: 1', 'foo: 3', 'foo: 3'] - + def test_invalidate(self): t = Template(""" <%%def name="foo()" cached="True"> @@ -385,10 +385,10 @@ class CacheTest(TemplateTest): assert result_lines(t.render(x=3)) == ["foo: 3", "bar: 1"] t.cache.invalidate_def('bar') assert result_lines(t.render(x=4)) == ["foo: 3", "bar: 4"] - + t = Template(""" <%%page cached="True" cache_type="dbm" cache_dir="%s"/> - + page: ${x} """ % module_base) assert result_lines(t.render(x=1)) == ["page: 1"] @@ -396,8 +396,8 @@ class CacheTest(TemplateTest): t.cache.invalidate_body() assert result_lines(t.render(x=3)) == ["page: 3"] assert result_lines(t.render(x=4)) == ["page: 3"] - - + + def _install_mock_cache(self, template): m = MockCache(template.module._template_cache) template.module._template_cache = m diff --git a/test/test_call.py b/test/test_call.py index fecb2de..6aadf62 100644 --- a/test/test_call.py +++ b/test/test_call.py @@ -9,7 +9,7 @@ class CallTest(TemplateTest): <%def name="foo()"> hi im foo ${caller.body(y=5)} </%def> - + <%call expr="foo()" args="y, **kwargs"> this is the body, y is ${y} </%call> @@ -23,16 +23,16 @@ class CallTest(TemplateTest): <%def name="bar()"> this is bar </%def> - + <%def name="comp1()"> this comp1 should not be called </%def> - + <%def name="foo()"> foo calling comp1: ${caller.comp1(x=5)} foo calling body: ${caller.body()} </%def> - + <%call expr="foo()"> <%def name="comp1(x)"> this is comp1, ${x} @@ -46,10 +46,10 @@ class CallTest(TemplateTest): 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} @@ -57,26 +57,26 @@ class CallTest(TemplateTest): ${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_ccall_caller(self): t = Template(""" <%def name="outer_func()"> @@ -104,7 +104,7 @@ class CallTest(TemplateTest): "INNER END", "OUTER END", ] - + def test_stack_pop(self): t = Template(""" <%def name="links()" buffered="True"> @@ -130,7 +130,7 @@ class CallTest(TemplateTest): "</h1>", "Some links" ] - + def test_conditional_call(self): """test that 'caller' is non-None only if the immediate <%def> was called via <%call>""" @@ -169,7 +169,7 @@ class CallTest(TemplateTest): "BBB", "CCC" ] - + def test_chained_call(self): """test %calls that are chained through their targets""" t = Template(""" @@ -184,11 +184,11 @@ class CallTest(TemplateTest): whats in the body's caller's body ? ${context.caller_stack[-2].body()} </%def> - + <%call expr="a()"> heres the main templ call </%call> - + """) assert result_lines(t.render()) == [ 'this is a.', @@ -225,7 +225,7 @@ class CallTest(TemplateTest): "bar:", "this is bar body: 10" ] - + def test_nested_call_2(self): t = Template(""" x is ${x} @@ -240,13 +240,13 @@ class CallTest(TemplateTest): <%call expr="foo()"> <%def name="foosub(x)"> this is foo body: ${x} - + <%call expr="bar()"> <%def name="barsub()"> this is bar body: ${x} </%def> </%call> - + </%def> </%call> @@ -278,7 +278,7 @@ class CallTest(TemplateTest): ''') assert flatten_result(template.render()) == "foo" - + def test_chained_call_in_nested(self): t = Template(""" <%def name="embedded()"> @@ -309,7 +309,7 @@ class CallTest(TemplateTest): "whats in the body's caller's body ?", 'heres the main templ call' ] - + def test_call_in_nested(self): t = Template(""" <%def name="a()"> @@ -339,7 +339,7 @@ class CallTest(TemplateTest): context.write("a is done") return '' %> - + <%def name="b()"> this is b our body: ${caller.body()} @@ -362,7 +362,7 @@ class CallTest(TemplateTest): </%call> - """) + """) #print t.code assert result_lines(t.render()) == [ "test 1", @@ -384,7 +384,7 @@ class CallTest(TemplateTest): "this is aa is done", "this is aa is done" ] - + def test_call_in_nested_2(self): t = Template(""" <%def name="a()"> @@ -415,7 +415,7 @@ class CallTest(TemplateTest): class SelfCacheTest(TemplateTest): """this test uses a now non-public API.""" - + def test_basic(self): t = Template(""" <%! @@ -435,7 +435,7 @@ class SelfCacheTest(TemplateTest): return cached %> </%def> - + ${foo()} ${foo()} """) @@ -444,4 +444,4 @@ class SelfCacheTest(TemplateTest): "cached:", "this is foo" ] - + diff --git a/test/test_decorators.py b/test/test_decorators.py index 62ba360..fc8768b 100644 --- a/test/test_decorators.py +++ b/test/test_decorators.py @@ -12,11 +12,11 @@ class DecoratorTest(unittest.TestCase): return "BAR" + runtime.capture(context, fn, *args, **kw) + "BAR" return decorate %> - + <%def name="foo(y, x)" decorator="bar"> this is foo ${y} ${x} </%def> - + ${foo(1, x=5)} """) @@ -56,7 +56,7 @@ class DecoratorTest(unittest.TestCase): %> <%def name="foo()"> - + <%def name="bar()" decorator="bat"> this is bar </%def> @@ -67,7 +67,7 @@ class DecoratorTest(unittest.TestCase): """) assert flatten_result(template.render()) == "BAT this is bar BAT" - + def test_toplevel_decorated_name(self): template = Template(""" <%! @@ -107,4 +107,4 @@ class DecoratorTest(unittest.TestCase): """) assert flatten_result(template.render()) == "function bar this is bar" - + diff --git a/test/test_def.py b/test/test_def.py index fa5908e..3ec63ff 100644 --- a/test/test_def.py +++ b/test/test_def.py @@ -6,13 +6,13 @@ from util import flatten_result, result_lines class DefTest(TemplateTest): def test_def_noargs(self): template = Template(""" - + ${mycomp()} - + <%def name="mycomp()"> hello mycomp ${variable} </%def> - + """) assert template.render(variable='hi').strip() == """hello mycomp hi""" @@ -55,7 +55,7 @@ class DefTest(TemplateTest): # check that "a" is declared in "b", but not in "c" 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 assert flatten_result(template.render()) == "im b and heres a: im a" @@ -63,9 +63,9 @@ class DefTest(TemplateTest): """test calling a def from the top level""" template = Template(""" - + this is the body - + <%def name="a()"> this is a </%def> @@ -73,22 +73,22 @@ class DefTest(TemplateTest): <%def name="b(x, y)"> this is b, ${x} ${y} </%def> - + """) - + self._do_test(template.get_def("a"), "this is a", filters=flatten_result) self._do_test(template.get_def("b"), "this is b, 10 15", template_args={'x':10, 'y':15}, filters=flatten_result) self._do_test(template.get_def("body"), "this is the body", filters=flatten_result) - + # test that args outside of the dict can be used self._do_test(template.get_def("a"), "this is a", filters=flatten_result, template_args={'q':5,'zq':'test'}) - + class ScopeTest(TemplateTest): """test scoping rules. The key is, enclosing scope always takes precedence over contextual scope.""" - + def test_scope_one(self): self._do_memory_test(""" <%def name="a()"> @@ -134,7 +134,7 @@ class ScopeTest(TemplateTest): <%def name="a()"> this is a. x is ${x}. </%def> - + <%def name="b()"> <% x = 9 @@ -142,11 +142,11 @@ class ScopeTest(TemplateTest): this is b. x is ${x}. calling a. ${a()} </%def> - + ${b()} """) assert flatten_result(t.render()) == "this is b. x is 9. calling a. this is a. x is 5." - + 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. @@ -225,7 +225,7 @@ class ScopeTest(TemplateTest): <% x = 10 %> - + b. x is ${x}. ${a()} </%def> @@ -237,7 +237,7 @@ class ScopeTest(TemplateTest): def test_scope_nine(self): """test that 'enclosing scope' doesnt get exported to other templates""" - + l = lookup.TemplateLookup() l.put_string('main', """ <% @@ -251,7 +251,7 @@ class ScopeTest(TemplateTest): """) assert flatten_result(l.get_template('main').render(x=2)) == "this is main. this is secondary. x is 2" - + def test_scope_ten(self): t = Template(""" <%def name="a()"> @@ -291,7 +291,7 @@ class ScopeTest(TemplateTest): this is b, x is ${x} </%def> </%def> - + ${a(x=5)} """) assert result_lines(t.render(x=10)) == [ @@ -349,23 +349,23 @@ class ScopeTest(TemplateTest): """test that arguments passed to the body() function are accessible by top-level defs""" l = lookup.TemplateLookup() l.put_string("base", """ - + ${next.body(x=12)} - + """) - + l.put_string("main", """ <%inherit file="base"/> <%page args="x"/> this is main. x is ${x} - + ${a()} - + <%def name="a(**args)"> this is a, x is ${x} </%def> """) - + # test via inheritance #print l.get_template("main").code assert result_lines(l.get_template("main").render()) == [ @@ -375,7 +375,7 @@ class ScopeTest(TemplateTest): l.put_string("another", """ <%namespace name="ns" file="main"/> - + ${ns.body(x=15)} """) # test via namespace @@ -389,15 +389,15 @@ class NestedDefTest(TemplateTest): t = Template(""" ${hi()} - + <%def name="hi()"> hey, im hi. and heres ${foo()}, ${bar()} - + <%def name="foo()"> this is foo </%def> - + <%def name="bar()"> this is bar </%def> @@ -417,9 +417,9 @@ class NestedDefTest(TemplateTest): </%def> ${a()} """) - + assert flatten_result(t.render(x=10)) == "x is 10 this is a, x is 10 this is b: 10" - + def test_nested_with_args(self): t = Template(""" ${a()} @@ -431,7 +431,7 @@ class NestedDefTest(TemplateTest): </%def> """) assert flatten_result(t.render()) == "a b x is 5 y is 2" - + def test_nested_def_2(self): template = Template(""" ${a()} @@ -449,7 +449,7 @@ class NestedDefTest(TemplateTest): def test_nested_nested_def(self): t = Template(""" - + ${a()} <%def name="a()"> a @@ -478,12 +478,12 @@ class NestedDefTest(TemplateTest): </%def> ${c2()} </%def> - + ${b1()} ${b2()} ${b3()} </%def> """) assert flatten_result(t.render(x=5, y=None)) == "a a_b1 a_b2 a_b2_c1 a_b3 a_b3_c1 heres x: 5 y is 7 a_b3_c2 y is None c1 is a_b3_c1 heres x: 5 y is 7" - + def test_nested_nested_def_2(self): t = Template(""" <%def name="a()"> @@ -492,7 +492,7 @@ class NestedDefTest(TemplateTest): this is b ${c()} </%def> - + <%def name="c()"> this is c </%def> @@ -514,16 +514,16 @@ class NestedDefTest(TemplateTest): %> c. x is ${x}. ${a()} </%def> - + b. ${c()} </%def> ${b()} - + x is ${x} """) assert flatten_result(t.render(x=5)) == "b. c. x is 10. a: x is 5 x is 5" - + class ExceptionTest(TemplateTest): def test_raise(self): template = Template(""" @@ -540,11 +540,11 @@ class ExceptionTest(TemplateTest): def handle(context, error): context.write("error message is " + str(error)) return True - + template = Template(""" <% raise Exception("this is a test") %> """, error_handler=handle) assert template.render().strip() == """error message is this is a test""" - + diff --git a/test/test_exceptions.py b/test/test_exceptions.py index 8adad6d..1ddca4f 100644 --- a/test/test_exceptions.py +++ b/test/test_exceptions.py @@ -53,11 +53,11 @@ class ExceptionsTest(TemplateTest): assert ("CompileException: Fragment 'i = 0' is not a partial " "control statement") in text_error - + def test_utf8_html_error_template(self): """test the html_error_template with a Template containing utf8 chars""" - + if util.py3k: code = """# -*- coding: utf-8 -*- % if 2 == 2: /an error @@ -79,7 +79,7 @@ ${u'привет'} "error' is not a partial control " "statement at line: 2 char: 1") in \ html_error.decode('utf-8') - + if util.py3k: assert u"3 ${'привет'}".encode(sys.getdefaultencoding(), 'htmlentityreplace') in html_error @@ -89,7 +89,7 @@ ${u'привет'} else: assert False, ("This function should trigger a CompileException, " "but didn't") - + def test_format_closures(self): try: exec "def foo():"\ @@ -99,7 +99,7 @@ ${u'привет'} except: html_error = exceptions.html_error_template().render() assert "RuntimeError: test" in str(html_error) - + def test_py_utf8_html_error_template(self): try: foo = u'日本' @@ -134,11 +134,11 @@ ${foobar} assert '<div class="sourceline">${foobar}</div>' in \ result_lines(l.get_template("foo.html").render_unicode()) - + def test_utf8_format_exceptions(self): """test that htmlentityreplace formatting is applied to exceptions reported with format_exceptions=True""" - + l = TemplateLookup(format_exceptions=True) if util.py3k: l.put_string("foo.html", """# -*- coding: utf-8 -*-\n${'привет' + foobar}""") @@ -152,21 +152,21 @@ ${foobar} assert '<div class="highlight">2 ${u'пр'\ 'ивет' + foobar}</div>' \ in result_lines(l.get_template("foo.html").render().decode('utf-8')) - - + + def test_custom_tback(self): try: raise RuntimeError("error 1") foo('bar') except: t, v, tback = sys.exc_info() - + try: raise RuntimeError("error 2") except: html_error = exceptions.html_error_template().\ render_unicode(error=v, traceback=tback) - + # obfuscate the text so that this text # isn't in the 'wrong' exception assert "".join(reversed(");93#&rab;93#&(oof")) in html_error @@ -181,9 +181,9 @@ ${foobar} if not util.py3k: # blow away tracebaack info sys.exc_clear() - + # and don't even send what we have. html_error = exceptions.html_error_template().\ render_unicode(error=v, traceback=None) - + assert "local variable 'y' referenced" in html_error diff --git a/test/test_filters.py b/test/test_filters.py index 027d949..2958711 100644 --- a/test/test_filters.py +++ b/test/test_filters.py @@ -28,17 +28,17 @@ class FilterTest(TemplateTest): ${x | trim} """) assert flatten_result(t.render(x=5)) == "5" - + def test_quoting(self): t = Template(""" foo ${bar | h} """) - + eq_( flatten_result(t.render(bar="<'some bar'>")), "foo <'some bar'>" ) - + @skip_if(lambda: util.py3k) def test_quoting_non_unicode(self): t = Template(""" @@ -49,8 +49,8 @@ class FilterTest(TemplateTest): flatten_result(t.render(bar="<'привет'>")), "foo <'привет'>" ) - - + + def test_def(self): t = Template(""" <%def name="foo()" filter="myfilter"> @@ -70,7 +70,7 @@ class FilterTest(TemplateTest): """) assert t.render().strip()=="trim this string: some string to trim continue" - + def test_import_2(self): t = Template(""" trim this string: ${" some string to trim " | filters.trim} continue\ @@ -84,18 +84,18 @@ class FilterTest(TemplateTest): """, default_filters=['decode.utf8']) #print t.code assert t.render_unicode(x="voix m’a réveillé").strip() == u"some stuff.... voix m’a réveillé" - + def test_custom_default(self): t = Template(""" <%! def myfilter(x): return "->" + x + "<-" %> - + hi ${'there'} """, default_filters=['myfilter']) assert t.render().strip()=="hi ->there<-" - + def test_global(self): t = Template(""" <%page expression_filter="h"/> @@ -120,7 +120,7 @@ class FilterTest(TemplateTest): ${"<tag>this is html</tag>" | n, h} """) assert t.render().strip() == "<tag>this is html</tag>" - + def testnonexpression(self): t = Template(""" <%! @@ -129,7 +129,7 @@ class FilterTest(TemplateTest): def b(text): return "this is b" %> - + ${foo()} <%def name="foo()" buffered="True"> this is text @@ -144,7 +144,7 @@ class FilterTest(TemplateTest): def b(text): return "this is b" %> - + ${'hi'} ${foo()} <%def name="foo()" buffered="True"> @@ -167,7 +167,7 @@ class FilterTest(TemplateTest): else: return "this is b" %> - + ${'hi'} ${foo()} <%def name="foo()" buffered="True"> @@ -183,7 +183,7 @@ class FilterTest(TemplateTest): def b(text): return "this is b" %> - + ${foo()} ${bar()} <%def name="foo()" filter="b"> @@ -195,19 +195,19 @@ class FilterTest(TemplateTest): """, buffer_filters=['a']) assert flatten_result(t.render()) == "this is b this is a" - + def test_builtins(self): t = Template(""" ${"this is <text>" | h} """) assert flatten_result(t.render()) == "this is <text>" - + t = Template(""" http://foo.com/arg1=${"hi! this is a string." | u} """) assert flatten_result(t.render()) == "http://foo.com/arg1=hi%21+this+is+a+string." -class BufferTest(unittest.TestCase): +class BufferTest(unittest.TestCase): def test_buffered_def(self): t = Template(""" <%def name="foo()" buffered="True"> @@ -253,7 +253,7 @@ class BufferTest(unittest.TestCase): assert False except TypeError: assert True - + def test_buffered_exception(self): template = Template(""" <%def name="a()" buffered="True"> @@ -261,16 +261,16 @@ class BufferTest(unittest.TestCase): raise TypeError("hi") %> </%def> - + ${a()} - + """) try: print template.render() assert False except TypeError: assert True - + def test_capture_ccall(self): t = Template(""" <%def name="foo()"> @@ -284,7 +284,7 @@ class BufferTest(unittest.TestCase): ccall body </%call> """) - + #print t.render() assert flatten_result(t.render()) == "this is foo. body: ccall body" - + diff --git a/test/test_inheritance.py b/test/test_inheritance.py index 9f978d2..a953847 100644 --- a/test/test_inheritance.py +++ b/test/test_inheritance.py @@ -52,7 +52,7 @@ main_body ${parent.d()} full stack from the top: ${self.name} ${parent.name} ${parent.context['parent'].name} ${parent.context['parent'].context['parent'].name} """) - + collection.put_string('layout', """ <%inherit file="general"/> <%def name="d()">layout_d</%def> @@ -94,11 +94,11 @@ ${next.body()} 'full stack from the top:', 'self:main self:layout self:general self:base' ] - + def test_includes(self): """test that an included template also has its full hierarchy invoked.""" collection = lookup.TemplateLookup() - + collection.put_string("base", """ <%def name="a()">base_a</%def> This is the base. @@ -134,7 +134,7 @@ ${next.body()} """test that templates used via <%namespace> have access to an inheriting 'self', and that the full 'self' is also exported.""" collection = lookup.TemplateLookup() - + collection.put_string("base", """ <%def name="a()">base_a</%def> <%def name="b()">base_b</%def> @@ -194,7 +194,7 @@ ${next.body()} <%def name="foo()"> ${next.body(**context.kwargs)} </%def> - + ${foo()} """) collection.put_string("index", """ @@ -202,7 +202,7 @@ ${next.body()} <%page args="x, y, z=7"/> print ${x}, ${y}, ${z} """) - + if util.py3k: assert result_lines(collection.get_template('index').render_unicode(x=5,y=10)) == [ "this is the base.", @@ -215,14 +215,14 @@ ${next.body()} "pageargs: (type: <type 'dict'>) [('x', 5), ('y', 10)]", "print 5, 10, 7" ] - + def test_pageargs_2(self): collection = lookup.TemplateLookup() collection.put_string("base", """ this is the base. - + ${next.body(**context.kwargs)} - + <%def name="foo(**kwargs)"> ${next.body(**kwargs)} </%def> @@ -245,7 +245,7 @@ ${next.body()} "pageargs: 12, 15, 8", "pageargs: 5, 10, 16" ] - + def test_pageargs_err(self): collection = lookup.TemplateLookup() collection.put_string("base", """ @@ -262,7 +262,7 @@ ${next.body()} assert False except TypeError: assert True - + def test_toplevel(self): collection = lookup.TemplateLookup() collection.put_string("base", """ @@ -305,7 +305,7 @@ ${next.body()} 'this is the base.', 'this is index.' ] - + def test_in_call(self): collection = lookup.TemplateLookup() collection.put_string("/layout.html",""" @@ -332,7 +332,7 @@ ${next.body()} </%def> <%inherit file="/layout.html"/> """) - + collection.put_string("/subdir/renderedtemplate.html",""" Holy smokes! <%inherit file="/subdir/layout.html"/> diff --git a/test/test_lexer.py b/test/test_lexer.py index f35b2ea..006abee 100644 --- a/test/test_lexer.py +++ b/test/test_lexer.py @@ -33,15 +33,15 @@ class %s(object): ", ".join(repr_arg(x) for x in self.args) ) """ % clsname) in locals() - + # NOTE: most assertion expressions were generated, then formatted # by PyTidy, hence the dense formatting. class LexerTest(TemplateTest): - + def _compare(self, node, expected): eq_(repr(node), repr(expected)) - + def test_text_and_tag(self): template = """ <b>Hello world</b> @@ -85,7 +85,7 @@ class LexerTest(TemplateTest): """ self.assertRaises(exceptions.SyntaxException, Lexer(template).parse) - + def test_noexpr_allowed(self): template = \ """ @@ -125,7 +125,7 @@ class LexerTest(TemplateTest): """ self.assertRaises(exceptions.CompileException, Lexer(template).parse) - + def test_percent_escape(self): template = \ """ @@ -143,7 +143,7 @@ class LexerTest(TemplateTest): ControlLine(u'if', u'if foo:', False, (6, 1)), ControlLine(u'if', u'endif', True, (7, 1)), Text(u' ', (8, 1))])) - + def test_text_tag(self): template = \ """ @@ -201,7 +201,7 @@ class LexerTest(TemplateTest): """ self.assertRaises(exceptions.CompileException, Lexer(template).parse) - + def test_def_syntax_2(self): template = \ """ @@ -240,7 +240,7 @@ class LexerTest(TemplateTest): CallNamespaceTag(u'self:go', {u'x': u'1', u'y' : u'2', u'z': u"${'hi' + ' ' + 'there'}"}, (3, 13), []), Text(u'\n ', (3, 64))])) - + def test_ns_tag_empty(self): template = \ """ @@ -271,7 +271,7 @@ class LexerTest(TemplateTest): this is the body ''', (3, 46))]), Text(u'\n ', (5, 24))])) - + def test_expr_in_attribute(self): """test some slightly trickier expressions. @@ -386,7 +386,7 @@ more text Code(u'\nimport foo\n \n', True, (8, 5)), Text(u'\n', (10, 7))]) ) - + def test_code_and_tags(self): template = \ """ @@ -447,7 +447,7 @@ more text Text(u'\n ', (4, 42))]), Text(u'\n ' , (5, 16)), Expression(u'hi()', [], (6, 9)), Text(u'\n', (6, 16))])) - + def test_tricky_expression(self): template = """ @@ -556,7 +556,7 @@ print(''' """comment\n \n""", False, (1, 1)), Text(u" '''and now some text '''", (10,11))])) - + def test_control_lines(self): template = \ """ @@ -660,7 +660,7 @@ text text la la "Keyword 'endlala' doesn't match keyword 'for' at line: 5 char: 1", Lexer(template).parse ) - + def test_ternary_control(self): template = \ """ @@ -685,7 +685,7 @@ text text la la ControlLine(u'else', u'else:', False, (8, 1)), Text(u' hi\n', (9, 1)), ControlLine(u'if', u'endif', True, (10, 1))])) - + def test_integration(self): template = \ """<%namespace name="foo" file="somefile.html"/> @@ -731,7 +731,7 @@ text text la la (17, 1)), Text(u' </tr>\n', (18, 1)), ControlLine(u'for', u'endfor', True, (19, 1)), Text(u'</table>\n', (20, 1))])) - + def test_comment_after_statement(self): template = \ """ @@ -776,7 +776,7 @@ text text la la ) assert flatten_result(Template(template).render()) \ == """<html> like the name says. 1 2 3 Dizzy </html>""" - + def test_comments(self): template = \ """ @@ -811,7 +811,7 @@ hi hi ''', (16, 8))])) - + def test_docs(self): template = \ """ diff --git a/test/test_lookup.py b/test/test_lookup.py index c62efd5..cfbb085 100644 --- a/test/test_lookup.py +++ b/test/test_lookup.py @@ -22,7 +22,7 @@ class LookupTest(unittest.TestCase): assert tl.get_template('/subdir/index.html').module_id \ == '_subdir_index_html' - + def test_updir(self): t = tl.get_template('/subdir/foo/../bar/../index.html') assert result_lines(t.render()) == [ @@ -30,15 +30,15 @@ class LookupTest(unittest.TestCase): "this is include 2" ] - + def test_directory_lookup(self): """test that hitting an existent directory still raises LookupError.""" - + self.assertRaises(exceptions.TopLevelLookupException, tl.get_template, "/subdir" ) - + def test_no_lookup(self): t = Template("hi <%include file='foo.html'/>") try: @@ -48,7 +48,7 @@ class LookupTest(unittest.TestCase): assert str(e) == \ "Template 'memory:%s' has no TemplateLookup associated" % \ hex(id(t)) - + def test_uri_adjust(self): tl = lookup.TemplateLookup(directories=['/foo/bar']) assert tl.filename_to_uri('/foo/bar/etc/lala/index.html') == \ @@ -57,9 +57,9 @@ class LookupTest(unittest.TestCase): tl = lookup.TemplateLookup(directories=['./foo/bar']) assert tl.filename_to_uri('./foo/bar/etc/index.html') == \ '/etc/index.html' - + def test_uri_cache(self): """test that the _uri_cache dictionary is available""" tl._uri_cache[('foo', 'bar')] = '/some/path' assert tl._uri_cache[('foo', 'bar')] == '/some/path' - + diff --git a/test/test_lru.py b/test/test_lru.py index e2b5c15..ade48a3 100644 --- a/test/test_lru.py +++ b/test/test_lru.py @@ -13,16 +13,16 @@ class item: class LRUTest(unittest.TestCase): - def testlru(self): + def testlru(self): l = LRUCache(10, threshold=.2) - + for id in range(1,20): l[id] = item(id) - + # first couple of items should be gone - self.assert_(not l.has_key(1)) + self.assert_(not l.has_key(1)) self.assert_(not l.has_key(2)) - + # next batch over the threshold of 10 should be present for id in range(11,20): self.assert_(l.has_key(id)) @@ -37,9 +37,9 @@ class LRUTest(unittest.TestCase): self.assert_(not l.has_key(11)) self.assert_(not l.has_key(13)) - + for id in (25, 24, 23, 14, 12, 19, 18, 17, 16, 15): - self.assert_(l.has_key(id)) + self.assert_(l.has_key(id)) def _disabled_test_threaded(self): size = 100 @@ -47,13 +47,13 @@ class LRUTest(unittest.TestCase): all_elems = 2000 hot_zone = range(30,40) cache = LRUCache(size, threshold) - + # element to store class Element(object): def __init__(self, id): self.id = id self.regets = 0 - + # return an element. we will favor ids in the relatively small # "hot zone" 25% of the time. def get_elem(): @@ -61,7 +61,7 @@ class LRUTest(unittest.TestCase): return hot_zone[random.randint(0, len(hot_zone) - 1)] else: return random.randint(1, all_elems) - + total = [0] # request thread. def request_elem(): @@ -74,19 +74,19 @@ class LRUTest(unittest.TestCase): except KeyError: e = Element(id) cache[id] = e - + time.sleep(random.random() / 1000) for x in range(0,20): thread.start_new_thread(request_elem, ()) - + # assert size doesn't grow unbounded, doesnt shrink well below size for x in range(0,5): time.sleep(1) print "size:", len(cache) assert len(cache) < size + size * threshold * 2 assert len(cache) > size - (size * .1) - + # computs the average number of times a range of elements were "reused", # i.e. without being removed from the cache. def average_regets_in_range(start, end): @@ -99,13 +99,13 @@ class LRUTest(unittest.TestCase): hotzone_avg = average_regets_in_range(30, 40) control_avg = average_regets_in_range(450,760) total_avg = average_regets_in_range(0, 2000) - + # hotzone should be way above the others print "total fetches", total[0], "hotzone", \ hotzone_avg, "control", \ control_avg, "total", total_avg - + assert hotzone_avg > total_avg * 5 > control_avg * 5 - - + + diff --git a/test/test_namespace.py b/test/test_namespace.py index 5e0d7a0..3c4c689 100644 --- a/test/test_namespace.py +++ b/test/test_namespace.py @@ -15,9 +15,9 @@ class NamespaceTest(TemplateTest): this is x b, and heres ${a()} </%def> </%namespace> - + ${x.a()} - + ${x.b()} """, "this is x a this is x b, and heres this is x a", @@ -98,13 +98,13 @@ class NamespaceTest(TemplateTest): flatten_result(collection.get_template('a').render(b_def='b')), "a. b: b." ) - + def test_template(self): collection = lookup.TemplateLookup() collection.put_string('main.html', """ <%namespace name="comp" file="defs.html"/> - + this is main. ${comp.def1("hi")} ${comp.def2("there")} """) @@ -113,14 +113,14 @@ class NamespaceTest(TemplateTest): <%def name="def1(s)"> def1: ${s} </%def> - + <%def name="def2(x)"> def2: ${x} </%def> """) assert flatten_result(collection.get_template('main.html').render()) == "this is main. def1: hi def2: there" - + def test_module(self): collection = lookup.TemplateLookup() @@ -168,7 +168,7 @@ class NamespaceTest(TemplateTest): """) assert flatten_result(collection.get_template('main.html').render()) == "this is main. this is foo1. this is foo2, x is hi" - + def test_context(self): """test that namespace callables get access to the current context""" collection = lookup.TemplateLookup() @@ -191,7 +191,7 @@ class NamespaceTest(TemplateTest): """) assert flatten_result(collection.get_template('main.html').render(x="context x")) == "this is main. def1: x is context x def2: x is there" - + def test_overload(self): collection = lookup.TemplateLookup() @@ -238,13 +238,13 @@ class NamespaceTest(TemplateTest): collection = lookup.TemplateLookup() collection.put_string("main.html", """ <%namespace name="foo" file="ns.html"/> - + this is main. ${bar()} <%def name="bar()"> this is bar, foo is ${foo.bar()} </%def> """) - + collection.put_string("ns.html", """ <%def name="bar()"> this is ns.html->bar @@ -274,24 +274,24 @@ class NamespaceTest(TemplateTest): this is ns.html->bar </%def> """) - + collection.put_string("index.html", """ <%namespace name="main" file="main.html"/> - + this is index ${main.bar()} """) - assert result_lines(collection.get_template("index.html").render()) == [ + assert result_lines(collection.get_template("index.html").render()) == [ "this is index", "this is bar, foo is" , "this is ns.html->bar" ] - + def test_dont_pollute_self(self): # test that get_namespace() doesn't modify the original context # incompatibly - + collection = lookup.TemplateLookup() collection.put_string("base.html", """ @@ -334,13 +334,13 @@ class NamespaceTest(TemplateTest): "name via bar:", "self:page.html" ] - + def test_inheritance(self): """test namespace initialization in a base inherited template that doesnt otherwise access the namespace""" collection = lookup.TemplateLookup() collection.put_string("base.html", """ <%namespace name="foo" file="ns.html" inheritable="True"/> - + ${next.body()} """) collection.put_string("ns.html", """ @@ -351,11 +351,11 @@ class NamespaceTest(TemplateTest): collection.put_string("index.html", """ <%inherit file="base.html"/> - + this is index ${self.foo.bar()} """) - + assert result_lines(collection.get_template("index.html").render()) == [ "this is index", "this is ns.html->bar" @@ -367,7 +367,7 @@ class NamespaceTest(TemplateTest): <%def name="foo()"> base.foo </%def> - + <%def name="bat()"> base.bat </%def> @@ -381,11 +381,11 @@ class NamespaceTest(TemplateTest): ${parent.bat()} ${self.bat()} </%def> - + <%def name="foo()"> lib.foo </%def> - + """) collection.put_string("front.html", """ @@ -424,7 +424,7 @@ class NamespaceTest(TemplateTest): <% self.attr.lala = "base lala" %> - + ${self.attr.basefoo} ${self.attr.foofoo} ${self.attr.onlyfoo} @@ -448,7 +448,7 @@ class NamespaceTest(TemplateTest): "base lala", "foo lala", ] - + def test_attr_raise(self): l = lookup.TemplateLookup() @@ -459,19 +459,19 @@ class NamespaceTest(TemplateTest): l.put_string("bar.html", """ <%namespace name="foo" file="foo.html"/> - + ${foo.notfoo()} """) self.assertRaises(AttributeError, l.get_template("bar.html").render) - + def test_custom_tag_1(self): template = Template(""" - + <%def name="foo(x, y)"> foo: ${x} ${y} </%def> - + <%self:foo x="5" y="${7+8}"/> """) assert result_lines(template.render()) == ['foo: 5 15'] @@ -482,32 +482,32 @@ class NamespaceTest(TemplateTest): <%def name="foo(x, y)"> foo: ${x} ${y} </%def> - + <%def name="bat(g)"><% return "the bat! %s" % g %></%def> - + <%def name="bar(x)"> ${caller.body(z=x)} </%def> """) - + collection.put_string("index.html", """ <%namespace name="myns" file="base.html"/> - + <%myns:foo x="${'some x'}" y="some y"/> - + <%myns:bar x="${myns.bat(10)}" args="z"> record: ${z} </%myns:bar> - + """) - + assert result_lines(collection.get_template("index.html").render()) == [ 'foo: some x some y', 'record: the bat! 10' ] - + def test_custom_tag_3(self): collection = lookup.TemplateLookup() collection.put_string("base.html", """ @@ -530,14 +530,14 @@ class NamespaceTest(TemplateTest): call body </%self.foo:bar> """) - + assert result_lines(collection.get_template("index.html").render()) == [ "this is index", "this is ns.html->bar", "caller body:", "call body" ] - + def test_custom_tag_case_sensitive(self): t = Template(""" <%def name="renderPanel()"> @@ -549,21 +549,21 @@ class NamespaceTest(TemplateTest): hi </%self:renderPanel> </%def> - + <%self:renderTablePanel/> """) assert result_lines(t.render()) == ['panel', 'hi'] - - + + def test_expr_grouping(self): """test that parenthesis are placed around string-embedded expressions.""" - + template = Template(""" <%def name="bar(x, y)"> ${x} ${y} </%def> - + <%self:bar x=" ${foo} " y="x${g and '1' or '2'}y"/> """, input_encoding='utf-8') @@ -573,7 +573,7 @@ class NamespaceTest(TemplateTest): "x2y" ] - + def test_ccall(self): collection = lookup.TemplateLookup() collection.put_string("base.html", """ @@ -652,11 +652,11 @@ class NamespaceTest(TemplateTest): <%def name="foo()"> this is foo </%def> - + <%def name="bar()"> this is bar </%def> - + <%def name="lala()"> this is lala </%def> @@ -689,7 +689,7 @@ class NamespaceTest(TemplateTest): "this is b", "this is x" ] - + def test_import_calledfromdef(self): l = lookup.TemplateLookup() l.put_string("a", """ @@ -712,29 +712,29 @@ class NamespaceTest(TemplateTest): t = l.get_template("b") assert flatten_result(t.render()) == "im table" - + def test_closure_import(self): collection = lookup.TemplateLookup() collection.put_string("functions.html",""" <%def name="foo()"> this is foo </%def> - + <%def name="bar()"> this is bar </%def> """) - + collection.put_string("index.html", """ <%namespace file="functions.html" import="*"/> <%def name="cl1()"> ${foo()} </%def> - + <%def name="cl2()"> ${bar()} </%def> - + ${cl1()} ${cl2()} """) @@ -750,26 +750,26 @@ class NamespaceTest(TemplateTest): this is foo </%def> </%namespace> - + ${foo()} - + """) assert flatten_result(t.render()) == "this is foo" - + def test_ccall_import(self): collection = lookup.TemplateLookup() collection.put_string("functions.html",""" <%def name="foo()"> this is foo </%def> - + <%def name="bar()"> this is bar. ${caller.body()} ${caller.lala()} </%def> """) - + collection.put_string("index.html", """ <%namespace name="func" file="functions.html" import="*"/> <%call expr="bar()"> diff --git a/test/test_pygen.py b/test/test_pygen.py index 181140f..58265ff 100644 --- a/test/test_pygen.py +++ b/test/test_pygen.py @@ -179,8 +179,8 @@ print "hi" # a comment # more comments print g -""" - +""" + def test_open_quotes_with_pound(self): text = ''' print """ this is text @@ -216,7 +216,7 @@ print ''' there ''' # someone else's comment -""" +""" def test_quotes_with_pound(self): diff --git a/test/test_template.py b/test/test_template.py index dbfd068..3d489f7 100644 --- a/test/test_template.py +++ b/test/test_template.py @@ -22,7 +22,7 @@ class EncodingTest(TemplateTest): u"""Alors vous imaginez ma surprise, au lever du jour, quand une drôle de petite voix m’a réveillé. Elle disait: « S’il vous plaît… dessine-moi un mouton! »""", output_encoding='utf-8' ) - + def test_unicode_arg(self): val = u"""Alors vous imaginez ma surprise, au lever du jour, quand une drôle de petite voix m’a réveillé. Elle disait: « S’il vous plaît… dessine-moi un mouton! »""" self._do_memory_test( @@ -81,7 +81,7 @@ class EncodingTest(TemplateTest): ("## -*- coding: utf-8 -*-\n" + val).encode('utf-8'), u"""Alors vous imaginez ma surprise, au lever du jour, quand une drôle de petite voix m’a réveillé. Elle disait: « S’il vous plaît… dessine-moi un mouton! »""" ) - + def test_unicode_text(self): val = u"""<%text>Alors vous imaginez ma surprise, au lever du jour, quand une drôle de petite voix m’a réveillé. Elle disait: « S’il vous plaît… dessine-moi un mouton! »</%text>""" self._do_memory_test( @@ -102,7 +102,7 @@ class EncodingTest(TemplateTest): u"""Alors vous imaginez ma surprise, au lever du jour, quand une drôle de petite voix m’a réveillé. Elle disait: « S’il vous plaît… dessine-moi un mouton! »""", filters=flatten_result ) - + def test_unicode_literal_in_expr(self): if util.py3k: self._do_memory_test( @@ -149,7 +149,7 @@ class EncodingTest(TemplateTest): u"""Alors vous imaginez ma surprise, au lever du jour, quand une drôle de petite voix m’a réveillé. Elle disait: « S’il vous plaît… dessine-moi un mouton! »""", filters=lambda s:s.strip() ) - + def test_unicode_literal_in_controlline(self): if util.py3k: self._do_memory_test( @@ -177,7 +177,7 @@ class EncodingTest(TemplateTest): u"""hi, drôle de petite voix m’a réveillé.""", filters=lambda s:s.strip(), ) - + def test_unicode_literal_in_tag(self): self._do_file_test( "unicode_arguments.html", @@ -200,7 +200,7 @@ class EncodingTest(TemplateTest): ], filters=result_lines ) - + def test_unicode_literal_in_def(self): if util.py3k: self._do_memory_test( @@ -237,7 +237,7 @@ class EncodingTest(TemplateTest): u"""Foo: árvíztűrő tükörfúrógép Bar: ÁRVÍZTŰRŐ TÜKÖRFÚRÓGÉP""", filters=flatten_result ) - + self._do_memory_test( u"""## -*- coding: utf-8 -*- <%def name="hello(foo=u'árvíztűrő tükörfúrógép', bar=u'ÁRVÍZTŰRŐ TÜKÖRFÚRÓGÉP')"> @@ -248,18 +248,18 @@ class EncodingTest(TemplateTest): u"""Foo: árvíztűrő tükörfúrógép Bar: ÁRVÍZTŰRŐ TÜKÖRFÚRÓGÉP""", filters=flatten_result ) - + def test_input_encoding(self): """test the 'input_encoding' flag on Template, and that unicode objects arent double-decoded""" - + if util.py3k: self._do_memory_test( u"hello ${f('śląsk')}", u"hello śląsk", input_encoding='utf-8', template_args={'f':lambda x:x} - ) + ) self._do_memory_test( u"## -*- coding: utf-8 -*-\nhello ${f('śląsk')}", @@ -272,7 +272,7 @@ class EncodingTest(TemplateTest): u"hello śląsk", input_encoding='utf-8', template_args={'f':lambda x:x} - ) + ) self._do_memory_test( u"## -*- coding: utf-8 -*-\nhello ${f(u'śląsk')}", @@ -297,7 +297,7 @@ class EncodingTest(TemplateTest): u"hello śląsk", template_args={'x':u'śląsk'} ) - + def test_encoding(self): self._do_memory_test( u"""Alors vous imaginez ma surprise, au lever du jour, quand une drôle de petite voix m’a réveillé. Elle disait: « S’il vous plaît… dessine-moi un mouton! »""", @@ -313,7 +313,7 @@ class EncodingTest(TemplateTest): output_encoding='iso-8859-1', encoding_errors='replace', unicode_=False ) - + def test_read_unicode(self): lookup = TemplateLookup(directories=[template_base], filesystem_checks=True, output_encoding='utf-8') @@ -357,7 +357,7 @@ class PageArgsTest(TemplateTest): def test_basic(self): template = Template(""" <%page args="x, y, z=7"/> - + this is page, ${x}, ${y}, ${z} """) @@ -368,7 +368,7 @@ class PageArgsTest(TemplateTest): assert False except TypeError, e: assert True - + def test_inherits(self): lookup = TemplateLookup() lookup.put_string("base.tmpl", @@ -390,7 +390,7 @@ class PageArgsTest(TemplateTest): "bar foo var", filters=flatten_result, template_args={'variable':'var', 'bar':'bar', 'foo':'foo'} - + ) def test_includes(self): @@ -421,7 +421,7 @@ class PageArgsTest(TemplateTest): template_args={'variable':'var', 'bar':'bar', 'foo':'foo'} ) - + def test_with_context(self): template = Template(""" <%page args="x, y, z=7"/> @@ -434,12 +434,12 @@ class PageArgsTest(TemplateTest): def test_overrides_builtins(self): template = Template(""" <%page args="id"/> - + this is page, id is ${id} """) - + assert flatten_result(template.render(id="im the id")) == "this is page, id is im the id" - + def test_canuse_builtin_names(self): template = Template(""" exception: ${Exception} @@ -465,7 +465,7 @@ class PageArgsTest(TemplateTest): assert flatten_result(lookup.get_template(template).render()) == "foo" assert flatten_result(lookup.get_template(template).render(id=5)) == "5" assert flatten_result(lookup.get_template(template).render(id=id)) == "<built-in function id>" - + def test_dict_locals(self): template = Template(""" <% @@ -501,8 +501,8 @@ class IncludeTest(TemplateTest): this is b. ${a}, ${b}, ${c} """) assert flatten_result(lookup.get_template("a").render(a=7,b=8)) == "this is a this is b. 7, 8, 5" - - def test_viakwargs(self): + + def test_viakwargs(self): lookup = TemplateLookup() lookup.put_string("a", """ this is a @@ -526,7 +526,7 @@ class IncludeTest(TemplateTest): this is b. ${a}, ${b}, ${c} """) assert flatten_result(lookup.get_template("a").render(a=7,b=8,i='b')) == "this is a this is b. 7, 8, 5" - + def test_within_ccall(self): lookup = TemplateLookup() lookup.put_string("a", """this is a""") @@ -553,7 +553,7 @@ class UndefinedVarsTest(TemplateTest): x: ${x} % endif """) - + assert result_lines(t.render(x=12)) == ["x: 12"] assert result_lines(t.render(y=12)) == ["undefined"] @@ -565,14 +565,14 @@ class UndefinedVarsTest(TemplateTest): x: ${x} % endif """, strict_undefined=True) - + assert result_lines(t.render(x=12)) == ['x: 12'] - + assert_raises( NameError, t.render, y=12 ) - + l = TemplateLookup(strict_undefined=True) l.put_string("a", "some template") l.put_string("b", """ @@ -585,41 +585,41 @@ class UndefinedVarsTest(TemplateTest): """) assert result_lines(t.render(x=12)) == ['x: 12'] - + assert_raises( NameError, t.render, y=12 ) - + def test_expression_declared(self): t = Template(""" ${",".join([t for t in ("a", "b", "c")])} """, strict_undefined=True) - + eq_(result_lines(t.render()), ['a,b,c']) t = Template(""" <%self:foo value="${[(val, n) for val, n in [(1, 2)]]}"/> - + <%def name="foo(value)"> ${value} </%def> - + """, strict_undefined=True) - + eq_(result_lines(t.render()), ['[(1, 2)]']) t = Template(""" <%call expr="foo(value=[(val, n) for val, n in [(1, 2)]])" /> - + <%def name="foo(value)"> ${value} </%def> - + """, strict_undefined=True) - + eq_(result_lines(t.render()), ['[(1, 2)]']) - + l = TemplateLookup(strict_undefined=True) l.put_string("i", "hi, ${pageargs['y']}") l.put_string("t", """ @@ -628,7 +628,7 @@ class UndefinedVarsTest(TemplateTest): eq_( result_lines(l.get_template("t").render()), ['hi, [0, 1, 2]'] ) - + l.put_string('q', """ <%namespace name="i" file="${(str([x for x in range(3)][2]) + 'i')[-1]}" /> ${i.body(y='x')} @@ -652,19 +652,19 @@ class UndefinedVarsTest(TemplateTest): # is treated as an "undefined", so is pulled from the context. t = Template(""" t is: ${t} - + ${",".join([t for t in ("a", "b", "c")])} """) - + eq_( result_lines(t.render(t="T")), ['t is: T', 'a,b,c'] ) - + def test_traditional_assignment_plus_undeclared(self): t = Template(""" t is: ${t} - + <% t = 12 %> @@ -673,22 +673,22 @@ class UndefinedVarsTest(TemplateTest): UnboundLocalError, t.render, t="T" ) - + def test_list_comprehensions_plus_undeclared_strict(self): # with strict, a list comprehension now behaves # like the undeclared case above. t = Template(""" t is: ${t} - + ${",".join([t for t in ("a", "b", "c")])} """, strict_undefined=True) - + eq_( result_lines(t.render(t="T")), ['t is: T', 'a,b,c'] ) - - + + class ControlTest(TemplateTest): def test_control(self): t = Template(""" @@ -706,7 +706,7 @@ class ControlTest(TemplateTest): "no x does not have test", "yes x has test" ] - + def test_blank_control(self): self._do_memory_test( """ @@ -716,7 +716,7 @@ class ControlTest(TemplateTest): "", filters=lambda s:s.strip() ) - + def test_multiline_control(self): t = Template(""" % for x in \\ @@ -726,7 +726,7 @@ class ControlTest(TemplateTest): """) #print t.code assert flatten_result(t.render()) == "1 2 3" - + class GlobalsTest(TemplateTest): def test_globals(self): self._do_memory_test( @@ -741,7 +741,7 @@ class GlobalsTest(TemplateTest): ) class RichTracebackTest(TemplateTest): - + def _do_test_traceback(self, utf8, memory, syntax): if memory: if syntax: @@ -825,7 +825,7 @@ class ModuleDirTest(TemplateTest): class FilenameToURITest(TemplateTest): def test_windows_paths(self): """test that windows filenames are handled appropriately by Template.""" - + current_path = os.path import ntpath os.path = ntpath @@ -834,11 +834,11 @@ class FilenameToURITest(TemplateTest): def _compile_from_file(self, path, filename): self.path = path return Template("foo bar").module - + t1 = NoCompileTemplate( filename="c:\\foo\\template.html", module_directory="c:\\modules\\") - + eq_(t1.uri, "/foo/template.html") eq_(t1.path, "c:\\modules\\foo\\template.html.py") @@ -846,7 +846,7 @@ class FilenameToURITest(TemplateTest): filename="c:\\path\\to\\templates\\template.html", uri = "/bar/template.html", module_directory="c:\\modules\\") - + eq_(t1.uri, "/bar/template.html") eq_(t1.path, "c:\\modules\\bar\\template.html.py") @@ -882,16 +882,16 @@ class FilenameToURITest(TemplateTest): finally: os.path = current_path - - - + + + class ModuleTemplateTest(TemplateTest): def test_module_roundtrip(self): lookup = TemplateLookup() template = Template(""" <%inherit file="base.html"/> - + % for x in range(5): ${x} % endfor @@ -904,30 +904,30 @@ class ModuleTemplateTest(TemplateTest): lookup.put_template("base.html", base) lookup.put_template("template.html", template) - + assert result_lines(template.render()) == [ "This is base.", "0", "1", "2", "3", "4" ] - + lookup = TemplateLookup() template = ModuleTemplate(template.module, lookup=lookup) base = ModuleTemplate(base.module, lookup=lookup) lookup.put_template("base.html", base) lookup.put_template("template.html", template) - + assert result_lines(template.render()) == [ "This is base.", "0", "1", "2", "3", "4" ] - - + + class PreprocessTest(TemplateTest): def test_old_comments(self): t = Template(""" im a template # old style comment # more old style comment - + ## new style comment - # not a comment - ## not a comment diff --git a/test/test_tgplugin.py b/test/test_tgplugin.py index f611a37..3aa6122 100644 --- a/test/test_tgplugin.py +++ b/test/test_tgplugin.py @@ -36,7 +36,7 @@ class TestTGPlugin(TemplateTest): ] assert tl.load_template('subdir.index').module_id == '_subdir_index_html' - + def test_string(self): t = tl.load_template('foo', "hello world") assert t.render() == "hello world" |
