3
from jinja2 import Environment
4
from jinja2 import nodes
5
from jinja2 import Template
6
from jinja2 import TemplateSyntaxError
7
from jinja2 import UndefinedError
8
from jinja2.lexer import Token
9
from jinja2.lexer import TOKEN_BLOCK_BEGIN
10
from jinja2.lexer import TOKEN_BLOCK_END
11
from jinja2.lexer import TOKEN_EOF
12
from jinja2.lexer import TokenStream
17
Token(1, TOKEN_BLOCK_BEGIN, ""),
18
Token(2, TOKEN_BLOCK_END, ""),
21
def test_simple(self, env):
22
ts = TokenStream(self.test_tokens, "foo", "bar")
23
assert ts.current.type is TOKEN_BLOCK_BEGIN
25
assert not bool(ts.eos)
27
assert ts.current.type is TOKEN_BLOCK_END
29
assert not bool(ts.eos)
31
assert ts.current.type is TOKEN_EOF
35
def test_iter(self, env):
36
token_types = [t.type for t in TokenStream(self.test_tokens, "foo", "bar")]
37
assert token_types == [
44
def test_raw1(self, env):
45
tmpl = env.from_string(
46
"{% raw %}foo{% endraw %}|"
47
"{%raw%}{{ bar }}|{% baz %}{% endraw %}"
49
assert tmpl.render() == "foo|{{ bar }}|{% baz %}"
51
def test_raw2(self, env):
52
tmpl = env.from_string("1 {%- raw -%} 2 {%- endraw -%} 3")
53
assert tmpl.render() == "123"
55
def test_raw3(self, env):
56
# The second newline after baz exists because it is AFTER the
57
# {% raw %} and is ignored.
58
env = Environment(lstrip_blocks=True, trim_blocks=True)
59
tmpl = env.from_string("bar\n{% raw %}\n {{baz}}2 spaces\n{% endraw %}\nfoo")
60
assert tmpl.render(baz="test") == "bar\n\n {{baz}}2 spaces\nfoo"
62
def test_raw4(self, env):
63
# The trailing dash of the {% raw -%} cleans both the spaces and
64
# newlines up to the first character of data.
65
env = Environment(lstrip_blocks=True, trim_blocks=False)
66
tmpl = env.from_string(
67
"bar\n{%- raw -%}\n\n \n 2 spaces\n space{%- endraw -%}\nfoo"
69
assert tmpl.render() == "bar2 spaces\n spacefoo"
71
def test_balancing(self, env):
72
env = Environment("{%", "%}", "${", "}")
73
tmpl = env.from_string(
75
%}${{'foo': item}|upper}{% endfor %}"""
77
assert tmpl.render(seq=list(range(3))) == "{'FOO': 0}{'FOO': 1}{'FOO': 2}"
79
def test_comments(self, env):
80
env = Environment("<!--", "-->", "{", "}")
81
tmpl = env.from_string(
84
<!--- for item in seq -->
89
assert tmpl.render(seq=list(range(3))) == (
90
"<ul>\n <li>0</li>\n <li>1</li>\n <li>2</li>\n</ul>"
93
def test_string_escapes(self, env):
94
for char in "\0", "\u2668", "\xe4", "\t", "\r", "\n":
95
tmpl = env.from_string(f"{{{{ {char!r} }}}}")
96
assert tmpl.render() == char
97
assert env.from_string('{{ "\N{HOT SPRINGS}" }}').render() == "\u2668"
99
def test_bytefallback(self, env):
100
from pprint import pformat
102
tmpl = env.from_string("""{{ 'foo'|pprint }}|{{ 'bär'|pprint }}""")
103
assert tmpl.render() == pformat("foo") + "|" + pformat("bär")
105
def test_operators(self, env):
106
from jinja2.lexer import operators
108
for test, expect in operators.items():
111
stream = env.lexer.tokenize(f"{{{{ {test} }}}}")
113
assert stream.current.type == expect
115
def test_normalizing(self, env):
116
for seq in "\r", "\r\n", "\n":
117
env = Environment(newline_sequence=seq)
118
tmpl = env.from_string("1\n2\r\n3\n4\n")
119
result = tmpl.render()
120
assert result.replace(seq, "X") == "1X2X3X4"
122
def test_trailing_newline(self, env):
123
for keep in [True, False]:
124
env = Environment(keep_trailing_newline=keep)
125
for template, expected in [
128
("with\nnewline\n", {False: "with\nnewline"}),
129
("with\nseveral\n\n\n", {False: "with\nseveral\n\n"}),
131
tmpl = env.from_string(template)
132
expect = expected.get(keep, template)
133
result = tmpl.render()
134
assert result == expect, (keep, template, result, expect)
136
@pytest.mark.parametrize(
143
("1a", False), # invalid ascii start
144
("a-", False), # invalid ascii continue
145
("\U0001f40da", False), # invalid unicode start
146
("a🐍\U0001f40d", False), # invalid unicode continue
147
# start characters not matched by \w
152
# continue character not matched by \w
157
def test_name(self, env, name, valid):
158
t = "{{ " + name + " }}"
161
# valid for version being tested, shouldn't raise
164
pytest.raises(TemplateSyntaxError, env.from_string, t)
166
def test_lineno_with_strip(self, env):
171
{%- block content -%}
179
lineno, token_type, value = tok
180
if token_type == "name" and value == "item":
186
def test_php_syntax(self, env):
187
env = Environment("<?", "?>", "<?=", "?>", "<!--", "-->")
188
tmpl = env.from_string(
190
<!-- I'm a comment, I'm not interesting -->\
191
<? for item in seq -?>
195
assert tmpl.render(seq=list(range(5))) == "01234"
197
def test_erb_syntax(self, env):
198
env = Environment("<%", "%>", "<%=", "%>", "<%#", "%>")
199
tmpl = env.from_string(
201
<%# I'm a comment, I'm not interesting %>\
202
<% for item in seq -%>
206
assert tmpl.render(seq=list(range(5))) == "01234"
208
def test_comment_syntax(self, env):
209
env = Environment("<!--", "-->", "${", "}", "<!--#", "-->")
210
tmpl = env.from_string(
212
<!--# I'm a comment, I'm not interesting -->\
213
<!-- for item in seq --->
217
assert tmpl.render(seq=list(range(5))) == "01234"
219
def test_balancing(self, env):
220
tmpl = env.from_string("""{{{'foo':'bar'}.foo}}""")
221
assert tmpl.render() == "bar"
223
def test_start_comment(self, env):
224
tmpl = env.from_string(
227
{% macro blub() %}foo{% endmacro %}
230
assert tmpl.render().strip() == "foo"
232
def test_line_syntax(self, env):
233
env = Environment("<%", "%>", "${", "}", "<%#", "%>", "%")
234
tmpl = env.from_string(
236
<%# regular comment %>
242
int(x.strip()) for x in tmpl.render(seq=list(range(5))).split()
245
env = Environment("<%", "%>", "${", "}", "<%#", "%>", "%", "##")
246
tmpl = env.from_string(
248
<%# regular comment %>
250
${item} ## the rest of the stuff
254
int(x.strip()) for x in tmpl.render(seq=list(range(5))).split()
257
def test_line_syntax_priority(self, env):
258
# XXX: why is the whitespace there in front of the newline?
259
env = Environment("{%", "%}", "${", "}", "/*", "*/", "##", "#")
260
tmpl = env.from_string(
263
I'm a multiline comment */
265
* ${item} # this is just extra stuff
268
assert tmpl.render(seq=[1, 2]).strip() == "* 1\n* 2"
269
env = Environment("{%", "%}", "${", "}", "/*", "*/", "#", "##")
270
tmpl = env.from_string(
273
I'm a multiline comment */
275
* ${item} ## this is just extra stuff
276
## extra stuff i just want to ignore
279
assert tmpl.render(seq=[1, 2]).strip() == "* 1\n\n* 2"
281
def test_error_messages(self, env):
282
def assert_error(code, expected):
283
with pytest.raises(TemplateSyntaxError, match=expected):
287
"{% for item in seq %}...{% endif %}",
288
"Encountered unknown tag 'endif'. Jinja was looking "
289
"for the following tags: 'endfor' or 'else'. The "
290
"innermost block that needs to be closed is 'for'.",
293
"{% if foo %}{% for item in seq %}...{% endfor %}{% endfor %}",
294
"Encountered unknown tag 'endfor'. Jinja was looking for "
295
"the following tags: 'elif' or 'else' or 'endif'. The "
296
"innermost block that needs to be closed is 'if'.",
300
"Unexpected end of template. Jinja was looking for the "
301
"following tags: 'elif' or 'else' or 'endif'. The "
302
"innermost block that needs to be closed is 'if'.",
305
"{% for item in seq %}",
306
"Unexpected end of template. Jinja was looking for the "
307
"following tags: 'endfor' or 'else'. The innermost block "
308
"that needs to be closed is 'for'.",
311
"{% block foo-bar-baz %}",
312
"Block names in Jinja have to be valid Python identifiers "
313
"and may not contain hyphens, use an underscore instead.",
315
assert_error("{% unknown_tag %}", "Encountered unknown tag 'unknown_tag'.")
319
def test_call(self, env):
321
env.globals["foo"] = lambda a, b, c, e, g: a + b + c + e + g
322
tmpl = env.from_string("{{ foo('a', c='d', e='f', *['b'], **{'g': 'h'}) }}")
323
assert tmpl.render() == "abdfh"
325
def test_slicing(self, env):
326
tmpl = env.from_string("{{ [1, 2, 3][:] }}|{{ [1, 2, 3][::-1] }}")
327
assert tmpl.render() == "[1, 2, 3]|[3, 2, 1]"
329
def test_attr(self, env):
330
tmpl = env.from_string("{{ foo.bar }}|{{ foo['bar'] }}")
331
assert tmpl.render(foo={"bar": 42}) == "42|42"
333
def test_subscript(self, env):
334
tmpl = env.from_string("{{ foo[0] }}|{{ foo[-1] }}")
335
assert tmpl.render(foo=[0, 1, 2]) == "0|2"
337
def test_tuple(self, env):
338
tmpl = env.from_string("{{ () }}|{{ (1,) }}|{{ (1, 2) }}")
339
assert tmpl.render() == "()|(1,)|(1, 2)"
341
def test_math(self, env):
342
tmpl = env.from_string("{{ (1 + 1 * 2) - 3 / 2 }}|{{ 2**3 }}")
343
assert tmpl.render() == "1.5|8"
345
def test_div(self, env):
346
tmpl = env.from_string("{{ 3 // 2 }}|{{ 3 / 2 }}|{{ 3 % 2 }}")
347
assert tmpl.render() == "1|1.5|1"
349
def test_unary(self, env):
350
tmpl = env.from_string("{{ +3 }}|{{ -3 }}")
351
assert tmpl.render() == "3|-3"
353
def test_concat(self, env):
354
tmpl = env.from_string("{{ [1, 2] ~ 'foo' }}")
355
assert tmpl.render() == "[1, 2]foo"
357
@pytest.mark.parametrize(
368
def test_compare(self, env, a, op, b):
369
t = env.from_string(f"{{{{ {a} {op} {b} }}}}")
370
assert t.render() == "True"
372
def test_compare_parens(self, env):
373
t = env.from_string("{{ i * (j < 5) }}")
374
assert t.render(i=2, j=3) == "2"
376
@pytest.mark.parametrize(
379
("{{ 4 < 2 < 3 }}", "False"),
380
("{{ a < b < c }}", "False"),
381
("{{ 4 > 2 > 3 }}", "False"),
382
("{{ a > b > c }}", "False"),
383
("{{ 4 > 2 < 3 }}", "True"),
384
("{{ a > b < c }}", "True"),
387
def test_compare_compound(self, env, src, expect):
388
t = env.from_string(src)
389
assert t.render(a=4, b=2, c=3) == expect
391
def test_inop(self, env):
392
tmpl = env.from_string("{{ 1 in [1, 2, 3] }}|{{ 1 not in [1, 2, 3] }}")
393
assert tmpl.render() == "True|False"
395
@pytest.mark.parametrize("value", ("[]", "{}", "()"))
396
def test_collection_literal(self, env, value):
397
t = env.from_string(f"{{{{ {value} }}}}")
398
assert t.render() == value
400
@pytest.mark.parametrize(
405
("12_34_56", "123456"),
408
("3_4.5_6", "34.56"),
411
("2.5e100", "2.5e+100"),
412
("2.5e+100", "2.5e+100"),
413
("25.6e-10", "2.56e-09"),
414
("1_2.3_4e5_6", "1.234e+57"),
417
("0b1001_1111", "159"),
420
("0x123abc", "1194684"),
421
("0x12_3abc", "1194684"),
424
def test_numeric_literal(self, env, value, expect):
425
t = env.from_string(f"{{{{ {value} }}}}")
426
assert t.render() == expect
428
def test_bool(self, env):
429
tmpl = env.from_string(
430
"{{ true and false }}|{{ false or true }}|{{ not false }}"
432
assert tmpl.render() == "False|True|True"
434
def test_grouping(self, env):
435
tmpl = env.from_string(
436
"{{ (true and false) or (false and true) and not false }}"
438
assert tmpl.render() == "False"
440
def test_django_attr(self, env):
441
tmpl = env.from_string("{{ [1, 2, 3].0 }}|{{ [[1]].0.0 }}")
442
assert tmpl.render() == "1|1"
444
def test_conditional_expression(self, env):
445
tmpl = env.from_string("""{{ 0 if true else 1 }}""")
446
assert tmpl.render() == "0"
448
def test_short_conditional_expression(self, env):
449
tmpl = env.from_string("<{{ 1 if false }}>")
450
assert tmpl.render() == "<>"
452
tmpl = env.from_string("<{{ (1 if false).bar }}>")
453
pytest.raises(UndefinedError, tmpl.render)
455
def test_filter_priority(self, env):
456
tmpl = env.from_string('{{ "foo"|upper + "bar"|upper }}')
457
assert tmpl.render() == "FOOBAR"
459
def test_function_calls(self, env):
462
(True, "*foo, *bar"),
463
(True, "**foo, *bar"),
464
(True, "**foo, bar"),
465
(True, "**foo, **bar"),
466
(True, "**foo, bar=42"),
468
(False, "foo, bar=42"),
469
(False, "foo, bar=23, *args"),
470
(False, "foo, *args, bar=23"),
471
(False, "a, b=c, *d, **e"),
472
(False, "*foo, bar=42"),
473
(False, "*foo, **bar"),
474
(False, "*foo, bar=42, **baz"),
475
(False, "foo, *args, bar=23, **baz"),
477
for should_fail, sig in tests:
479
with pytest.raises(TemplateSyntaxError):
480
env.from_string(f"{{{{ foo({sig}) }}}}")
482
env.from_string(f"foo({sig})")
484
def test_tuple_expr(self, env):
491
"{% for foo, bar in seq %}...{% endfor %}",
492
"{% for x in foo, bar %}...{% endfor %}",
493
"{% for x in foo, %}...{% endfor %}",
495
assert env.from_string(tmpl)
497
def test_trailing_comma(self, env):
498
tmpl = env.from_string("{{ (1, 2,) }}|{{ [1, 2,] }}|{{ {1: 2,} }}")
499
assert tmpl.render().lower() == "(1, 2)|[1, 2]|{1: 2}"
501
def test_block_end_name(self, env):
502
env.from_string("{% block foo %}...{% endblock foo %}")
504
TemplateSyntaxError, env.from_string, "{% block x %}{% endblock y %}"
507
def test_constant_casing(self, env):
508
for const in True, False, None:
510
tmpl = env.from_string(
511
f"{{{{ {const} }}}}|{{{{ {const.lower()} }}}}|{{{{ {const.upper()} }}}}"
513
assert tmpl.render() == f"{const}|{const}|"
515
def test_test_chaining(self, env):
517
TemplateSyntaxError, env.from_string, "{{ foo is string is sequence }}"
519
assert env.from_string("{{ 42 is string or 42 is number }}").render() == "True"
521
def test_string_concatenation(self, env):
522
tmpl = env.from_string('{{ "foo" "bar" "baz" }}')
523
assert tmpl.render() == "foobarbaz"
525
def test_notin(self, env):
527
tmpl = env.from_string("""{{ not 42 in bar }}""")
528
assert tmpl.render(bar=bar) == "False"
530
def test_operator_precedence(self, env):
531
tmpl = env.from_string("""{{ 2 * 3 + 4 % 2 + 1 - 2 }}""")
532
assert tmpl.render() == "5"
534
def test_implicit_subscribed_tuple(self, env):
536
def __getitem__(self, x):
539
t = env.from_string("{{ foo[1, 2] }}")
540
assert t.render(foo=Foo()) == "(1, 2)"
542
def test_raw2(self, env):
543
tmpl = env.from_string("{% raw %}{{ FOO }} and {% BAR %}{% endraw %}")
544
assert tmpl.render() == "{{ FOO }} and {% BAR %}"
546
def test_const(self, env):
547
tmpl = env.from_string(
548
"{{ true }}|{{ false }}|{{ none }}|"
549
"{{ none is defined }}|{{ missing is defined }}"
551
assert tmpl.render() == "True|False|None|True|False"
553
def test_neg_filter_priority(self, env):
554
node = env.parse("{{ -1|foo }}")
555
assert isinstance(node.body[0].nodes[0], nodes.Filter)
556
assert isinstance(node.body[0].nodes[0].node, nodes.Neg)
558
def test_const_assign(self, env):
559
constass1 = """{% set true = 42 %}"""
560
constass2 = """{% for none in seq %}{% endfor %}"""
561
for tmpl in constass1, constass2:
562
pytest.raises(TemplateSyntaxError, env.from_string, tmpl)
564
def test_localset(self, env):
565
tmpl = env.from_string(
566
"""{% set foo = 0 %}\
567
{% for item in [1, 2] %}{% set foo = 1 %}{% endfor %}\
570
assert tmpl.render() == "0"
572
def test_parse_unary(self, env):
573
tmpl = env.from_string('{{ -foo["bar"] }}')
574
assert tmpl.render(foo={"bar": 42}) == "-42"
575
tmpl = env.from_string('{{ -foo["bar"]|abs }}')
576
assert tmpl.render(foo={"bar": 42}) == "42"
579
class TestLstripBlocks:
580
def test_lstrip(self, env):
581
env = Environment(lstrip_blocks=True, trim_blocks=False)
582
tmpl = env.from_string(""" {% if True %}\n {% endif %}""")
583
assert tmpl.render() == "\n"
585
def test_lstrip_trim(self, env):
586
env = Environment(lstrip_blocks=True, trim_blocks=True)
587
tmpl = env.from_string(""" {% if True %}\n {% endif %}""")
588
assert tmpl.render() == ""
590
def test_no_lstrip(self, env):
591
env = Environment(lstrip_blocks=True, trim_blocks=False)
592
tmpl = env.from_string(""" {%+ if True %}\n {%+ endif %}""")
593
assert tmpl.render() == " \n "
595
def test_lstrip_blocks_false_with_no_lstrip(self, env):
596
# Test that + is a NOP (but does not cause an error) if lstrip_blocks=False
597
env = Environment(lstrip_blocks=False, trim_blocks=False)
598
tmpl = env.from_string(""" {% if True %}\n {% endif %}""")
599
assert tmpl.render() == " \n "
600
tmpl = env.from_string(""" {%+ if True %}\n {%+ endif %}""")
601
assert tmpl.render() == " \n "
603
def test_lstrip_endline(self, env):
604
env = Environment(lstrip_blocks=True, trim_blocks=False)
605
tmpl = env.from_string(""" hello{% if True %}\n goodbye{% endif %}""")
606
assert tmpl.render() == " hello\n goodbye"
608
def test_lstrip_inline(self, env):
609
env = Environment(lstrip_blocks=True, trim_blocks=False)
610
tmpl = env.from_string(""" {% if True %}hello {% endif %}""")
611
assert tmpl.render() == "hello "
613
def test_lstrip_nested(self, env):
614
env = Environment(lstrip_blocks=True, trim_blocks=False)
615
tmpl = env.from_string(
616
""" {% if True %}a {% if True %}b {% endif %}c {% endif %}"""
618
assert tmpl.render() == "a b c "
620
def test_lstrip_left_chars(self, env):
621
env = Environment(lstrip_blocks=True, trim_blocks=False)
622
tmpl = env.from_string(
623
""" abc {% if True %}
626
assert tmpl.render() == " abc \n hello"
628
def test_lstrip_embeded_strings(self, env):
629
env = Environment(lstrip_blocks=True, trim_blocks=False)
630
tmpl = env.from_string(""" {% set x = " {% str %} " %}{{ x }}""")
631
assert tmpl.render() == " {% str %} "
633
def test_lstrip_preserve_leading_newlines(self, env):
634
env = Environment(lstrip_blocks=True, trim_blocks=False)
635
tmpl = env.from_string("""\n\n\n{% set hello = 1 %}""")
636
assert tmpl.render() == "\n\n\n"
638
def test_lstrip_comment(self, env):
639
env = Environment(lstrip_blocks=True, trim_blocks=False)
640
tmpl = env.from_string(
645
assert tmpl.render() == "\nhello\n"
647
def test_lstrip_angle_bracket_simple(self, env):
660
tmpl = env.from_string(""" <% if True %>hello <% endif %>""")
661
assert tmpl.render() == "hello "
663
def test_lstrip_angle_bracket_comment(self, env):
676
tmpl = env.from_string(""" <%# if True %>hello <%# endif %>""")
677
assert tmpl.render() == "hello "
679
def test_lstrip_angle_bracket(self, env):
692
tmpl = env.from_string(
694
<%# regular comment %>
695
<% for item in seq %>
696
${item} ## the rest of the stuff
699
assert tmpl.render(seq=range(5)) == "".join(f"{x}\n" for x in range(5))
701
def test_lstrip_angle_bracket_compact(self, env):
714
tmpl = env.from_string(
718
${item} ## the rest of the stuff
721
assert tmpl.render(seq=range(5)) == "".join(f"{x}\n" for x in range(5))
723
def test_lstrip_blocks_outside_with_new_line(self):
724
env = Environment(lstrip_blocks=True, trim_blocks=False)
725
tmpl = env.from_string(
727
" {% for k, v in kvs %}{{ k }}={{ v }} {% endfor %}\n"
730
out = tmpl.render(kvs=[("a", 1), ("b", 2)])
731
assert out == "(\na=1 b=2 \n )"
733
def test_lstrip_trim_blocks_outside_with_new_line(self):
734
env = Environment(lstrip_blocks=True, trim_blocks=True)
735
tmpl = env.from_string(
737
" {% for k, v in kvs %}{{ k }}={{ v }} {% endfor %}\n"
740
out = tmpl.render(kvs=[("a", 1), ("b", 2)])
741
assert out == "(\na=1 b=2 )"
743
def test_lstrip_blocks_inside_with_new_line(self):
744
env = Environment(lstrip_blocks=True, trim_blocks=False)
745
tmpl = env.from_string(
747
" {% for k, v in kvs %}{{ k }}={{ v }} {% endfor %}\n"
750
out = tmpl.render(kvs=[("a", 1), ("b", 2)])
751
assert out == " (\na=1 b=2 \n)"
753
def test_lstrip_trim_blocks_inside_with_new_line(self):
754
env = Environment(lstrip_blocks=True, trim_blocks=True)
755
tmpl = env.from_string(
757
" {% for k, v in kvs %}{{ k }}={{ v }} {% endfor %}\n"
760
out = tmpl.render(kvs=[("a", 1), ("b", 2)])
761
assert out == " (a=1 b=2 )"
763
def test_lstrip_blocks_without_new_line(self):
764
env = Environment(lstrip_blocks=True, trim_blocks=False)
765
tmpl = env.from_string(
767
" {% for k, v in kvs %}{{ k }}={{ v }} {% endfor %}"
770
out = tmpl.render(kvs=[("a", 1), ("b", 2)])
771
assert out == " a=1 b=2 "
773
def test_lstrip_trim_blocks_without_new_line(self):
774
env = Environment(lstrip_blocks=True, trim_blocks=True)
775
tmpl = env.from_string(
777
" {% for k, v in kvs %}{{ k }}={{ v }} {% endfor %}"
780
out = tmpl.render(kvs=[("a", 1), ("b", 2)])
781
assert out == " a=1 b=2 "
783
def test_lstrip_blocks_consume_after_without_new_line(self):
784
env = Environment(lstrip_blocks=True, trim_blocks=False)
785
tmpl = env.from_string(
787
" {% for k, v in kvs %}{{ k }}={{ v }} {% endfor -%}"
790
out = tmpl.render(kvs=[("a", 1), ("b", 2)])
791
assert out == "a=1 b=2 "
793
def test_lstrip_trim_blocks_consume_before_without_new_line(self):
794
env = Environment(lstrip_blocks=False, trim_blocks=False)
795
tmpl = env.from_string(
797
" {%- for k, v in kvs %}{{ k }}={{ v }} {% endfor -%}"
800
out = tmpl.render(kvs=[("a", 1), ("b", 2)])
801
assert out == "a=1 b=2 "
803
def test_lstrip_trim_blocks_comment(self):
804
env = Environment(lstrip_blocks=True, trim_blocks=True)
805
tmpl = env.from_string(" {# 1 space #}\n {# 2 spaces #} {# 4 spaces #}")
807
assert out == " " * 4
809
def test_lstrip_trim_blocks_raw(self):
810
env = Environment(lstrip_blocks=True, trim_blocks=True)
811
tmpl = env.from_string("{{x}}\n{%- raw %} {% endraw -%}\n{{ y }}")
812
out = tmpl.render(x=1, y=2)
815
def test_php_syntax_with_manual(self, env):
817
"<?", "?>", "<?=", "?>", "<!--", "-->", lstrip_blocks=True, trim_blocks=True
819
tmpl = env.from_string(
821
<!-- I'm a comment, I'm not interesting -->
822
<? for item in seq -?>
826
assert tmpl.render(seq=range(5)) == "01234"
828
def test_php_syntax(self, env):
830
"<?", "?>", "<?=", "?>", "<!--", "-->", lstrip_blocks=True, trim_blocks=True
832
tmpl = env.from_string(
834
<!-- I'm a comment, I'm not interesting -->
835
<? for item in seq ?>
839
assert tmpl.render(seq=range(5)) == "".join(f" {x}\n" for x in range(5))
841
def test_php_syntax_compact(self, env):
843
"<?", "?>", "<?=", "?>", "<!--", "-->", lstrip_blocks=True, trim_blocks=True
845
tmpl = env.from_string(
847
<!-- I'm a comment, I'm not interesting -->
852
assert tmpl.render(seq=range(5)) == "".join(f" {x}\n" for x in range(5))
854
def test_erb_syntax(self, env):
856
"<%", "%>", "<%=", "%>", "<%#", "%>", lstrip_blocks=True, trim_blocks=True
858
tmpl = env.from_string(
860
<%# I'm a comment, I'm not interesting %>
861
<% for item in seq %>
866
assert tmpl.render(seq=range(5)) == "".join(f" {x}\n" for x in range(5))
868
def test_erb_syntax_with_manual(self, env):
870
"<%", "%>", "<%=", "%>", "<%#", "%>", lstrip_blocks=True, trim_blocks=True
872
tmpl = env.from_string(
874
<%# I'm a comment, I'm not interesting %>
875
<% for item in seq -%>
879
assert tmpl.render(seq=range(5)) == "01234"
881
def test_erb_syntax_no_lstrip(self, env):
883
"<%", "%>", "<%=", "%>", "<%#", "%>", lstrip_blocks=True, trim_blocks=True
885
tmpl = env.from_string(
887
<%# I'm a comment, I'm not interesting %>
888
<%+ for item in seq -%>
892
assert tmpl.render(seq=range(5)) == " 01234"
894
def test_comment_syntax(self, env):
905
tmpl = env.from_string(
907
<!--# I'm a comment, I'm not interesting -->\
908
<!-- for item in seq --->
912
assert tmpl.render(seq=range(5)) == "01234"
916
def test_trim(self, env):
917
env = Environment(trim_blocks=True, lstrip_blocks=False)
918
tmpl = env.from_string(" {% if True %}\n {% endif %}")
919
assert tmpl.render() == " "
921
def test_no_trim(self, env):
922
env = Environment(trim_blocks=True, lstrip_blocks=False)
923
tmpl = env.from_string(" {% if True +%}\n {% endif %}")
924
assert tmpl.render() == " \n "
926
def test_no_trim_outer(self, env):
927
env = Environment(trim_blocks=True, lstrip_blocks=False)
928
tmpl = env.from_string("{% if True %}X{% endif +%}\nmore things")
929
assert tmpl.render() == "X\nmore things"
931
def test_lstrip_no_trim(self, env):
932
env = Environment(trim_blocks=True, lstrip_blocks=True)
933
tmpl = env.from_string(" {% if True +%}\n {% endif %}")
934
assert tmpl.render() == "\n"
936
def test_trim_blocks_false_with_no_trim(self, env):
937
# Test that + is a NOP (but does not cause an error) if trim_blocks=False
938
env = Environment(trim_blocks=False, lstrip_blocks=False)
939
tmpl = env.from_string(" {% if True %}\n {% endif %}")
940
assert tmpl.render() == " \n "
941
tmpl = env.from_string(" {% if True +%}\n {% endif %}")
942
assert tmpl.render() == " \n "
944
tmpl = env.from_string(" {# comment #}\n ")
945
assert tmpl.render() == " \n "
946
tmpl = env.from_string(" {# comment +#}\n ")
947
assert tmpl.render() == " \n "
949
tmpl = env.from_string(" {% raw %}{% endraw %}\n ")
950
assert tmpl.render() == " \n "
951
tmpl = env.from_string(" {% raw %}{% endraw +%}\n ")
952
assert tmpl.render() == " \n "
954
def test_trim_nested(self, env):
955
env = Environment(trim_blocks=True, lstrip_blocks=True)
956
tmpl = env.from_string(
957
" {% if True %}\na {% if True %}\nb {% endif %}\nc {% endif %}"
959
assert tmpl.render() == "a b c "
961
def test_no_trim_nested(self, env):
962
env = Environment(trim_blocks=True, lstrip_blocks=True)
963
tmpl = env.from_string(
964
" {% if True +%}\na {% if True +%}\nb {% endif +%}\nc {% endif %}"
966
assert tmpl.render() == "\na \nb \nc "
968
def test_comment_trim(self, env):
969
env = Environment(trim_blocks=True, lstrip_blocks=True)
970
tmpl = env.from_string(""" {# comment #}\n\n """)
971
assert tmpl.render() == "\n "
973
def test_comment_no_trim(self, env):
974
env = Environment(trim_blocks=True, lstrip_blocks=True)
975
tmpl = env.from_string(""" {# comment +#}\n\n """)
976
assert tmpl.render() == "\n\n "
978
def test_multiple_comment_trim_lstrip(self, env):
979
env = Environment(trim_blocks=True, lstrip_blocks=True)
980
tmpl = env.from_string(
981
" {# comment #}\n\n{# comment2 #}\n \n{# comment3 #}\n\n "
983
assert tmpl.render() == "\n \n\n "
985
def test_multiple_comment_no_trim_lstrip(self, env):
986
env = Environment(trim_blocks=True, lstrip_blocks=True)
987
tmpl = env.from_string(
988
" {# comment +#}\n\n{# comment2 +#}\n \n{# comment3 +#}\n\n "
990
assert tmpl.render() == "\n\n\n \n\n\n "
992
def test_raw_trim_lstrip(self, env):
993
env = Environment(trim_blocks=True, lstrip_blocks=True)
994
tmpl = env.from_string("{{x}}{% raw %}\n\n {% endraw %}\n\n{{ y }}")
995
assert tmpl.render(x=1, y=2) == "1\n\n\n2"
997
def test_raw_no_trim_lstrip(self, env):
998
env = Environment(trim_blocks=False, lstrip_blocks=True)
999
tmpl = env.from_string("{{x}}{% raw %}\n\n {% endraw +%}\n\n{{ y }}")
1000
assert tmpl.render(x=1, y=2) == "1\n\n\n\n2"
1002
# raw blocks do not process inner text, so start tag cannot ignore trim
1003
with pytest.raises(TemplateSyntaxError):
1004
tmpl = env.from_string("{{x}}{% raw +%}\n\n {% endraw +%}\n\n{{ y }}")
1006
def test_no_trim_angle_bracket(self, env):
1008
"<%", "%>", "${", "}", "<%#", "%>", lstrip_blocks=True, trim_blocks=True
1010
tmpl = env.from_string(" <% if True +%>\n\n <% endif %>")
1011
assert tmpl.render() == "\n\n"
1013
tmpl = env.from_string(" <%# comment +%>\n\n ")
1014
assert tmpl.render() == "\n\n "
1016
def test_no_trim_php_syntax(self, env):
1024
lstrip_blocks=False,
1027
tmpl = env.from_string(" <? if True +?>\n\n <? endif ?>")
1028
assert tmpl.render() == " \n\n "
1029
tmpl = env.from_string(" <!-- comment +-->\n\n ")
1030
assert tmpl.render() == " \n\n "