Skip to content
Myr

test_ext.py

This file

Path

tests/test_ext.py

738 lines · 25.7 KiB · Python

Last changed by

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

History of this file

Take 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–8why, one step back
1import re
2from io import BytesIO34import pytest56from jinja2 import DictLoader7from jinja2 import Environment8from jinja2 import nodes

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 9why, one step back
9from jinja2 import pass_context

Merge branch '3.1.x'David Lordbefore adoption3fd91e4

line 10why, one step back
10from jinja2 import TemplateSyntaxError

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 11–21why, one step back
11from jinja2.exceptions import TemplateAssertionError
12from jinja2.ext import Extension13from jinja2.lexer import count_newlines14from jinja2.lexer import Token1516importable_object = 231718_gettext_re = re.compile(r"_\((.*?)\)", re.DOTALL)192021i18n_templates = {

Merge remote-tracking branch 'origin/3.0.x'David Lordbefore adoptionf1c51b3

line 22why, one step back
22 "default.html": '<title>{{ page_title|default(_("missing")) }}</title>'

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 23why, one step back
23 "{% block body %}{% endblock %}",

Merge remote-tracking branch 'origin/3.0.x'David Lordbefore adoptionf1c51b3

line 24why, one step back
24 "child.html": '{% extends "default.html" %}{% block body %}'

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 25–33why, one step back
25 "{% trans %}watch out{% endtrans %}{% endblock %}",
26 "plural.html": "{% trans user_count %}One user online{% pluralize %}"27 "{{ user_count }} users online{% endtrans %}",28 "plural2.html": "{% trans user_count=get_user_count() %}{{ user_count }}s"29 "{% pluralize %}{{ user_count }}p{% endtrans %}",30 "stringformat.html": '{{ _("User: %(num)s")|format(num=user_count) }}',31}3233newstyle_i18n_templates = {

Merge remote-tracking branch 'origin/3.0.x'David Lordbefore adoptionf1c51b3

line 34why, one step back
34 "default.html": '<title>{{ page_title|default(_("missing")) }}</title>'

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 35why, one step back
35 "{% block body %}{% endblock %}",

Merge remote-tracking branch 'origin/3.0.x'David Lordbefore adoptionf1c51b3

line 36why, one step back
36 "child.html": '{% extends "default.html" %}{% block body %}'

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 37–43why, one step back
37 "{% trans %}watch out{% endtrans %}{% endblock %}",
38 "plural.html": "{% trans user_count %}One user online{% pluralize %}"39 "{{ user_count }} users online{% endtrans %}",40 "stringformat.html": '{{ _("User: %(num)s", num=user_count) }}',41 "ngettext.html": '{{ ngettext("%(num)s apple", "%(num)s apples", apples) }}',42 "ngettext_long.html": "{% trans num=apples %}{{ num }} apple{% pluralize %}"43 "{{ num }} apples{% endtrans %}",

Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228

lines 44–46why, one step back
44 "pgettext.html": '{{ pgettext("fruit", "Apple") }}',
45 "npgettext.html": '{{ npgettext("fruit", "%(num)s apple", "%(num)s apples",'46 " apples) }}",

Merge pull request #1559 from pallets/i18n-context-blockDavid Lordbefore adoption4f5c79c

lines 47–49why, one step back
47 "pgettext_block": "{% trans 'fruit' num=apples %}Apple{% endtrans %}",
48 "npgettext_block": "{% trans 'fruit' num=apples %}{{ num }} apple"49 "{% pluralize %}{{ num }} apples{% endtrans %}",

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 50–66why, one step back
50 "transvars1.html": "{% trans %}User: {{ num }}{% endtrans %}",
51 "transvars2.html": "{% trans num=count %}User: {{ num }}{% endtrans %}",52 "transvars3.html": "{% trans count=num %}User: {{ count }}{% endtrans %}",53 "novars.html": "{% trans %}%(hello)s{% endtrans %}",54 "vars.html": "{% trans %}{{ foo }}%(foo)s{% endtrans %}",55 "explicitvars.html": '{% trans foo="42" %}%(foo)s{% endtrans %}',56}575859languages = {60 "de": {61 "missing": "fehlend",62 "watch out": "pass auf",63 "One user online": "Ein Benutzer online",64 "%(user_count)s users online": "%(user_count)s Benutzer online",65 "User: %(num)s": "Benutzer: %(num)s",66 "User: %(count)s": "Benutzer: %(count)s",

Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228

lines 67–69why, one step back
67 "Apple": {None: "Apfel", "fruit": "Apple"},
68 "%(num)s apple": {None: "%(num)s Apfel", "fruit": "%(num)s Apple"},69 "%(num)s apples": {None: "%(num)s Äpfel", "fruit": "%(num)s Apples"},

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 70–73why, one step back
70 }
71}7273

Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228

lines 74–80why, one step back
74def _get_with_context(value, ctx=None):
75 if isinstance(value, dict):76 return value.get(ctx, value)7778 return value7980

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 81why, one step back
81@pass_context

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 82–83why, one step back
82def gettext(context, string):
83 language = context.get("LANGUAGE", "en")

Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228

lines 84–85why, one step back
84 value = languages.get(language, {}).get(string, string)
85 return _get_with_context(value)

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 86–87why, one step back
86
87

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 88why, one step back
88@pass_context

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 89–90why, one step back
89def ngettext(context, s, p, n):
90 language = context.get("LANGUAGE", "en")

Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228

line 91why, one step back
91

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 92why, one step back
92 if n != 1:

Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228

lines 93–94why, one step back
93 value = languages.get(language, {}).get(p, p)
94 return _get_with_context(value)

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 95why, one step back
95

Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228

lines 96–97why, one step back
96 value = languages.get(language, {}).get(s, s)
97 return _get_with_context(value)

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 98why, one step back
98

Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228

line 99why, one step back
99

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 100why, one step back
100@pass_context

Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228

lines 101–106why, one step back
101def pgettext(context, c, s):
102 language = context.get("LANGUAGE", "en")103 value = languages.get(language, {}).get(s, s)104 return _get_with_context(value, c)105106

Merge pull request #1389 from pallets/unify-decoratorsDavid Lordbefore adoption39846a8

line 107why, one step back
107@pass_context

Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228

lines 108–118why, one step back
108def npgettext(context, c, s, p, n):
109 language = context.get("LANGUAGE", "en")110111 if n != 1:112 value = languages.get(language, {}).get(p, p)113 return _get_with_context(value, c)114115 value = languages.get(language, {}).get(s, s)116 return _get_with_context(value, c)117118

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 119–121why, one step back
119i18n_env = Environment(
120 loader=DictLoader(i18n_templates), extensions=["jinja2.ext.i18n"]121)

Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228

lines 122–130why, one step back
122i18n_env.globals.update(
123 {124 "_": gettext,125 "gettext": gettext,126 "ngettext": ngettext,127 "pgettext": pgettext,128 "npgettext": npgettext,129 }130)

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 131why, one step back
131i18n_env_trimmed = Environment(extensions=["jinja2.ext.i18n"])

Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228

line 132why, one step back
132

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 133–134why, one step back
133i18n_env_trimmed.policies["ext.i18n.trimmed"] = True
134i18n_env_trimmed.globals.update(

Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228

lines 135–141why, one step back
135 {
136 "_": gettext,137 "gettext": gettext,138 "ngettext": ngettext,139 "pgettext": pgettext,140 "npgettext": npgettext,141 }

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 142–147why, one step back
142)
143144newstyle_i18n_env = Environment(145 loader=DictLoader(newstyle_i18n_templates), extensions=["jinja2.ext.i18n"]146)147newstyle_i18n_env.install_gettext_callables( # type: ignore

Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228

line 148why, one step back
148 gettext, ngettext, newstyle=True, pgettext=pgettext, npgettext=npgettext

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 149–199why, one step back
149)
150151152class ExampleExtension(Extension):153 tags = {"test"}154 ext_attr = 42155 context_reference_node_cls = nodes.ContextReference156157 def parse(self, parser):158 return nodes.Output(159 [160 self.call_method(161 "_dump",162 [163 nodes.EnvironmentAttribute("sandboxed"),164 self.attr("ext_attr"),165 nodes.ImportedName(__name__ + ".importable_object"),166 self.context_reference_node_cls(),167 ],168 )169 ]170 ).set_lineno(next(parser.stream).lineno)171172 def _dump(self, sandboxed, ext_attr, imported_object, context):173 return (174 f"{sandboxed}|{ext_attr}|{imported_object}|{context.blocks}"175 f"|{context.get('test_var')}"176 )177178179class DerivedExampleExtension(ExampleExtension):180 context_reference_node_cls = nodes.DerivedContextReference # type: ignore181182183class PreprocessorExtension(Extension):184 def preprocess(self, source, name, filename=None):185 return source.replace("[[TEST]]", "({{ foo }})")186187188class StreamFilterExtension(Extension):189 def filter_stream(self, stream):190 for token in stream:191 if token.type == "data":192 yield from self.interpolate(token)193 else:194 yield token195196 def interpolate(self, token):197 pos = 0198 end = len(token.value)199 lineno = token.lineno

Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b

line 200why, one step back
200 while True:

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 201–457why, one step back
201 match = _gettext_re.search(token.value, pos)
202 if match is None:203 break204 value = token.value[pos : match.start()]205 if value:206 yield Token(lineno, "data", value)207 lineno += count_newlines(token.value)208 yield Token(lineno, "variable_begin", None)209 yield Token(lineno, "name", "gettext")210 yield Token(lineno, "lparen", None)211 yield Token(lineno, "string", match.group(1))212 yield Token(lineno, "rparen", None)213 yield Token(lineno, "variable_end", None)214 pos = match.end()215 if pos < end:216 yield Token(lineno, "data", token.value[pos:])217218219class TestExtensions:220 def test_extend_late(self):221 env = Environment()222 t = env.from_string('{% autoescape true %}{{ "<test>" }}{% endautoescape %}')223 assert t.render() == "&lt;test&gt;"224225 def test_loop_controls(self):226 env = Environment(extensions=["jinja2.ext.loopcontrols"])227228 tmpl = env.from_string(229 """230 {%- for item in [1, 2, 3, 4] %}231 {%- if item % 2 == 0 %}{% continue %}{% endif -%}232 {{ item }}233 {%- endfor %}"""234 )235 assert tmpl.render() == "13"236237 tmpl = env.from_string(238 """239 {%- for item in [1, 2, 3, 4] %}240 {%- if item > 2 %}{% break %}{% endif -%}241 {{ item }}242 {%- endfor %}"""243 )244 assert tmpl.render() == "12"245246 def test_do(self):247 env = Environment(extensions=["jinja2.ext.do"])248 tmpl = env.from_string(249 """250 {%- set items = [] %}251 {%- for char in "foo" %}252 {%- do items.append(loop.index0 ~ char) %}253 {%- endfor %}{{ items|join(', ') }}"""254 )255 assert tmpl.render() == "0f, 1o, 2o"256257 def test_extension_nodes(self):258 env = Environment(extensions=[ExampleExtension])259 tmpl = env.from_string("{% test %}")260 assert tmpl.render() == "False|42|23|{}|None"261262 def test_contextreference_node_passes_context(self):263 env = Environment(extensions=[ExampleExtension])264 tmpl = env.from_string('{% set test_var="test_content" %}{% test %}')265 assert tmpl.render() == "False|42|23|{}|test_content"266267 def test_contextreference_node_can_pass_locals(self):268 env = Environment(extensions=[DerivedExampleExtension])269 tmpl = env.from_string(270 '{% for test_var in ["test_content"] %}{% test %}{% endfor %}'271 )272 assert tmpl.render() == "False|42|23|{}|test_content"273274 def test_identifier(self):275 assert ExampleExtension.identifier == __name__ + ".ExampleExtension"276277 def test_rebinding(self):278 original = Environment(extensions=[ExampleExtension])279 overlay = original.overlay()280 for env in original, overlay:281 for ext in env.extensions.values():282 assert ext.environment is env283284 def test_preprocessor_extension(self):285 env = Environment(extensions=[PreprocessorExtension])286 tmpl = env.from_string("{[[TEST]]}")287 assert tmpl.render(foo=42) == "{(42)}"288289 def test_streamfilter_extension(self):290 env = Environment(extensions=[StreamFilterExtension])291 env.globals["gettext"] = lambda x: x.upper()292 tmpl = env.from_string("Foo _(bar) Baz")293 out = tmpl.render()294 assert out == "Foo BAR Baz"295296 def test_extension_ordering(self):297 class T1(Extension):298 priority = 1299300 class T2(Extension):301 priority = 2302303 env = Environment(extensions=[T1, T2])304 ext = list(env.iter_extensions())305 assert ext[0].__class__ is T1306 assert ext[1].__class__ is T2307308 def test_debug(self):309 env = Environment(extensions=["jinja2.ext.debug"])310 t = env.from_string("Hello\n{% debug %}\nGoodbye")311 out = t.render()312313 for value in ("context", "cycler", "filters", "abs", "tests", "!="):314 assert f"'{value}'" in out315316317class TestInternationalization:318 def test_trans(self):319 tmpl = i18n_env.get_template("child.html")320 assert tmpl.render(LANGUAGE="de") == "<title>fehlend</title>pass auf"321322 def test_trans_plural(self):323 tmpl = i18n_env.get_template("plural.html")324 assert tmpl.render(LANGUAGE="de", user_count=1) == "Ein Benutzer online"325 assert tmpl.render(LANGUAGE="de", user_count=2) == "2 Benutzer online"326327 def test_trans_plural_with_functions(self):328 tmpl = i18n_env.get_template("plural2.html")329330 def get_user_count():331 get_user_count.called += 1332 return 1333334 get_user_count.called = 0335 assert tmpl.render(LANGUAGE="de", get_user_count=get_user_count) == "1s"336 assert get_user_count.called == 1337338 def test_complex_plural(self):339 tmpl = i18n_env.from_string(340 "{% trans foo=42, count=2 %}{{ count }} item{% "341 "pluralize count %}{{ count }} items{% endtrans %}"342 )343 assert tmpl.render() == "2 items"344 pytest.raises(345 TemplateAssertionError,346 i18n_env.from_string,347 "{% trans foo %}...{% pluralize bar %}...{% endtrans %}",348 )349350 def test_trans_stringformatting(self):351 tmpl = i18n_env.get_template("stringformat.html")352 assert tmpl.render(LANGUAGE="de", user_count=5) == "Benutzer: 5"353354 def test_trimmed(self):355 tmpl = i18n_env.from_string(356 "{%- trans trimmed %} hello\n world {% endtrans -%}"357 )358 assert tmpl.render() == "hello world"359360 def test_trimmed_policy(self):361 s = "{%- trans %} hello\n world {% endtrans -%}"362 tmpl = i18n_env.from_string(s)363 trimmed_tmpl = i18n_env_trimmed.from_string(s)364 assert tmpl.render() == " hello\n world "365 assert trimmed_tmpl.render() == "hello world"366367 def test_trimmed_policy_override(self):368 tmpl = i18n_env_trimmed.from_string(369 "{%- trans notrimmed %} hello\n world {% endtrans -%}"370 )371 assert tmpl.render() == " hello\n world "372373 def test_trimmed_vars(self):374 tmpl = i18n_env.from_string(375 '{%- trans trimmed x="world" %} hello\n {{ x }} {% endtrans -%}'376 )377 assert tmpl.render() == "hello world"378379 def test_trimmed_varname_trimmed(self):380 # unlikely variable name, but when used as a variable381 # it should not enable trimming382 tmpl = i18n_env.from_string(383 "{%- trans trimmed = 'world' %} hello\n {{ trimmed }} {% endtrans -%}"384 )385 assert tmpl.render() == " hello\n world "386387 def test_extract(self):388 from jinja2.ext import babel_extract389390 source = BytesIO(391 b"""392 {{ gettext('Hello World') }}393 {% trans %}Hello World{% endtrans %}394 {% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %}395 """396 )397 assert list(babel_extract(source, ("gettext", "ngettext", "_"), [], {})) == [398 (2, "gettext", "Hello World", []),399 (3, "gettext", "Hello World", []),400 (4, "ngettext", ("%(users)s user", "%(users)s users", None), []),401 ]402403 def test_extract_trimmed(self):404 from jinja2.ext import babel_extract405406 source = BytesIO(407 b"""408 {{ gettext(' Hello \n World') }}409 {% trans trimmed %} Hello \n World{% endtrans %}410 {% trans trimmed %}{{ users }} \n user411 {%- pluralize %}{{ users }} \n users{% endtrans %}412 """413 )414 assert list(babel_extract(source, ("gettext", "ngettext", "_"), [], {})) == [415 (2, "gettext", " Hello \n World", []),416 (4, "gettext", "Hello World", []),417 (6, "ngettext", ("%(users)s user", "%(users)s users", None), []),418 ]419420 def test_extract_trimmed_option(self):421 from jinja2.ext import babel_extract422423 source = BytesIO(424 b"""425 {{ gettext(' Hello \n World') }}426 {% trans %} Hello \n World{% endtrans %}427 {% trans %}{{ users }} \n user428 {%- pluralize %}{{ users }} \n users{% endtrans %}429 """430 )431 opts = {"trimmed": "true"}432 assert list(babel_extract(source, ("gettext", "ngettext", "_"), [], opts)) == [433 (2, "gettext", " Hello \n World", []),434 (4, "gettext", "Hello World", []),435 (6, "ngettext", ("%(users)s user", "%(users)s users", None), []),436 ]437438 def test_comment_extract(self):439 from jinja2.ext import babel_extract440441 source = BytesIO(442 b"""443 {# trans first #}444 {{ gettext('Hello World') }}445 {% trans %}Hello World{% endtrans %}{# trans second #}446 {#: third #}447 {% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %}448 """449 )450 assert list(451 babel_extract(source, ("gettext", "ngettext", "_"), ["trans", ":"], {})452 ) == [453 (3, "gettext", "Hello World", ["first"]),454 (4, "gettext", "Hello World", ["second"]),455 (6, "ngettext", ("%(users)s user", "%(users)s users", None), ["third"]),456 ]457

Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228

lines 458–459why, one step back
458 def test_extract_context(self):
459 from jinja2.ext import babel_extract

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

line 460why, one step back
460

Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228

lines 461–470why, one step back
461 source = BytesIO(
462 b"""463 {{ pgettext("babel", "Hello World") }}464 {{ npgettext("babel", "%(users)s user", "%(users)s users", users) }}465 """466 )467 assert list(babel_extract(source, ("pgettext", "npgettext", "_"), [], {})) == [468 (2, "pgettext", ("babel", "Hello World"), []),469 (3, "npgettext", ("babel", "%(users)s user", "%(users)s users", None), []),470 ]

Merge branch '3.1.x'David Lordbefore adoption3fd91e4

lines 471–482why, one step back
471
472 def test_nested_trans_error(self):473 s = "{% trans %}foo{% trans %}{% endtrans %}"474 with pytest.raises(TemplateSyntaxError) as excinfo:475 i18n_env.from_string(s)476 assert "trans blocks can't be nested" in str(excinfo.value)477478 def test_trans_block_error(self):479 s = "{% trans %}foo{% wibble bar %}{% endwibble %}{% endtrans %}"480 with pytest.raises(TemplateSyntaxError) as excinfo:481 i18n_env.from_string(s)482 assert "saw `wibble`" in str(excinfo.value)

Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228

lines 483–484why, one step back
483
484

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 485–556why, one step back
485class TestScope:
486 def test_basic_scope_behavior(self):487 # This is what the old with statement compiled down to488 class ScopeExt(Extension):489 tags = {"scope"}490491 def parse(self, parser):492 node = nodes.Scope(lineno=next(parser.stream).lineno)493 assignments = []494 while parser.stream.current.type != "block_end":495 lineno = parser.stream.current.lineno496 if assignments:497 parser.stream.expect("comma")498 target = parser.parse_assign_target()499 parser.stream.expect("assign")500 expr = parser.parse_expression()501 assignments.append(nodes.Assign(target, expr, lineno=lineno))502 node.body = assignments + list(503 parser.parse_statements(("name:endscope",), drop_needle=True)504 )505 return node506507 env = Environment(extensions=[ScopeExt])508 tmpl = env.from_string(509 """\510 {%- scope a=1, b=2, c=b, d=e, e=5 -%}511 {{ a }}|{{ b }}|{{ c }}|{{ d }}|{{ e }}512 {%- endscope -%}513 """514 )515 assert tmpl.render(b=3, e=4) == "1|2|2|4|5"516517518class TestNewstyleInternationalization:519 def test_trans(self):520 tmpl = newstyle_i18n_env.get_template("child.html")521 assert tmpl.render(LANGUAGE="de") == "<title>fehlend</title>pass auf"522523 def test_trans_plural(self):524 tmpl = newstyle_i18n_env.get_template("plural.html")525 assert tmpl.render(LANGUAGE="de", user_count=1) == "Ein Benutzer online"526 assert tmpl.render(LANGUAGE="de", user_count=2) == "2 Benutzer online"527528 def test_complex_plural(self):529 tmpl = newstyle_i18n_env.from_string(530 "{% trans foo=42, count=2 %}{{ count }} item{% "531 "pluralize count %}{{ count }} items{% endtrans %}"532 )533 assert tmpl.render() == "2 items"534 pytest.raises(535 TemplateAssertionError,536 i18n_env.from_string,537 "{% trans foo %}...{% pluralize bar %}...{% endtrans %}",538 )539540 def test_trans_stringformatting(self):541 tmpl = newstyle_i18n_env.get_template("stringformat.html")542 assert tmpl.render(LANGUAGE="de", user_count=5) == "Benutzer: 5"543544 def test_newstyle_plural(self):545 tmpl = newstyle_i18n_env.get_template("ngettext.html")546 assert tmpl.render(LANGUAGE="de", apples=1) == "1 Apfel"547 assert tmpl.render(LANGUAGE="de", apples=5) == "5 Äpfel"548549 def test_autoescape_support(self):550 env = Environment(extensions=["jinja2.ext.i18n"])551 env.install_gettext_callables(552 lambda x: "<strong>Wert: %(name)s</strong>",553 lambda s, p, n: s,554 newstyle=True,555 )556 t = env.from_string(

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

line 557why, one step back
557 '{% autoescape ae %}{{ gettext("foo", name="<test>") }}{% endautoescape %}'

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 558–605why, one step back
558 )
559 assert t.render(ae=True) == "<strong>Wert: &lt;test&gt;</strong>"560 assert t.render(ae=False) == "<strong>Wert: <test></strong>"561562 def test_autoescape_macros(self):563 env = Environment(autoescape=False)564 template = (565 "{% macro m() %}<html>{% endmacro %}"566 "{% autoescape true %}{{ m() }}{% endautoescape %}"567 )568 assert env.from_string(template).render() == "<html>"569570 def test_num_used_twice(self):571 tmpl = newstyle_i18n_env.get_template("ngettext_long.html")572 assert tmpl.render(apples=5, LANGUAGE="de") == "5 Äpfel"573574 def test_num_called_num(self):575 source = newstyle_i18n_env.compile(576 """577 {% trans num=3 %}{{ num }} apple{% pluralize578 %}{{ num }} apples{% endtrans %}579 """,580 raw=True,581 )582 # quite hacky, but the only way to properly test that. The idea is583 # that the generated code does not pass num twice (although that584 # would work) for better performance. This only works on the585 # newstyle gettext of course586 assert (587 re.search(r"u?'%\(num\)s apple', u?'%\(num\)s apples', 3", source)588 is not None589 )590591 def test_trans_vars(self):592 t1 = newstyle_i18n_env.get_template("transvars1.html")593 t2 = newstyle_i18n_env.get_template("transvars2.html")594 t3 = newstyle_i18n_env.get_template("transvars3.html")595 assert t1.render(num=1, LANGUAGE="de") == "Benutzer: 1"596 assert t2.render(count=23, LANGUAGE="de") == "Benutzer: 23"597 assert t3.render(num=42, LANGUAGE="de") == "Benutzer: 42"598599 def test_novars_vars_escaping(self):600 t = newstyle_i18n_env.get_template("novars.html")601 assert t.render() == "%(hello)s"602 t = newstyle_i18n_env.get_template("vars.html")603 assert t.render(foo="42") == "42%(foo)s"604 t = newstyle_i18n_env.get_template("explicitvars.html")605 assert t.render() == "%(foo)s"

Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228

lines 606–610why, one step back
606
607 def test_context(self):608 tmpl = newstyle_i18n_env.get_template("pgettext.html")609 assert tmpl.render(LANGUAGE="de") == "Apple"610

Merge pull request #1559 from pallets/i18n-context-blockDavid Lordbefore adoption4f5c79c

line 611why, one step back
611 def test_context_plural(self):

Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228

line 612why, one step back
612 tmpl = newstyle_i18n_env.get_template("npgettext.html")

Merge pull request #1559 from pallets/i18n-context-blockDavid Lordbefore adoption4f5c79c

lines 613–621why, one step back
613 assert tmpl.render(LANGUAGE="de", apples=1) == "1 Apple"
614 assert tmpl.render(LANGUAGE="de", apples=5) == "5 Apples"615616 def test_context_block(self):617 tmpl = newstyle_i18n_env.get_template("pgettext_block")618 assert tmpl.render(LANGUAGE="de") == "Apple"619620 def test_context_plural_block(self):621 tmpl = newstyle_i18n_env.get_template("npgettext_block")

Merge pull request #1126 from imomaliev/pgettext-supportAdrianbefore adoption43d4228

lines 622–623why, one step back
622 assert tmpl.render(LANGUAGE="de", apples=1) == "1 Apple"
623 assert tmpl.render(LANGUAGE="de", apples=5) == "5 Apples"

update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0

lines 624–738why, one step back
624
625626class TestAutoEscape:627 def test_scoped_setting(self):628 env = Environment(autoescape=True)629 tmpl = env.from_string(630 """631 {{ "<HelloWorld>" }}632 {% autoescape false %}633 {{ "<HelloWorld>" }}634 {% endautoescape %}635 {{ "<HelloWorld>" }}636 """637 )638 assert tmpl.render().split() == [639 "&lt;HelloWorld&gt;",640 "<HelloWorld>",641 "&lt;HelloWorld&gt;",642 ]643644 env = Environment(autoescape=False)645 tmpl = env.from_string(646 """647 {{ "<HelloWorld>" }}648 {% autoescape true %}649 {{ "<HelloWorld>" }}650 {% endautoescape %}651 {{ "<HelloWorld>" }}652 """653 )654 assert tmpl.render().split() == [655 "<HelloWorld>",656 "&lt;HelloWorld&gt;",657 "<HelloWorld>",658 ]659660 def test_nonvolatile(self):661 env = Environment(autoescape=True)662 tmpl = env.from_string('{{ {"foo": "<test>"}|xmlattr|escape }}')663 assert tmpl.render() == ' foo="&lt;test&gt;"'664 tmpl = env.from_string(665 '{% autoescape false %}{{ {"foo": "<test>"}'666 "|xmlattr|escape }}{% endautoescape %}"667 )668 assert tmpl.render() == " foo=&#34;&amp;lt;test&amp;gt;&#34;"669670 def test_volatile(self):671 env = Environment(autoescape=True)672 tmpl = env.from_string(673 '{% autoescape foo %}{{ {"foo": "<test>"}'674 "|xmlattr|escape }}{% endautoescape %}"675 )676 assert tmpl.render(foo=False) == " foo=&#34;&amp;lt;test&amp;gt;&#34;"677 assert tmpl.render(foo=True) == ' foo="&lt;test&gt;"'678679 def test_scoping(self):680 env = Environment()681 tmpl = env.from_string(682 '{% autoescape true %}{% set x = "<x>" %}{{ x }}'683 '{% endautoescape %}{{ x }}{{ "<y>" }}'684 )685 assert tmpl.render(x=1) == "&lt;x&gt;1<y>"686687 def test_volatile_scoping(self):688 env = Environment()689 tmplsource = """690 {% autoescape val %}691 {% macro foo(x) %}692 [{{ x }}]693 {% endmacro %}694 {{ foo().__class__.__name__ }}695 {% endautoescape %}696 {{ '<testing>' }}697 """698 tmpl = env.from_string(tmplsource)699 assert tmpl.render(val=True).split()[0] == "Markup"700 assert tmpl.render(val=False).split()[0] == "str"701702 # looking at the source we should see <testing> there in raw703 # (and then escaped as well)704 env = Environment()705 pysource = env.compile(tmplsource, raw=True)706 assert "<testing>\\n" in pysource707708 env = Environment(autoescape=True)709 pysource = env.compile(tmplsource, raw=True)710 assert "&lt;testing&gt;\\n" in pysource711712 def test_overlay_scopes(self):713 class MagicScopeExtension(Extension):714 tags = {"overlay"}715716 def parse(self, parser):717 node = nodes.OverlayScope(lineno=next(parser.stream).lineno)718 node.body = list(719 parser.parse_statements(("name:endoverlay",), drop_needle=True)720 )721 node.context = self.call_method("get_scope")722 return node723724 def get_scope(self):725 return {"x": [1, 2, 3]}726727 env = Environment(extensions=[MagicScopeExtension])728729 tmpl = env.from_string(730 """731 {{- x }}|{% set z = 99 %}732 {%- overlay %}733 {{- y }}|{{ z }}|{% for item in x %}[{{ item }}]{% endfor %}734 {%- endoverlay %}|735 {{- x -}}736 """737 )738 assert tmpl.render(x=42, y=23) == "42|23|99|[1][2][3]|42"