Skip to content
Myr

test_lexnparse.py

This file

Path

tests/test_lexnparse.py

930 lines · 30.5 KiB · Python

Last changed by

Merge pull request #1183 from exponea/1138-fix-unintended-lstrip-behavior-changeDavid Lordbefore adoptionf1756a3

History of this file

Take it

1# -*- coding: utf-8 -*-2import pytest34from jinja2 import Environment5from jinja2 import nodes6from jinja2 import Template7from jinja2 import TemplateSyntaxError8from jinja2 import UndefinedError9from jinja2._compat import iteritems10from jinja2._compat import PY211from jinja2._compat import text_type12from jinja2.lexer import Token13from jinja2.lexer import TOKEN_BLOCK_BEGIN14from jinja2.lexer import TOKEN_BLOCK_END15from jinja2.lexer import TOKEN_EOF16from jinja2.lexer import TokenStream171819# how does a string look like in jinja syntax?20if PY2:2122    def jinja_string_repr(string):23        return repr(string)[1:]242526else:27    jinja_string_repr = repr282930class TestTokenStream(object):31    test_tokens = [32        Token(1, TOKEN_BLOCK_BEGIN, ""),33        Token(2, TOKEN_BLOCK_END, ""),34    ]3536    def test_simple(self, env):37        ts = TokenStream(self.test_tokens, "foo", "bar")38        assert ts.current.type is TOKEN_BLOCK_BEGIN39        assert bool(ts)40        assert not bool(ts.eos)41        next(ts)42        assert ts.current.type is TOKEN_BLOCK_END43        assert bool(ts)44        assert not bool(ts.eos)45        next(ts)46        assert ts.current.type is TOKEN_EOF47        assert not bool(ts)48        assert bool(ts.eos)4950    def test_iter(self, env):51        token_types = [t.type for t in TokenStream(self.test_tokens, "foo", "bar")]52        assert token_types == [53            "block_begin",54            "block_end",55        ]565758class TestLexer(object):59    def test_raw1(self, env):60        tmpl = env.from_string(61            "{% raw %}foo{% endraw %}|"62            "{%raw%}{{ bar }}|{% baz %}{%       endraw    %}"63        )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_raw3(self, env):71        # The second newline after baz exists because it is AFTER the72        # {% raw %} and is ignored.73        env = Environment(lstrip_blocks=True, trim_blocks=True)74        tmpl = env.from_string("bar\n{% raw %}\n  {{baz}}2 spaces\n{% endraw %}\nfoo")75        assert tmpl.render(baz="test") == "bar\n\n  {{baz}}2 spaces\nfoo"7677    def test_raw4(self, env):78        # The trailing dash of the {% raw -%} cleans both the spaces and79        # newlines up to the first character of data.80        env = Environment(lstrip_blocks=True, trim_blocks=False)81        tmpl = env.from_string(82            "bar\n{%- raw -%}\n\n  \n  2 spaces\n space{%- endraw -%}\nfoo"83        )84        assert tmpl.render() == "bar2 spaces\n spacefoo"8586    def test_balancing(self, env):87        env = Environment("{%", "%}", "${", "}")88        tmpl = env.from_string(89            """{% for item in seq90            %}${{'foo': item}|upper}{% endfor %}"""91        )92        assert tmpl.render(seq=list(range(3))) == "{'FOO': 0}{'FOO': 1}{'FOO': 2}"9394    def test_comments(self, env):95        env = Environment("<!--", "-->", "{", "}")96        tmpl = env.from_string(97            """\98<ul>99<!--- for item in seq -->100  <li>{item}</li>101<!--- endfor -->102</ul>"""103        )104        assert tmpl.render(seq=list(range(3))) == (105            "<ul>\n  <li>0</li>\n  <li>1</li>\n  <li>2</li>\n</ul>"106        )107108    def test_string_escapes(self, env):109        for char in u"\0", u"\u2668", u"\xe4", u"\t", u"\r", u"\n":110            tmpl = env.from_string("{{ %s }}" % jinja_string_repr(char))111            assert tmpl.render() == char112        assert env.from_string('{{ "\N{HOT SPRINGS}" }}').render() == u"\u2668"113114    def test_bytefallback(self, env):115        from pprint import pformat116117        tmpl = env.from_string(u"""{{ 'foo'|pprint }}|{{ 'bär'|pprint }}""")118        assert tmpl.render() == pformat("foo") + "|" + pformat(u"bär")119120    def test_operators(self, env):121        from jinja2.lexer import operators122123        for test, expect in iteritems(operators):124            if test in "([{}])":125                continue126            stream = env.lexer.tokenize("{{ %s }}" % test)127            next(stream)128            assert stream.current.type == expect129130    def test_normalizing(self, env):131        for seq in "\r", "\r\n", "\n":132            env = Environment(newline_sequence=seq)133            tmpl = env.from_string("1\n2\r\n3\n4\n")134            result = tmpl.render()135            assert result.replace(seq, "X") == "1X2X3X4"136137    def test_trailing_newline(self, env):138        for keep in [True, False]:139            env = Environment(keep_trailing_newline=keep)140            for template, expected in [141                ("", {}),142                ("no\nnewline", {}),143                ("with\nnewline\n", {False: "with\nnewline"}),144                ("with\nseveral\n\n\n", {False: "with\nseveral\n\n"}),145            ]:146                tmpl = env.from_string(template)147                expect = expected.get(keep, template)148                result = tmpl.render()149                assert result == expect, (keep, template, result, expect)150151    @pytest.mark.parametrize(152        "name,valid2,valid3",153        (154            (u"foo", True, True),155            (u"föö", False, True),156            (u"き", False, True),157            (u"_", True, True),158            (u"1a", False, False),  # invalid ascii start159            (u"a-", False, False),  # invalid ascii continue160            (u"🐍", False, False),  # invalid unicode start161            (u"a🐍", False, False),  # invalid unicode continue162            # start characters not matched by \w163            (u"\u1885", False, True),164            (u"\u1886", False, True),165            (u"\u2118", False, True),166            (u"\u212e", False, True),167            # continue character not matched by \w168            (u"\xb7", False, False),169            (u"a\xb7", False, True),170        ),171    )172    def test_name(self, env, name, valid2, valid3):173        t = u"{{ " + name + u" }}"174175        if (valid2 and PY2) or (valid3 and not PY2):176            # valid for version being tested, shouldn't raise177            env.from_string(t)178        else:179            pytest.raises(TemplateSyntaxError, env.from_string, t)180181    def test_lineno_with_strip(self, env):182        tokens = env.lex(183            """\184<html>185    <body>186    {%- block content -%}187        <hr>188        {{ item }}189    {% endblock %}190    </body>191</html>"""192        )193        for tok in tokens:194            lineno, token_type, value = tok195            if token_type == "name" and value == "item":196                assert lineno == 5197                break198199200class TestParser(object):201    def test_php_syntax(self, env):202        env = Environment("<?", "?>", "<?=", "?>", "<!--", "-->")203        tmpl = env.from_string(204            """\205<!-- I'm a comment, I'm not interesting -->\206<? for item in seq -?>207    <?= item ?>208<?- endfor ?>"""209        )210        assert tmpl.render(seq=list(range(5))) == "01234"211212    def test_erb_syntax(self, env):213        env = Environment("<%", "%>", "<%=", "%>", "<%#", "%>")214        tmpl = env.from_string(215            """\216<%# I'm a comment, I'm not interesting %>\217<% for item in seq -%>218    <%= item %>219<%- endfor %>"""220        )221        assert tmpl.render(seq=list(range(5))) == "01234"222223    def test_comment_syntax(self, env):224        env = Environment("<!--", "-->", "${", "}", "<!--#", "-->")225        tmpl = env.from_string(226            """\227<!--# I'm a comment, I'm not interesting -->\228<!-- for item in seq --->229    ${item}230<!--- endfor -->"""231        )232        assert tmpl.render(seq=list(range(5))) == "01234"233234    def test_balancing(self, env):235        tmpl = env.from_string("""{{{'foo':'bar'}.foo}}""")236        assert tmpl.render() == "bar"237238    def test_start_comment(self, env):239        tmpl = env.from_string(240            """{# foo comment241and bar comment #}242{% macro blub() %}foo{% endmacro %}243{{ blub() }}"""244        )245        assert tmpl.render().strip() == "foo"246247    def test_line_syntax(self, env):248        env = Environment("<%", "%>", "${", "}", "<%#", "%>", "%")249        tmpl = env.from_string(250            """\251<%# regular comment %>252% for item in seq:253    ${item}254% endfor"""255        )256        assert [257            int(x.strip()) for x in tmpl.render(seq=list(range(5))).split()258        ] == list(range(5))259260        env = Environment("<%", "%>", "${", "}", "<%#", "%>", "%", "##")261        tmpl = env.from_string(262            """\263<%# regular comment %>264% for item in seq:265    ${item} ## the rest of the stuff266% endfor"""267        )268        assert [269            int(x.strip()) for x in tmpl.render(seq=list(range(5))).split()270        ] == list(range(5))271272    def test_line_syntax_priority(self, env):273        # XXX: why is the whitespace there in front of the newline?274        env = Environment("{%", "%}", "${", "}", "/*", "*/", "##", "#")275        tmpl = env.from_string(276            """\277/* ignore me.278   I'm a multiline comment */279## for item in seq:280* ${item}          # this is just extra stuff281## endfor"""282        )283        assert tmpl.render(seq=[1, 2]).strip() == "* 1\n* 2"284        env = Environment("{%", "%}", "${", "}", "/*", "*/", "#", "##")285        tmpl = env.from_string(286            """\287/* ignore me.288   I'm a multiline comment */289# for item in seq:290* ${item}          ## this is just extra stuff291    ## extra stuff i just want to ignore292# endfor"""293        )294        assert tmpl.render(seq=[1, 2]).strip() == "* 1\n\n* 2"295296    def test_error_messages(self, env):297        def assert_error(code, expected):298            with pytest.raises(TemplateSyntaxError, match=expected):299                Template(code)300301        assert_error(302            "{% for item in seq %}...{% endif %}",303            "Encountered unknown tag 'endif'. Jinja was looking "304            "for the following tags: 'endfor' or 'else'. The "305            "innermost block that needs to be closed is 'for'.",306        )307        assert_error(308            "{% if foo %}{% for item in seq %}...{% endfor %}{% endfor %}",309            "Encountered unknown tag 'endfor'. Jinja was looking for "310            "the following tags: 'elif' or 'else' or 'endif'. The "311            "innermost block that needs to be closed is 'if'.",312        )313        assert_error(314            "{% if foo %}",315            "Unexpected end of template. Jinja was looking for the "316            "following tags: 'elif' or 'else' or 'endif'. The "317            "innermost block that needs to be closed is 'if'.",318        )319        assert_error(320            "{% for item in seq %}",321            "Unexpected end of template. Jinja was looking for the "322            "following tags: 'endfor' or 'else'. The innermost block "323            "that needs to be closed is 'for'.",324        )325        assert_error(326            "{% block foo-bar-baz %}",327            "Block names in Jinja have to be valid Python identifiers "328            "and may not contain hyphens, use an underscore instead.",329        )330        assert_error("{% unknown_tag %}", "Encountered unknown tag 'unknown_tag'.")331332333class TestSyntax(object):334    def test_call(self, env):335        env = Environment()336        env.globals["foo"] = lambda a, b, c, e, g: a + b + c + e + g337        tmpl = env.from_string("{{ foo('a', c='d', e='f', *['b'], **{'g': 'h'}) }}")338        assert tmpl.render() == "abdfh"339340    def test_slicing(self, env):341        tmpl = env.from_string("{{ [1, 2, 3][:] }}|{{ [1, 2, 3][::-1] }}")342        assert tmpl.render() == "[1, 2, 3]|[3, 2, 1]"343344    def test_attr(self, env):345        tmpl = env.from_string("{{ foo.bar }}|{{ foo['bar'] }}")346        assert tmpl.render(foo={"bar": 42}) == "42|42"347348    def test_subscript(self, env):349        tmpl = env.from_string("{{ foo[0] }}|{{ foo[-1] }}")350        assert tmpl.render(foo=[0, 1, 2]) == "0|2"351352    def test_tuple(self, env):353        tmpl = env.from_string("{{ () }}|{{ (1,) }}|{{ (1, 2) }}")354        assert tmpl.render() == "()|(1,)|(1, 2)"355356    def test_math(self, env):357        tmpl = env.from_string("{{ (1 + 1 * 2) - 3 / 2 }}|{{ 2**3 }}")358        assert tmpl.render() == "1.5|8"359360    def test_div(self, env):361        tmpl = env.from_string("{{ 3 // 2 }}|{{ 3 / 2 }}|{{ 3 % 2 }}")362        assert tmpl.render() == "1|1.5|1"363364    def test_unary(self, env):365        tmpl = env.from_string("{{ +3 }}|{{ -3 }}")366        assert tmpl.render() == "3|-3"367368    def test_concat(self, env):369        tmpl = env.from_string("{{ [1, 2] ~ 'foo' }}")370        assert tmpl.render() == "[1, 2]foo"371372    @pytest.mark.parametrize(373        ("a", "op", "b"),374        [375            (1, ">", 0),376            (1, ">=", 1),377            (2, "<", 3),378            (3, "<=", 4),379            (4, "==", 4),380            (4, "!=", 5),381        ],382    )383    def test_compare(self, env, a, op, b):384        t = env.from_string("{{ %d %s %d }}" % (a, op, b))385        assert t.render() == "True"386387    def test_compare_parens(self, env):388        t = env.from_string("{{ i * (j < 5) }}")389        assert t.render(i=2, j=3) == "2"390391    @pytest.mark.parametrize(392        ("src", "expect"),393        [394            ("{{ 4 < 2 < 3 }}", "False"),395            ("{{ a < b < c }}", "False"),396            ("{{ 4 > 2 > 3 }}", "False"),397            ("{{ a > b > c }}", "False"),398            ("{{ 4 > 2 < 3 }}", "True"),399            ("{{ a > b < c }}", "True"),400        ],401    )402    def test_compare_compound(self, env, src, expect):403        t = env.from_string(src)404        assert t.render(a=4, b=2, c=3) == expect405406    def test_inop(self, env):407        tmpl = env.from_string("{{ 1 in [1, 2, 3] }}|{{ 1 not in [1, 2, 3] }}")408        assert tmpl.render() == "True|False"409410    @pytest.mark.parametrize("value", ("[]", "{}", "()"))411    def test_collection_literal(self, env, value):412        t = env.from_string("{{ %s }}" % value)413        assert t.render() == value414415    @pytest.mark.parametrize(416        ("value", "expect"),417        (418            ("1", "1"),419            ("123", "123"),420            ("12_34_56", "123456"),421            ("1.2", "1.2"),422            ("34.56", "34.56"),423            ("3_4.5_6", "34.56"),424            ("1e0", "1.0"),425            ("10e1", "100.0"),426            ("2.5e100", "2.5e+100"),427            ("2.5e+100", "2.5e+100"),428            ("25.6e-10", "2.56e-09"),429            ("1_2.3_4e5_6", "1.234e+57"),430        ),431    )432    def test_numeric_literal(self, env, value, expect):433        t = env.from_string("{{ %s }}" % value)434        assert t.render() == expect435436    def test_bool(self, env):437        tmpl = env.from_string(438            "{{ true and false }}|{{ false or true }}|{{ not false }}"439        )440        assert tmpl.render() == "False|True|True"441442    def test_grouping(self, env):443        tmpl = env.from_string(444            "{{ (true and false) or (false and true) and not false }}"445        )446        assert tmpl.render() == "False"447448    def test_django_attr(self, env):449        tmpl = env.from_string("{{ [1, 2, 3].0 }}|{{ [[1]].0.0 }}")450        assert tmpl.render() == "1|1"451452    def test_conditional_expression(self, env):453        tmpl = env.from_string("""{{ 0 if true else 1 }}""")454        assert tmpl.render() == "0"455456    def test_short_conditional_expression(self, env):457        tmpl = env.from_string("<{{ 1 if false }}>")458        assert tmpl.render() == "<>"459460        tmpl = env.from_string("<{{ (1 if false).bar }}>")461        pytest.raises(UndefinedError, tmpl.render)462463    def test_filter_priority(self, env):464        tmpl = env.from_string('{{ "foo"|upper + "bar"|upper }}')465        assert tmpl.render() == "FOOBAR"466467    def test_function_calls(self, env):468        tests = [469            (True, "*foo, bar"),470            (True, "*foo, *bar"),471            (True, "**foo, *bar"),472            (True, "**foo, bar"),473            (True, "**foo, **bar"),474            (True, "**foo, bar=42"),475            (False, "foo, bar"),476            (False, "foo, bar=42"),477            (False, "foo, bar=23, *args"),478            (False, "foo, *args, bar=23"),479            (False, "a, b=c, *d, **e"),480            (False, "*foo, bar=42"),481            (False, "*foo, **bar"),482            (False, "*foo, bar=42, **baz"),483            (False, "foo, *args, bar=23, **baz"),484        ]485        for should_fail, sig in tests:486            if should_fail:487                pytest.raises(488                    TemplateSyntaxError, env.from_string, "{{ foo(%s) }}" % sig489                )490            else:491                env.from_string("foo(%s)" % sig)492493    def test_tuple_expr(self, env):494        for tmpl in [495            "{{ () }}",496            "{{ (1, 2) }}",497            "{{ (1, 2,) }}",498            "{{ 1, }}",499            "{{ 1, 2 }}",500            "{% for foo, bar in seq %}...{% endfor %}",501            "{% for x in foo, bar %}...{% endfor %}",502            "{% for x in foo, %}...{% endfor %}",503        ]:504            assert env.from_string(tmpl)505506    def test_trailing_comma(self, env):507        tmpl = env.from_string("{{ (1, 2,) }}|{{ [1, 2,] }}|{{ {1: 2,} }}")508        assert tmpl.render().lower() == "(1, 2)|[1, 2]|{1: 2}"509510    def test_block_end_name(self, env):511        env.from_string("{% block foo %}...{% endblock foo %}")512        pytest.raises(513            TemplateSyntaxError, env.from_string, "{% block x %}{% endblock y %}"514        )515516    def test_constant_casing(self, env):517        for const in True, False, None:518            tmpl = env.from_string(519                "{{ %s }}|{{ %s }}|{{ %s }}"520                % (str(const), str(const).lower(), str(const).upper())521            )522            assert tmpl.render() == "%s|%s|" % (const, const)523524    def test_test_chaining(self, env):525        pytest.raises(526            TemplateSyntaxError, env.from_string, "{{ foo is string is sequence }}"527        )528        assert env.from_string("{{ 42 is string or 42 is number }}").render() == "True"529530    def test_string_concatenation(self, env):531        tmpl = env.from_string('{{ "foo" "bar" "baz" }}')532        assert tmpl.render() == "foobarbaz"533534    def test_notin(self, env):535        bar = range(100)536        tmpl = env.from_string("""{{ not 42 in bar }}""")537        assert tmpl.render(bar=bar) == "False"538539    def test_operator_precedence(self, env):540        tmpl = env.from_string("""{{ 2 * 3 + 4 % 2 + 1 - 2 }}""")541        assert tmpl.render() == text_type(2 * 3 + 4 % 2 + 1 - 2)542543    def test_implicit_subscribed_tuple(self, env):544        class Foo(object):545            def __getitem__(self, x):546                return x547548        t = env.from_string("{{ foo[1, 2] }}")549        assert t.render(foo=Foo()) == u"(1, 2)"550551    def test_raw2(self, env):552        tmpl = env.from_string("{% raw %}{{ FOO }} and {% BAR %}{% endraw %}")553        assert tmpl.render() == "{{ FOO }} and {% BAR %}"554555    def test_const(self, env):556        tmpl = env.from_string(557            "{{ true }}|{{ false }}|{{ none }}|"558            "{{ none is defined }}|{{ missing is defined }}"559        )560        assert tmpl.render() == "True|False|None|True|False"561562    def test_neg_filter_priority(self, env):563        node = env.parse("{{ -1|foo }}")564        assert isinstance(node.body[0].nodes[0], nodes.Filter)565        assert isinstance(node.body[0].nodes[0].node, nodes.Neg)566567    def test_const_assign(self, env):568        constass1 = """{% set true = 42 %}"""569        constass2 = """{% for none in seq %}{% endfor %}"""570        for tmpl in constass1, constass2:571            pytest.raises(TemplateSyntaxError, env.from_string, tmpl)572573    def test_localset(self, env):574        tmpl = env.from_string(575            """{% set foo = 0 %}\576{% for item in [1, 2] %}{% set foo = 1 %}{% endfor %}\577{{ foo }}"""578        )579        assert tmpl.render() == "0"580581    def test_parse_unary(self, env):582        tmpl = env.from_string('{{ -foo["bar"] }}')583        assert tmpl.render(foo={"bar": 42}) == "-42"584        tmpl = env.from_string('{{ -foo["bar"]|abs }}')585        assert tmpl.render(foo={"bar": 42}) == "42"586587588class TestLstripBlocks(object):589    def test_lstrip(self, env):590        env = Environment(lstrip_blocks=True, trim_blocks=False)591        tmpl = env.from_string("""    {% if True %}\n    {% endif %}""")592        assert tmpl.render() == "\n"593594    def test_lstrip_trim(self, env):595        env = Environment(lstrip_blocks=True, trim_blocks=True)596        tmpl = env.from_string("""    {% if True %}\n    {% endif %}""")597        assert tmpl.render() == ""598599    def test_no_lstrip(self, env):600        env = Environment(lstrip_blocks=True, trim_blocks=False)601        tmpl = env.from_string("""    {%+ if True %}\n    {%+ endif %}""")602        assert tmpl.render() == "    \n    "603604    def test_lstrip_blocks_false_with_no_lstrip(self, env):605        # Test that + is a NOP (but does not cause an error) if lstrip_blocks=False606        env = Environment(lstrip_blocks=False, trim_blocks=False)607        tmpl = env.from_string("""    {% if True %}\n    {% endif %}""")608        assert tmpl.render() == "    \n    "609        tmpl = env.from_string("""    {%+ if True %}\n    {%+ endif %}""")610        assert tmpl.render() == "    \n    "611612    def test_lstrip_endline(self, env):613        env = Environment(lstrip_blocks=True, trim_blocks=False)614        tmpl = env.from_string("""    hello{% if True %}\n    goodbye{% endif %}""")615        assert tmpl.render() == "    hello\n    goodbye"616617    def test_lstrip_inline(self, env):618        env = Environment(lstrip_blocks=True, trim_blocks=False)619        tmpl = env.from_string("""    {% if True %}hello    {% endif %}""")620        assert tmpl.render() == "hello    "621622    def test_lstrip_nested(self, env):623        env = Environment(lstrip_blocks=True, trim_blocks=False)624        tmpl = env.from_string(625            """    {% if True %}a {% if True %}b {% endif %}c {% endif %}"""626        )627        assert tmpl.render() == "a b c "628629    def test_lstrip_left_chars(self, env):630        env = Environment(lstrip_blocks=True, trim_blocks=False)631        tmpl = env.from_string(632            """    abc {% if True %}633        hello{% endif %}"""634        )635        assert tmpl.render() == "    abc \n        hello"636637    def test_lstrip_embeded_strings(self, env):638        env = Environment(lstrip_blocks=True, trim_blocks=False)639        tmpl = env.from_string("""    {% set x = " {% str %} " %}{{ x }}""")640        assert tmpl.render() == " {% str %} "641642    def test_lstrip_preserve_leading_newlines(self, env):643        env = Environment(lstrip_blocks=True, trim_blocks=False)644        tmpl = env.from_string("""\n\n\n{% set hello = 1 %}""")645        assert tmpl.render() == "\n\n\n"646647    def test_lstrip_comment(self, env):648        env = Environment(lstrip_blocks=True, trim_blocks=False)649        tmpl = env.from_string(650            """    {# if True #}651hello652    {#endif#}"""653        )654        assert tmpl.render() == "\nhello\n"655656    def test_lstrip_angle_bracket_simple(self, env):657        env = Environment(658            "<%",659            "%>",660            "${",661            "}",662            "<%#",663            "%>",664            "%",665            "##",666            lstrip_blocks=True,667            trim_blocks=True,668        )669        tmpl = env.from_string("""    <% if True %>hello    <% endif %>""")670        assert tmpl.render() == "hello    "671672    def test_lstrip_angle_bracket_comment(self, env):673        env = Environment(674            "<%",675            "%>",676            "${",677            "}",678            "<%#",679            "%>",680            "%",681            "##",682            lstrip_blocks=True,683            trim_blocks=True,684        )685        tmpl = env.from_string("""    <%# if True %>hello    <%# endif %>""")686        assert tmpl.render() == "hello    "687688    def test_lstrip_angle_bracket(self, env):689        env = Environment(690            "<%",691            "%>",692            "${",693            "}",694            "<%#",695            "%>",696            "%",697            "##",698            lstrip_blocks=True,699            trim_blocks=True,700        )701        tmpl = env.from_string(702            """\703    <%# regular comment %>704    <% for item in seq %>705${item} ## the rest of the stuff706   <% endfor %>"""707        )708        assert tmpl.render(seq=range(5)) == "".join("%s\n" % x for x in range(5))709710    def test_lstrip_angle_bracket_compact(self, env):711        env = Environment(712            "<%",713            "%>",714            "${",715            "}",716            "<%#",717            "%>",718            "%",719            "##",720            lstrip_blocks=True,721            trim_blocks=True,722        )723        tmpl = env.from_string(724            """\725    <%#regular comment%>726    <%for item in seq%>727${item} ## the rest of the stuff728   <%endfor%>"""729        )730        assert tmpl.render(seq=range(5)) == "".join("%s\n" % x for x in range(5))731732    def test_lstrip_blocks_outside_with_new_line(self):733        env = Environment(lstrip_blocks=True, trim_blocks=False)734        tmpl = env.from_string(735            "  {% if kvs %}(\n"736            "   {% for k, v in kvs %}{{ k }}={{ v }} {% endfor %}\n"737            "  ){% endif %}"738        )739        out = tmpl.render(kvs=[("a", 1), ("b", 2)])740        assert out == "(\na=1 b=2 \n  )"741742    def test_lstrip_trim_blocks_outside_with_new_line(self):743        env = Environment(lstrip_blocks=True, trim_blocks=True)744        tmpl = env.from_string(745            "  {% if kvs %}(\n"746            "   {% for k, v in kvs %}{{ k }}={{ v }} {% endfor %}\n"747            "  ){% endif %}"748        )749        out = tmpl.render(kvs=[("a", 1), ("b", 2)])750        assert out == "(\na=1 b=2   )"751752    def test_lstrip_blocks_inside_with_new_line(self):753        env = Environment(lstrip_blocks=True, trim_blocks=False)754        tmpl = env.from_string(755            "  ({% if kvs %}\n"756            "   {% for k, v in kvs %}{{ k }}={{ v }} {% endfor %}\n"757            "  {% endif %})"758        )759        out = tmpl.render(kvs=[("a", 1), ("b", 2)])760        assert out == "  (\na=1 b=2 \n)"761762    def test_lstrip_trim_blocks_inside_with_new_line(self):763        env = Environment(lstrip_blocks=True, trim_blocks=True)764        tmpl = env.from_string(765            "  ({% if kvs %}\n"766            "   {% for k, v in kvs %}{{ k }}={{ v }} {% endfor %}\n"767            "  {% endif %})"768        )769        out = tmpl.render(kvs=[("a", 1), ("b", 2)])770        assert out == "  (a=1 b=2 )"771772    def test_lstrip_blocks_without_new_line(self):773        env = Environment(lstrip_blocks=True, trim_blocks=False)774        tmpl = env.from_string(775            "  {% if kvs %}"776            "   {% for k, v in kvs %}{{ k }}={{ v }} {% endfor %}"777            "  {% endif %}"778        )779        out = tmpl.render(kvs=[("a", 1), ("b", 2)])780        assert out == "   a=1 b=2   "781782    def test_lstrip_trim_blocks_without_new_line(self):783        env = Environment(lstrip_blocks=True, trim_blocks=True)784        tmpl = env.from_string(785            "  {% if kvs %}"786            "   {% for k, v in kvs %}{{ k }}={{ v }} {% endfor %}"787            "  {% endif %}"788        )789        out = tmpl.render(kvs=[("a", 1), ("b", 2)])790        assert out == "   a=1 b=2   "791792    def test_lstrip_blocks_consume_after_without_new_line(self):793        env = Environment(lstrip_blocks=True, trim_blocks=False)794        tmpl = env.from_string(795            "  {% if kvs -%}"796            "   {% for k, v in kvs %}{{ k }}={{ v }} {% endfor -%}"797            "  {% endif -%}"798        )799        out = tmpl.render(kvs=[("a", 1), ("b", 2)])800        assert out == "a=1 b=2 "801802    def test_lstrip_trim_blocks_consume_before_without_new_line(self):803        env = Environment(lstrip_blocks=False, trim_blocks=False)804        tmpl = env.from_string(805            "  {%- if kvs %}"806            "   {%- for k, v in kvs %}{{ k }}={{ v }} {% endfor -%}"807            "  {%- endif %}"808        )809        out = tmpl.render(kvs=[("a", 1), ("b", 2)])810        assert out == "a=1 b=2 "811812    def test_lstrip_trim_blocks_comment(self):813        env = Environment(lstrip_blocks=True, trim_blocks=True)814        tmpl = env.from_string(" {# 1 space #}\n  {# 2 spaces #}    {# 4 spaces #}")815        out = tmpl.render()816        assert out == " " * 4817818    def test_lstrip_trim_blocks_raw(self):819        env = Environment(lstrip_blocks=True, trim_blocks=True)820        tmpl = env.from_string("{{x}}\n{%- raw %} {% endraw -%}\n{{ y }}")821        out = tmpl.render(x=1, y=2)822        assert out == "1 2"823824    def test_php_syntax_with_manual(self, env):825        env = Environment(826            "<?", "?>", "<?=", "?>", "<!--", "-->", lstrip_blocks=True, trim_blocks=True827        )828        tmpl = env.from_string(829            """\830    <!-- I'm a comment, I'm not interesting -->831    <? for item in seq -?>832        <?= item ?>833    <?- endfor ?>"""834        )835        assert tmpl.render(seq=range(5)) == "01234"836837    def test_php_syntax(self, env):838        env = Environment(839            "<?", "?>", "<?=", "?>", "<!--", "-->", lstrip_blocks=True, trim_blocks=True840        )841        tmpl = env.from_string(842            """\843    <!-- I'm a comment, I'm not interesting -->844    <? for item in seq ?>845        <?= item ?>846    <? endfor ?>"""847        )848        assert tmpl.render(seq=range(5)) == "".join(849            "        %s\n" % x for x in range(5)850        )851852    def test_php_syntax_compact(self, env):853        env = Environment(854            "<?", "?>", "<?=", "?>", "<!--", "-->", lstrip_blocks=True, trim_blocks=True855        )856        tmpl = env.from_string(857            """\858    <!-- I'm a comment, I'm not interesting -->859    <?for item in seq?>860        <?=item?>861    <?endfor?>"""862        )863        assert tmpl.render(seq=range(5)) == "".join(864            "        %s\n" % x for x in range(5)865        )866867    def test_erb_syntax(self, env):868        env = Environment(869            "<%", "%>", "<%=", "%>", "<%#", "%>", lstrip_blocks=True, trim_blocks=True870        )871        # env.from_string('')872        # for n,r in env.lexer.rules.iteritems():873        #    print n874        # print env.lexer.rules['root'][0][0].pattern875        # print "'%s'" % tmpl.render(seq=range(5))876        tmpl = env.from_string(877            """\878<%# I'm a comment, I'm not interesting %>879    <% for item in seq %>880    <%= item %>881    <% endfor %>882"""883        )884        assert tmpl.render(seq=range(5)) == "".join("    %s\n" % x for x in range(5))885886    def test_erb_syntax_with_manual(self, env):887        env = Environment(888            "<%", "%>", "<%=", "%>", "<%#", "%>", lstrip_blocks=True, trim_blocks=True889        )890        tmpl = env.from_string(891            """\892<%# I'm a comment, I'm not interesting %>893    <% for item in seq -%>894        <%= item %>895    <%- endfor %>"""896        )897        assert tmpl.render(seq=range(5)) == "01234"898899    def test_erb_syntax_no_lstrip(self, env):900        env = Environment(901            "<%", "%>", "<%=", "%>", "<%#", "%>", lstrip_blocks=True, trim_blocks=True902        )903        tmpl = env.from_string(904            """\905<%# I'm a comment, I'm not interesting %>906    <%+ for item in seq -%>907        <%= item %>908    <%- endfor %>"""909        )910        assert tmpl.render(seq=range(5)) == "    01234"911912    def test_comment_syntax(self, env):913        env = Environment(914            "<!--",915            "-->",916            "${",917            "}",918            "<!--#",919            "-->",920            lstrip_blocks=True,921            trim_blocks=True,922        )923        tmpl = env.from_string(924            """\925<!--# I'm a comment, I'm not interesting -->\926<!-- for item in seq --->927    ${item}928<!--- endfor -->"""929        )930        assert tmpl.render(seq=range(5)) == "01234"