Skip to content
Myr

test_lexnparse.py

This file

Path

tests/test_lexnparse.py

613 lines · 22.2 KiB · Python

Last changed by

Fixed long standing wrong operator precedenceArmin Ronacherbefore adoption4fa3712

History of this file

Take it

1# -*- coding: utf-8 -*-2"""3    jinja2.testsuite.lexnparse4    ~~~~~~~~~~~~~~~~~~~~~~~~~~56    All the unittests regarding lexing, parsing and syntax.78    :copyright: (c) 2010 by the Jinja Team.9    :license: BSD, see LICENSE for more details.10"""11import pytest1213from jinja2 import Environment, Template, TemplateSyntaxError, \14     UndefinedError, nodes15from jinja2._compat import iteritems, text_type, PY216from jinja2.lexer import Token, TokenStream, TOKEN_EOF, \17     TOKEN_BLOCK_BEGIN, TOKEN_BLOCK_END181920# how does a string look like in jinja syntax?21if PY2:22    def jinja_string_repr(string):23        return repr(string)[1:]24else:25    jinja_string_repr = repr262728@pytest.mark.lexnparse29@pytest.mark.tokenstream30class TestTokenStream():31    test_tokens = [Token(1, TOKEN_BLOCK_BEGIN, ''),32                   Token(2, TOKEN_BLOCK_END, ''),33                   ]3435    def test_simple(self, env):36        ts = TokenStream(self.test_tokens, "foo", "bar")37        assert ts.current.type is TOKEN_BLOCK_BEGIN38        assert bool(ts)39        assert not bool(ts.eos)40        next(ts)41        assert ts.current.type is TOKEN_BLOCK_END42        assert bool(ts)43        assert not bool(ts.eos)44        next(ts)45        assert ts.current.type is TOKEN_EOF46        assert not bool(ts)47        assert bool(ts.eos)4849    def test_iter(self, env):50        token_types = [51            t.type for t in TokenStream(self.test_tokens, "foo", "bar")52        ]53        assert token_types == ['block_begin', 'block_end', ]545556@pytest.mark.lexnparse57@pytest.mark.lexer58class TestLexer():5960    def test_raw1(self, env):61        tmpl = env.from_string(62            '{% raw %}foo{% endraw %}|'63            '{%raw%}{{ bar }}|{% baz %}{%       endraw    %}')64        assert tmpl.render() == 'foo|{{ bar }}|{% baz %}'6566    def test_raw2(self, env):67        tmpl = env.from_string('1  {%- raw -%}   2   {%- endraw -%}   3')68        assert tmpl.render() == '123'6970    def test_balancing(self, env):71        env = Environment('{%', '%}', '${', '}')72        tmpl = env.from_string('''{% for item in seq73            %}${{'foo': item}|upper}{% endfor %}''')74        assert tmpl.render(seq=list(range(3))) \75            == "{'FOO': 0}{'FOO': 1}{'FOO': 2}"7677    def test_comments(self, env):78        env = Environment('<!--', '-->', '{', '}')79        tmpl = env.from_string('''\80<ul>81<!--- for item in seq -->82  <li>{item}</li>83<!--- endfor -->84</ul>''')85        assert tmpl.render(seq=list(range(3))) \86            == ("<ul>\n  <li>0</li>\n  ""<li>1</li>\n  <li>2</li>\n</ul>")8788    def test_string_escapes(self, env):89        for char in u'\0', u'\u2668', u'\xe4', u'\t', u'\r', u'\n':90            tmpl = env.from_string('{{ %s }}' % jinja_string_repr(char))91            assert tmpl.render() == char92        assert env.from_string('{{ "\N{HOT SPRINGS}" }}').render() == u'\u2668'9394    def test_bytefallback(self, env):95        from pprint import pformat96        tmpl = env.from_string(u'''{{ 'foo'|pprint }}|{{ 'bär'|pprint }}''')97        assert tmpl.render() == pformat('foo') + '|' + pformat(u'bär')9899    def test_operators(self, env):100        from jinja2.lexer import operators101        for test, expect in iteritems(operators):102            if test in '([{}])':103                continue104            stream = env.lexer.tokenize('{{ %s }}' % test)105            next(stream)106            assert stream.current.type == expect107108    def test_normalizing(self, env):109        for seq in '\r', '\r\n', '\n':110            env = Environment(newline_sequence=seq)111            tmpl = env.from_string('1\n2\r\n3\n4\n')112            result = tmpl.render()113            assert result.replace(seq, 'X') == '1X2X3X4'114115    def test_trailing_newline(self, env):116        for keep in [True, False]:117            env = Environment(keep_trailing_newline=keep)118            for template, expected in [119                    ('', {}),120                    ('no\nnewline', {}),121                    ('with\nnewline\n', {False: 'with\nnewline'}),122                    ('with\nseveral\n\n\n', {False: 'with\nseveral\n\n'}),123                    ]:124                tmpl = env.from_string(template)125                expect = expected.get(keep, template)126                result = tmpl.render()127                assert result == expect, (keep, template, result, expect)128129130@pytest.mark.lexnparse131@pytest.mark.parser132class TestParser():133134    def test_php_syntax(self, env):135        env = Environment('<?', '?>', '<?=', '?>', '<!--', '-->')136        tmpl = env.from_string('''\137<!-- I'm a comment, I'm not interesting -->\138<? for item in seq -?>139    <?= item ?>140<?- endfor ?>''')141        assert tmpl.render(seq=list(range(5))) == '01234'142143    def test_erb_syntax(self, env):144        env = Environment('<%', '%>', '<%=', '%>', '<%#', '%>')145        tmpl = env.from_string('''\146<%# I'm a comment, I'm not interesting %>\147<% for item in seq -%>148    <%= item %>149<%- endfor %>''')150        assert tmpl.render(seq=list(range(5))) == '01234'151152    def test_comment_syntax(self, env):153        env = Environment('<!--', '-->', '${', '}', '<!--#', '-->')154        tmpl = env.from_string('''\155<!--# I'm a comment, I'm not interesting -->\156<!-- for item in seq --->157    ${item}158<!--- endfor -->''')159        assert tmpl.render(seq=list(range(5))) == '01234'160161    def test_balancing(self, env):162        tmpl = env.from_string('''{{{'foo':'bar'}.foo}}''')163        assert tmpl.render() == 'bar'164165    def test_start_comment(self, env):166        tmpl = env.from_string('''{# foo comment167and bar comment #}168{% macro blub() %}foo{% endmacro %}169{{ blub() }}''')170        assert tmpl.render().strip() == 'foo'171172    def test_line_syntax(self, env):173        env = Environment('<%', '%>', '${', '}', '<%#', '%>', '%')174        tmpl = env.from_string('''\175<%# regular comment %>176% for item in seq:177    ${item}178% endfor''')179        assert [180            int(x.strip()) for x in tmpl.render(seq=list(range(5))).split()181        ] == list(range(5))182183        env = Environment('<%', '%>', '${', '}', '<%#', '%>', '%', '##')184        tmpl = env.from_string('''\185<%# regular comment %>186% for item in seq:187    ${item} ## the rest of the stuff188% endfor''')189        assert [190            int(x.strip()) for x in tmpl.render(seq=list(range(5))).split()191        ] == list(range(5))192193    def test_line_syntax_priority(self, env):194        # XXX: why is the whitespace there in front of the newline?195        env = Environment('{%', '%}', '${', '}', '/*', '*/', '##', '#')196        tmpl = env.from_string('''\197/* ignore me.198   I'm a multiline comment */199## for item in seq:200* ${item}          # this is just extra stuff201## endfor''')202        assert tmpl.render(seq=[1, 2]).strip() == '* 1\n* 2'203        env = Environment('{%', '%}', '${', '}', '/*', '*/', '#', '##')204        tmpl = env.from_string('''\205/* ignore me.206   I'm a multiline comment */207# for item in seq:208* ${item}          ## this is just extra stuff209    ## extra stuff i just want to ignore210# endfor''')211        assert tmpl.render(seq=[1, 2]).strip() == '* 1\n\n* 2'212213    def test_error_messages(self, env):214        def assert_error(code, expected):215            try:216                Template(code)217            except TemplateSyntaxError as e:218                assert str(e) == expected, 'unexpected error message'219            else:220                assert False, 'that was supposed to be an error'221222        assert_error('{% for item in seq %}...{% endif %}',223                     "Encountered unknown tag 'endif'. Jinja was looking "224                     "for the following tags: 'endfor' or 'else'. The "225                     "innermost block that needs to be closed is 'for'.")226        assert_error(227            '{% if foo %}{% for item in seq %}...{% endfor %}{% endfor %}',228            "Encountered unknown tag 'endfor'. Jinja was looking for "229            "the following tags: 'elif' or 'else' or 'endif'. The "230            "innermost block that needs to be closed is 'if'.")231        assert_error('{% if foo %}',232                     "Unexpected end of template. Jinja was looking for the "233                     "following tags: 'elif' or 'else' or 'endif'. The "234                     "innermost block that needs to be closed is 'if'.")235        assert_error('{% for item in seq %}',236                     "Unexpected end of template. Jinja was looking for the "237                     "following tags: 'endfor' or 'else'. The innermost block "238                     "that needs to be closed is 'for'.")239        assert_error(240            '{% block foo-bar-baz %}',241            "Block names in Jinja have to be valid Python identifiers "242            "and may not contain hyphens, use an underscore instead.")243        assert_error('{% unknown_tag %}',244                     "Encountered unknown tag 'unknown_tag'.")245246247@pytest.mark.lexnparse248@pytest.mark.syntax249class TestSyntax():250251    def test_call(self, env):252        env = Environment()253        env.globals['foo'] = lambda a, b, c, e, g: a + b + c + e + g254        tmpl = env.from_string(255            "{{ foo('a', c='d', e='f', *['b'], **{'g': 'h'}) }}"256        )257        assert tmpl.render() == 'abdfh'258259    def test_slicing(self, env):260        tmpl = env.from_string('{{ [1, 2, 3][:] }}|{{ [1, 2, 3][::-1] }}')261        assert tmpl.render() == '[1, 2, 3]|[3, 2, 1]'262263    def test_attr(self, env):264        tmpl = env.from_string("{{ foo.bar }}|{{ foo['bar'] }}")265        assert tmpl.render(foo={'bar': 42}) == '42|42'266267    def test_subscript(self, env):268        tmpl = env.from_string("{{ foo[0] }}|{{ foo[-1] }}")269        assert tmpl.render(foo=[0, 1, 2]) == '0|2'270271    def test_tuple(self, env):272        tmpl = env.from_string('{{ () }}|{{ (1,) }}|{{ (1, 2) }}')273        assert tmpl.render() == '()|(1,)|(1, 2)'274275    def test_math(self, env):276        tmpl = env.from_string('{{ (1 + 1 * 2) - 3 / 2 }}|{{ 2**3 }}')277        assert tmpl.render() == '1.5|8'278279    def test_div(self, env):280        tmpl = env.from_string('{{ 3 // 2 }}|{{ 3 / 2 }}|{{ 3 % 2 }}')281        assert tmpl.render() == '1|1.5|1'282283    def test_unary(self, env):284        tmpl = env.from_string('{{ +3 }}|{{ -3 }}')285        assert tmpl.render() == '3|-3'286287    def test_concat(self, env):288        tmpl = env.from_string("{{ [1, 2] ~ 'foo' }}")289        assert tmpl.render() == '[1, 2]foo'290291    def test_compare(self, env):292        tmpl = env.from_string('{{ 1 > 0 }}|{{ 1 >= 1 }}|{{ 2 < 3 }}|'293                               '{{ 2 == 2 }}|{{ 1 <= 1 }}')294        assert tmpl.render() == 'True|True|True|True|True'295296    def test_inop(self, env):297        tmpl = env.from_string('{{ 1 in [1, 2, 3] }}|{{ 1 not in [1, 2, 3] }}')298        assert tmpl.render() == 'True|False'299300    def test_literals(self, env):301        tmpl = env.from_string('{{ [] }}|{{ {} }}|{{ () }}')302        assert tmpl.render().lower() == '[]|{}|()'303304    def test_bool(self, env):305        tmpl = env.from_string('{{ true and false }}|{{ false '306                               'or true }}|{{ not false }}')307        assert tmpl.render() == 'False|True|True'308309    def test_grouping(self, env):310        tmpl = env.from_string(311            '{{ (true and false) or (false and true) and not false }}')312        assert tmpl.render() == 'False'313314    def test_django_attr(self, env):315        tmpl = env.from_string('{{ [1, 2, 3].0 }}|{{ [[1]].0.0 }}')316        assert tmpl.render() == '1|1'317318    def test_conditional_expression(self, env):319        tmpl = env.from_string('''{{ 0 if true else 1 }}''')320        assert tmpl.render() == '0'321322    def test_short_conditional_expression(self, env):323        tmpl = env.from_string('<{{ 1 if false }}>')324        assert tmpl.render() == '<>'325326        tmpl = env.from_string('<{{ (1 if false).bar }}>')327        pytest.raises(UndefinedError, tmpl.render)328329    def test_filter_priority(self, env):330        tmpl = env.from_string('{{ "foo"|upper + "bar"|upper }}')331        assert tmpl.render() == 'FOOBAR'332333    def test_function_calls(self, env):334        tests = [335            (True, '*foo, bar'),336            (True, '*foo, *bar'),337            (True, '*foo, bar=42'),338            (True, '**foo, *bar'),339            (True, '**foo, bar'),340            (False, 'foo, bar'),341            (False, 'foo, bar=42'),342            (False, 'foo, bar=23, *args'),343            (False, 'a, b=c, *d, **e'),344            (False, '*foo, **bar')345        ]346        for should_fail, sig in tests:347            if should_fail:348                pytest.raises(TemplateSyntaxError,349                              env.from_string, '{{ foo(%s) }}' % sig)350            else:351                env.from_string('foo(%s)' % sig)352353    def test_tuple_expr(self, env):354        for tmpl in [355            '{{ () }}',356            '{{ (1, 2) }}',357            '{{ (1, 2,) }}',358            '{{ 1, }}',359            '{{ 1, 2 }}',360            '{% for foo, bar in seq %}...{% endfor %}',361            '{% for x in foo, bar %}...{% endfor %}',362            '{% for x in foo, %}...{% endfor %}'363        ]:364            assert env.from_string(tmpl)365366    def test_trailing_comma(self, env):367        tmpl = env.from_string('{{ (1, 2,) }}|{{ [1, 2,] }}|{{ {1: 2,} }}')368        assert tmpl.render().lower() == '(1, 2)|[1, 2]|{1: 2}'369370    def test_block_end_name(self, env):371        env.from_string('{% block foo %}...{% endblock foo %}')372        pytest.raises(TemplateSyntaxError, env.from_string,373                      '{% block x %}{% endblock y %}')374375    def test_constant_casing(self, env):376        for const in True, False, None:377            tmpl = env.from_string('{{ %s }}|{{ %s }}|{{ %s }}' % (378                str(const), str(const).lower(), str(const).upper()379            ))380            assert tmpl.render() == '%s|%s|' % (const, const)381382    def test_test_chaining(self, env):383        pytest.raises(TemplateSyntaxError, env.from_string,384                      '{{ foo is string is sequence }}')385        assert env.from_string(386            '{{ 42 is string or 42 is number }}'387        ).render() == 'True'388389    def test_string_concatenation(self, env):390        tmpl = env.from_string('{{ "foo" "bar" "baz" }}')391        assert tmpl.render() == 'foobarbaz'392393    def test_notin(self, env):394        bar = range(100)395        tmpl = env.from_string('''{{ not 42 in bar }}''')396        assert tmpl.render(bar=bar) == text_type(not 42 in bar)397398    def test_operator_precedence(self, env):399        tmpl = env.from_string('''{{ 2 * 3 + 4 % 2 + 1 - 2 }}''')400        assert tmpl.render() == text_type(2 * 3 + 4 % 2 + 1 - 2)401402    def test_implicit_subscribed_tuple(self, env):403        class Foo(object):404            def __getitem__(self, x):405                return x406        t = env.from_string('{{ foo[1, 2] }}')407        assert t.render(foo=Foo()) == u'(1, 2)'408409    def test_raw2(self, env):410        tmpl = env.from_string('{% raw %}{{ FOO }} and {% BAR %}{% endraw %}')411        assert tmpl.render() == '{{ FOO }} and {% BAR %}'412413    def test_const(self, env):414        tmpl = env.from_string(415            '{{ true }}|{{ false }}|{{ none }}|'416            '{{ none is defined }}|{{ missing is defined }}')417        assert tmpl.render() == 'True|False|None|True|False'418419    def test_neg_filter_priority(self, env):420        node = env.parse('{{ -1|foo }}')421        assert isinstance(node.body[0].nodes[0], nodes.Filter)422        assert isinstance(node.body[0].nodes[0].node, nodes.Neg)423424    def test_const_assign(self, env):425        constass1 = '''{% set true = 42 %}'''426        constass2 = '''{% for none in seq %}{% endfor %}'''427        for tmpl in constass1, constass2:428            pytest.raises(TemplateSyntaxError, env.from_string, tmpl)429430    def test_localset(self, env):431        tmpl = env.from_string('''{% set foo = 0 %}\432{% for item in [1, 2] %}{% set foo = 1 %}{% endfor %}\433{{ foo }}''')434        assert tmpl.render() == '0'435436    def test_parse_unary(self, env):437        tmpl = env.from_string('{{ -foo["bar"] }}')438        assert tmpl.render(foo={'bar': 42}) == '-42'439        tmpl = env.from_string('{{ -foo["bar"]|abs }}')440        assert tmpl.render(foo={'bar': 42}) == '42'441442443@pytest.mark.lexnparse444@pytest.mark.lstripblocks445class TestLstripBlocks():446447    def test_lstrip(self, env):448        env = Environment(lstrip_blocks=True, trim_blocks=False)449        tmpl = env.from_string('''    {% if True %}\n    {% endif %}''')450        assert tmpl.render() == "\n"451452    def test_lstrip_trim(self, env):453        env = Environment(lstrip_blocks=True, trim_blocks=True)454        tmpl = env.from_string('''    {% if True %}\n    {% endif %}''')455        assert tmpl.render() == ""456457    def test_no_lstrip(self, env):458        env = Environment(lstrip_blocks=True, trim_blocks=False)459        tmpl = env.from_string('''    {%+ if True %}\n    {%+ endif %}''')460        assert tmpl.render() == "    \n    "461462    def test_lstrip_endline(self, env):463        env = Environment(lstrip_blocks=True, trim_blocks=False)464        tmpl = env.from_string(465            '''    hello{% if True %}\n    goodbye{% endif %}''')466        assert tmpl.render() == "    hello\n    goodbye"467468    def test_lstrip_inline(self, env):469        env = Environment(lstrip_blocks=True, trim_blocks=False)470        tmpl = env.from_string('''    {% if True %}hello    {% endif %}''')471        assert tmpl.render() == 'hello    '472473    def test_lstrip_nested(self, env):474        env = Environment(lstrip_blocks=True, trim_blocks=False)475        tmpl = env.from_string(476            '''    {% if True %}a {% if True %}b {% endif %}c {% endif %}''')477        assert tmpl.render() == 'a b c '478479    def test_lstrip_left_chars(self, env):480        env = Environment(lstrip_blocks=True, trim_blocks=False)481        tmpl = env.from_string('''    abc {% if True %}482        hello{% endif %}''')483        assert tmpl.render() == '    abc \n        hello'484485    def test_lstrip_embeded_strings(self, env):486        env = Environment(lstrip_blocks=True, trim_blocks=False)487        tmpl = env.from_string('''    {% set x = " {% str %} " %}{{ x }}''')488        assert tmpl.render() == ' {% str %} '489490    def test_lstrip_preserve_leading_newlines(self, env):491        env = Environment(lstrip_blocks=True, trim_blocks=False)492        tmpl = env.from_string('''\n\n\n{% set hello = 1 %}''')493        assert tmpl.render() == '\n\n\n'494495    def test_lstrip_comment(self, env):496        env = Environment(lstrip_blocks=True, trim_blocks=False)497        tmpl = env.from_string('''    {# if True #}498hello499    {#endif#}''')500        assert tmpl.render() == '\nhello\n'501502    def test_lstrip_angle_bracket_simple(self, env):503        env = Environment('<%', '%>', '${', '}', '<%#', '%>', '%', '##',504                          lstrip_blocks=True, trim_blocks=True)505        tmpl = env.from_string('''    <% if True %>hello    <% endif %>''')506        assert tmpl.render() == 'hello    '507508    def test_lstrip_angle_bracket_comment(self, env):509        env = Environment('<%', '%>', '${', '}', '<%#', '%>', '%', '##',510                          lstrip_blocks=True, trim_blocks=True)511        tmpl = env.from_string('''    <%# if True %>hello    <%# endif %>''')512        assert tmpl.render() == 'hello    '513514    def test_lstrip_angle_bracket(self, env):515        env = Environment('<%', '%>', '${', '}', '<%#', '%>', '%', '##',516                          lstrip_blocks=True, trim_blocks=True)517        tmpl = env.from_string('''\518    <%# regular comment %>519    <% for item in seq %>520${item} ## the rest of the stuff521   <% endfor %>''')522        assert tmpl.render(seq=range(5)) == \523            ''.join('%s\n' % x for x in range(5))524525    def test_lstrip_angle_bracket_compact(self, env):526        env = Environment('<%', '%>', '${', '}', '<%#', '%>', '%', '##',527                          lstrip_blocks=True, trim_blocks=True)528        tmpl = env.from_string('''\529    <%#regular comment%>530    <%for item in seq%>531${item} ## the rest of the stuff532   <%endfor%>''')533        assert tmpl.render(seq=range(5)) == \534            ''.join('%s\n' % x for x in range(5))535536    def test_php_syntax_with_manual(self, env):537        env = Environment('<?', '?>', '<?=', '?>', '<!--', '-->',538                          lstrip_blocks=True, trim_blocks=True)539        tmpl = env.from_string('''\540    <!-- I'm a comment, I'm not interesting -->541    <? for item in seq -?>542        <?= item ?>543    <?- endfor ?>''')544        assert tmpl.render(seq=range(5)) == '01234'545546    def test_php_syntax(self, env):547        env = Environment('<?', '?>', '<?=', '?>', '<!--', '-->',548                          lstrip_blocks=True, trim_blocks=True)549        tmpl = env.from_string('''\550    <!-- I'm a comment, I'm not interesting -->551    <? for item in seq ?>552        <?= item ?>553    <? endfor ?>''')554        assert tmpl.render(seq=range(5)) \555            == ''.join('        %s\n' % x for x in range(5))556557    def test_php_syntax_compact(self, env):558        env = Environment('<?', '?>', '<?=', '?>', '<!--', '-->',559                          lstrip_blocks=True, trim_blocks=True)560        tmpl = env.from_string('''\561    <!-- I'm a comment, I'm not interesting -->562    <?for item in seq?>563        <?=item?>564    <?endfor?>''')565        assert tmpl.render(seq=range(5)) \566            == ''.join('        %s\n' % x for x in range(5))567568    def test_erb_syntax(self, env):569        env = Environment('<%', '%>', '<%=', '%>', '<%#', '%>',570                          lstrip_blocks=True, trim_blocks=True)571        # env.from_string('')572        # for n,r in env.lexer.rules.iteritems():573        #    print n574        # print env.lexer.rules['root'][0][0].pattern575        # print "'%s'" % tmpl.render(seq=range(5))576        tmpl = env.from_string('''\577<%# I'm a comment, I'm not interesting %>578    <% for item in seq %>579    <%= item %>580    <% endfor %>581''')582        assert tmpl.render(seq=range(5)) \583            == ''.join('    %s\n' % x for x in range(5))584585    def test_erb_syntax_with_manual(self, env):586        env = Environment('<%', '%>', '<%=', '%>', '<%#', '%>',587                          lstrip_blocks=True, trim_blocks=True)588        tmpl = env.from_string('''\589<%# I'm a comment, I'm not interesting %>590    <% for item in seq -%>591        <%= item %>592    <%- endfor %>''')593        assert tmpl.render(seq=range(5)) == '01234'594595    def test_erb_syntax_no_lstrip(self, env):596        env = Environment('<%', '%>', '<%=', '%>', '<%#', '%>',597                          lstrip_blocks=True, trim_blocks=True)598        tmpl = env.from_string('''\599<%# I'm a comment, I'm not interesting %>600    <%+ for item in seq -%>601        <%= item %>602    <%- endfor %>''')603        assert tmpl.render(seq=range(5)) == '    01234'604605    def test_comment_syntax(self, env):606        env = Environment('<!--', '-->', '${', '}', '<!--#', '-->',607                          lstrip_blocks=True, trim_blocks=True)608        tmpl = env.from_string('''\609<!--# I'm a comment, I'm not interesting -->\610<!-- for item in seq --->611    ${item}612<!--- endfor -->''')613        assert tmpl.render(seq=range(5)) == '01234'