From: Armin Ronacher Date: Tue, 9 Feb 2010 20:27:54 +0000 (+0100) Subject: Removed old testsuite. X-Git-Tag: 2.3~10 X-Git-Url: http://git.ipfire.org/cgi-bin/gitweb.cgi?a=commitdiff_plain;h=b36ddc9a97c3f17b8f728707f0e61ec6cb49d148;p=thirdparty%2Fjinja.git Removed old testsuite. --HG-- branch : trunk --- diff --git a/Makefile b/Makefile index 31756939..60ca1d7a 100644 --- a/Makefile +++ b/Makefile @@ -1,8 +1,4 @@ test: - nosetests --with-doctest jinja2 tests - -2to3: - rm -rf build/lib - python3 setup.py build + python setup.py test .PHONY: test diff --git a/tests/loaderres/__init__.py b/tests/loaderres/__init__.py deleted file mode 100644 index e69de29b..00000000 diff --git a/tests/loaderres/templates/broken.html b/tests/loaderres/templates/broken.html deleted file mode 100644 index 77669fae..00000000 --- a/tests/loaderres/templates/broken.html +++ /dev/null @@ -1,3 +0,0 @@ -Before -{{ fail() }} -After diff --git a/tests/loaderres/templates/foo/test.html b/tests/loaderres/templates/foo/test.html deleted file mode 100644 index b7d6715e..00000000 --- a/tests/loaderres/templates/foo/test.html +++ /dev/null @@ -1 +0,0 @@ -FOO diff --git a/tests/loaderres/templates/syntaxerror.html b/tests/loaderres/templates/syntaxerror.html deleted file mode 100644 index f21b8179..00000000 --- a/tests/loaderres/templates/syntaxerror.html +++ /dev/null @@ -1,4 +0,0 @@ -Foo -{% for item in broken %} - ... -{% endif %} diff --git a/tests/loaderres/templates/test.html b/tests/loaderres/templates/test.html deleted file mode 100644 index ba578e48..00000000 --- a/tests/loaderres/templates/test.html +++ /dev/null @@ -1 +0,0 @@ -BAR diff --git a/tests/test_debug.py b/tests/test_debug.py deleted file mode 100644 index 921b3350..00000000 --- a/tests/test_debug.py +++ /dev/null @@ -1,51 +0,0 @@ -# -*- coding: utf-8 -*- -""" - Test debug interface - ~~~~~~~~~~~~~~~~~~~~ - - Tests the traceback rewriter. - - :copyright: (c) 2009 by the Jinja Team. - :license: BSD. -""" -from jinja2 import Environment -from test_loaders import filesystem_loader - -env = Environment(loader=filesystem_loader) - - -def test_runtime_error(): - ''' ->>> tmpl = env.get_template('broken.html') ->>> tmpl.render(fail=lambda: 1 / 0) -Traceback (most recent call last): - File "loaderres/templates/broken.html", line 2, in top-level template code - {{ fail() }} - File "", line 1, in - tmpl.render(fail=lambda: 1 / 0) -ZeroDivisionError: integer division or modulo by zero -''' - - -def test_syntax_error(): - ''' ->>> tmpl = env.get_template('syntaxerror.html') -Traceback (most recent call last): - ... - File "tests/loaderres/templates/syntaxerror.html", line 4, in template - {% endif %} -TemplateSyntaxError: Encountered unknown tag 'endif'. Jinja was looking for the following tags: 'endfor' or 'else'. The innermost block that needs to be closed is 'for'. -''' - - -def test_regular_syntax_error(): - ''' ->>> from jinja2.exceptions import TemplateSyntaxError ->>> raise TemplateSyntaxError('wtf', 42) -Traceback (most recent call last): - ... - File "", line 1, in - raise TemplateSyntaxError('wtf', 42) -TemplateSyntaxError: wtf - line 42 -''' diff --git a/tests/test_ext.py b/tests/test_ext.py deleted file mode 100644 index ef33de7e..00000000 --- a/tests/test_ext.py +++ /dev/null @@ -1,173 +0,0 @@ -# -*- coding: utf-8 -*- -""" - unit test for some extensions - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - :copyright: (c) 2009 by the Jinja Team. - :license: BSD, see LICENSE for more details. -""" -import re -from jinja2 import Environment, nodes -from jinja2.ext import Extension -from jinja2.lexer import Token, count_newlines - - -importable_object = 23 - - -_gettext_re = re.compile(r'_\((.*?)\)(?s)') - - -class TestExtension(Extension): - tags = set(['test']) - ext_attr = 42 - - def parse(self, parser): - return nodes.Output([self.call_method('_dump', [ - nodes.EnvironmentAttribute('sandboxed'), - self.attr('ext_attr'), - nodes.ImportedName(__name__ + '.importable_object'), - nodes.ContextReference() - ])]).set_lineno(parser.stream.next().lineno) - - def _dump(self, sandboxed, ext_attr, imported_object, context): - return '%s|%s|%s|%s' % ( - sandboxed, - ext_attr, - imported_object, - context.blocks - ) - - -class PreprocessorExtension(Extension): - - def preprocess(self, source, name, filename=None): - return source.replace('[[TEST]]', '({{ foo }})') - - -class StreamFilterExtension(Extension): - - def filter_stream(self, stream): - for token in stream: - if token.type == 'data': - for t in self.interpolate(token): - yield t - else: - yield token - - def interpolate(self, token): - pos = 0 - end = len(token.value) - lineno = token.lineno - while 1: - match = _gettext_re.search(token.value, pos) - if match is None: - break - value = token.value[pos:match.start()] - if value: - yield Token(lineno, 'data', value) - lineno += count_newlines(token.value) - yield Token(lineno, 'variable_begin', None) - yield Token(lineno, 'name', 'gettext') - yield Token(lineno, 'lparen', None) - yield Token(lineno, 'string', match.group(1)) - yield Token(lineno, 'rparen', None) - yield Token(lineno, 'variable_end', None) - pos = match.end() - if pos < end: - yield Token(lineno, 'data', token.value[pos:]) - - -def test_loop_controls(): - env = Environment(extensions=['jinja2.ext.loopcontrols']) - - tmpl = env.from_string(''' - {%- for item in [1, 2, 3, 4] %} - {%- if item % 2 == 0 %}{% continue %}{% endif -%} - {{ item }} - {%- endfor %}''') - assert tmpl.render() == '13' - - tmpl = env.from_string(''' - {%- for item in [1, 2, 3, 4] %} - {%- if item > 2 %}{% break %}{% endif -%} - {{ item }} - {%- endfor %}''') - assert tmpl.render() == '12' - - -def test_do(): - env = Environment(extensions=['jinja2.ext.do']) - tmpl = env.from_string(''' - {%- set items = [] %} - {%- for char in "foo" %} - {%- do items.append(loop.index0 ~ char) %} - {%- endfor %}{{ items|join(', ') }}''') - assert tmpl.render() == '0f, 1o, 2o' - - -def test_with(): - env = Environment(extensions=['jinja2.ext.with_']) - tmpl = env.from_string('''\ - {% with a=42, b=23 -%} - {{ a }} = {{ b }} - {% endwith -%} - {{ a }} = {{ b }}\ - ''') - assert [x.strip() for x in tmpl.render(a=1, b=2).splitlines()] \ - == ['42 = 23', '1 = 2'] - - -def test_extension_nodes(): - env = Environment(extensions=[TestExtension]) - tmpl = env.from_string('{% test %}') - assert tmpl.render() == 'False|42|23|{}' - - -def test_identifier(): - assert TestExtension.identifier == __name__ + '.TestExtension' - - -def test_rebinding(): - original = Environment(extensions=[TestExtension]) - overlay = original.overlay() - for env in original, overlay: - for ext in env.extensions.itervalues(): - assert ext.environment is env - - -def test_preprocessor_extension(): - env = Environment(extensions=[PreprocessorExtension]) - tmpl = env.from_string('{[[TEST]]}') - assert tmpl.render(foo=42) == '{(42)}' - - -def test_streamfilter_extension(): - env = Environment(extensions=[StreamFilterExtension]) - env.globals['gettext'] = lambda x: x.upper() - tmpl = env.from_string('Foo _(bar) Baz') - out = tmpl.render() - assert out == 'Foo BAR Baz' - - -class WithExtension(Extension): - tags = frozenset(['with']) - - def parse(self, parser): - lineno = parser.stream.next().lineno - value = parser.parse_expression() - parser.stream.expect('name:as') - name = parser.stream.expect('name') - - body = parser.parse_statements(['name:endwith'], drop_needle=True) - body.insert(0, nodes.Assign(nodes.Name(name.value, 'store'), value)) - return nodes.Scope(body) - - -def test_with_extension(): - env = Environment(extensions=[WithExtension]) - t = env.from_string('{{ a }}{% with 2 as a %}{{ a }}{% endwith %}{{ a }}') - assert t.render(a=1) == '121' - - t = env.from_string('{% with 2 as a %}{{ a }}{% endwith %}{{ a }}') - assert t.render(a=3) == '23' diff --git a/tests/test_filters.py b/tests/test_filters.py deleted file mode 100644 index 57416937..00000000 --- a/tests/test_filters.py +++ /dev/null @@ -1,328 +0,0 @@ -# -*- coding: utf-8 -*- -""" - unit test for the filters - ~~~~~~~~~~~~~~~~~~~~~~~~~ - - :copyright: (c) 2009 by the Jinja Team. - :license: BSD, see LICENSE for more details. -""" -from jinja2 import Markup, Environment - -env = Environment() - - -CAPITALIZE = '''{{ "foo bar"|capitalize }}''' -CENTER = '''{{ "foo"|center(9) }}''' -DEFAULT = '''{{ missing|default("no") }}|{{ false|default('no') }}|\ -{{ false|default('no', true) }}|{{ given|default("no") }}''' -DICTSORT = '''{{ foo|dictsort }}|\ -{{ foo|dictsort(true) }}|\ -{{ foo|dictsort(false, 'value') }}''' -BATCH = '''{{ foo|batch(3)|list }}|{{ foo|batch(3, 'X')|list }}''' -SLICE = '''{{ foo|slice(3)|list }}|{{ foo|slice(3, 'X')|list }}''' -ESCAPE = '''{{ '<">&'|escape }}''' -STRIPTAGS = '''{{ foo|striptags }}''' -FILESIZEFORMAT = '{{ 100|filesizeformat }}|\ -{{ 1000|filesizeformat }}|\ -{{ 1000000|filesizeformat }}|\ -{{ 1000000000|filesizeformat }}|\ -{{ 1000000000000|filesizeformat }}|\ -{{ 100|filesizeformat(true) }}|\ -{{ 1000|filesizeformat(true) }}|\ -{{ 1000000|filesizeformat(true) }}|\ -{{ 1000000000|filesizeformat(true) }}|\ -{{ 1000000000000|filesizeformat(true) }}' -FIRST = '''{{ foo|first }}''' -FLOAT = '''{{ "42"|float }}|{{ "ajsghasjgd"|float }}|{{ "32.32"|float }}''' -FORMAT = '''{{ "%s|%s"|format("a", "b") }}''' -INDENT = '''{{ foo|indent(2) }}|{{ foo|indent(2, true) }}''' -INT = '''{{ "42"|int }}|{{ "ajsghasjgd"|int }}|{{ "32.32"|int }}''' -JOIN = '''{{ [1, 2, 3]|join("|") }}''' -LAST = '''{{ foo|last }}''' -LENGTH = '''{{ "hello world"|length }}''' -LOWER = '''{{ "FOO"|lower }}''' -PPRINT = '''{{ data|pprint }}''' -RANDOM = '''{{ seq|random }}''' -REVERSE = '''{{ "foobar"|reverse|join }}|{{ [1, 2, 3]|reverse|list }}''' -STRING = '''{{ range(10)|string }}''' -TITLE = '''{{ "foo bar"|title }}''' -TRIM = '''{{ " foo "|trim }}''' -TRUNCATE = '''{{ data|truncate(15, true, ">>>") }}|\ -{{ data|truncate(15, false, ">>>") }}|\ -{{ smalldata|truncate(15) }}''' -UPPER = '''{{ "foo"|upper }}''' -URLIZE = '''{{ "foo http://www.example.com/ bar"|urlize }}''' -WORDCOUNT = '''{{ "foo bar baz"|wordcount }}''' -BLOCK = '''{% filter lower|escape %}{% endfilter %}''' -CHAINING = '''{{ ['', '']|first|upper|escape }}''' -SUM = '''{{ [1, 2, 3, 4, 5, 6]|sum }}''' -ABS = '''{{ -1|abs }}|{{ 1|abs }}''' -ROUND = '''{{ 2.7|round }}|{{ 2.1|round }}|\ -{{ 2.1234|round(2, 'floor') }}|{{ 2.1|round(0, 'ceil') }}''' -XMLATTR = '''{{ {'foo': 42, 'bar': 23, 'fish': none, -'spam': missing, 'blub:blub': ''}|xmlattr }}''' -SORT1 = '''{{ [2, 3, 1]|sort }}|{{ [2, 3, 1]|sort(true) }}''' -GROUPBY = '''{% for grouper, list in [{'foo': 1, 'bar': 2}, - {'foo': 2, 'bar': 3}, - {'foo': 1, 'bar': 1}, - {'foo': 3, 'bar': 4}]|groupby('foo') -%} -{{ grouper }}: {{ list|join(', ') }} -{% endfor %}''' -FILTERTAG = '''{% filter upper|replace('FOO', 'foo') %}foobar{% endfilter %}''' -SORT2 = '''{{ ['foo', 'Bar', 'blah']|sort }}''' - - -def test_capitalize(): - tmpl = env.from_string(CAPITALIZE) - assert tmpl.render() == 'Foo bar' - - -def test_center(): - tmpl = env.from_string(CENTER) - assert tmpl.render() == ' foo ' - - -def test_default(): - tmpl = env.from_string(DEFAULT) - assert tmpl.render(given='yes') == 'no|False|no|yes' - - -def test_dictsort(): - tmpl = env.from_string(DICTSORT) - out = tmpl.render(foo={"aa": 0, "b": 1, "c": 2, "AB": 3}) - assert out == ("[('aa', 0), ('AB', 3), ('b', 1), ('c', 2)]|" - "[('AB', 3), ('aa', 0), ('b', 1), ('c', 2)]|" - "[('aa', 0), ('b', 1), ('c', 2), ('AB', 3)]") - - -def test_batch(): - tmpl = env.from_string(BATCH) - out = tmpl.render(foo=range(10)) - assert out == ("[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]|" - "[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 'X', 'X']]") - - -def test_slice(): - tmpl = env.from_string(SLICE) - out = tmpl.render(foo=range(10)) - assert out == ("[[0, 1, 2, 3], [4, 5, 6], [7, 8, 9]]|" - "[[0, 1, 2, 3], [4, 5, 6, 'X'], [7, 8, 9, 'X']]") - - -def test_escape(): - tmpl = env.from_string(ESCAPE) - out = tmpl.render() - assert out == '<">&' - - -def test_striptags(): - tmpl = env.from_string(STRIPTAGS) - out = tmpl.render(foo='

just a small \n ' - 'example link

\n

to a webpage

' - '') - assert out == 'just a small example link to a webpage' - - -def test_filesizeformat(): - tmpl = env.from_string(FILESIZEFORMAT) - out = tmpl.render() - assert out == ( - '100 Bytes|1.0 KB|1.0 MB|1.0 GB|1000.0 GB|' - '100 Bytes|1000 Bytes|976.6 KiB|953.7 MiB|931.3 GiB' - ) - - -def test_first(): - tmpl = env.from_string(FIRST) - out = tmpl.render(foo=range(10)) - assert out == '0' - - -def test_float(): - tmpl = env.from_string(FLOAT) - out = tmpl.render() - assert out == '42.0|0.0|32.32' - - -def test_format(): - tmpl = env.from_string(FORMAT) - out = tmpl.render() - assert out == 'a|b' - - -def test_indent(): - tmpl = env.from_string(INDENT) - text = '\n'.join([' '.join(['foo', 'bar'] * 2)] * 2) - out = tmpl.render(foo=text) - assert out == ('foo bar foo bar\n foo bar foo bar| ' - 'foo bar foo bar\n foo bar foo bar') - - -def test_int(): - tmpl = env.from_string(INT) - out = tmpl.render() - assert out == '42|0|32' - - -def test_join(): - tmpl = env.from_string(JOIN) - out = tmpl.render() - assert out == '1|2|3' - - env2 = Environment(autoescape=True) - tmpl = env2.from_string('{{ ["", "foo"|safe]|join }}') - assert tmpl.render() == '<foo>foo' - - -def test_last(): - tmpl = env.from_string(LAST) - out = tmpl.render(foo=range(10)) - assert out == '9' - - -def test_length(): - tmpl = env.from_string(LENGTH) - out = tmpl.render() - assert out == '11' - - -def test_lower(): - tmpl = env.from_string(LOWER) - out = tmpl.render() - assert out == 'foo' - - -def test_pprint(): - from pprint import pformat - tmpl = env.from_string(PPRINT) - data = range(1000) - assert tmpl.render(data=data) == pformat(data) - - -def test_random(): - tmpl = env.from_string(RANDOM) - seq = range(100) - for _ in range(10): - assert int(tmpl.render(seq=seq)) in seq - - -def test_reverse(): - tmpl = env.from_string(REVERSE) - assert tmpl.render() == 'raboof|[3, 2, 1]' - - -def test_string(): - tmpl = env.from_string(STRING) - assert tmpl.render(foo=range(10)) == unicode(xrange(10)) - - -def test_title(): - tmpl = env.from_string(TITLE) - assert tmpl.render() == "Foo Bar" - - -def test_truncate(): - tmpl = env.from_string(TRUNCATE) - out = tmpl.render(data='foobar baz bar' * 1000, - smalldata='foobar baz bar') - assert out == 'foobar baz barf>>>|foobar baz >>>|foobar baz bar' - - -def test_upper(): - tmpl = env.from_string(UPPER) - assert tmpl.render() == 'FOO' - - -def test_urlize(): - tmpl = env.from_string(URLIZE) - assert tmpl.render() == 'foo '\ - 'http://www.example.com/ bar' - - -def test_wordcount(): - tmpl = env.from_string(WORDCOUNT) - assert tmpl.render() == '3' - - -def test_block(): - tmpl = env.from_string(BLOCK) - assert tmpl.render() == '<hehe>' - - -def test_chaining(): - tmpl = env.from_string(CHAINING) - assert tmpl.render() == '<FOO>' - - -def test_sum(): - tmpl = env.from_string(SUM) - assert tmpl.render() == '21' - - -def test_abs(): - tmpl = env.from_string(ABS) - return tmpl.render() == '1|1' - - -def test_round(): - tmpl = env.from_string(ROUND) - return tmpl.render() == '3.0|2.0|2.1|3.0' - - -def test_xmlattr(): - tmpl = env.from_string(XMLATTR) - out = tmpl.render().split() - assert len(out) == 3 - assert 'foo="42"' in out - assert 'bar="23"' in out - assert 'blub:blub="<?>"' in out - - -def test_sort1(): - tmpl = env.from_string(SORT1) - assert tmpl.render() == '[1, 2, 3]|[3, 2, 1]' - - -def test_groupby(): - tmpl = env.from_string(GROUPBY) - assert tmpl.render().splitlines() == [ - "1: {'foo': 1, 'bar': 2}, {'foo': 1, 'bar': 1}", - "2: {'foo': 2, 'bar': 3}", - "3: {'foo': 3, 'bar': 4}" - ] - - -def test_filtertag(): - tmpl = env.from_string(FILTERTAG) - assert tmpl.render() == 'fooBAR' - - -def test_replace(): - env = Environment() - tmpl = env.from_string('{{ string|replace("o", 42) }}') - assert tmpl.render(string='') == '' - - env = Environment(autoescape=True) - tmpl = env.from_string('{{ string|replace("o", 42) }}') - assert tmpl.render(string='') == '<f4242>' - tmpl = env.from_string('{{ string|replace("<", 42) }}') - assert tmpl.render(string='') == '42foo>' - tmpl = env.from_string('{{ string|replace("o", ">x<") }}') - assert tmpl.render(string=Markup('foo')) == 'f>x<>x<' - - -def test_forceescape(): - tmpl = env.from_string('{{ x|forceescape }}') - assert tmpl.render(x=Markup('
')) == u'<div />' - - -def test_safe(): - env = Environment(autoescape=True) - tmpl = env.from_string('{{ "
foo
"|safe }}') - assert tmpl.render() == '
foo
' - tmpl = env.from_string('{{ "
foo
" }}') - assert tmpl.render() == '<div>foo</div>' - - -def test_sort2(): - assert env.from_string(SORT2).render() == "['Bar', 'blah', 'foo']" diff --git a/tests/test_forloop.py b/tests/test_forloop.py deleted file mode 100644 index dd66ca02..00000000 --- a/tests/test_forloop.py +++ /dev/null @@ -1,190 +0,0 @@ -# -*- coding: utf-8 -*- -""" - unit test for loop functions - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - :copyright: (c) 2009 by the Jinja Team. - :license: BSD, see LICENSE for more details. -""" -from jinja2 import Environment -from jinja2.exceptions import UndefinedError, TemplateSyntaxError - -from nose.tools import assert_raises - -env = Environment() - - -SIMPLE = '''{% for item in seq %}{{ item }}{% endfor %}''' -ELSE = '''{% for item in seq %}XXX{% else %}...{% endfor %}''' -EMPTYBLOCKS = '''<{% for item in seq %}{% else %}{% endfor %}>''' -CONTEXTVARS = '''{% for item in seq %}\ -{{ loop.index }}|{{ loop.index0 }}|{{ loop.revindex }}|{{ - loop.revindex0 }}|{{ loop.first }}|{{ loop.last }}|{{ - loop.length }}###{% endfor %}''' -CYCLING = '''{% for item in seq %}{{ loop.cycle('<1>', '<2>') }}{% endfor %}\ -{% for item in seq %}{{ loop.cycle(*through) }}{% endfor %}''' -SCOPE = '''{% for item in seq %}{% endfor %}{{ item }}''' -VARLEN = '''{% for item in iter %}{{ item }}{% endfor %}''' -NONITER = '''{% for item in none %}...{% endfor %}''' -RECURSIVE = '''{% for item in seq recursive -%} - [{{ item.a }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}] -{%- endfor %}''' -LOOPLOOP = '''{% for row in table %} - {%- set rowloop = loop -%} - {% for cell in row -%} - [{{ rowloop.index }}|{{ loop.index }}] - {%- endfor %} -{%- endfor %}''' -LOOPERROR1 = '''\ -{% for item in [1] if loop.index == 0 %}...{% endfor %}''' -LOOPERROR2 = '''\ -{% for item in [] %}...{% else %}{{ loop }}{% endfor %}''' -LOOPFILTER = '''\ -{% for item in range(10) if item is even %}[{{ item }}]{% endfor %}''' -EXTENDEDLOOPFILTER = '''\ -{% for item in range(10) if item is even %}[{{ loop.index -}}:{{ item }}]{% endfor %}''' -LOOPUNASSIGNABLE = '''\ -{% for loop in seq %}...{% endfor %}''' - - -def test_simple(): - tmpl = env.from_string(SIMPLE) - assert tmpl.render(seq=range(10)) == '0123456789' - - -def test_else(): - tmpl = env.from_string(ELSE) - assert tmpl.render() == '...' - - -def test_empty_blocks(): - tmpl = env.from_string(EMPTYBLOCKS) - assert tmpl.render() == '<>' - - -def test_context_vars(): - tmpl = env.from_string(CONTEXTVARS) - one, two, _ = tmpl.render(seq=[0, 1]).split('###') - (one_index, one_index0, one_revindex, one_revindex0, one_first, - one_last, one_length) = one.split('|') - (two_index, two_index0, two_revindex, two_revindex0, two_first, - two_last, two_length) = two.split('|') - - assert int(one_index) == 1 and int(two_index) == 2 - assert int(one_index0) == 0 and int(two_index0) == 1 - assert int(one_revindex) == 2 and int(two_revindex) == 1 - assert int(one_revindex0) == 1 and int(two_revindex0) == 0 - assert one_first == 'True' and two_first == 'False' - assert one_last == 'False' and two_last == 'True' - assert one_length == two_length == '2' - - -def test_cycling(): - tmpl = env.from_string(CYCLING) - output = tmpl.render(seq=range(4), through=('<1>', '<2>')) - assert output == '<1><2>' * 4 - - -def test_scope(): - tmpl = env.from_string(SCOPE) - output = tmpl.render(seq=range(10)) - assert not output - - -def test_varlen(): - def inner(): - for item in range(5): - yield item - tmpl = env.from_string(VARLEN) - output = tmpl.render(iter=inner()) - assert output == '01234' - - -def test_noniter(): - tmpl = env.from_string(NONITER) - assert_raises(TypeError, tmpl.render) - - -def test_recursive(): - tmpl = env.from_string(RECURSIVE) - assert tmpl.render(seq=[ - dict(a=1, b=[dict(a=1), dict(a=2)]), - dict(a=2, b=[dict(a=1), dict(a=2)]), - dict(a=3, b=[dict(a='a')]) - ]) == '[1<[1][2]>][2<[1][2]>][3<[a]>]' - - -def test_looploop(): - tmpl = env.from_string(LOOPLOOP) - assert tmpl.render(table=['ab', 'cd']) == '[1|1][1|2][2|1][2|2]' - - -def test_reversed_bug(): - tmpl = env.from_string('{% for i in items %}{{ i }}{% if not loop.last %}' - ',{% endif %}{% endfor %}') - assert tmpl.render(items=reversed([3, 2, 1])) == '1,2,3' - - -def test_loop_errors(): - tmpl = env.from_string(LOOPERROR1) - assert_raises(UndefinedError, tmpl.render) - tmpl = env.from_string(LOOPERROR2) - assert tmpl.render() == '' - - -def test_loop_filter(): - tmpl = env.from_string(LOOPFILTER) - assert tmpl.render() == '[0][2][4][6][8]' - tmpl = env.from_string(EXTENDEDLOOPFILTER) - assert tmpl.render() == '[1:0][2:2][3:4][4:6][5:8]' - - -def test_loop_unassignable(): - assert_raises(TemplateSyntaxError, env.from_string, LOOPUNASSIGNABLE) - - -def test_scoped_special_var(): - t = env.from_string('{% for s in seq %}[{{ loop.first }}{% for c in s %}' - '|{{ loop.first }}{% endfor %}]{% endfor %}') - assert t.render(seq=('ab', 'cd')) == '[True|True|False][False|True|False]' - - -def test_scoped_loop_var(): - t = env.from_string('{% for x in seq %}{{ loop.first }}' - '{% for y in seq %}{% endfor %}{% endfor %}') - assert t.render(seq='ab') == 'TrueFalse' - t = env.from_string('{% for x in seq %}{% for y in seq %}' - '{{ loop.first }}{% endfor %}{% endfor %}') - assert t.render(seq='ab') == 'TrueFalseTrueFalse' - - -def test_recursive_empty_loop_iter(): - t = env.from_string(''' - {%- for item in foo recursive -%}{%- endfor -%} - ''') - assert t.render(dict(foo=[])) == '' - - -def test_call_in_loop(): - t = env.from_string(''' - {%- macro do_something() -%} - [{{ caller() }}] - {%- endmacro %} - - {%- for i in [1, 2, 3] %} - {%- call do_something() -%} - {{ i }} - {%- endcall %} - {%- endfor -%} - ''') - assert t.render() == '[1][2][3]' - - -def test_scoping_bug(): - t = env.from_string(''' - {%- for item in foo %}...{{ item }}...{% endfor %} - {%- macro item(a) %}...{{ a }}...{% endmacro %} - {{- item(2) -}} - ''') - assert t.render(foo=(1,)) == '...1......2...' diff --git a/tests/test_heavy.py b/tests/test_heavy.py deleted file mode 100644 index b045fbb8..00000000 --- a/tests/test_heavy.py +++ /dev/null @@ -1,73 +0,0 @@ -# -*- coding: utf-8 -*- -""" - Heavy tests - ~~~~~~~~~~~ - - The tests in this module test complex Jinja2 situations to ensure - corner cases (unfortunately mostly undocumented scoping behavior) - does not change between versions. - - :copyright: Copyright 2009 by the Jinja Team. - :license: BSD. -""" -from jinja2 import Environment -env = Environment() - - -def test_assigned_scoping(): - t = env.from_string(''' - {%- for item in (1, 2, 3, 4) -%} - [{{ item }}] - {%- endfor %} - {{- item -}} - ''') - assert t.render(item=42) == '[1][2][3][4]42' - - t = env.from_string(''' - {%- for item in (1, 2, 3, 4) -%} - [{{ item }}] - {%- endfor %} - {%- set item = 42 %} - {{- item -}} - ''') - assert t.render() == '[1][2][3][4]42' - - t = env.from_string(''' - {%- set item = 42 %} - {%- for item in (1, 2, 3, 4) -%} - [{{ item }}] - {%- endfor %} - {{- item -}} - ''') - assert t.render() == '[1][2][3][4]42' - - -def test_closure_scoping(): - t = env.from_string(''' - {%- set wrapper = "" %} - {%- for item in (1, 2, 3, 4) %} - {%- macro wrapper() %}[{{ item }}]{% endmacro %} - {{- wrapper() }} - {%- endfor %} - {{- wrapper -}} - ''') - assert t.render() == '[1][2][3][4]' - - t = env.from_string(''' - {%- for item in (1, 2, 3, 4) %} - {%- macro wrapper() %}[{{ item }}]{% endmacro %} - {{- wrapper() }} - {%- endfor %} - {%- set wrapper = "" %} - {{- wrapper -}} - ''') - assert t.render() == '[1][2][3][4]' - - t = env.from_string(''' - {%- for item in (1, 2, 3, 4) %} - {%- macro wrapper() %}[{{ item }}]{% endmacro %} - {{- wrapper() }} - {%- endfor %} - {{- wrapper -}} - ''') - assert t.render(wrapper=23) == '[1][2][3][4]23' diff --git a/tests/test_i18n.py b/tests/test_i18n.py deleted file mode 100644 index 823ce850..00000000 --- a/tests/test_i18n.py +++ /dev/null @@ -1,114 +0,0 @@ -# -*- coding: utf-8 -*- -""" - unit test for the i18n functions - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - :copyright: (c) 2009 by the Jinja Team. - :license: BSD, see LICENSE for more details. -""" -from jinja2 import Environment, DictLoader, contextfunction -from jinja2.exceptions import TemplateAssertionError - -from nose.tools import assert_raises - -templates = { - 'master.html': '{{ page_title|default(_("missing")) }}' - '{% block body %}{% endblock %}', - 'child.html': '{% extends "master.html" %}{% block body %}' - '{% trans %}watch out{% endtrans %}{% endblock %}', - 'plural.html': '{% trans user_count %}One user online{% pluralize %}' - '{{ user_count }} users online{% endtrans %}', - 'stringformat.html': '{{ _("User: %d")|format(user_count) }}' -} - - -languages = { - 'de': { - 'missing': 'fehlend', - 'watch out': 'pass auf', - 'One user online': 'Ein Benutzer online', - '%(user_count)s users online': '%(user_count)s Benutzer online', - 'User: %d': 'Benutzer: %d' - } -} - - -@contextfunction -def gettext(context, string): - language = context.get('LANGUAGE', 'en') - return languages.get(language, {}).get(string, string) - - -@contextfunction -def ngettext(context, s, p, n): - language = context.get('LANGUAGE', 'en') - if n != 1: - return languages.get(language, {}).get(p, p) - return languages.get(language, {}).get(s, s) - - -i18n_env = Environment( - loader=DictLoader(templates), - extensions=['jinja2.ext.i18n'] -) -i18n_env.globals.update({ - '_': gettext, - 'gettext': gettext, - 'ngettext': ngettext -}) - - -def test_trans(): - tmpl = i18n_env.get_template('child.html') - assert tmpl.render(LANGUAGE='de') == 'fehlendpass auf' - - -def test_trans_plural(): - tmpl = i18n_env.get_template('plural.html') - assert tmpl.render(LANGUAGE='de', user_count=1) == 'Ein Benutzer online' - assert tmpl.render(LANGUAGE='de', user_count=2) == '2 Benutzer online' - - -def test_complex_plural(): - tmpl = i18n_env.from_string('{% trans foo=42, count=2 %}{{ count }} item{% ' - 'pluralize count %}{{ count }} items{% endtrans %}') - assert tmpl.render() == '2 items' - assert_raises(TemplateAssertionError, i18n_env.from_string, - '{% trans foo %}...{% pluralize bar %}...{% endtrans %}') - - -def test_trans_stringformatting(): - tmpl = i18n_env.get_template('stringformat.html') - assert tmpl.render(LANGUAGE='de', user_count=5) == 'Benutzer: 5' - - -def test_extract(): - from jinja2.ext import babel_extract - from StringIO import StringIO - source = StringIO(''' - {{ gettext('Hello World') }} - {% trans %}Hello World{% endtrans %} - {% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %} - ''') - assert list(babel_extract(source, ('gettext', 'ngettext', '_'), [], {})) == [ - (2, 'gettext', u'Hello World', []), - (3, 'gettext', u'Hello World', []), - (4, 'ngettext', (u'%(users)s user', u'%(users)s users', None), []) - ] - - -def test_comment_extract(): - from jinja2.ext import babel_extract - from StringIO import StringIO - source = StringIO(''' - {# trans first #} - {{ gettext('Hello World') }} - {% trans %}Hello World{% endtrans %}{# trans second #} - {#: third #} - {% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %} - ''') - assert list(babel_extract(source, ('gettext', 'ngettext', '_'), ['trans', ':'], {})) == [ - (3, 'gettext', u'Hello World', ['first']), - (4, 'gettext', u'Hello World', ['second']), - (6, 'ngettext', (u'%(users)s user', u'%(users)s users', None), ['third']) - ] diff --git a/tests/test_ifcondition.py b/tests/test_ifcondition.py deleted file mode 100644 index 52bbaecb..00000000 --- a/tests/test_ifcondition.py +++ /dev/null @@ -1,50 +0,0 @@ -# -*- coding: utf-8 -*- -""" - unit test for if conditions - ~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - :copyright: (c) 2009 by the Jinja Team. - :license: BSD, see LICENSE for more details. -""" - -from jinja2 import Environment -env = Environment() - - -SIMPLE = '''{% if true %}...{% endif %}''' -ELIF = '''{% if false %}XXX{% elif true %}...{% else %}XXX{% endif %}''' -ELSE = '''{% if false %}XXX{% else %}...{% endif %}''' -EMPTY = '''[{% if true %}{% else %}{% endif %}]''' - - -def test_simple(): - tmpl = env.from_string(SIMPLE) - assert tmpl.render() == '...' - - -def test_elif(): - tmpl = env.from_string(ELIF) - assert tmpl.render() == '...' - - -def test_else(): - tmpl = env.from_string(ELSE) - assert tmpl.render() == '...' - - -def test_empty(): - tmpl = env.from_string(EMPTY) - assert tmpl.render() == '[]' - - -def test_complete(): - tmpl = env.from_string('{% if a %}A{% elif b %}B{% elif c == d %}' - 'C{% else %}D{% endif %}') - assert tmpl.render(a=0, b=False, c=42, d=42.0) == 'C' - - -def test_no_scope(): - tmpl = env.from_string('{% if a %}{% set foo = 1 %}{% endif %}{{ foo }}') - assert tmpl.render(a=True) == '1' - tmpl = env.from_string('{% if true %}{% set foo = 1 %}{% endif %}{{ foo }}') - assert tmpl.render() == '1' diff --git a/tests/test_imports.py b/tests/test_imports.py deleted file mode 100644 index 1758a59a..00000000 --- a/tests/test_imports.py +++ /dev/null @@ -1,132 +0,0 @@ -# -*- coding: utf-8 -*- -""" - unit test for the imports and includes - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - :copyright: (c) 2009 by the Jinja Team. - :license: BSD, see LICENSE for more details. -""" -from jinja2 import Environment, DictLoader -from jinja2.exceptions import TemplateNotFound, TemplatesNotFound - -from nose.tools import assert_raises - - -test_env = Environment(loader=DictLoader(dict( - module='{% macro test() %}[{{ foo }}|{{ bar }}]{% endmacro %}', - header='[{{ foo }}|{{ 23 }}]', - o_printer='({{ o }})' -))) -test_env.globals['bar'] = 23 - - -def test_context_imports(): - t = test_env.from_string('{% import "module" as m %}{{ m.test() }}') - assert t.render(foo=42) == '[|23]' - t = test_env.from_string('{% import "module" as m without context %}{{ m.test() }}') - assert t.render(foo=42) == '[|23]' - t = test_env.from_string('{% import "module" as m with context %}{{ m.test() }}') - assert t.render(foo=42) == '[42|23]' - t = test_env.from_string('{% from "module" import test %}{{ test() }}') - assert t.render(foo=42) == '[|23]' - t = test_env.from_string('{% from "module" import test without context %}{{ test() }}') - assert t.render(foo=42) == '[|23]' - t = test_env.from_string('{% from "module" import test with context %}{{ test() }}') - assert t.render(foo=42) == '[42|23]' - - -def test_context_include(): - t = test_env.from_string('{% include "header" %}') - assert t.render(foo=42) == '[42|23]' - t = test_env.from_string('{% include "header" with context %}') - assert t.render(foo=42) == '[42|23]' - t = test_env.from_string('{% include "header" without context %}') - assert t.render(foo=42) == '[|23]' - - -def test_choice_includes(): - t = test_env.from_string('{% include ["missing", "header"] %}') - assert t.render(foo=42) == '[42|23]' - - t = test_env.from_string('{% include ["missing", "missing2"] ignore missing %}') - assert t.render(foo=42) == '' - - t = test_env.from_string('{% include ["missing", "missing2"] %}') - assert_raises(TemplateNotFound, t.render) - try: - t.render() - except TemplatesNotFound, e: - assert e.templates == ['missing', 'missing2'] - assert e.name == 'missing2' - else: - assert False, 'thou shalt raise' - - def test_includes(t, **ctx): - ctx['foo'] = 42 - assert t.render(ctx) == '[42|23]' - - t = test_env.from_string('{% include ["missing", "header"] %}') - test_includes(t) - t = test_env.from_string('{% include x %}') - test_includes(t, x=['missing', 'header']) - t = test_env.from_string('{% include [x, "header"] %}') - test_includes(t, x='missing') - t = test_env.from_string('{% include x %}') - test_includes(t, x='header') - t = test_env.from_string('{% include x %}') - test_includes(t, x='header') - t = test_env.from_string('{% include [x] %}') - test_includes(t, x='header') - - -def test_include_ignoring_missing(): - t = test_env.from_string('{% include "missing" %}') - assert_raises(TemplateNotFound, t.render) - for extra in '', 'with context', 'without context': - t = test_env.from_string('{% include "missing" ignore missing ' + - extra + ' %}') - assert t.render() == '' - - -def test_context_include_with_overrides(): - env = Environment(loader=DictLoader(dict( - main="{% for item in [1, 2, 3] %}{% include 'item' %}{% endfor %}", - item="{{ item }}" - ))) - assert env.get_template("main").render() == "123" - - -def test_trailing_comma(): - test_env.from_string('{% from "foo" import bar, baz with context %}') - test_env.from_string('{% from "foo" import bar, baz, with context %}') - test_env.from_string('{% from "foo" import bar, with context %}') - test_env.from_string('{% from "foo" import bar, with, context %}') - test_env.from_string('{% from "foo" import bar, with with context %}') - - -def test_exports(): - m = test_env.from_string(''' - {% macro toplevel() %}...{% endmacro %} - {% macro __private() %}...{% endmacro %} - {% set variable = 42 %} - {% for item in [1] %} - {% macro notthere() %}{% endmacro %} - {% endfor %} - ''').module - assert m.toplevel() == '...' - assert not hasattr(m, '__missing') - assert m.variable == 42 - assert not hasattr(m, 'notthere') - - -def test_unoptimized_scopes(): - t = test_env.from_string(""" - {% macro outer(o) %} - {% macro inner() %} - {% include "o_printer" %} - {% endmacro %} - {{ inner() }} - {% endmacro %} - {{ outer("FOO") }} - """) - assert t.render().strip() == '(FOO)' diff --git a/tests/test_inheritance.py b/tests/test_inheritance.py deleted file mode 100644 index 58b992fa..00000000 --- a/tests/test_inheritance.py +++ /dev/null @@ -1,197 +0,0 @@ -# -*- coding: utf-8 -*- -""" - unit test for the inheritance - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - :copyright: (c) 2009 by the Jinja Team. - :license: BSD, see LICENSE for more details. -""" - -from jinja2 import Environment, DictLoader -from jinja2.exceptions import TemplateSyntaxError - - -LAYOUTTEMPLATE = '''\ -|{% block block1 %}block 1 from layout{% endblock %} -|{% block block2 %}block 2 from layout{% endblock %} -|{% block block3 %} -{% block block4 %}nested block 4 from layout{% endblock %} -{% endblock %}|''' - -LEVEL1TEMPLATE = '''\ -{% extends "layout" %} -{% block block1 %}block 1 from level1{% endblock %}''' - -LEVEL2TEMPLATE = '''\ -{% extends "level1" %} -{% block block2 %}{% block block5 %}nested block 5 from level2{% -endblock %}{% endblock %}''' - -LEVEL3TEMPLATE = '''\ -{% extends "level2" %} -{% block block5 %}block 5 from level3{% endblock %} -{% block block4 %}block 4 from level3{% endblock %} -''' - -LEVEL4TEMPLATE = '''\ -{% extends "level3" %} -{% block block3 %}block 3 from level4{% endblock %} -''' - -WORKINGTEMPLATE = '''\ -{% extends "layout" %} -{% block block1 %} - {% if false %} - {% block block2 %} - this should workd - {% endblock %} - {% endif %} -{% endblock %} -''' - -env = Environment(loader=DictLoader({ - 'layout': LAYOUTTEMPLATE, - 'level1': LEVEL1TEMPLATE, - 'level2': LEVEL2TEMPLATE, - 'level3': LEVEL3TEMPLATE, - 'level4': LEVEL4TEMPLATE, - 'working': WORKINGTEMPLATE -}), trim_blocks=True) - -def test_layout(): - tmpl = env.get_template('layout') - assert tmpl.render() == ('|block 1 from layout|block 2 from ' - 'layout|nested block 4 from layout|') - - -def test_level1(): - tmpl = env.get_template('level1') - assert tmpl.render() == ('|block 1 from level1|block 2 from ' - 'layout|nested block 4 from layout|') - - -def test_level2(): - tmpl = env.get_template('level2') - assert tmpl.render() == ('|block 1 from level1|nested block 5 from ' - 'level2|nested block 4 from layout|') - - -def test_level3(): - tmpl = env.get_template('level3') - assert tmpl.render() == ('|block 1 from level1|block 5 from level3|' - 'block 4 from level3|') - - -def test_level4(): - tmpl = env.get_template('level4') - assert tmpl.render() == ('|block 1 from level1|block 5 from ' - 'level3|block 3 from level4|') - - -def test_super(): - env = Environment(loader=DictLoader({ - 'a': '{% block intro %}INTRO{% endblock %}|' - 'BEFORE|{% block data %}INNER{% endblock %}|AFTER', - 'b': '{% extends "a" %}{% block data %}({{ ' - 'super() }}){% endblock %}', - 'c': '{% extends "b" %}{% block intro %}--{{ ' - 'super() }}--{% endblock %}\n{% block data ' - '%}[{{ super() }}]{% endblock %}' - })) - tmpl = env.get_template('c') - assert tmpl.render() == '--INTRO--|BEFORE|[(INNER)]|AFTER' - - -def test_working(): - tmpl = env.get_template('working') - - -def test_reuse_blocks(): - tmpl = env.from_string('{{ self.foo() }}|{% block foo %}42{% endblock %}|{{ self.foo() }}') - assert tmpl.render() == '42|42|42' - - -def test_preserve_blocks(): - env = Environment(loader=DictLoader({ - 'a': '{% if false %}{% block x %}A{% endblock %}{% endif %}{{ self.x() }}', - 'b': '{% extends "a" %}{% block x %}B{{ super() }}{% endblock %}' - })) - tmpl = env.get_template('b') - assert tmpl.render() == 'BA' - - -def test_dynamic_inheritance(): - env = Environment(loader=DictLoader({ - 'master1': 'MASTER1{% block x %}{% endblock %}', - 'master2': 'MASTER2{% block x %}{% endblock %}', - 'child': '{% extends master %}{% block x %}CHILD{% endblock %}' - })) - tmpl = env.get_template('child') - for m in range(1, 3): - assert tmpl.render(master='master%d' % m) == 'MASTER%dCHILD' % m - - -def test_multi_inheritance(): - env = Environment(loader=DictLoader({ - 'master1': 'MASTER1{% block x %}{% endblock %}', - 'master2': 'MASTER2{% block x %}{% endblock %}', - 'child': '''{% if master %}{% extends master %}{% else %}{% extends - 'master1' %}{% endif %}{% block x %}CHILD{% endblock %}''' - })) - tmpl = env.get_template('child') - assert tmpl.render(master='master2') == 'MASTER2CHILD' - assert tmpl.render(master='master1') == 'MASTER1CHILD' - assert tmpl.render() == 'MASTER1CHILD' - - -def test_fixed_macro_scoping_bug(): - assert Environment(loader=DictLoader({ - 'test.html': '''\ - {% extends 'details.html' %} - - {% macro my_macro() %} - my_macro - {% endmacro %} - - {% block inner_box %} - {{ my_macro() }} - {% endblock %} - ''', - 'details.html': '''\ - {% extends 'standard.html' %} - - {% macro my_macro() %} - my_macro - {% endmacro %} - - {% block content %} - {% block outer_box %} - outer_box - {% block inner_box %} - inner_box - {% endblock %} - {% endblock %} - {% endblock %} - ''', - 'standard.html': ''' - {% block content %} {% endblock %} - ''' - })).get_template("test.html").render().split() == [u'outer_box', u'my_macro'] - - -def test_scoped_block(): - env = Environment(loader=DictLoader({ - 'master.html': '{% for item in seq %}[{% block item scoped %}' - '{% endblock %}]{% endfor %}' - })) - t = env.from_string('{% extends "master.html" %}{% block item %}{{ item }}{% endblock %}') - assert t.render(seq=range(5)) == '[0][1][2][3][4]' - - -def test_super_in_scoped_block(): - env = Environment(loader=DictLoader({ - 'master.html': '{% for item in seq %}[{% block item scoped %}' - '{{ item }}{% endblock %}]{% endfor %}' - })) - t = env.from_string('{% extends "master.html" %}{% block item %}{{ super() }}|{{ item * 2 }}{% endblock %}') - assert t.render(seq=range(5)) == '[0|0][1|2][2|4][3|6][4|8]' diff --git a/tests/test_lexer.py b/tests/test_lexer.py deleted file mode 100644 index 1b12eb4d..00000000 --- a/tests/test_lexer.py +++ /dev/null @@ -1,73 +0,0 @@ -# -*- coding: utf-8 -*- -""" - unit test for the lexer - ~~~~~~~~~~~~~~~~~~~~~~~ - - :copyright: (c) 2009 by the Jinja Team. - :license: BSD, see LICENSE for more details. -""" -from jinja2 import Environment - -env = Environment() - - -RAW = '{% raw %}foo{% endraw %}|{%raw%}{{ bar }}|{% baz %}{% endraw %}' -BALANCING = '''{% for item in seq %}${{'foo': item}|upper}{% endfor %}''' -COMMENTS = '''\ -
    - -
  • {item}
  • - -
''' -BYTEFALLBACK = u'''{{ 'foo'|pprint }}|{{ 'bär'|pprint }}''' - - -def test_raw(): - tmpl = env.from_string(RAW) - assert tmpl.render() == 'foo|{{ bar }}|{% baz %}' - - -def test_balancing(): - from jinja2 import Environment - env = Environment('{%', '%}', '${', '}') - tmpl = env.from_string(BALANCING) - assert tmpl.render(seq=range(3)) == "{'FOO': 0}{'FOO': 1}{'FOO': 2}" - - -def test_comments(): - from jinja2 import Environment - env = Environment('', '{', '}') - tmpl = env.from_string(COMMENTS) - assert tmpl.render(seq=range(3)) == ("
    \n
  • 0
  • \n " - "
  • 1
  • \n
  • 2
  • \n
") - - -def test_string_escapes(): - for char in u'\0', u'\u2668', u'\xe4', u'\t', u'\r', u'\n': - tmpl = env.from_string('{{ %s }}' % repr(char)[1:]) - assert tmpl.render() == char - assert env.from_string('{{ "\N{HOT SPRINGS}" }}').render() == u'\u2668' - - -def test_bytefallback(): - tmpl = env.from_string(BYTEFALLBACK) - assert tmpl.render() == u"'foo'|u'b\\xe4r'" - - -def test_operators(): - from jinja2.lexer import operators - for test, expect in operators.iteritems(): - if test in '([{}])': - continue - stream = env.lexer.tokenize('{{ %s }}' % test) - stream.next() - assert stream.current.type == expect - - -def test_normalizing(): - from jinja2 import Environment - for seq in '\r', '\r\n', '\n': - env = Environment(newline_sequence=seq) - tmpl = env.from_string('1\n2\r\n3\n4\n') - result = tmpl.render() - assert result.replace(seq, 'X') == '1X2X3X4' diff --git a/tests/test_loaders.py b/tests/test_loaders.py deleted file mode 100644 index 64193f33..00000000 --- a/tests/test_loaders.py +++ /dev/null @@ -1,112 +0,0 @@ -# -*- coding: utf-8 -*- -""" - unit test for the loaders - ~~~~~~~~~~~~~~~~~~~~~~~~~ - - :copyright: (c) 2009 by the Jinja Team. - :license: BSD, see LICENSE for more details. -""" - -import os -import time -import tempfile -from jinja2 import Environment, loaders -from jinja2.loaders import split_template_path -from jinja2.exceptions import TemplateNotFound - -from nose.tools import assert_raises - - -dict_loader = loaders.DictLoader({ - 'justdict.html': 'FOO' -}) -package_loader = loaders.PackageLoader('loaderres', 'templates') -filesystem_loader = loaders.FileSystemLoader('tests/loaderres/templates') -function_loader = loaders.FunctionLoader({'justfunction.html': 'FOO'}.get) -choice_loader = loaders.ChoiceLoader([dict_loader, package_loader]) -prefix_loader = loaders.PrefixLoader({ - 'a': filesystem_loader, - 'b': dict_loader -}) - - -def test_dict_loader(): - env = Environment(loader=dict_loader) - tmpl = env.get_template('justdict.html') - assert tmpl.render().strip() == 'FOO' - assert_raises(TemplateNotFound, env.get_template, 'missing.html') - - -def test_package_loader(): - env = Environment(loader=package_loader) - tmpl = env.get_template('test.html') - assert tmpl.render().strip() == 'BAR' - assert_raises(TemplateNotFound, env.get_template, 'missing.html') - - -def test_filesystem_loader(): - env = Environment(loader=filesystem_loader) - tmpl = env.get_template('test.html') - assert tmpl.render().strip() == 'BAR' - tmpl = env.get_template('foo/test.html') - assert tmpl.render().strip() == 'FOO' - assert_raises(TemplateNotFound, env.get_template, 'missing.html') - - -def test_choice_loader(): - env = Environment(loader=choice_loader) - tmpl = env.get_template('justdict.html') - assert tmpl.render().strip() == 'FOO' - tmpl = env.get_template('test.html') - assert tmpl.render().strip() == 'BAR' - assert_raises(TemplateNotFound, env.get_template, 'missing.html') - - -def test_function_loader(): - env = Environment(loader=function_loader) - tmpl = env.get_template('justfunction.html') - assert tmpl.render().strip() == 'FOO' - assert_raises(TemplateNotFound, env.get_template, 'missing.html') - - -def test_prefix_loader(): - env = Environment(loader=prefix_loader) - tmpl = env.get_template('a/test.html') - assert tmpl.render().strip() == 'BAR' - tmpl = env.get_template('b/justdict.html') - assert tmpl.render().strip() == 'FOO' - assert_raises(TemplateNotFound, env.get_template, 'missing') - - -def test_caching(): - changed = False - class TestLoader(loaders.BaseLoader): - def get_source(self, environment, template): - return u'foo', None, lambda: not changed - env = Environment(loader=TestLoader(), cache_size=-1) - tmpl = env.get_template('template') - assert tmpl is env.get_template('template') - changed = True - assert tmpl is not env.get_template('template') - changed = False - - env = Environment(loader=TestLoader(), cache_size=0) - assert env.get_template('template') \ - is not env.get_template('template') - - env = Environment(loader=TestLoader(), cache_size=2) - t1 = env.get_template('one') - t2 = env.get_template('two') - print env.cache - assert t2 is env.get_template('two') - assert t1 is env.get_template('one') - t3 = env.get_template('three') - assert 'one' in env.cache - assert 'two' not in env.cache - assert 'three' in env.cache - - -def test_split_template_path(): - assert split_template_path('foo/bar') == ['foo', 'bar'] - assert split_template_path('./foo/bar') == ['foo', 'bar'] - assert_raises(TemplateNotFound, split_template_path, '../foo') diff --git a/tests/test_lrucache.py b/tests/test_lrucache.py deleted file mode 100644 index 5ce43503..00000000 --- a/tests/test_lrucache.py +++ /dev/null @@ -1,39 +0,0 @@ -# -*- coding: utf-8 -*- -""" - Tests the LRUCache - ~~~~~~~~~~~~~~~~~~ - - This module tests the LRU Cache - - :copyright: (c) 2009 by the Jinja Team. - :license: BSD. -""" -import thread -import time -import random -import pickle -from jinja2.utils import LRUCache - - -def test_simple(): - d = LRUCache(3) - d["a"] = 1 - d["b"] = 2 - d["c"] = 3 - d["a"] - d["d"] = 4 - assert len(d) == 3 - assert 'a' in d and 'c' in d and 'd' in d and 'b' not in d - - -def test_pickleable(): - cache = LRUCache(2) - cache["foo"] = 42 - cache["bar"] = 23 - cache["foo"] - - for protocol in range(3): - copy = pickle.loads(pickle.dumps(cache, protocol)) - assert copy.capacity == cache.capacity - assert copy._mapping == cache._mapping - assert copy._queue == cache._queue diff --git a/tests/test_macros.py b/tests/test_macros.py deleted file mode 100644 index 4fd7202c..00000000 --- a/tests/test_macros.py +++ /dev/null @@ -1,112 +0,0 @@ -# -*- coding: utf-8 -*- -""" - unit test for the macros - ~~~~~~~~~~~~~~~~~~~~~~~~ - - :copyright: (c) 2009 by the Jinja Team. - :license: BSD, see LICENSE for more details. -""" - -from jinja2 import Environment, DictLoader - -env = Environment(trim_blocks=True) - - -SIMPLE = '''\ -{% macro say_hello(name) %}Hello {{ name }}!{% endmacro %} -{{ say_hello('Peter') }}\ -''' - -SCOPING = '''\ -{% macro level1(data1) %} -{% macro level2(data2) %}{{ data1 }}|{{ data2 }}{% endmacro %} -{{ level2('bar') }}{% endmacro %} -{{ level1('foo') }}\ -''' - -ARGUMENTS = '''\ -{% macro m(a, b, c='c', d='d') %}{{ a }}|{{ b }}|{{ c }}|{{ d }}{% endmacro %} -{{ m() }}|{{ m('a') }}|{{ m('a', 'b') }}|{{ m(1, 2, 3) }}\ -''' - -VARARGS = '''\ -{% macro test() %}{{ varargs|join('|') }}{% endmacro %}\ -{{ test(1, 2, 3) }}\ -''' - -SIMPLECALL = '''\ -{% macro test() %}[[{{ caller() }}]]{% endmacro %}\ -{% call test() %}data{% endcall %}\ -''' - -COMPLEXCALL = '''\ -{% macro test() %}[[{{ caller('data') }}]]{% endmacro %}\ -{% call(data) test() %}{{ data }}{% endcall %}\ -''' - -CALLERUNDEFINED = '''\ -{% set caller = 42 %}\ -{% macro test() %}{{ caller is not defined }}{% endmacro %}\ -{{ test() }}\ -''' - -INCLUDETEMPLATE = '''{% macro test(foo) %}[{{ foo }}]{% endmacro %}''' - - -def test_simple(): - tmpl = env.from_string(SIMPLE) - assert tmpl.render() == 'Hello Peter!' - - -def test_scoping(): - tmpl = env.from_string(SCOPING) - assert tmpl.render() == 'foo|bar' - - -def test_arguments(): - tmpl = env.from_string(ARGUMENTS) - assert tmpl.render() == '||c|d|a||c|d|a|b|c|d|1|2|3|d' - - -def test_varargs(): - tmpl = env.from_string(VARARGS) - assert tmpl.render() == '1|2|3' - - -def test_simple_call(): - tmpl = env.from_string(SIMPLECALL) - assert tmpl.render() == '[[data]]' - - -def test_complex_call(): - tmpl = env.from_string(COMPLEXCALL) - assert tmpl.render() == '[[data]]' - - -def test_caller_undefined(): - tmpl = env.from_string(CALLERUNDEFINED) - assert tmpl.render() == 'True' - - -def test_include(): - env = Environment(loader=DictLoader({'include': INCLUDETEMPLATE})) - tmpl = env.from_string('{% from "include" import test %}{{ test("foo") }}') - assert tmpl.render() == '[foo]' - - -def test_macro_api(): - tmpl = env.from_string('{% macro foo(a, b) %}{% endmacro %}' - '{% macro bar() %}{{ varargs }}{{ kwargs }}{% endmacro %}' - '{% macro baz() %}{{ caller() }}{% endmacro %}') - assert tmpl.module.foo.arguments == ('a', 'b') - assert tmpl.module.foo.defaults == () - assert tmpl.module.foo.name == 'foo' - assert not tmpl.module.foo.caller - assert not tmpl.module.foo.catch_kwargs - assert not tmpl.module.foo.catch_varargs - assert tmpl.module.bar.arguments == () - assert tmpl.module.bar.defaults == () - assert not tmpl.module.bar.caller - assert tmpl.module.bar.catch_kwargs - assert tmpl.module.bar.catch_varargs - assert tmpl.module.baz.caller diff --git a/tests/test_meta.py b/tests/test_meta.py deleted file mode 100644 index c0ef97cb..00000000 --- a/tests/test_meta.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -""" - unit test for the meta module - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - :copyright: (c) 2009 by the Jinja Team. - :license: BSD, see LICENSE for more details. -""" -from jinja2 import Environment, meta - - -def test_find_undeclared_variables(): - env = Environment() - ast = env.parse('{% set foo = 42 %}{{ bar + foo }}') - x = meta.find_undeclared_variables(ast) - assert x == set(['bar']) - - ast = env.parse('{% set foo = 42 %}{{ bar + foo }}' - '{% macro meh(x) %}{{ x }}{% endmacro %}' - '{% for item in seq %}{{ muh(item) + meh(seq) }}{% endfor %}') - x = meta.find_undeclared_variables(ast) - assert x == set(['bar', 'seq', 'muh']) - - -def test_find_refererenced_templates(): - env = Environment() - ast = env.parse('{% extends "layout.html" %}{% include helper %}') - i = meta.find_referenced_templates(ast) - assert i.next() == 'layout.html' - assert i.next() is None - assert list(i) == [] - - ast = env.parse('{% extends "layout.html" %}' - '{% from "test.html" import a, b as c %}' - '{% import "meh.html" as meh %}' - '{% include "muh.html" %}') - i = meta.find_referenced_templates(ast) - assert list(i) == ['layout.html', 'test.html', 'meh.html', 'muh.html'] - - -def test_find_included_templates(): - env = Environment() - ast = env.parse('{% include ["foo.html", "bar.html"] %}') - i = meta.find_referenced_templates(ast) - assert list(i) == ['foo.html', 'bar.html'] - - ast = env.parse('{% include ("foo.html", "bar.html") %}') - i = meta.find_referenced_templates(ast) - assert list(i) == ['foo.html', 'bar.html'] - - ast = env.parse('{% include ["foo.html", "bar.html", foo] %}') - i = meta.find_referenced_templates(ast) - assert list(i) == ['foo.html', 'bar.html', None] - - ast = env.parse('{% include ("foo.html", "bar.html", foo) %}') - i = meta.find_referenced_templates(ast) - assert list(i) == ['foo.html', 'bar.html', None] diff --git a/tests/test_old_bugs.py b/tests/test_old_bugs.py deleted file mode 100644 index 1ff5a550..00000000 --- a/tests/test_old_bugs.py +++ /dev/null @@ -1,183 +0,0 @@ -# -*- coding: utf-8 -*- -""" - Tests for old bugs - ~~~~~~~~~~~~~~~~~~ - - Unittest that test situations caused by various older bugs. - - :copyright: (c) 2009 by the Jinja Team. - :license: BSD. -""" -from jinja2 import Template, Environment, DictLoader, TemplateSyntaxError, \ - TemplateNotFound, PrefixLoader - -env = Environment() - -from nose import SkipTest -from nose.tools import assert_raises - - -def test_keyword_folding(): - env = Environment() - env.filters['testing'] = lambda value, some: value + some - assert env.from_string("{{ 'test'|testing(some='stuff') }}") \ - .render() == 'teststuff' - - -def test_extends_output_bugs(): - env = Environment(loader=DictLoader({ - 'parent.html': '(({% block title %}{% endblock %}))' - })) - - t = env.from_string('{% if expr %}{% extends "parent.html" %}{% endif %}' - '[[{% block title %}title{% endblock %}]]' - '{% for item in [1, 2, 3] %}({{ item }}){% endfor %}') - assert t.render(expr=False) == '[[title]](1)(2)(3)' - assert t.render(expr=True) == '((title))' - - -def test_urlize_filter_escaping(): - tmpl = env.from_string('{{ "http://www.example.org/http://www.example.org/<foo' - - -def test_loop_call_loop(): - tmpl = env.from_string(''' - - {% macro test() %} - {{ caller() }} - {% endmacro %} - - {% for num1 in range(5) %} - {% call test() %} - {% for num2 in range(10) %} - {{ loop.index }} - {% endfor %} - {% endcall %} - {% endfor %} - - ''') - - assert tmpl.render().split() == map(unicode, range(1, 11)) * 5 - - -def test_weird_inline_comment(): - env = Environment(line_statement_prefix='%') - assert_raises(TemplateSyntaxError, env.from_string, - '% for item in seq {# missing #}\n...% endfor') - - -def test_old_macro_loop_scoping_bug(): - tmpl = env.from_string('{% for i in (1, 2) %}{{ i }}{% endfor %}' - '{% macro i() %}3{% endmacro %}{{ i() }}') - assert tmpl.render() == '123' - - -def test_partial_conditional_assignments(): - tmpl = env.from_string('{% if b %}{% set a = 42 %}{% endif %}{{ a }}') - assert tmpl.render(a=23) == '23' - assert tmpl.render(b=True) == '42' - - -def test_stacked_locals_scoping_bug(): - env = Environment(line_statement_prefix='#') - t = env.from_string('''\ -# for j in [1, 2]: -# set x = 1 -# for i in [1, 2]: -# print x -# if i % 2 == 0: -# set x = x + 1 -# endif -# endfor -# endfor -# if a -# print 'A' -# elif b -# print 'B' -# elif c == d -# print 'C' -# else -# print 'D' -# endif -''') - assert t.render(a=0, b=False, c=42, d=42.0) == '1111C' - - -def test_call_with_args(): - t = Template("""{% macro dump_users(users) -%} -
    - {%- for user in users -%} -
  • {{ user.username|e }}

    {{ caller(user) }}
  • - {%- endfor -%} -
- {%- endmacro -%} - - {% call(user) dump_users(list_of_user) -%} -
-
Realname
-
{{ user.realname|e }}
-
Description
-
{{ user.description }}
-
- {% endcall %}""") - - assert [x.strip() for x in t.render(list_of_user=[{ - 'username':'apo', - 'realname':'something else', - 'description':'test' - }]).splitlines()] == [ - u'
  • apo

    ', - u'
    Realname
    ', - u'
    something else
    ', - u'
    Description
    ', - u'
    test
    ', - u'
    ', - u'
' - ] - - -def test_empty_if_condition_fails(): - assert_raises(TemplateSyntaxError, Template, '{% if %}....{% endif %}') - assert_raises(TemplateSyntaxError, Template, '{% if foo %}...{% elif %}...{% endif %}') - assert_raises(TemplateSyntaxError, Template, '{% for x in %}..{% endfor %}') - - -def test_recursive_loop_bug(): - tpl1 = Template(""" - {% for p in foo recursive%} - {{p.bar}} - {% for f in p.fields recursive%} - {{f.baz}} - {{p.bar}} - {% if f.rec %} - {{ loop(f.sub) }} - {% endif %} - {% endfor %} - {% endfor %} - """) - - tpl2 = Template(""" - {% for p in foo%} - {{p.bar}} - {% for f in p.fields recursive%} - {{f.baz}} - {{p.bar}} - {% if f.rec %} - {{ loop(f.sub) }} - {% endif %} - {% endfor %} - {% endfor %} - """) - - -def test_correct_prefix_loader_name(): - env = Environment(loader=PrefixLoader({ - 'foo': DictLoader({}) - })) - try: - env.get_template('foo/bar.html') - except TemplateNotFound, e: - assert e.name == 'foo/bar.html' - else: - assert False, 'expected error here' diff --git a/tests/test_parser.py b/tests/test_parser.py deleted file mode 100644 index 9e546c48..00000000 --- a/tests/test_parser.py +++ /dev/null @@ -1,146 +0,0 @@ -# -*- coding: utf-8 -*- -""" - unit test for the parser - ~~~~~~~~~~~~~~~~~~~~~~~~ - - :copyright: (c) 2009 by the Jinja Team. - :license: BSD, see LICENSE for more details. -""" -from jinja2 import Environment, Template, TemplateSyntaxError - -env = Environment() - - -PHP_SYNTAX = '''\ -\ - - -''' - -ERB_SYNTAX = '''\ -<%# I'm a comment, I'm not interesting %>\ -<% for item in seq -%> - <%= item %> -<%- endfor %>''' - -COMMENT_SYNTAX = '''\ -\ - - ${item} -''' - -MAKO_SYNTAX = '''\ -<%# regular comment %> -% for item in seq: - ${item} -% endfor''' - -MAKO_SYNTAX_LINECOMMENTS = '''\ -<%# regular comment %> -% for item in seq: - ${item} ## the rest of the stuff -% endfor''' - -BALANCING = '''{{{'foo':'bar'}.foo}}''' - -STARTCOMMENT = '''{# foo comment -and bar comment #} -{% macro blub() %}foo{% endmacro %} -{{ blub() }}''' - -LINE_SYNTAX_PRIORITY1 = '''\ -/* ignore me. - I'm a multiline comment */ -## for item in seq: -* ${item} # this is just extra stuff -## endfor -''' - -LINE_SYNTAX_PRIORITY2 = '''\ -/* ignore me. - I'm a multiline comment */ -# for item in seq: -* ${item} ## this is just extra stuff - ## extra stuff i just want to ignore -# endfor -''' - - -def test_php_syntax(): - env = Environment('', '', '') - tmpl = env.from_string(PHP_SYNTAX) - assert tmpl.render(seq=range(5)) == '01234' - - -def test_erb_syntax(): - env = Environment('<%', '%>', '<%=', '%>', '<%#', '%>') - tmpl = env.from_string(ERB_SYNTAX) - assert tmpl.render(seq=range(5)) == '01234' - - -def test_comment_syntax(): - env = Environment('', '${', '}', '') - tmpl = env.from_string(COMMENT_SYNTAX) - assert tmpl.render(seq=range(5)) == '01234' - - -def test_balancing(): - tmpl = env.from_string(BALANCING) - assert tmpl.render() == 'bar' - - -def test_start_comment(): - tmpl = env.from_string(STARTCOMMENT) - assert tmpl.render().strip() == 'foo' - - -def test_line_syntax(): - env = Environment('<%', '%>', '${', '}', '<%#', '%>', '%') - tmpl = env.from_string(MAKO_SYNTAX) - assert [int(x.strip()) for x in tmpl.render(seq=range(5)).split()] == \ - range(5) - - env = Environment('<%', '%>', '${', '}', '<%#', '%>', '%', '##') - tmpl = env.from_string(MAKO_SYNTAX_LINECOMMENTS) - assert [int(x.strip()) for x in tmpl.render(seq=range(5)).split()] == \ - range(5) - - -def test_line_syntax_priority(): - # XXX: why is the whitespace there in front of the newline? - env = Environment('{%', '%}', '${', '}', '/*', '*/', '##', '#') - tmpl = env.from_string(LINE_SYNTAX_PRIORITY1) - assert tmpl.render(seq=[1, 2]).strip() == '* 1\n* 2' - env = Environment('{%', '%}', '${', '}', '/*', '*/', '#', '##') - tmpl = env.from_string(LINE_SYNTAX_PRIORITY2) - assert tmpl.render(seq=[1, 2]).strip() == '* 1\n\n* 2' - - -def test_error_messages(): - def assert_error(code, expected): - try: - Template(code) - except TemplateSyntaxError, e: - assert str(e) == expected, 'unexpected error message' - else: - assert False, 'that was suposed to be an error' - - assert_error('{% for item in seq %}...{% endif %}', - "Encountered unknown tag 'endif'. Jinja was looking " - "for the following tags: 'endfor' or 'else'. The " - "innermost block that needs to be closed is 'for'.") - assert_error('{% if foo %}{% for item in seq %}...{% endfor %}{% endfor %}', - "Encountered unknown tag 'endfor'. Jinja was looking for " - "the following tags: 'elif' or 'else' or 'endif'. The " - "innermost block that needs to be closed is 'if'.") - assert_error('{% if foo %}', - "Unexpected end of template. Jinja was looking for the " - "following tags: 'elif' or 'else' or 'endif'. The " - "innermost block that needs to be closed is 'if'.") - assert_error('{% for item in seq %}', - "Unexpected end of template. Jinja was looking for the " - "following tags: 'endfor' or 'else'. The innermost block " - "that needs to be closed is 'for'.") - assert_error('{% block foo-bar-baz %}', - "Block names in Jinja have to be valid Python identifiers " - "and may not contain hypens, use an underscore instead.") diff --git a/tests/test_security.py b/tests/test_security.py deleted file mode 100644 index 9d910b64..00000000 --- a/tests/test_security.py +++ /dev/null @@ -1,141 +0,0 @@ -# -*- coding: utf-8 -*- -""" - unit test for security features - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - :copyright: (c) 2009 by the Jinja Team. - :license: BSD, see LICENSE for more details. -""" -from jinja2 import Environment -from jinja2.sandbox import SandboxedEnvironment, \ - ImmutableSandboxedEnvironment, unsafe -from jinja2 import Markup, escape -from jinja2.exceptions import SecurityError, TemplateSyntaxError - - -from nose.tools import assert_raises - -class PrivateStuff(object): - - def bar(self): - return 23 - - @unsafe - def foo(self): - return 42 - - def __repr__(self): - return 'PrivateStuff' - - -class PublicStuff(object): - bar = lambda self: 23 - _foo = lambda self: 42 - - def __repr__(self): - return 'PublicStuff' - - -def test_unsafe(): - ''' ->>> env = SandboxedEnvironment() ->>> env.from_string("{{ foo.foo() }}").render(foo=PrivateStuff()) -Traceback (most recent call last): - ... -SecurityError: is not safely callable ->>> env.from_string("{{ foo.bar() }}").render(foo=PrivateStuff()) -u'23' - ->>> env.from_string("{{ foo._foo() }}").render(foo=PublicStuff()) -Traceback (most recent call last): - ... -SecurityError: access to attribute '_foo' of 'PublicStuff' object is unsafe. ->>> env.from_string("{{ foo.bar() }}").render(foo=PublicStuff()) -u'23' - ->>> env.from_string("{{ foo.__class__ }}").render(foo=42) -u'' ->>> env.from_string("{{ foo.func_code }}").render(foo=lambda:None) -u'' ->>> env.from_string("{{ foo.__class__.__subclasses__() }}").render(foo=42) -Traceback (most recent call last): - ... -SecurityError: access to attribute '__class__' of 'int' object is unsafe. -''' - - -def test_restricted(): - env = SandboxedEnvironment() - assert_raises(TemplateSyntaxError, env.from_string, - "{% for item.attribute in seq %}...{% endfor %}") - assert_raises(TemplateSyntaxError, env.from_string, - "{% for foo, bar.baz in seq %}...{% endfor %}") - - -def test_immutable_environment(): - ''' ->>> env = ImmutableSandboxedEnvironment() ->>> env.from_string('{{ [].append(23) }}').render() -Traceback (most recent call last): - ... -SecurityError: access to attribute 'append' of 'list' object is unsafe. ->>> env.from_string('{{ {1:2}.clear() }}').render() -Traceback (most recent call last): - ... -SecurityError: access to attribute 'clear' of 'dict' object is unsafe. -''' - - -def test_markup_operations(): - # adding two strings should escape the unsafe one - unsafe = '' - safe = Markup('username') - assert unsafe + safe == unicode(escape(unsafe)) + unicode(safe) - - # string interpolations are safe to use too - assert Markup('%s') % '' == \ - '<bad user>' - assert Markup('%(username)s') % { - 'username': '' - } == '<bad user>' - - # an escaped object is markup too - assert type(Markup('foo') + 'bar') is Markup - - # and it implements __html__ by returning itself - x = Markup("foo") - assert x.__html__() is x - - # it also knows how to treat __html__ objects - class Foo(object): - def __html__(self): - return 'awesome' - def __unicode__(self): - return 'awesome' - assert Markup(Foo()) == 'awesome' - assert Markup('%s') % Foo() == \ - 'awesome' - - # escaping and unescaping - assert escape('"<>&\'') == '"<>&'' - assert Markup("Foo & Bar").striptags() == "Foo & Bar" - assert Markup("<test>").unescape() == "" - - -def test_template_data(): - env = Environment(autoescape=True) - t = env.from_string('{% macro say_hello(name) %}' - '

Hello {{ name }}!

{% endmacro %}' - '{{ say_hello("foo") }}') - escaped_out = '

Hello <blink>foo</blink>!

' - assert t.render() == escaped_out - assert unicode(t.module) == escaped_out - assert escape(t.module) == escaped_out - assert t.module.say_hello('foo') == escaped_out - assert escape(t.module.say_hello('foo')) == escaped_out - - -def test_attr_filter(): - env = SandboxedEnvironment() - tmpl = env.from_string('{{ 42|attr("__class__")|attr("__subclasses__")() }}') - assert_raises(SecurityError, tmpl.render) diff --git a/tests/test_streaming.py b/tests/test_streaming.py deleted file mode 100644 index 8b4e36f4..00000000 --- a/tests/test_streaming.py +++ /dev/null @@ -1,57 +0,0 @@ -# -*- coding: utf-8 -*- -""" - unit test for streaming interface - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - :copyright: (c) 2009 by the Jinja Team. - :license: BSD, see LICENSE for more details. -""" - -from jinja2 import Environment -env = Environment() - - -def test_basic_streaming(): - r""" ->>> tmpl = env.from_string("
    {% for item in seq %}
  • {{ loop.index " -... "}} - {{ item }}
  • {%- endfor %}
") ->>> stream = tmpl.stream(seq=range(4)) ->>> stream.next() -u'
    ' ->>> stream.next() -u'
  • 1 - 0
  • ' ->>> stream.next() -u'
  • 2 - 1
  • ' ->>> stream.next() -u'
  • 3 - 2
  • ' ->>> stream.next() -u'
  • 4 - 3
  • ' ->>> stream.next() -u'
' -""" - -def test_buffered_streaming(): - r""" ->>> tmpl = env.from_string("
    {% for item in seq %}
  • {{ loop.index " -... "}} - {{ item }}
  • {%- endfor %}
") ->>> stream = tmpl.stream(seq=range(4)) ->>> stream.enable_buffering(size=3) ->>> stream.next() -u'
  • 1 - 0
  • 2 - 1
  • ' ->>> stream.next() -u'
  • 3 - 2
  • 4 - 3
' -""" - -def test_streaming_behavior(): - r""" ->>> tmpl = env.from_string("") ->>> stream = tmpl.stream() ->>> stream.buffered -False ->>> stream.enable_buffering(20) ->>> stream.buffered -True ->>> stream.disable_buffering() ->>> stream.buffered -False -""" diff --git a/tests/test_syntax.py b/tests/test_syntax.py deleted file mode 100644 index 759af6a9..00000000 --- a/tests/test_syntax.py +++ /dev/null @@ -1,207 +0,0 @@ -# -*- coding: utf-8 -*- -""" - unit test for expression syntax - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - :copyright: (c) 2009 by the Jinja Team. - :license: BSD, see LICENSE for more details. -""" -from jinja2 import Environment -from jinja2.exceptions import TemplateSyntaxError, UndefinedError - -from nose.tools import assert_raises - -env = Environment() - - -CALL = '''{{ foo('a', c='d', e='f', *['b'], **{'g': 'h'}) }}''' -SLICING = '''{{ [1, 2, 3][:] }}|{{ [1, 2, 3][::-1] }}''' -ATTR = '''{{ foo.bar }}|{{ foo['bar'] }}''' -SUBSCRIPT = '''{{ foo[0] }}|{{ foo[-1] }}''' -TUPLE = '''{{ () }}|{{ (1,) }}|{{ (1, 2) }}''' -MATH = '''{{ (1 + 1 * 2) - 3 / 2 }}|{{ 2**3 }}''' -DIV = '''{{ 3 // 2 }}|{{ 3 / 2 }}|{{ 3 % 2 }}''' -UNARY = '''{{ +3 }}|{{ -3 }}''' -CONCAT = '''{{ [1, 2] ~ 'foo' }}''' -COMPARE = '''{{ 1 > 0 }}|{{ 1 >= 1 }}|{{ 2 < 3 }}|{{ 2 == 2 }}|{{ 1 <= 1 }}''' -INOP = '''{{ 1 in [1, 2, 3] }}|{{ 1 not in [1, 2, 3] }}''' -LITERALS = '''{{ [] }}|{{ {} }}|{{ () }}''' -BOOL = '''{{ true and false }}|{{ false or true }}|{{ not false }}''' -GROUPING = '''{{ (true and false) or (false and true) and not false }}''' -CONDEXPR = '''{{ 0 if true else 1 }}''' -DJANGOATTR = '''{{ [1, 2, 3].0 }}|{{ [[1]].0.0 }}''' -FILTERPRIORITY = '''{{ "foo"|upper + "bar"|upper }}''' -TUPLETEMPLATES = [ - '{{ () }}', - '{{ (1, 2) }}', - '{{ (1, 2,) }}', - '{{ 1, }}', - '{{ 1, 2 }}', - '{% for foo, bar in seq %}...{% endfor %}', - '{% for x in foo, bar %}...{% endfor %}', - '{% for x in foo, %}...{% endfor %}' -] -TRAILINGCOMMA = '''{{ (1, 2,) }}|{{ [1, 2,] }}|{{ {1: 2,} }}''' - - -def test_call(): - env = Environment() - env.globals['foo'] = lambda a, b, c, e, g: a + b + c + e + g - tmpl = env.from_string(CALL) - assert tmpl.render() == 'abdfh' - - -def test_slicing(): - tmpl = env.from_string(SLICING) - assert tmpl.render() == '[1, 2, 3]|[3, 2, 1]' - - -def test_attr(): - tmpl = env.from_string(ATTR) - assert tmpl.render(foo={'bar': 42}) == '42|42' - - -def test_subscript(): - tmpl = env.from_string(SUBSCRIPT) - assert tmpl.render(foo=[0, 1, 2]) == '0|2' - - -def test_tuple(): - tmpl = env.from_string(TUPLE) - assert tmpl.render() == '()|(1,)|(1, 2)' - - -def test_math(): - tmpl = env.from_string(MATH) - assert tmpl.render() == '1.5|8' - - -def test_div(): - tmpl = env.from_string(DIV) - assert tmpl.render() == '1|1.5|1' - - -def test_unary(): - tmpl = env.from_string(UNARY) - assert tmpl.render() == '3|-3' - - -def test_concat(): - tmpl = env.from_string(CONCAT) - assert tmpl.render() == '[1, 2]foo' - - -def test_compare(): - tmpl = env.from_string(COMPARE) - assert tmpl.render() == 'True|True|True|True|True' - - -def test_inop(): - tmpl = env.from_string(INOP) - assert tmpl.render() == 'True|False' - - -def test_literals(): - tmpl = env.from_string(LITERALS) - assert tmpl.render().lower() == '[]|{}|()' - - -def test_bool(): - tmpl = env.from_string(BOOL) - assert tmpl.render() == 'False|True|True' - - -def test_grouping(): - tmpl = env.from_string(GROUPING) - assert tmpl.render() == 'False' - - -def test_django_attr(): - tmpl = env.from_string(DJANGOATTR) - assert tmpl.render() == '1|1' - - -def test_conditional_expression(): - tmpl = env.from_string(CONDEXPR) - assert tmpl.render() == '0' - - -def test_short_conditional_expression(): - tmpl = env.from_string('<{{ 1 if false }}>') - assert tmpl.render() == '<>' - - tmpl = env.from_string('<{{ (1 if false).bar }}>') - assert_raises(UndefinedError, tmpl.render) - - -def test_filter_priority(): - tmpl = env.from_string(FILTERPRIORITY) - assert tmpl.render() == 'FOOBAR' - - -def test_function_calls(): - tests = [ - (True, '*foo, bar'), - (True, '*foo, *bar'), - (True, '*foo, bar=42'), - (True, '**foo, *bar'), - (True, '**foo, bar'), - (False, 'foo, bar'), - (False, 'foo, bar=42'), - (False, 'foo, bar=23, *args'), - (False, 'a, b=c, *d, **e'), - (False, '*foo, **bar') - ] - for should_fail, sig in tests: - if should_fail: - assert_raises(TemplateSyntaxError, env.from_string, '{{ foo(%s) }}' % sig) - else: - env.from_string('foo(%s)' % sig) - - -def test_tuple_expr(): - for tmpl in TUPLETEMPLATES: - print tmpl - assert env.from_string(tmpl) - - -def test_trailing_comma(): - tmpl = env.from_string(TRAILINGCOMMA) - assert tmpl.render().lower() == '(1, 2)|[1, 2]|{1: 2}' - - -def test_block_end_name(): - env.from_string('{% block foo %}...{% endblock foo %}') - assert_raises(TemplateSyntaxError, env.from_string, '{% block x %}{% endblock y %}') - - -def test_contant_casing(): - for const in True, False, None: - tmpl = env.from_string('{{ %s }}|{{ %s }}|{{ %s }}' % ( - str(const), str(const).lower(), str(const).upper() - )) - assert tmpl.render() == '%s|%s|' % (const, const) - - -def test_test_chaining(): - assert_raises(TemplateSyntaxError, env.from_string, '{{ foo is string is sequence }}') - env.from_string('{{ 42 is string or 42 is number }}').render() == 'True' - - -def test_string_concatenation(): - tmpl = env.from_string('{{ "foo" "bar" "baz" }}') - assert tmpl.render() == 'foobarbaz' - - -def test_notin(): - bar = xrange(100) - tmpl = env.from_string('''{{ not 42 in bar }}''') - assert tmpl.render(bar=bar) == unicode(not 42 in bar) - - -def test_implicit_subscribed_tuple(): - class Foo(object): - def __getitem__(self, x): - return x - t = env.from_string('{{ foo[1, 2] }}') - assert t.render(foo=Foo()) == u'(1, 2)' diff --git a/tests/test_tests.py b/tests/test_tests.py deleted file mode 100644 index 23128899..00000000 --- a/tests/test_tests.py +++ /dev/null @@ -1,94 +0,0 @@ -# -*- coding: utf-8 -*- -""" - unit test for the test functions - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - :copyright: (c) 2009 by the Jinja Team. - :license: BSD, see LICENSE for more details. -""" -from jinja2 import Environment, Markup -env = Environment() - - -DEFINED = '''{{ missing is defined }}|{{ true is defined }}''' -EVEN = '''{{ 1 is even }}|{{ 2 is even }}''' -LOWER = '''{{ "foo" is lower }}|{{ "FOO" is lower }}''' -ODD = '''{{ 1 is odd }}|{{ 2 is odd }}''' -SEQUENCE = '''{{ [1, 2, 3] is sequence }}|\ -{{ "foo" is sequence }}|\ -{{ 42 is sequence }}''' -UPPER = '''{{ "FOO" is upper }}|{{ "foo" is upper }}''' -SAMEAS = '''{{ foo is sameas false }}|{{ 0 is sameas false }}''' -NOPARENFORARG1 = '''{{ foo is sameas none }}''' -TYPECHECKS = '''\ -{{ 42 is undefined }} -{{ 42 is defined }} -{{ 42 is none }} -{{ none is none }} -{{ 42 is number }} -{{ 42 is string }} -{{ "foo" is string }} -{{ "foo" is sequence }} -{{ [1] is sequence }} -{{ range is callable }} -{{ 42 is callable }} -{{ range(5) is iterable }}''' - - -def test_defined(): - tmpl = env.from_string(DEFINED) - assert tmpl.render() == 'False|True' - - -def test_even(): - tmpl = env.from_string(EVEN) - assert tmpl.render() == 'False|True' - - -def test_odd(): - tmpl = env.from_string(ODD) - assert tmpl.render() == 'True|False' - - -def test_lower(): - tmpl = env.from_string(LOWER) - assert tmpl.render() == 'True|False' - - -def test_typechecks(): - tmpl = env.from_string(TYPECHECKS) - assert tmpl.render() == '' - - -def test_sequence(): - tmpl = env.from_string(SEQUENCE) - assert tmpl.render() == 'True|True|False' - - -def test_upper(): - tmpl = env.from_string(UPPER) - assert tmpl.render() == 'True|False' - - -def test_sameas(): - tmpl = env.from_string(SAMEAS) - assert tmpl.render(foo=False) == 'True|False' - - -def test_typechecks(): - tmpl = env.from_string(TYPECHECKS) - assert tmpl.render() == ( - 'False\nTrue\nFalse\nTrue\nTrue\nFalse\n' - 'True\nTrue\nTrue\nTrue\nFalse\nTrue' - ) - - -def test_no_paren_for_arg1(): - tmpl = env.from_string(NOPARENFORARG1) - assert tmpl.render(foo=None) == 'True' - - -def test_escaped(): - env = Environment(autoescape=True) - tmpl = env.from_string('{{ x is escaped }}|{{ y is escaped }}') - assert tmpl.render(x='foo', y=Markup('foo')) == 'False|True' diff --git a/tests/test_undefined.py b/tests/test_undefined.py deleted file mode 100644 index d9e3c934..00000000 --- a/tests/test_undefined.py +++ /dev/null @@ -1,86 +0,0 @@ -# -*- coding: utf-8 -*- -""" - unit test for the undefined types - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - :copyright: (c) 2009 by the Jinja Team. - :license: BSD, see LICENSE for more details. -""" -from jinja2 import Template -from jinja2.exceptions import UndefinedError - -from nose.tools import assert_raises - - -def test_default_undefined(): - ''' ->>> from jinja2 import Environment, Undefined ->>> env = Environment(undefined=Undefined) ->>> env.from_string('{{ missing }}').render() -u'' ->>> env.from_string('{{ missing.attribute }}').render() -Traceback (most recent call last): - ... -UndefinedError: 'missing' is undefined ->>> env.from_string('{{ missing|list }}').render() -u'[]' ->>> env.from_string('{{ missing is not defined }}').render() -u'True' ->>> env.from_string('{{ foo.missing }}').render(foo=42) -u'' ->>> env.from_string('{{ not missing }}').render() -u'True' -''' - -def test_debug_undefined(): - ''' ->>> from jinja2 import Environment, DebugUndefined ->>> env = Environment(undefined=DebugUndefined) ->>> env.from_string('{{ missing }}').render() -u'{{ missing }}' ->>> env.from_string('{{ missing.attribute }}').render() -Traceback (most recent call last): - ... -UndefinedError: 'missing' is undefined ->>> env.from_string('{{ missing|list }}').render() -u'[]' ->>> env.from_string('{{ missing is not defined }}').render() -u'True' ->>> env.from_string('{{ foo.missing }}').render(foo=42) -u"{{ no such element: int['missing'] }}" ->>> env.from_string('{{ not missing }}').render() -u'True' -''' - -def test_strict_undefined(): - ''' ->>> from jinja2 import Environment, StrictUndefined ->>> env = Environment(undefined=StrictUndefined) ->>> env.from_string('{{ missing }}').render() -Traceback (most recent call last): - ... -UndefinedError: 'missing' is undefined ->>> env.from_string('{{ missing.attribute }}').render() -Traceback (most recent call last): - ... -UndefinedError: 'missing' is undefined ->>> env.from_string('{{ missing|list }}').render() -Traceback (most recent call last): - ... -UndefinedError: 'missing' is undefined ->>> env.from_string('{{ missing is not defined }}').render() -u'True' ->>> env.from_string('{{ foo.missing }}').render(foo=42) -Traceback (most recent call last): - ... -UndefinedError: 'int' object has no attribute 'missing' ->>> env.from_string('{{ not missing }}').render() -Traceback (most recent call last): - ... -UndefinedError: 'missing' is undefined -''' - - -def test_indexing_gives_undefined(): - t = Template("{{ var[42].foo }}") - assert_raises(UndefinedError, t.render, var=0) diff --git a/tests/test_various.py b/tests/test_various.py deleted file mode 100644 index 942c1c3f..00000000 --- a/tests/test_various.py +++ /dev/null @@ -1,115 +0,0 @@ -# -*- coding: utf-8 -*- -""" - unit test for various things - ~~~~~~~~~~~~~~~~~~~~~~~~~~~~ - - :copyright: (c) 2009 by the Jinja Team. - :license: BSD, see LICENSE for more details. -""" -import gc -from jinja2 import escape, is_undefined, Environment -from jinja2.utils import Cycler -from jinja2.exceptions import TemplateSyntaxError - -from nose import SkipTest -from nose.tools import assert_raises - -env = Environment() - - -UNPACKING = '''{% for a, b, c in [[1, 2, 3]] %}{{ a }}|{{ b }}|{{ c }}{% endfor %}''' -RAW = '''{% raw %}{{ FOO }} and {% BAR %}{% endraw %}''' -CONST = '''{{ true }}|{{ false }}|{{ none }}|\ -{{ none is defined }}|{{ missing is defined }}''' -LOCALSET = '''{% set foo = 0 %}\ -{% for item in [1, 2] %}{% set foo = 1 %}{% endfor %}\ -{{ foo }}''' -CONSTASS1 = '''{% set true = 42 %}''' -CONSTASS2 = '''{% for none in seq %}{% endfor %}''' - - -def test_unpacking(): - tmpl = env.from_string(UNPACKING) - assert tmpl.render() == '1|2|3' - - -def test_raw(): - tmpl = env.from_string(RAW) - assert tmpl.render() == '{{ FOO }} and {% BAR %}' - - -def test_const(): - tmpl = env.from_string(CONST) - assert tmpl.render() == 'True|False|None|True|False' - - -def test_const_assign(): - for tmpl in CONSTASS1, CONSTASS2: - assert_raises(TemplateSyntaxError, env.from_string, tmpl) - - -def test_localset(): - tmpl = env.from_string(LOCALSET) - assert tmpl.render() == '0' - - -def test_markup_leaks(): - # this test only tests the c extension - if hasattr(escape, 'func_code'): - raise SkipTest() - counts = set() - for count in xrange(20): - for item in xrange(1000): - escape("foo") - escape("") - escape(u"foo") - escape(u"") - counts.add(len(gc.get_objects())) - assert len(counts) == 1, 'ouch, c extension seems to leak objects' - - -def test_item_and_attribute(): - from jinja2.sandbox import SandboxedEnvironment - - for env in Environment(), SandboxedEnvironment(): - tmpl = env.from_string('{{ foo.items() }}') - assert tmpl.render(foo={'items': 42}) == "[('items', 42)]" - tmpl = env.from_string('{{ foo|attr("items")() }}') - assert tmpl.render(foo={'items': 42}) == "[('items', 42)]" - tmpl = env.from_string('{{ foo["items"] }}') - assert tmpl.render(foo={'items': 42}) == '42' - - -def test_finalizer(): - def finalize_none_empty(value): - if value is None: - value = u'' - return value - env = Environment(finalize=finalize_none_empty) - tmpl = env.from_string('{% for item in seq %}|{{ item }}{% endfor %}') - assert tmpl.render(seq=(None, 1, "foo")) == '||1|foo' - tmpl = env.from_string('<{{ none }}>') - assert tmpl.render() == '<>' - - -def test_cycler(): - items = 1, 2, 3 - c = Cycler(*items) - for item in items + items: - assert c.current == item - assert c.next() == item - c.next() - assert c.current == 2 - c.reset() - assert c.current == 1 - - -def test_expressions(): - expr = env.compile_expression("foo") - assert expr() is None - assert expr(foo=42) == 42 - expr2 = env.compile_expression("foo", undefined_to_none=False) - assert is_undefined(expr2()) - - expr = env.compile_expression("42 + foo") - assert expr(foo=42) == 84