test_ext.py
This file
Path
tests/test_ext.py
655 lines · 23.3 KiB · Python
Last changed by
remove custom pytest marksDavid Lordbefore adoptiondd5a050
History of this fileTake it
1# -*- coding: utf-8 -*-2import re34import pytest56from jinja2 import contextfunction7from jinja2 import DictLoader8from jinja2 import Environment9from jinja2 import nodes10from jinja2._compat import BytesIO11from jinja2._compat import itervalues12from jinja2._compat import text_type13from jinja2.exceptions import TemplateAssertionError14from jinja2.ext import Extension15from jinja2.lexer import count_newlines16from jinja2.lexer import Token1718importable_object = 231920_gettext_re = re.compile(r"_\((.*?)\)", re.DOTALL)212223i18n_templates = {24 "master.html": '<title>{{ page_title|default(_("missing")) }}</title>'25 "{% block body %}{% endblock %}",26 "child.html": '{% extends "master.html" %}{% block body %}'27 "{% trans %}watch out{% endtrans %}{% endblock %}",28 "plural.html": "{% trans user_count %}One user online{% pluralize %}"29 "{{ user_count }} users online{% endtrans %}",30 "plural2.html": "{% trans user_count=get_user_count() %}{{ user_count }}s"31 "{% pluralize %}{{ user_count }}p{% endtrans %}",32 "stringformat.html": '{{ _("User: %(num)s")|format(num=user_count) }}',33}3435newstyle_i18n_templates = {36 "master.html": '<title>{{ page_title|default(_("missing")) }}</title>'37 "{% block body %}{% endblock %}",38 "child.html": '{% extends "master.html" %}{% block body %}'39 "{% trans %}watch out{% endtrans %}{% endblock %}",40 "plural.html": "{% trans user_count %}One user online{% pluralize %}"41 "{{ user_count }} users online{% endtrans %}",42 "stringformat.html": '{{ _("User: %(num)s", num=user_count) }}',43 "ngettext.html": '{{ ngettext("%(num)s apple", "%(num)s apples", apples) }}',44 "ngettext_long.html": "{% trans num=apples %}{{ num }} apple{% pluralize %}"45 "{{ num }} apples{% endtrans %}",46 "transvars1.html": "{% trans %}User: {{ num }}{% endtrans %}",47 "transvars2.html": "{% trans num=count %}User: {{ num }}{% endtrans %}",48 "transvars3.html": "{% trans count=num %}User: {{ count }}{% endtrans %}",49 "novars.html": "{% trans %}%(hello)s{% endtrans %}",50 "vars.html": "{% trans %}{{ foo }}%(foo)s{% endtrans %}",51 "explicitvars.html": '{% trans foo="42" %}%(foo)s{% endtrans %}',52}535455languages = {56 "de": {57 "missing": u"fehlend",58 "watch out": u"pass auf",59 "One user online": u"Ein Benutzer online",60 "%(user_count)s users online": u"%(user_count)s Benutzer online",61 "User: %(num)s": u"Benutzer: %(num)s",62 "User: %(count)s": u"Benutzer: %(count)s",63 "%(num)s apple": u"%(num)s Apfel",64 "%(num)s apples": u"%(num)s Äpfel",65 }66}676869@contextfunction70def gettext(context, string):71 language = context.get("LANGUAGE", "en")72 return languages.get(language, {}).get(string, string)737475@contextfunction76def ngettext(context, s, p, n):77 language = context.get("LANGUAGE", "en")78 if n != 1:79 return languages.get(language, {}).get(p, p)80 return languages.get(language, {}).get(s, s)818283i18n_env = Environment(84 loader=DictLoader(i18n_templates), extensions=["jinja2.ext.i18n"]85)86i18n_env.globals.update({"_": gettext, "gettext": gettext, "ngettext": ngettext})87i18n_env_trimmed = Environment(extensions=["jinja2.ext.i18n"])88i18n_env_trimmed.policies["ext.i18n.trimmed"] = True89i18n_env_trimmed.globals.update(90 {"_": gettext, "gettext": gettext, "ngettext": ngettext}91)9293newstyle_i18n_env = Environment(94 loader=DictLoader(newstyle_i18n_templates), extensions=["jinja2.ext.i18n"]95)96newstyle_i18n_env.install_gettext_callables(gettext, ngettext, newstyle=True)979899class ExampleExtension(Extension):100 tags = set(["test"])101 ext_attr = 42102 context_reference_node_cls = nodes.ContextReference103104 def parse(self, parser):105 return nodes.Output(106 [107 self.call_method(108 "_dump",109 [110 nodes.EnvironmentAttribute("sandboxed"),111 self.attr("ext_attr"),112 nodes.ImportedName(__name__ + ".importable_object"),113 self.context_reference_node_cls(),114 ],115 )116 ]117 ).set_lineno(next(parser.stream).lineno)118119 def _dump(self, sandboxed, ext_attr, imported_object, context):120 return "%s|%s|%s|%s|%s" % (121 sandboxed,122 ext_attr,123 imported_object,124 context.blocks,125 context.get("test_var"),126 )127128129class DerivedExampleExtension(ExampleExtension):130 context_reference_node_cls = nodes.DerivedContextReference131132133class PreprocessorExtension(Extension):134 def preprocess(self, source, name, filename=None):135 return source.replace("[[TEST]]", "({{ foo }})")136137138class StreamFilterExtension(Extension):139 def filter_stream(self, stream):140 for token in stream:141 if token.type == "data":142 for t in self.interpolate(token):143 yield t144 else:145 yield token146147 def interpolate(self, token):148 pos = 0149 end = len(token.value)150 lineno = token.lineno151 while 1:152 match = _gettext_re.search(token.value, pos)153 if match is None:154 break155 value = token.value[pos : match.start()]156 if value:157 yield Token(lineno, "data", value)158 lineno += count_newlines(token.value)159 yield Token(lineno, "variable_begin", None)160 yield Token(lineno, "name", "gettext")161 yield Token(lineno, "lparen", None)162 yield Token(lineno, "string", match.group(1))163 yield Token(lineno, "rparen", None)164 yield Token(lineno, "variable_end", None)165 pos = match.end()166 if pos < end:167 yield Token(lineno, "data", token.value[pos:])168169170class TestExtensions(object):171 def test_extend_late(self):172 env = Environment()173 env.add_extension("jinja2.ext.autoescape")174 t = env.from_string('{% autoescape true %}{{ "<test>" }}{% endautoescape %}')175 assert t.render() == "<test>"176177 def test_loop_controls(self):178 env = Environment(extensions=["jinja2.ext.loopcontrols"])179180 tmpl = env.from_string(181 """182 {%- for item in [1, 2, 3, 4] %}183 {%- if item % 2 == 0 %}{% continue %}{% endif -%}184 {{ item }}185 {%- endfor %}"""186 )187 assert tmpl.render() == "13"188189 tmpl = env.from_string(190 """191 {%- for item in [1, 2, 3, 4] %}192 {%- if item > 2 %}{% break %}{% endif -%}193 {{ item }}194 {%- endfor %}"""195 )196 assert tmpl.render() == "12"197198 def test_do(self):199 env = Environment(extensions=["jinja2.ext.do"])200 tmpl = env.from_string(201 """202 {%- set items = [] %}203 {%- for char in "foo" %}204 {%- do items.append(loop.index0 ~ char) %}205 {%- endfor %}{{ items|join(', ') }}"""206 )207 assert tmpl.render() == "0f, 1o, 2o"208209 def test_extension_nodes(self):210 env = Environment(extensions=[ExampleExtension])211 tmpl = env.from_string("{% test %}")212 assert tmpl.render() == "False|42|23|{}|None"213214 def test_contextreference_node_passes_context(self):215 env = Environment(extensions=[ExampleExtension])216 tmpl = env.from_string('{% set test_var="test_content" %}{% test %}')217 assert tmpl.render() == "False|42|23|{}|test_content"218219 def test_contextreference_node_can_pass_locals(self):220 env = Environment(extensions=[DerivedExampleExtension])221 tmpl = env.from_string(222 '{% for test_var in ["test_content"] %}{% test %}{% endfor %}'223 )224 assert tmpl.render() == "False|42|23|{}|test_content"225226 def test_identifier(self):227 assert ExampleExtension.identifier == __name__ + ".ExampleExtension"228229 def test_rebinding(self):230 original = Environment(extensions=[ExampleExtension])231 overlay = original.overlay()232 for env in original, overlay:233 for ext in itervalues(env.extensions):234 assert ext.environment is env235236 def test_preprocessor_extension(self):237 env = Environment(extensions=[PreprocessorExtension])238 tmpl = env.from_string("{[[TEST]]}")239 assert tmpl.render(foo=42) == "{(42)}"240241 def test_streamfilter_extension(self):242 env = Environment(extensions=[StreamFilterExtension])243 env.globals["gettext"] = lambda x: x.upper()244 tmpl = env.from_string("Foo _(bar) Baz")245 out = tmpl.render()246 assert out == "Foo BAR Baz"247248 def test_extension_ordering(self):249 class T1(Extension):250 priority = 1251252 class T2(Extension):253 priority = 2254255 env = Environment(extensions=[T1, T2])256 ext = list(env.iter_extensions())257 assert ext[0].__class__ is T1258 assert ext[1].__class__ is T2259260 def test_debug(self):261 env = Environment(extensions=["jinja2.ext.debug"])262 t = env.from_string("Hello\n{% debug %}\nGoodbye")263 out = t.render()264265 for value in ("context", "cycler", "filters", "abs", "tests", "!="):266 assert "'{}'".format(value) in out267268269class TestInternationalization(object):270 def test_trans(self):271 tmpl = i18n_env.get_template("child.html")272 assert tmpl.render(LANGUAGE="de") == "<title>fehlend</title>pass auf"273274 def test_trans_plural(self):275 tmpl = i18n_env.get_template("plural.html")276 assert tmpl.render(LANGUAGE="de", user_count=1) == "Ein Benutzer online"277 assert tmpl.render(LANGUAGE="de", user_count=2) == "2 Benutzer online"278279 def test_trans_plural_with_functions(self):280 tmpl = i18n_env.get_template("plural2.html")281282 def get_user_count():283 get_user_count.called += 1284 return 1285286 get_user_count.called = 0287 assert tmpl.render(LANGUAGE="de", get_user_count=get_user_count) == "1s"288 assert get_user_count.called == 1289290 def test_complex_plural(self):291 tmpl = i18n_env.from_string(292 "{% trans foo=42, count=2 %}{{ count }} item{% "293 "pluralize count %}{{ count }} items{% endtrans %}"294 )295 assert tmpl.render() == "2 items"296 pytest.raises(297 TemplateAssertionError,298 i18n_env.from_string,299 "{% trans foo %}...{% pluralize bar %}...{% endtrans %}",300 )301302 def test_trans_stringformatting(self):303 tmpl = i18n_env.get_template("stringformat.html")304 assert tmpl.render(LANGUAGE="de", user_count=5) == "Benutzer: 5"305306 def test_trimmed(self):307 tmpl = i18n_env.from_string(308 "{%- trans trimmed %} hello\n world {% endtrans -%}"309 )310 assert tmpl.render() == "hello world"311312 def test_trimmed_policy(self):313 s = "{%- trans %} hello\n world {% endtrans -%}"314 tmpl = i18n_env.from_string(s)315 trimmed_tmpl = i18n_env_trimmed.from_string(s)316 assert tmpl.render() == " hello\n world "317 assert trimmed_tmpl.render() == "hello world"318319 def test_trimmed_policy_override(self):320 tmpl = i18n_env_trimmed.from_string(321 "{%- trans notrimmed %} hello\n world {% endtrans -%}"322 )323 assert tmpl.render() == " hello\n world "324325 def test_trimmed_vars(self):326 tmpl = i18n_env.from_string(327 '{%- trans trimmed x="world" %} hello\n {{ x }} {% endtrans -%}'328 )329 assert tmpl.render() == "hello world"330331 def test_trimmed_varname_trimmed(self):332 # unlikely variable name, but when used as a variable333 # it should not enable trimming334 tmpl = i18n_env.from_string(335 "{%- trans trimmed = 'world' %} hello\n {{ trimmed }} {% endtrans -%}"336 )337 assert tmpl.render() == " hello\n world "338339 def test_extract(self):340 from jinja2.ext import babel_extract341342 source = BytesIO(343 """344 {{ gettext('Hello World') }}345 {% trans %}Hello World{% endtrans %}346 {% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %}347 """.encode(348 "ascii"349 )350 ) # make python 3 happy351 assert list(babel_extract(source, ("gettext", "ngettext", "_"), [], {})) == [352 (2, "gettext", u"Hello World", []),353 (3, "gettext", u"Hello World", []),354 (4, "ngettext", (u"%(users)s user", u"%(users)s users", None), []),355 ]356357 def test_extract_trimmed(self):358 from jinja2.ext import babel_extract359360 source = BytesIO(361 """362 {{ gettext(' Hello \n World') }}363 {% trans trimmed %} Hello \n World{% endtrans %}364 {% trans trimmed %}{{ users }} \n user365 {%- pluralize %}{{ users }} \n users{% endtrans %}366 """.encode(367 "ascii"368 )369 ) # make python 3 happy370 assert list(babel_extract(source, ("gettext", "ngettext", "_"), [], {})) == [371 (2, "gettext", u" Hello \n World", []),372 (4, "gettext", u"Hello World", []),373 (6, "ngettext", (u"%(users)s user", u"%(users)s users", None), []),374 ]375376 def test_extract_trimmed_option(self):377 from jinja2.ext import babel_extract378379 source = BytesIO(380 """381 {{ gettext(' Hello \n World') }}382 {% trans %} Hello \n World{% endtrans %}383 {% trans %}{{ users }} \n user384 {%- pluralize %}{{ users }} \n users{% endtrans %}385 """.encode(386 "ascii"387 )388 ) # make python 3 happy389 opts = {"trimmed": "true"}390 assert list(babel_extract(source, ("gettext", "ngettext", "_"), [], opts)) == [391 (2, "gettext", u" Hello \n World", []),392 (4, "gettext", u"Hello World", []),393 (6, "ngettext", (u"%(users)s user", u"%(users)s users", None), []),394 ]395396 def test_comment_extract(self):397 from jinja2.ext import babel_extract398399 source = BytesIO(400 """401 {# trans first #}402 {{ gettext('Hello World') }}403 {% trans %}Hello World{% endtrans %}{# trans second #}404 {#: third #}405 {% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %}406 """.encode(407 "utf-8"408 )409 ) # make python 3 happy410 assert list(411 babel_extract(source, ("gettext", "ngettext", "_"), ["trans", ":"], {})412 ) == [413 (3, "gettext", u"Hello World", ["first"]),414 (4, "gettext", u"Hello World", ["second"]),415 (6, "ngettext", (u"%(users)s user", u"%(users)s users", None), ["third"]),416 ]417418419class TestScope(object):420 def test_basic_scope_behavior(self):421 # This is what the old with statement compiled down to422 class ScopeExt(Extension):423 tags = set(["scope"])424425 def parse(self, parser):426 node = nodes.Scope(lineno=next(parser.stream).lineno)427 assignments = []428 while parser.stream.current.type != "block_end":429 lineno = parser.stream.current.lineno430 if assignments:431 parser.stream.expect("comma")432 target = parser.parse_assign_target()433 parser.stream.expect("assign")434 expr = parser.parse_expression()435 assignments.append(nodes.Assign(target, expr, lineno=lineno))436 node.body = assignments + list(437 parser.parse_statements(("name:endscope",), drop_needle=True)438 )439 return node440441 env = Environment(extensions=[ScopeExt])442 tmpl = env.from_string(443 """\444 {%- scope a=1, b=2, c=b, d=e, e=5 -%}445 {{ a }}|{{ b }}|{{ c }}|{{ d }}|{{ e }}446 {%- endscope -%}447 """448 )449 assert tmpl.render(b=3, e=4) == "1|2|2|4|5"450451452class TestNewstyleInternationalization(object):453 def test_trans(self):454 tmpl = newstyle_i18n_env.get_template("child.html")455 assert tmpl.render(LANGUAGE="de") == "<title>fehlend</title>pass auf"456457 def test_trans_plural(self):458 tmpl = newstyle_i18n_env.get_template("plural.html")459 assert tmpl.render(LANGUAGE="de", user_count=1) == "Ein Benutzer online"460 assert tmpl.render(LANGUAGE="de", user_count=2) == "2 Benutzer online"461462 def test_complex_plural(self):463 tmpl = newstyle_i18n_env.from_string(464 "{% trans foo=42, count=2 %}{{ count }} item{% "465 "pluralize count %}{{ count }} items{% endtrans %}"466 )467 assert tmpl.render() == "2 items"468 pytest.raises(469 TemplateAssertionError,470 i18n_env.from_string,471 "{% trans foo %}...{% pluralize bar %}...{% endtrans %}",472 )473474 def test_trans_stringformatting(self):475 tmpl = newstyle_i18n_env.get_template("stringformat.html")476 assert tmpl.render(LANGUAGE="de", user_count=5) == "Benutzer: 5"477478 def test_newstyle_plural(self):479 tmpl = newstyle_i18n_env.get_template("ngettext.html")480 assert tmpl.render(LANGUAGE="de", apples=1) == "1 Apfel"481 assert tmpl.render(LANGUAGE="de", apples=5) == u"5 Äpfel"482483 def test_autoescape_support(self):484 env = Environment(extensions=["jinja2.ext.autoescape", "jinja2.ext.i18n"])485 env.install_gettext_callables(486 lambda x: u"<strong>Wert: %(name)s</strong>",487 lambda s, p, n: s,488 newstyle=True,489 )490 t = env.from_string(491 '{% autoescape ae %}{{ gettext("foo", name='492 '"<test>") }}{% endautoescape %}'493 )494 assert t.render(ae=True) == "<strong>Wert: <test></strong>"495 assert t.render(ae=False) == "<strong>Wert: <test></strong>"496497 def test_autoescape_macros(self):498 env = Environment(autoescape=False, extensions=["jinja2.ext.autoescape"])499 template = (500 "{% macro m() %}<html>{% endmacro %}"501 "{% autoescape true %}{{ m() }}{% endautoescape %}"502 )503 assert env.from_string(template).render() == "<html>"504505 def test_num_used_twice(self):506 tmpl = newstyle_i18n_env.get_template("ngettext_long.html")507 assert tmpl.render(apples=5, LANGUAGE="de") == u"5 Äpfel"508509 def test_num_called_num(self):510 source = newstyle_i18n_env.compile(511 """512 {% trans num=3 %}{{ num }} apple{% pluralize513 %}{{ num }} apples{% endtrans %}514 """,515 raw=True,516 )517 # quite hacky, but the only way to properly test that. The idea is518 # that the generated code does not pass num twice (although that519 # would work) for better performance. This only works on the520 # newstyle gettext of course521 assert (522 re.search(r"u?'\%\(num\)s apple', u?'\%\(num\)s " r"apples', 3", source)523 is not None524 )525526 def test_trans_vars(self):527 t1 = newstyle_i18n_env.get_template("transvars1.html")528 t2 = newstyle_i18n_env.get_template("transvars2.html")529 t3 = newstyle_i18n_env.get_template("transvars3.html")530 assert t1.render(num=1, LANGUAGE="de") == "Benutzer: 1"531 assert t2.render(count=23, LANGUAGE="de") == "Benutzer: 23"532 assert t3.render(num=42, LANGUAGE="de") == "Benutzer: 42"533534 def test_novars_vars_escaping(self):535 t = newstyle_i18n_env.get_template("novars.html")536 assert t.render() == "%(hello)s"537 t = newstyle_i18n_env.get_template("vars.html")538 assert t.render(foo="42") == "42%(foo)s"539 t = newstyle_i18n_env.get_template("explicitvars.html")540 assert t.render() == "%(foo)s"541542543class TestAutoEscape(object):544 def test_scoped_setting(self):545 env = Environment(extensions=["jinja2.ext.autoescape"], autoescape=True)546 tmpl = env.from_string(547 """548 {{ "<HelloWorld>" }}549 {% autoescape false %}550 {{ "<HelloWorld>" }}551 {% endautoescape %}552 {{ "<HelloWorld>" }}553 """554 )555 assert tmpl.render().split() == [556 u"<HelloWorld>",557 u"<HelloWorld>",558 u"<HelloWorld>",559 ]560561 env = Environment(extensions=["jinja2.ext.autoescape"], autoescape=False)562 tmpl = env.from_string(563 """564 {{ "<HelloWorld>" }}565 {% autoescape true %}566 {{ "<HelloWorld>" }}567 {% endautoescape %}568 {{ "<HelloWorld>" }}569 """570 )571 assert tmpl.render().split() == [572 u"<HelloWorld>",573 u"<HelloWorld>",574 u"<HelloWorld>",575 ]576577 def test_nonvolatile(self):578 env = Environment(extensions=["jinja2.ext.autoescape"], autoescape=True)579 tmpl = env.from_string('{{ {"foo": "<test>"}|xmlattr|escape }}')580 assert tmpl.render() == ' foo="<test>"'581 tmpl = env.from_string(582 '{% autoescape false %}{{ {"foo": "<test>"}'583 "|xmlattr|escape }}{% endautoescape %}"584 )585 assert tmpl.render() == " foo="&lt;test&gt;""586587 def test_volatile(self):588 env = Environment(extensions=["jinja2.ext.autoescape"], autoescape=True)589 tmpl = env.from_string(590 '{% autoescape foo %}{{ {"foo": "<test>"}'591 "|xmlattr|escape }}{% endautoescape %}"592 )593 assert tmpl.render(foo=False) == " foo="&lt;test&gt;""594 assert tmpl.render(foo=True) == ' foo="<test>"'595596 def test_scoping(self):597 env = Environment(extensions=["jinja2.ext.autoescape"])598 tmpl = env.from_string(599 '{% autoescape true %}{% set x = "<x>" %}{{ x }}'600 '{% endautoescape %}{{ x }}{{ "<y>" }}'601 )602 assert tmpl.render(x=1) == "<x>1<y>"603604 def test_volatile_scoping(self):605 env = Environment(extensions=["jinja2.ext.autoescape"])606 tmplsource = """607 {% autoescape val %}608 {% macro foo(x) %}609 [{{ x }}]610 {% endmacro %}611 {{ foo().__class__.__name__ }}612 {% endautoescape %}613 {{ '<testing>' }}614 """615 tmpl = env.from_string(tmplsource)616 assert tmpl.render(val=True).split()[0] == "Markup"617 assert tmpl.render(val=False).split()[0] == text_type.__name__618619 # looking at the source we should see <testing> there in raw620 # (and then escaped as well)621 env = Environment(extensions=["jinja2.ext.autoescape"])622 pysource = env.compile(tmplsource, raw=True)623 assert "<testing>\\n" in pysource624625 env = Environment(extensions=["jinja2.ext.autoescape"], autoescape=True)626 pysource = env.compile(tmplsource, raw=True)627 assert "<testing>\\n" in pysource628629 def test_overlay_scopes(self):630 class MagicScopeExtension(Extension):631 tags = set(["overlay"])632633 def parse(self, parser):634 node = nodes.OverlayScope(lineno=next(parser.stream).lineno)635 node.body = list(636 parser.parse_statements(("name:endoverlay",), drop_needle=True)637 )638 node.context = self.call_method("get_scope")639 return node640641 def get_scope(self):642 return {"x": [1, 2, 3]}643644 env = Environment(extensions=[MagicScopeExtension])645646 tmpl = env.from_string(647 """648 {{- x }}|{% set z = 99 %}649 {%- overlay %}650 {{- y }}|{{ z }}|{% for item in x %}[{{ item }}]{% endfor %}651 {%- endoverlay %}|652 {{- x -}}653 """654 )655 assert tmpl.render(x=42, y=23) == "42|23|99|[1][2][3]|42"