test_ext.py
This file
Path
tests/test_ext.py
726 lines · 25.2 KiB · Python
Last changed by
Merge pull request #1559 from pallets/i18n-context-blockDavid Lordbefore adoption4f5c79c
History of this fileTake it
1import re2from io import BytesIO34import pytest56from jinja2 import DictLoader7from jinja2 import Environment8from jinja2 import nodes9from jinja2 import pass_context10from jinja2.exceptions import TemplateAssertionError11from jinja2.ext import Extension12from jinja2.lexer import count_newlines13from jinja2.lexer import Token1415importable_object = 231617_gettext_re = re.compile(r"_\((.*?)\)", re.DOTALL)181920i18n_templates = {21 "default.html": '<title>{{ page_title|default(_("missing")) }}</title>'22 "{% block body %}{% endblock %}",23 "child.html": '{% extends "default.html" %}{% block body %}'24 "{% trans %}watch out{% endtrans %}{% endblock %}",25 "plural.html": "{% trans user_count %}One user online{% pluralize %}"26 "{{ user_count }} users online{% endtrans %}",27 "plural2.html": "{% trans user_count=get_user_count() %}{{ user_count }}s"28 "{% pluralize %}{{ user_count }}p{% endtrans %}",29 "stringformat.html": '{{ _("User: %(num)s")|format(num=user_count) }}',30}3132newstyle_i18n_templates = {33 "default.html": '<title>{{ page_title|default(_("missing")) }}</title>'34 "{% block body %}{% endblock %}",35 "child.html": '{% extends "default.html" %}{% block body %}'36 "{% trans %}watch out{% endtrans %}{% endblock %}",37 "plural.html": "{% trans user_count %}One user online{% pluralize %}"38 "{{ user_count }} users online{% endtrans %}",39 "stringformat.html": '{{ _("User: %(num)s", num=user_count) }}',40 "ngettext.html": '{{ ngettext("%(num)s apple", "%(num)s apples", apples) }}',41 "ngettext_long.html": "{% trans num=apples %}{{ num }} apple{% pluralize %}"42 "{{ num }} apples{% endtrans %}",43 "pgettext.html": '{{ pgettext("fruit", "Apple") }}',44 "npgettext.html": '{{ npgettext("fruit", "%(num)s apple", "%(num)s apples",'45 " apples) }}",46 "pgettext_block": "{% trans 'fruit' num=apples %}Apple{% endtrans %}",47 "npgettext_block": "{% trans 'fruit' num=apples %}{{ num }} apple"48 "{% pluralize %}{{ num }} apples{% endtrans %}",49 "transvars1.html": "{% trans %}User: {{ num }}{% endtrans %}",50 "transvars2.html": "{% trans num=count %}User: {{ num }}{% endtrans %}",51 "transvars3.html": "{% trans count=num %}User: {{ count }}{% endtrans %}",52 "novars.html": "{% trans %}%(hello)s{% endtrans %}",53 "vars.html": "{% trans %}{{ foo }}%(foo)s{% endtrans %}",54 "explicitvars.html": '{% trans foo="42" %}%(foo)s{% endtrans %}',55}565758languages = {59 "de": {60 "missing": "fehlend",61 "watch out": "pass auf",62 "One user online": "Ein Benutzer online",63 "%(user_count)s users online": "%(user_count)s Benutzer online",64 "User: %(num)s": "Benutzer: %(num)s",65 "User: %(count)s": "Benutzer: %(count)s",66 "Apple": {None: "Apfel", "fruit": "Apple"},67 "%(num)s apple": {None: "%(num)s Apfel", "fruit": "%(num)s Apple"},68 "%(num)s apples": {None: "%(num)s Äpfel", "fruit": "%(num)s Apples"},69 }70}717273def _get_with_context(value, ctx=None):74 if isinstance(value, dict):75 return value.get(ctx, value)7677 return value787980@pass_context81def gettext(context, string):82 language = context.get("LANGUAGE", "en")83 value = languages.get(language, {}).get(string, string)84 return _get_with_context(value)858687@pass_context88def ngettext(context, s, p, n):89 language = context.get("LANGUAGE", "en")9091 if n != 1:92 value = languages.get(language, {}).get(p, p)93 return _get_with_context(value)9495 value = languages.get(language, {}).get(s, s)96 return _get_with_context(value)979899@pass_context100def pgettext(context, c, s):101 language = context.get("LANGUAGE", "en")102 value = languages.get(language, {}).get(s, s)103 return _get_with_context(value, c)104105106@pass_context107def npgettext(context, c, s, p, n):108 language = context.get("LANGUAGE", "en")109110 if n != 1:111 value = languages.get(language, {}).get(p, p)112 return _get_with_context(value, c)113114 value = languages.get(language, {}).get(s, s)115 return _get_with_context(value, c)116117118i18n_env = Environment(119 loader=DictLoader(i18n_templates), extensions=["jinja2.ext.i18n"]120)121i18n_env.globals.update(122 {123 "_": gettext,124 "gettext": gettext,125 "ngettext": ngettext,126 "pgettext": pgettext,127 "npgettext": npgettext,128 }129)130i18n_env_trimmed = Environment(extensions=["jinja2.ext.i18n"])131132i18n_env_trimmed.policies["ext.i18n.trimmed"] = True133i18n_env_trimmed.globals.update(134 {135 "_": gettext,136 "gettext": gettext,137 "ngettext": ngettext,138 "pgettext": pgettext,139 "npgettext": npgettext,140 }141)142143newstyle_i18n_env = Environment(144 loader=DictLoader(newstyle_i18n_templates), extensions=["jinja2.ext.i18n"]145)146newstyle_i18n_env.install_gettext_callables( # type: ignore147 gettext, ngettext, newstyle=True, pgettext=pgettext, npgettext=npgettext148)149150151class ExampleExtension(Extension):152 tags = {"test"}153 ext_attr = 42154 context_reference_node_cls = nodes.ContextReference155156 def parse(self, parser):157 return nodes.Output(158 [159 self.call_method(160 "_dump",161 [162 nodes.EnvironmentAttribute("sandboxed"),163 self.attr("ext_attr"),164 nodes.ImportedName(__name__ + ".importable_object"),165 self.context_reference_node_cls(),166 ],167 )168 ]169 ).set_lineno(next(parser.stream).lineno)170171 def _dump(self, sandboxed, ext_attr, imported_object, context):172 return (173 f"{sandboxed}|{ext_attr}|{imported_object}|{context.blocks}"174 f"|{context.get('test_var')}"175 )176177178class DerivedExampleExtension(ExampleExtension):179 context_reference_node_cls = nodes.DerivedContextReference # type: ignore180181182class PreprocessorExtension(Extension):183 def preprocess(self, source, name, filename=None):184 return source.replace("[[TEST]]", "({{ foo }})")185186187class StreamFilterExtension(Extension):188 def filter_stream(self, stream):189 for token in stream:190 if token.type == "data":191 yield from self.interpolate(token)192 else:193 yield token194195 def interpolate(self, token):196 pos = 0197 end = len(token.value)198 lineno = token.lineno199 while True:200 match = _gettext_re.search(token.value, pos)201 if match is None:202 break203 value = token.value[pos : match.start()]204 if value:205 yield Token(lineno, "data", value)206 lineno += count_newlines(token.value)207 yield Token(lineno, "variable_begin", None)208 yield Token(lineno, "name", "gettext")209 yield Token(lineno, "lparen", None)210 yield Token(lineno, "string", match.group(1))211 yield Token(lineno, "rparen", None)212 yield Token(lineno, "variable_end", None)213 pos = match.end()214 if pos < end:215 yield Token(lineno, "data", token.value[pos:])216217218class TestExtensions:219 def test_extend_late(self):220 env = Environment()221 t = env.from_string('{% autoescape true %}{{ "<test>" }}{% endautoescape %}')222 assert t.render() == "<test>"223224 def test_loop_controls(self):225 env = Environment(extensions=["jinja2.ext.loopcontrols"])226227 tmpl = env.from_string(228 """229 {%- for item in [1, 2, 3, 4] %}230 {%- if item % 2 == 0 %}{% continue %}{% endif -%}231 {{ item }}232 {%- endfor %}"""233 )234 assert tmpl.render() == "13"235236 tmpl = env.from_string(237 """238 {%- for item in [1, 2, 3, 4] %}239 {%- if item > 2 %}{% break %}{% endif -%}240 {{ item }}241 {%- endfor %}"""242 )243 assert tmpl.render() == "12"244245 def test_do(self):246 env = Environment(extensions=["jinja2.ext.do"])247 tmpl = env.from_string(248 """249 {%- set items = [] %}250 {%- for char in "foo" %}251 {%- do items.append(loop.index0 ~ char) %}252 {%- endfor %}{{ items|join(', ') }}"""253 )254 assert tmpl.render() == "0f, 1o, 2o"255256 def test_extension_nodes(self):257 env = Environment(extensions=[ExampleExtension])258 tmpl = env.from_string("{% test %}")259 assert tmpl.render() == "False|42|23|{}|None"260261 def test_contextreference_node_passes_context(self):262 env = Environment(extensions=[ExampleExtension])263 tmpl = env.from_string('{% set test_var="test_content" %}{% test %}')264 assert tmpl.render() == "False|42|23|{}|test_content"265266 def test_contextreference_node_can_pass_locals(self):267 env = Environment(extensions=[DerivedExampleExtension])268 tmpl = env.from_string(269 '{% for test_var in ["test_content"] %}{% test %}{% endfor %}'270 )271 assert tmpl.render() == "False|42|23|{}|test_content"272273 def test_identifier(self):274 assert ExampleExtension.identifier == __name__ + ".ExampleExtension"275276 def test_rebinding(self):277 original = Environment(extensions=[ExampleExtension])278 overlay = original.overlay()279 for env in original, overlay:280 for ext in env.extensions.values():281 assert ext.environment is env282283 def test_preprocessor_extension(self):284 env = Environment(extensions=[PreprocessorExtension])285 tmpl = env.from_string("{[[TEST]]}")286 assert tmpl.render(foo=42) == "{(42)}"287288 def test_streamfilter_extension(self):289 env = Environment(extensions=[StreamFilterExtension])290 env.globals["gettext"] = lambda x: x.upper()291 tmpl = env.from_string("Foo _(bar) Baz")292 out = tmpl.render()293 assert out == "Foo BAR Baz"294295 def test_extension_ordering(self):296 class T1(Extension):297 priority = 1298299 class T2(Extension):300 priority = 2301302 env = Environment(extensions=[T1, T2])303 ext = list(env.iter_extensions())304 assert ext[0].__class__ is T1305 assert ext[1].__class__ is T2306307 def test_debug(self):308 env = Environment(extensions=["jinja2.ext.debug"])309 t = env.from_string("Hello\n{% debug %}\nGoodbye")310 out = t.render()311312 for value in ("context", "cycler", "filters", "abs", "tests", "!="):313 assert f"'{value}'" in out314315316class TestInternationalization:317 def test_trans(self):318 tmpl = i18n_env.get_template("child.html")319 assert tmpl.render(LANGUAGE="de") == "<title>fehlend</title>pass auf"320321 def test_trans_plural(self):322 tmpl = i18n_env.get_template("plural.html")323 assert tmpl.render(LANGUAGE="de", user_count=1) == "Ein Benutzer online"324 assert tmpl.render(LANGUAGE="de", user_count=2) == "2 Benutzer online"325326 def test_trans_plural_with_functions(self):327 tmpl = i18n_env.get_template("plural2.html")328329 def get_user_count():330 get_user_count.called += 1331 return 1332333 get_user_count.called = 0334 assert tmpl.render(LANGUAGE="de", get_user_count=get_user_count) == "1s"335 assert get_user_count.called == 1336337 def test_complex_plural(self):338 tmpl = i18n_env.from_string(339 "{% trans foo=42, count=2 %}{{ count }} item{% "340 "pluralize count %}{{ count }} items{% endtrans %}"341 )342 assert tmpl.render() == "2 items"343 pytest.raises(344 TemplateAssertionError,345 i18n_env.from_string,346 "{% trans foo %}...{% pluralize bar %}...{% endtrans %}",347 )348349 def test_trans_stringformatting(self):350 tmpl = i18n_env.get_template("stringformat.html")351 assert tmpl.render(LANGUAGE="de", user_count=5) == "Benutzer: 5"352353 def test_trimmed(self):354 tmpl = i18n_env.from_string(355 "{%- trans trimmed %} hello\n world {% endtrans -%}"356 )357 assert tmpl.render() == "hello world"358359 def test_trimmed_policy(self):360 s = "{%- trans %} hello\n world {% endtrans -%}"361 tmpl = i18n_env.from_string(s)362 trimmed_tmpl = i18n_env_trimmed.from_string(s)363 assert tmpl.render() == " hello\n world "364 assert trimmed_tmpl.render() == "hello world"365366 def test_trimmed_policy_override(self):367 tmpl = i18n_env_trimmed.from_string(368 "{%- trans notrimmed %} hello\n world {% endtrans -%}"369 )370 assert tmpl.render() == " hello\n world "371372 def test_trimmed_vars(self):373 tmpl = i18n_env.from_string(374 '{%- trans trimmed x="world" %} hello\n {{ x }} {% endtrans -%}'375 )376 assert tmpl.render() == "hello world"377378 def test_trimmed_varname_trimmed(self):379 # unlikely variable name, but when used as a variable380 # it should not enable trimming381 tmpl = i18n_env.from_string(382 "{%- trans trimmed = 'world' %} hello\n {{ trimmed }} {% endtrans -%}"383 )384 assert tmpl.render() == " hello\n world "385386 def test_extract(self):387 from jinja2.ext import babel_extract388389 source = BytesIO(390 b"""391 {{ gettext('Hello World') }}392 {% trans %}Hello World{% endtrans %}393 {% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %}394 """395 )396 assert list(babel_extract(source, ("gettext", "ngettext", "_"), [], {})) == [397 (2, "gettext", "Hello World", []),398 (3, "gettext", "Hello World", []),399 (4, "ngettext", ("%(users)s user", "%(users)s users", None), []),400 ]401402 def test_extract_trimmed(self):403 from jinja2.ext import babel_extract404405 source = BytesIO(406 b"""407 {{ gettext(' Hello \n World') }}408 {% trans trimmed %} Hello \n World{% endtrans %}409 {% trans trimmed %}{{ users }} \n user410 {%- pluralize %}{{ users }} \n users{% endtrans %}411 """412 )413 assert list(babel_extract(source, ("gettext", "ngettext", "_"), [], {})) == [414 (2, "gettext", " Hello \n World", []),415 (4, "gettext", "Hello World", []),416 (6, "ngettext", ("%(users)s user", "%(users)s users", None), []),417 ]418419 def test_extract_trimmed_option(self):420 from jinja2.ext import babel_extract421422 source = BytesIO(423 b"""424 {{ gettext(' Hello \n World') }}425 {% trans %} Hello \n World{% endtrans %}426 {% trans %}{{ users }} \n user427 {%- pluralize %}{{ users }} \n users{% endtrans %}428 """429 )430 opts = {"trimmed": "true"}431 assert list(babel_extract(source, ("gettext", "ngettext", "_"), [], opts)) == [432 (2, "gettext", " Hello \n World", []),433 (4, "gettext", "Hello World", []),434 (6, "ngettext", ("%(users)s user", "%(users)s users", None), []),435 ]436437 def test_comment_extract(self):438 from jinja2.ext import babel_extract439440 source = BytesIO(441 b"""442 {# trans first #}443 {{ gettext('Hello World') }}444 {% trans %}Hello World{% endtrans %}{# trans second #}445 {#: third #}446 {% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %}447 """448 )449 assert list(450 babel_extract(source, ("gettext", "ngettext", "_"), ["trans", ":"], {})451 ) == [452 (3, "gettext", "Hello World", ["first"]),453 (4, "gettext", "Hello World", ["second"]),454 (6, "ngettext", ("%(users)s user", "%(users)s users", None), ["third"]),455 ]456457 def test_extract_context(self):458 from jinja2.ext import babel_extract459460 source = BytesIO(461 b"""462 {{ pgettext("babel", "Hello World") }}463 {{ npgettext("babel", "%(users)s user", "%(users)s users", users) }}464 """465 )466 assert list(babel_extract(source, ("pgettext", "npgettext", "_"), [], {})) == [467 (2, "pgettext", ("babel", "Hello World"), []),468 (3, "npgettext", ("babel", "%(users)s user", "%(users)s users", None), []),469 ]470471472class TestScope:473 def test_basic_scope_behavior(self):474 # This is what the old with statement compiled down to475 class ScopeExt(Extension):476 tags = {"scope"}477478 def parse(self, parser):479 node = nodes.Scope(lineno=next(parser.stream).lineno)480 assignments = []481 while parser.stream.current.type != "block_end":482 lineno = parser.stream.current.lineno483 if assignments:484 parser.stream.expect("comma")485 target = parser.parse_assign_target()486 parser.stream.expect("assign")487 expr = parser.parse_expression()488 assignments.append(nodes.Assign(target, expr, lineno=lineno))489 node.body = assignments + list(490 parser.parse_statements(("name:endscope",), drop_needle=True)491 )492 return node493494 env = Environment(extensions=[ScopeExt])495 tmpl = env.from_string(496 """\497 {%- scope a=1, b=2, c=b, d=e, e=5 -%}498 {{ a }}|{{ b }}|{{ c }}|{{ d }}|{{ e }}499 {%- endscope -%}500 """501 )502 assert tmpl.render(b=3, e=4) == "1|2|2|4|5"503504505class TestNewstyleInternationalization:506 def test_trans(self):507 tmpl = newstyle_i18n_env.get_template("child.html")508 assert tmpl.render(LANGUAGE="de") == "<title>fehlend</title>pass auf"509510 def test_trans_plural(self):511 tmpl = newstyle_i18n_env.get_template("plural.html")512 assert tmpl.render(LANGUAGE="de", user_count=1) == "Ein Benutzer online"513 assert tmpl.render(LANGUAGE="de", user_count=2) == "2 Benutzer online"514515 def test_complex_plural(self):516 tmpl = newstyle_i18n_env.from_string(517 "{% trans foo=42, count=2 %}{{ count }} item{% "518 "pluralize count %}{{ count }} items{% endtrans %}"519 )520 assert tmpl.render() == "2 items"521 pytest.raises(522 TemplateAssertionError,523 i18n_env.from_string,524 "{% trans foo %}...{% pluralize bar %}...{% endtrans %}",525 )526527 def test_trans_stringformatting(self):528 tmpl = newstyle_i18n_env.get_template("stringformat.html")529 assert tmpl.render(LANGUAGE="de", user_count=5) == "Benutzer: 5"530531 def test_newstyle_plural(self):532 tmpl = newstyle_i18n_env.get_template("ngettext.html")533 assert tmpl.render(LANGUAGE="de", apples=1) == "1 Apfel"534 assert tmpl.render(LANGUAGE="de", apples=5) == "5 Äpfel"535536 def test_autoescape_support(self):537 env = Environment(extensions=["jinja2.ext.i18n"])538 env.install_gettext_callables(539 lambda x: "<strong>Wert: %(name)s</strong>",540 lambda s, p, n: s,541 newstyle=True,542 )543 t = env.from_string(544 '{% autoescape ae %}{{ gettext("foo", name='545 '"<test>") }}{% endautoescape %}'546 )547 assert t.render(ae=True) == "<strong>Wert: <test></strong>"548 assert t.render(ae=False) == "<strong>Wert: <test></strong>"549550 def test_autoescape_macros(self):551 env = Environment(autoescape=False)552 template = (553 "{% macro m() %}<html>{% endmacro %}"554 "{% autoescape true %}{{ m() }}{% endautoescape %}"555 )556 assert env.from_string(template).render() == "<html>"557558 def test_num_used_twice(self):559 tmpl = newstyle_i18n_env.get_template("ngettext_long.html")560 assert tmpl.render(apples=5, LANGUAGE="de") == "5 Äpfel"561562 def test_num_called_num(self):563 source = newstyle_i18n_env.compile(564 """565 {% trans num=3 %}{{ num }} apple{% pluralize566 %}{{ num }} apples{% endtrans %}567 """,568 raw=True,569 )570 # quite hacky, but the only way to properly test that. The idea is571 # that the generated code does not pass num twice (although that572 # would work) for better performance. This only works on the573 # newstyle gettext of course574 assert (575 re.search(r"u?'%\(num\)s apple', u?'%\(num\)s apples', 3", source)576 is not None577 )578579 def test_trans_vars(self):580 t1 = newstyle_i18n_env.get_template("transvars1.html")581 t2 = newstyle_i18n_env.get_template("transvars2.html")582 t3 = newstyle_i18n_env.get_template("transvars3.html")583 assert t1.render(num=1, LANGUAGE="de") == "Benutzer: 1"584 assert t2.render(count=23, LANGUAGE="de") == "Benutzer: 23"585 assert t3.render(num=42, LANGUAGE="de") == "Benutzer: 42"586587 def test_novars_vars_escaping(self):588 t = newstyle_i18n_env.get_template("novars.html")589 assert t.render() == "%(hello)s"590 t = newstyle_i18n_env.get_template("vars.html")591 assert t.render(foo="42") == "42%(foo)s"592 t = newstyle_i18n_env.get_template("explicitvars.html")593 assert t.render() == "%(foo)s"594595 def test_context(self):596 tmpl = newstyle_i18n_env.get_template("pgettext.html")597 assert tmpl.render(LANGUAGE="de") == "Apple"598599 def test_context_plural(self):600 tmpl = newstyle_i18n_env.get_template("npgettext.html")601 assert tmpl.render(LANGUAGE="de", apples=1) == "1 Apple"602 assert tmpl.render(LANGUAGE="de", apples=5) == "5 Apples"603604 def test_context_block(self):605 tmpl = newstyle_i18n_env.get_template("pgettext_block")606 assert tmpl.render(LANGUAGE="de") == "Apple"607608 def test_context_plural_block(self):609 tmpl = newstyle_i18n_env.get_template("npgettext_block")610 assert tmpl.render(LANGUAGE="de", apples=1) == "1 Apple"611 assert tmpl.render(LANGUAGE="de", apples=5) == "5 Apples"612613614class TestAutoEscape:615 def test_scoped_setting(self):616 env = Environment(autoescape=True)617 tmpl = env.from_string(618 """619 {{ "<HelloWorld>" }}620 {% autoescape false %}621 {{ "<HelloWorld>" }}622 {% endautoescape %}623 {{ "<HelloWorld>" }}624 """625 )626 assert tmpl.render().split() == [627 "<HelloWorld>",628 "<HelloWorld>",629 "<HelloWorld>",630 ]631632 env = Environment(autoescape=False)633 tmpl = env.from_string(634 """635 {{ "<HelloWorld>" }}636 {% autoescape true %}637 {{ "<HelloWorld>" }}638 {% endautoescape %}639 {{ "<HelloWorld>" }}640 """641 )642 assert tmpl.render().split() == [643 "<HelloWorld>",644 "<HelloWorld>",645 "<HelloWorld>",646 ]647648 def test_nonvolatile(self):649 env = Environment(autoescape=True)650 tmpl = env.from_string('{{ {"foo": "<test>"}|xmlattr|escape }}')651 assert tmpl.render() == ' foo="<test>"'652 tmpl = env.from_string(653 '{% autoescape false %}{{ {"foo": "<test>"}'654 "|xmlattr|escape }}{% endautoescape %}"655 )656 assert tmpl.render() == " foo="&lt;test&gt;""657658 def test_volatile(self):659 env = Environment(autoescape=True)660 tmpl = env.from_string(661 '{% autoescape foo %}{{ {"foo": "<test>"}'662 "|xmlattr|escape }}{% endautoescape %}"663 )664 assert tmpl.render(foo=False) == " foo="&lt;test&gt;""665 assert tmpl.render(foo=True) == ' foo="<test>"'666667 def test_scoping(self):668 env = Environment()669 tmpl = env.from_string(670 '{% autoescape true %}{% set x = "<x>" %}{{ x }}'671 '{% endautoescape %}{{ x }}{{ "<y>" }}'672 )673 assert tmpl.render(x=1) == "<x>1<y>"674675 def test_volatile_scoping(self):676 env = Environment()677 tmplsource = """678 {% autoescape val %}679 {% macro foo(x) %}680 [{{ x }}]681 {% endmacro %}682 {{ foo().__class__.__name__ }}683 {% endautoescape %}684 {{ '<testing>' }}685 """686 tmpl = env.from_string(tmplsource)687 assert tmpl.render(val=True).split()[0] == "Markup"688 assert tmpl.render(val=False).split()[0] == "str"689690 # looking at the source we should see <testing> there in raw691 # (and then escaped as well)692 env = Environment()693 pysource = env.compile(tmplsource, raw=True)694 assert "<testing>\\n" in pysource695696 env = Environment(autoescape=True)697 pysource = env.compile(tmplsource, raw=True)698 assert "<testing>\\n" in pysource699700 def test_overlay_scopes(self):701 class MagicScopeExtension(Extension):702 tags = {"overlay"}703704 def parse(self, parser):705 node = nodes.OverlayScope(lineno=next(parser.stream).lineno)706 node.body = list(707 parser.parse_statements(("name:endoverlay",), drop_needle=True)708 )709 node.context = self.call_method("get_scope")710 return node711712 def get_scope(self):713 return {"x": [1, 2, 3]}714715 env = Environment(extensions=[MagicScopeExtension])716717 tmpl = env.from_string(718 """719 {{- x }}|{% set z = 99 %}720 {%- overlay %}721 {{- y }}|{{ z }}|{% for item in x %}[{{ item }}]{% endfor %}722 {%- endoverlay %}|723 {{- x -}}724 """725 )726 assert tmpl.render(x=42, y=23) == "42|23|99|[1][2][3]|42"