test_lexnparse.py
This file
Path
tests/test_lexnparse.py
1,029 lines · 34.6 KiB · Python
Last changed by
Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
History of this fileTake it
The walk stopped after 200 commits: lines older than c580dd0 point at it.
update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1–45why, one step back1import pytest23from jinja2 import Environment4from jinja2 import nodes5from jinja2 import Template6from jinja2 import TemplateSyntaxError7from jinja2 import UndefinedError8from jinja2.lexer import Token9from jinja2.lexer import TOKEN_BLOCK_BEGIN10from jinja2.lexer import TOKEN_BLOCK_END11from jinja2.lexer import TOKEN_EOF12from jinja2.lexer import TokenStream131415class TestTokenStream:16 test_tokens = [17 Token(1, TOKEN_BLOCK_BEGIN, ""),18 Token(2, TOKEN_BLOCK_END, ""),19 ]2021 def test_simple(self, env):22 ts = TokenStream(self.test_tokens, "foo", "bar")23 assert ts.current.type is TOKEN_BLOCK_BEGIN24 assert bool(ts)25 assert not bool(ts.eos)26 next(ts)27 assert ts.current.type is TOKEN_BLOCK_END28 assert bool(ts)29 assert not bool(ts.eos)30 next(ts)31 assert ts.current.type is TOKEN_EOF32 assert not bool(ts)33 assert bool(ts.eos)3435 def test_iter(self, env):36 token_types = [t.type for t in TokenStream(self.test_tokens, "foo", "bar")]37 assert token_types == [38 "block_begin",39 "block_end",40 ]414243class TestLexer:44 def test_raw1(self, env):45 tmpl = env.from_string(Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 46why, one step back46 "{% raw %}foo{% endraw %}|{%raw%}{{ bar }}|{% baz %}{% endraw %}"update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 47–413why, one step back47 )48 assert tmpl.render() == "foo|{{ bar }}|{% baz %}"4950 def test_raw2(self, env):51 tmpl = env.from_string("1 {%- raw -%} 2 {%- endraw -%} 3")52 assert tmpl.render() == "123"5354 def test_raw3(self, env):55 # The second newline after baz exists because it is AFTER the56 # {% raw %} and is ignored.57 env = Environment(lstrip_blocks=True, trim_blocks=True)58 tmpl = env.from_string("bar\n{% raw %}\n {{baz}}2 spaces\n{% endraw %}\nfoo")59 assert tmpl.render(baz="test") == "bar\n\n {{baz}}2 spaces\nfoo"6061 def test_raw4(self, env):62 # The trailing dash of the {% raw -%} cleans both the spaces and63 # newlines up to the first character of data.64 env = Environment(lstrip_blocks=True, trim_blocks=False)65 tmpl = env.from_string(66 "bar\n{%- raw -%}\n\n \n 2 spaces\n space{%- endraw -%}\nfoo"67 )68 assert tmpl.render() == "bar2 spaces\n spacefoo"6970 def test_balancing(self, env):71 env = Environment("{%", "%}", "${", "}")72 tmpl = env.from_string(73 """{% for item in seq74 %}${{'foo': item}|upper}{% endfor %}"""75 )76 assert tmpl.render(seq=list(range(3))) == "{'FOO': 0}{'FOO': 1}{'FOO': 2}"7778 def test_comments(self, env):79 env = Environment("<!--", "-->", "{", "}")80 tmpl = env.from_string(81 """\82<ul>83<!--- for item in seq -->84 <li>{item}</li>85<!--- endfor -->86</ul>"""87 )88 assert tmpl.render(seq=list(range(3))) == (89 "<ul>\n <li>0</li>\n <li>1</li>\n <li>2</li>\n</ul>"90 )9192 def test_string_escapes(self, env):93 for char in "\0", "\u2668", "\xe4", "\t", "\r", "\n":94 tmpl = env.from_string(f"{{{{ {char!r} }}}}")95 assert tmpl.render() == char96 assert env.from_string('{{ "\N{HOT SPRINGS}" }}').render() == "\u2668"9798 def test_bytefallback(self, env):99 from pprint import pformat100101 tmpl = env.from_string("""{{ 'foo'|pprint }}|{{ 'bär'|pprint }}""")102 assert tmpl.render() == pformat("foo") + "|" + pformat("bär")103104 def test_operators(self, env):105 from jinja2.lexer import operators106107 for test, expect in operators.items():108 if test in "([{}])":109 continue110 stream = env.lexer.tokenize(f"{{{{ {test} }}}}")111 next(stream)112 assert stream.current.type == expect113114 def test_normalizing(self, env):115 for seq in "\r", "\r\n", "\n":116 env = Environment(newline_sequence=seq)117 tmpl = env.from_string("1\n2\r\n3\n4\n")118 result = tmpl.render()119 assert result.replace(seq, "X") == "1X2X3X4"120121 def test_trailing_newline(self, env):122 for keep in [True, False]:123 env = Environment(keep_trailing_newline=keep)124 for template, expected in [125 ("", {}),126 ("no\nnewline", {}),127 ("with\nnewline\n", {False: "with\nnewline"}),128 ("with\nseveral\n\n\n", {False: "with\nseveral\n\n"}),129 ]:130 tmpl = env.from_string(template)131 expect = expected.get(keep, template)132 result = tmpl.render()133 assert result == expect, (keep, template, result, expect)134135 @pytest.mark.parametrize(136 ("name", "valid"),137 [138 ("foo", True),139 ("föö", True),140 ("き", True),141 ("_", True),142 ("1a", False), # invalid ascii start143 ("a-", False), # invalid ascii continue144 ("\U0001f40da", False), # invalid unicode start145 ("a🐍\U0001f40d", False), # invalid unicode continue146 # start characters not matched by \w147 ("\u1885", True),148 ("\u1886", True),149 ("\u2118", True),150 ("\u212e", True),151 # continue character not matched by \w152 ("\xb7", False),153 ("a\xb7", True),154 ],155 )156 def test_name(self, env, name, valid):157 t = "{{ " + name + " }}"158159 if valid:160 # valid for version being tested, shouldn't raise161 env.from_string(t)162 else:163 pytest.raises(TemplateSyntaxError, env.from_string, t)164165 def test_lineno_with_strip(self, env):166 tokens = env.lex(167 """\168<html>169 <body>170 {%- block content -%}171 <hr>172 {{ item }}173 {% endblock %}174 </body>175</html>"""176 )177 for tok in tokens:178 lineno, token_type, value = tok179 if token_type == "name" and value == "item":180 assert lineno == 5181 break182183184class TestParser:185 def test_php_syntax(self, env):186 env = Environment("<?", "?>", "<?=", "?>", "<!--", "-->")187 tmpl = env.from_string(188 """\189<!-- I'm a comment, I'm not interesting -->\190<? for item in seq -?>191 <?= item ?>192<?- endfor ?>"""193 )194 assert tmpl.render(seq=list(range(5))) == "01234"195196 def test_erb_syntax(self, env):197 env = Environment("<%", "%>", "<%=", "%>", "<%#", "%>")198 tmpl = env.from_string(199 """\200<%# I'm a comment, I'm not interesting %>\201<% for item in seq -%>202 <%= item %>203<%- endfor %>"""204 )205 assert tmpl.render(seq=list(range(5))) == "01234"206207 def test_comment_syntax(self, env):208 env = Environment("<!--", "-->", "${", "}", "<!--#", "-->")209 tmpl = env.from_string(210 """\211<!--# I'm a comment, I'm not interesting -->\212<!-- for item in seq --->213 ${item}214<!--- endfor -->"""215 )216 assert tmpl.render(seq=list(range(5))) == "01234"217218 def test_balancing(self, env):219 tmpl = env.from_string("""{{{'foo':'bar'}.foo}}""")220 assert tmpl.render() == "bar"221222 def test_start_comment(self, env):223 tmpl = env.from_string(224 """{# foo comment225and bar comment #}226{% macro blub() %}foo{% endmacro %}227{{ blub() }}"""228 )229 assert tmpl.render().strip() == "foo"230231 def test_line_syntax(self, env):232 env = Environment("<%", "%>", "${", "}", "<%#", "%>", "%")233 tmpl = env.from_string(234 """\235<%# regular comment %>236% for item in seq:237 ${item}238% endfor"""239 )240 assert [241 int(x.strip()) for x in tmpl.render(seq=list(range(5))).split()242 ] == list(range(5))243244 env = Environment("<%", "%>", "${", "}", "<%#", "%>", "%", "##")245 tmpl = env.from_string(246 """\247<%# regular comment %>248% for item in seq:249 ${item} ## the rest of the stuff250% endfor"""251 )252 assert [253 int(x.strip()) for x in tmpl.render(seq=list(range(5))).split()254 ] == list(range(5))255256 def test_line_syntax_priority(self, env):257 # XXX: why is the whitespace there in front of the newline?258 env = Environment("{%", "%}", "${", "}", "/*", "*/", "##", "#")259 tmpl = env.from_string(260 """\261/* ignore me.262 I'm a multiline comment */263## for item in seq:264* ${item} # this is just extra stuff265## endfor"""266 )267 assert tmpl.render(seq=[1, 2]).strip() == "* 1\n* 2"268 env = Environment("{%", "%}", "${", "}", "/*", "*/", "#", "##")269 tmpl = env.from_string(270 """\271/* ignore me.272 I'm a multiline comment */273# for item in seq:274* ${item} ## this is just extra stuff275 ## extra stuff i just want to ignore276# endfor"""277 )278 assert tmpl.render(seq=[1, 2]).strip() == "* 1\n\n* 2"279280 def test_error_messages(self, env):281 def assert_error(code, expected):282 with pytest.raises(TemplateSyntaxError, match=expected):283 Template(code)284285 assert_error(286 "{% for item in seq %}...{% endif %}",287 "Encountered unknown tag 'endif'. Jinja was looking "288 "for the following tags: 'endfor' or 'else'. The "289 "innermost block that needs to be closed is 'for'.",290 )291 assert_error(292 "{% if foo %}{% for item in seq %}...{% endfor %}{% endfor %}",293 "Encountered unknown tag 'endfor'. Jinja was looking for "294 "the following tags: 'elif' or 'else' or 'endif'. The "295 "innermost block that needs to be closed is 'if'.",296 )297 assert_error(298 "{% if foo %}",299 "Unexpected end of template. Jinja was looking for the "300 "following tags: 'elif' or 'else' or 'endif'. The "301 "innermost block that needs to be closed is 'if'.",302 )303 assert_error(304 "{% for item in seq %}",305 "Unexpected end of template. Jinja was looking for the "306 "following tags: 'endfor' or 'else'. The innermost block "307 "that needs to be closed is 'for'.",308 )309 assert_error(310 "{% block foo-bar-baz %}",311 "Block names in Jinja have to be valid Python identifiers "312 "and may not contain hyphens, use an underscore instead.",313 )314 assert_error("{% unknown_tag %}", "Encountered unknown tag 'unknown_tag'.")315316317class TestSyntax:318 def test_call(self, env):319 env = Environment()320 env.globals["foo"] = lambda a, b, c, e, g: a + b + c + e + g321 tmpl = env.from_string("{{ foo('a', c='d', e='f', *['b'], **{'g': 'h'}) }}")322 assert tmpl.render() == "abdfh"323324 def test_slicing(self, env):325 tmpl = env.from_string("{{ [1, 2, 3][:] }}|{{ [1, 2, 3][::-1] }}")326 assert tmpl.render() == "[1, 2, 3]|[3, 2, 1]"327328 def test_attr(self, env):329 tmpl = env.from_string("{{ foo.bar }}|{{ foo['bar'] }}")330 assert tmpl.render(foo={"bar": 42}) == "42|42"331332 def test_subscript(self, env):333 tmpl = env.from_string("{{ foo[0] }}|{{ foo[-1] }}")334 assert tmpl.render(foo=[0, 1, 2]) == "0|2"335336 def test_tuple(self, env):337 tmpl = env.from_string("{{ () }}|{{ (1,) }}|{{ (1, 2) }}")338 assert tmpl.render() == "()|(1,)|(1, 2)"339340 def test_math(self, env):341 tmpl = env.from_string("{{ (1 + 1 * 2) - 3 / 2 }}|{{ 2**3 }}")342 assert tmpl.render() == "1.5|8"343344 def test_div(self, env):345 tmpl = env.from_string("{{ 3 // 2 }}|{{ 3 / 2 }}|{{ 3 % 2 }}")346 assert tmpl.render() == "1|1.5|1"347348 def test_unary(self, env):349 tmpl = env.from_string("{{ +3 }}|{{ -3 }}")350 assert tmpl.render() == "3|-3"351352 def test_concat(self, env):353 tmpl = env.from_string("{{ [1, 2] ~ 'foo' }}")354 assert tmpl.render() == "[1, 2]foo"355356 @pytest.mark.parametrize(357 ("a", "op", "b"),358 [359 (1, ">", 0),360 (1, ">=", 1),361 (2, "<", 3),362 (3, "<=", 4),363 (4, "==", 4),364 (4, "!=", 5),365 ],366 )367 def test_compare(self, env, a, op, b):368 t = env.from_string(f"{{{{ {a} {op} {b} }}}}")369 assert t.render() == "True"370371 def test_compare_parens(self, env):372 t = env.from_string("{{ i * (j < 5) }}")373 assert t.render(i=2, j=3) == "2"374375 @pytest.mark.parametrize(376 ("src", "expect"),377 [378 ("{{ 4 < 2 < 3 }}", "False"),379 ("{{ a < b < c }}", "False"),380 ("{{ 4 > 2 > 3 }}", "False"),381 ("{{ a > b > c }}", "False"),382 ("{{ 4 > 2 < 3 }}", "True"),383 ("{{ a > b < c }}", "True"),384 ],385 )386 def test_compare_compound(self, env, src, expect):387 t = env.from_string(src)388 assert t.render(a=4, b=2, c=3) == expect389390 def test_inop(self, env):391 tmpl = env.from_string("{{ 1 in [1, 2, 3] }}|{{ 1 not in [1, 2, 3] }}")392 assert tmpl.render() == "True|False"393394 @pytest.mark.parametrize("value", ("[]", "{}", "()"))395 def test_collection_literal(self, env, value):396 t = env.from_string(f"{{{{ {value} }}}}")397 assert t.render() == value398399 @pytest.mark.parametrize(400 ("value", "expect"),401 (402 ("1", "1"),403 ("123", "123"),404 ("12_34_56", "123456"),405 ("1.2", "1.2"),406 ("34.56", "34.56"),407 ("3_4.5_6", "34.56"),408 ("1e0", "1.0"),409 ("10e1", "100.0"),410 ("2.5e100", "2.5e+100"),411 ("2.5e+100", "2.5e+100"),412 ("25.6e-10", "2.56e-09"),413 ("1_2.3_4e5_6", "1.234e+57"),Merge pull request #1171 from amykyta3/feature/base-integer-literalsDavid Lordbefore adoptionfd001b2
lines 414–420why, one step back414 ("0", "0"),415 ("0_00", "0"),416 ("0b1001_1111", "159"),417 ("0o123", "83"),418 ("0o1_23", "83"),419 ("0x123abc", "1194684"),420 ("0x12_3abc", "1194684"),update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 421–1029why, one step back421 ),422 )423 def test_numeric_literal(self, env, value, expect):424 t = env.from_string(f"{{{{ {value} }}}}")425 assert t.render() == expect426427 def test_bool(self, env):428 tmpl = env.from_string(429 "{{ true and false }}|{{ false or true }}|{{ not false }}"430 )431 assert tmpl.render() == "False|True|True"432433 def test_grouping(self, env):434 tmpl = env.from_string(435 "{{ (true and false) or (false and true) and not false }}"436 )437 assert tmpl.render() == "False"438439 def test_django_attr(self, env):440 tmpl = env.from_string("{{ [1, 2, 3].0 }}|{{ [[1]].0.0 }}")441 assert tmpl.render() == "1|1"442443 def test_conditional_expression(self, env):444 tmpl = env.from_string("""{{ 0 if true else 1 }}""")445 assert tmpl.render() == "0"446447 def test_short_conditional_expression(self, env):448 tmpl = env.from_string("<{{ 1 if false }}>")449 assert tmpl.render() == "<>"450451 tmpl = env.from_string("<{{ (1 if false).bar }}>")452 pytest.raises(UndefinedError, tmpl.render)453454 def test_filter_priority(self, env):455 tmpl = env.from_string('{{ "foo"|upper + "bar"|upper }}')456 assert tmpl.render() == "FOOBAR"457458 def test_function_calls(self, env):459 tests = [460 (True, "*foo, bar"),461 (True, "*foo, *bar"),462 (True, "**foo, *bar"),463 (True, "**foo, bar"),464 (True, "**foo, **bar"),465 (True, "**foo, bar=42"),466 (False, "foo, bar"),467 (False, "foo, bar=42"),468 (False, "foo, bar=23, *args"),469 (False, "foo, *args, bar=23"),470 (False, "a, b=c, *d, **e"),471 (False, "*foo, bar=42"),472 (False, "*foo, **bar"),473 (False, "*foo, bar=42, **baz"),474 (False, "foo, *args, bar=23, **baz"),475 ]476 for should_fail, sig in tests:477 if should_fail:478 with pytest.raises(TemplateSyntaxError):479 env.from_string(f"{{{{ foo({sig}) }}}}")480 else:481 env.from_string(f"foo({sig})")482483 def test_tuple_expr(self, env):484 for tmpl in [485 "{{ () }}",486 "{{ (1, 2) }}",487 "{{ (1, 2,) }}",488 "{{ 1, }}",489 "{{ 1, 2 }}",490 "{% for foo, bar in seq %}...{% endfor %}",491 "{% for x in foo, bar %}...{% endfor %}",492 "{% for x in foo, %}...{% endfor %}",493 ]:494 assert env.from_string(tmpl)495496 def test_trailing_comma(self, env):497 tmpl = env.from_string("{{ (1, 2,) }}|{{ [1, 2,] }}|{{ {1: 2,} }}")498 assert tmpl.render().lower() == "(1, 2)|[1, 2]|{1: 2}"499500 def test_block_end_name(self, env):501 env.from_string("{% block foo %}...{% endblock foo %}")502 pytest.raises(503 TemplateSyntaxError, env.from_string, "{% block x %}{% endblock y %}"504 )505506 def test_constant_casing(self, env):507 for const in True, False, None:508 const = str(const)509 tmpl = env.from_string(510 f"{{{{ {const} }}}}|{{{{ {const.lower()} }}}}|{{{{ {const.upper()} }}}}"511 )512 assert tmpl.render() == f"{const}|{const}|"513514 def test_test_chaining(self, env):515 pytest.raises(516 TemplateSyntaxError, env.from_string, "{{ foo is string is sequence }}"517 )518 assert env.from_string("{{ 42 is string or 42 is number }}").render() == "True"519520 def test_string_concatenation(self, env):521 tmpl = env.from_string('{{ "foo" "bar" "baz" }}')522 assert tmpl.render() == "foobarbaz"523524 def test_notin(self, env):525 bar = range(100)526 tmpl = env.from_string("""{{ not 42 in bar }}""")527 assert tmpl.render(bar=bar) == "False"528529 def test_operator_precedence(self, env):530 tmpl = env.from_string("""{{ 2 * 3 + 4 % 2 + 1 - 2 }}""")531 assert tmpl.render() == "5"532533 def test_implicit_subscribed_tuple(self, env):534 class Foo:535 def __getitem__(self, x):536 return x537538 t = env.from_string("{{ foo[1, 2] }}")539 assert t.render(foo=Foo()) == "(1, 2)"540541 def test_raw2(self, env):542 tmpl = env.from_string("{% raw %}{{ FOO }} and {% BAR %}{% endraw %}")543 assert tmpl.render() == "{{ FOO }} and {% BAR %}"544545 def test_const(self, env):546 tmpl = env.from_string(547 "{{ true }}|{{ false }}|{{ none }}|"548 "{{ none is defined }}|{{ missing is defined }}"549 )550 assert tmpl.render() == "True|False|None|True|False"551552 def test_neg_filter_priority(self, env):553 node = env.parse("{{ -1|foo }}")554 assert isinstance(node.body[0].nodes[0], nodes.Filter)555 assert isinstance(node.body[0].nodes[0].node, nodes.Neg)556557 def test_const_assign(self, env):558 constass1 = """{% set true = 42 %}"""559 constass2 = """{% for none in seq %}{% endfor %}"""560 for tmpl in constass1, constass2:561 pytest.raises(TemplateSyntaxError, env.from_string, tmpl)562563 def test_localset(self, env):564 tmpl = env.from_string(565 """{% set foo = 0 %}\566{% for item in [1, 2] %}{% set foo = 1 %}{% endfor %}\567{{ foo }}"""568 )569 assert tmpl.render() == "0"570571 def test_parse_unary(self, env):572 tmpl = env.from_string('{{ -foo["bar"] }}')573 assert tmpl.render(foo={"bar": 42}) == "-42"574 tmpl = env.from_string('{{ -foo["bar"]|abs }}')575 assert tmpl.render(foo={"bar": 42}) == "42"576577578class TestLstripBlocks:579 def test_lstrip(self, env):580 env = Environment(lstrip_blocks=True, trim_blocks=False)581 tmpl = env.from_string(""" {% if True %}\n {% endif %}""")582 assert tmpl.render() == "\n"583584 def test_lstrip_trim(self, env):585 env = Environment(lstrip_blocks=True, trim_blocks=True)586 tmpl = env.from_string(""" {% if True %}\n {% endif %}""")587 assert tmpl.render() == ""588589 def test_no_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_blocks_false_with_no_lstrip(self, env):595 # Test that + is a NOP (but does not cause an error) if lstrip_blocks=False596 env = Environment(lstrip_blocks=False, trim_blocks=False)597 tmpl = env.from_string(""" {% if True %}\n {% endif %}""")598 assert tmpl.render() == " \n "599 tmpl = env.from_string(""" {%+ if True %}\n {%+ endif %}""")600 assert tmpl.render() == " \n "601602 def test_lstrip_endline(self, env):603 env = Environment(lstrip_blocks=True, trim_blocks=False)604 tmpl = env.from_string(""" hello{% if True %}\n goodbye{% endif %}""")605 assert tmpl.render() == " hello\n goodbye"606607 def test_lstrip_inline(self, env):608 env = Environment(lstrip_blocks=True, trim_blocks=False)609 tmpl = env.from_string(""" {% if True %}hello {% endif %}""")610 assert tmpl.render() == "hello "611612 def test_lstrip_nested(self, env):613 env = Environment(lstrip_blocks=True, trim_blocks=False)614 tmpl = env.from_string(615 """ {% if True %}a {% if True %}b {% endif %}c {% endif %}"""616 )617 assert tmpl.render() == "a b c "618619 def test_lstrip_left_chars(self, env):620 env = Environment(lstrip_blocks=True, trim_blocks=False)621 tmpl = env.from_string(622 """ abc {% if True %}623 hello{% endif %}"""624 )625 assert tmpl.render() == " abc \n hello"626627 def test_lstrip_embeded_strings(self, env):628 env = Environment(lstrip_blocks=True, trim_blocks=False)629 tmpl = env.from_string(""" {% set x = " {% str %} " %}{{ x }}""")630 assert tmpl.render() == " {% str %} "631632 def test_lstrip_preserve_leading_newlines(self, env):633 env = Environment(lstrip_blocks=True, trim_blocks=False)634 tmpl = env.from_string("""\n\n\n{% set hello = 1 %}""")635 assert tmpl.render() == "\n\n\n"636637 def test_lstrip_comment(self, env):638 env = Environment(lstrip_blocks=True, trim_blocks=False)639 tmpl = env.from_string(640 """ {# if True #}641hello642 {#endif#}"""643 )644 assert tmpl.render() == "\nhello\n"645646 def test_lstrip_angle_bracket_simple(self, env):647 env = Environment(648 "<%",649 "%>",650 "${",651 "}",652 "<%#",653 "%>",654 "%",655 "##",656 lstrip_blocks=True,657 trim_blocks=True,658 )659 tmpl = env.from_string(""" <% if True %>hello <% endif %>""")660 assert tmpl.render() == "hello "661662 def test_lstrip_angle_bracket_comment(self, env):663 env = Environment(664 "<%",665 "%>",666 "${",667 "}",668 "<%#",669 "%>",670 "%",671 "##",672 lstrip_blocks=True,673 trim_blocks=True,674 )675 tmpl = env.from_string(""" <%# if True %>hello <%# endif %>""")676 assert tmpl.render() == "hello "677678 def test_lstrip_angle_bracket(self, env):679 env = Environment(680 "<%",681 "%>",682 "${",683 "}",684 "<%#",685 "%>",686 "%",687 "##",688 lstrip_blocks=True,689 trim_blocks=True,690 )691 tmpl = env.from_string(692 """\693 <%# regular comment %>694 <% for item in seq %>695${item} ## the rest of the stuff696 <% endfor %>"""697 )698 assert tmpl.render(seq=range(5)) == "".join(f"{x}\n" for x in range(5))699700 def test_lstrip_angle_bracket_compact(self, env):701 env = Environment(702 "<%",703 "%>",704 "${",705 "}",706 "<%#",707 "%>",708 "%",709 "##",710 lstrip_blocks=True,711 trim_blocks=True,712 )713 tmpl = env.from_string(714 """\715 <%#regular comment%>716 <%for item in seq%>717${item} ## the rest of the stuff718 <%endfor%>"""719 )720 assert tmpl.render(seq=range(5)) == "".join(f"{x}\n" for x in range(5))721722 def test_lstrip_blocks_outside_with_new_line(self):723 env = Environment(lstrip_blocks=True, trim_blocks=False)724 tmpl = env.from_string(725 " {% if kvs %}(\n"726 " {% for k, v in kvs %}{{ k }}={{ v }} {% endfor %}\n"727 " ){% endif %}"728 )729 out = tmpl.render(kvs=[("a", 1), ("b", 2)])730 assert out == "(\na=1 b=2 \n )"731732 def test_lstrip_trim_blocks_outside_with_new_line(self):733 env = Environment(lstrip_blocks=True, trim_blocks=True)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 )"741742 def test_lstrip_blocks_inside_with_new_line(self):743 env = Environment(lstrip_blocks=True, trim_blocks=False)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 \n)"751752 def test_lstrip_trim_blocks_inside_with_new_line(self):753 env = Environment(lstrip_blocks=True, trim_blocks=True)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 == " (a=1 b=2 )"761762 def test_lstrip_blocks_without_new_line(self):763 env = Environment(lstrip_blocks=True, trim_blocks=False)764 tmpl = env.from_string(765 " {% if kvs %}"766 " {% for k, v in kvs %}{{ k }}={{ v }} {% endfor %}"767 " {% endif %}"768 )769 out = tmpl.render(kvs=[("a", 1), ("b", 2)])770 assert out == " a=1 b=2 "771772 def test_lstrip_trim_blocks_without_new_line(self):773 env = Environment(lstrip_blocks=True, trim_blocks=True)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_blocks_consume_after_without_new_line(self):783 env = Environment(lstrip_blocks=True, trim_blocks=False)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_trim_blocks_consume_before_without_new_line(self):793 env = Environment(lstrip_blocks=False, 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_comment(self):803 env = Environment(lstrip_blocks=True, trim_blocks=True)804 tmpl = env.from_string(" {# 1 space #}\n {# 2 spaces #} {# 4 spaces #}")805 out = tmpl.render()806 assert out == " " * 4807808 def test_lstrip_trim_blocks_raw(self):809 env = Environment(lstrip_blocks=True, trim_blocks=True)810 tmpl = env.from_string("{{x}}\n{%- raw %} {% endraw -%}\n{{ y }}")811 out = tmpl.render(x=1, y=2)812 assert out == "1 2"813814 def test_php_syntax_with_manual(self, env):815 env = Environment(816 "<?", "?>", "<?=", "?>", "<!--", "-->", lstrip_blocks=True, trim_blocks=True817 )818 tmpl = env.from_string(819 """\820 <!-- I'm a comment, I'm not interesting -->821 <? for item in seq -?>822 <?= item ?>823 <?- endfor ?>"""824 )825 assert tmpl.render(seq=range(5)) == "01234"826827 def test_php_syntax(self, env):828 env = Environment(829 "<?", "?>", "<?=", "?>", "<!--", "-->", lstrip_blocks=True, trim_blocks=True830 )831 tmpl = env.from_string(832 """\833 <!-- I'm a comment, I'm not interesting -->834 <? for item in seq ?>835 <?= item ?>836 <? endfor ?>"""837 )838 assert tmpl.render(seq=range(5)) == "".join(f" {x}\n" for x in range(5))839840 def test_php_syntax_compact(self, env):841 env = Environment(842 "<?", "?>", "<?=", "?>", "<!--", "-->", lstrip_blocks=True, trim_blocks=True843 )844 tmpl = env.from_string(845 """\846 <!-- I'm a comment, I'm not interesting -->847 <?for item in seq?>848 <?=item?>849 <?endfor?>"""850 )851 assert tmpl.render(seq=range(5)) == "".join(f" {x}\n" for x in range(5))852853 def test_erb_syntax(self, env):854 env = Environment(855 "<%", "%>", "<%=", "%>", "<%#", "%>", lstrip_blocks=True, trim_blocks=True856 )857 tmpl = env.from_string(858 """\859<%# I'm a comment, I'm not interesting %>860 <% for item in seq %>861 <%= item %>862 <% endfor %>863"""864 )865 assert tmpl.render(seq=range(5)) == "".join(f" {x}\n" for x in range(5))866867 def test_erb_syntax_with_manual(self, env):868 env = Environment(869 "<%", "%>", "<%=", "%>", "<%#", "%>", lstrip_blocks=True, trim_blocks=True870 )871 tmpl = env.from_string(872 """\873<%# I'm a comment, I'm not interesting %>874 <% for item in seq -%>875 <%= item %>876 <%- endfor %>"""877 )878 assert tmpl.render(seq=range(5)) == "01234"879880 def test_erb_syntax_no_lstrip(self, env):881 env = Environment(882 "<%", "%>", "<%=", "%>", "<%#", "%>", lstrip_blocks=True, trim_blocks=True883 )884 tmpl = env.from_string(885 """\886<%# I'm a comment, I'm not interesting %>887 <%+ for item in seq -%>888 <%= item %>889 <%- endfor %>"""890 )891 assert tmpl.render(seq=range(5)) == " 01234"892893 def test_comment_syntax(self, env):894 env = Environment(895 "<!--",896 "-->",897 "${",898 "}",899 "<!--#",900 "-->",901 lstrip_blocks=True,902 trim_blocks=True,903 )904 tmpl = env.from_string(905 """\906<!--# I'm a comment, I'm not interesting -->\907<!-- for item in seq --->908 ${item}909<!--- endfor -->"""910 )911 assert tmpl.render(seq=range(5)) == "01234"912913914class TestTrimBlocks:915 def test_trim(self, env):916 env = Environment(trim_blocks=True, lstrip_blocks=False)917 tmpl = env.from_string(" {% if True %}\n {% endif %}")918 assert tmpl.render() == " "919920 def test_no_trim(self, env):921 env = Environment(trim_blocks=True, lstrip_blocks=False)922 tmpl = env.from_string(" {% if True +%}\n {% endif %}")923 assert tmpl.render() == " \n "924925 def test_no_trim_outer(self, env):926 env = Environment(trim_blocks=True, lstrip_blocks=False)927 tmpl = env.from_string("{% if True %}X{% endif +%}\nmore things")928 assert tmpl.render() == "X\nmore things"929930 def test_lstrip_no_trim(self, env):931 env = Environment(trim_blocks=True, lstrip_blocks=True)932 tmpl = env.from_string(" {% if True +%}\n {% endif %}")933 assert tmpl.render() == "\n"934935 def test_trim_blocks_false_with_no_trim(self, env):936 # Test that + is a NOP (but does not cause an error) if trim_blocks=False937 env = Environment(trim_blocks=False, lstrip_blocks=False)938 tmpl = env.from_string(" {% if True %}\n {% endif %}")939 assert tmpl.render() == " \n "940 tmpl = env.from_string(" {% if True +%}\n {% endif %}")941 assert tmpl.render() == " \n "942943 tmpl = env.from_string(" {# comment #}\n ")944 assert tmpl.render() == " \n "945 tmpl = env.from_string(" {# comment +#}\n ")946 assert tmpl.render() == " \n "947948 tmpl = env.from_string(" {% raw %}{% endraw %}\n ")949 assert tmpl.render() == " \n "950 tmpl = env.from_string(" {% raw %}{% endraw +%}\n ")951 assert tmpl.render() == " \n "952953 def test_trim_nested(self, env):954 env = Environment(trim_blocks=True, lstrip_blocks=True)955 tmpl = env.from_string(956 " {% if True %}\na {% if True %}\nb {% endif %}\nc {% endif %}"957 )958 assert tmpl.render() == "a b c "959960 def test_no_trim_nested(self, env):961 env = Environment(trim_blocks=True, lstrip_blocks=True)962 tmpl = env.from_string(963 " {% if True +%}\na {% if True +%}\nb {% endif +%}\nc {% endif %}"964 )965 assert tmpl.render() == "\na \nb \nc "966967 def test_comment_trim(self, env):968 env = Environment(trim_blocks=True, lstrip_blocks=True)969 tmpl = env.from_string(""" {# comment #}\n\n """)970 assert tmpl.render() == "\n "971972 def test_comment_no_trim(self, env):973 env = Environment(trim_blocks=True, lstrip_blocks=True)974 tmpl = env.from_string(""" {# comment +#}\n\n """)975 assert tmpl.render() == "\n\n "976977 def test_multiple_comment_trim_lstrip(self, env):978 env = Environment(trim_blocks=True, lstrip_blocks=True)979 tmpl = env.from_string(980 " {# comment #}\n\n{# comment2 #}\n \n{# comment3 #}\n\n "981 )982 assert tmpl.render() == "\n \n\n "983984 def test_multiple_comment_no_trim_lstrip(self, env):985 env = Environment(trim_blocks=True, lstrip_blocks=True)986 tmpl = env.from_string(987 " {# comment +#}\n\n{# comment2 +#}\n \n{# comment3 +#}\n\n "988 )989 assert tmpl.render() == "\n\n\n \n\n\n "990991 def test_raw_trim_lstrip(self, env):992 env = Environment(trim_blocks=True, lstrip_blocks=True)993 tmpl = env.from_string("{{x}}{% raw %}\n\n {% endraw %}\n\n{{ y }}")994 assert tmpl.render(x=1, y=2) == "1\n\n\n2"995996 def test_raw_no_trim_lstrip(self, env):997 env = Environment(trim_blocks=False, lstrip_blocks=True)998 tmpl = env.from_string("{{x}}{% raw %}\n\n {% endraw +%}\n\n{{ y }}")999 assert tmpl.render(x=1, y=2) == "1\n\n\n\n2"10001001 # raw blocks do not process inner text, so start tag cannot ignore trim1002 with pytest.raises(TemplateSyntaxError):1003 tmpl = env.from_string("{{x}}{% raw +%}\n\n {% endraw +%}\n\n{{ y }}")10041005 def test_no_trim_angle_bracket(self, env):1006 env = Environment(1007 "<%", "%>", "${", "}", "<%#", "%>", lstrip_blocks=True, trim_blocks=True1008 )1009 tmpl = env.from_string(" <% if True +%>\n\n <% endif %>")1010 assert tmpl.render() == "\n\n"10111012 tmpl = env.from_string(" <%# comment +%>\n\n ")1013 assert tmpl.render() == "\n\n "10141015 def test_no_trim_php_syntax(self, env):1016 env = Environment(1017 "<?",1018 "?>",1019 "<?=",1020 "?>",1021 "<!--",1022 "-->",1023 lstrip_blocks=False,1024 trim_blocks=True,1025 )1026 tmpl = env.from_string(" <? if True +?>\n\n <? endif ?>")1027 assert tmpl.render() == " \n\n "1028 tmpl = env.from_string(" <!-- comment +-->\n\n ")1029 assert tmpl.render() == " \n\n "