test_async.py
This file
Path
tests/test_async.py
660 lines · 21.7 KiB · Python
Last changed by
Merge pull request #1614 from pallets/async-env-filterDavid Lordbefore adoption20eb7f5
History of this fileTake it
1import asyncio23import pytest45from jinja2 import ChainableUndefined6from jinja2 import DictLoader7from jinja2 import Environment8from jinja2 import Template9from jinja2.async_utils import auto_aiter10from jinja2.exceptions import TemplateNotFound11from jinja2.exceptions import TemplatesNotFound12from jinja2.exceptions import UndefinedError13from jinja2.nativetypes import NativeEnvironment141516def test_basic_async():17 t = Template(18 "{% for item in [1, 2, 3] %}[{{ item }}]{% endfor %}", enable_async=True19 )2021 async def func():22 return await t.render_async()2324 rv = asyncio.run(func())25 assert rv == "[1][2][3]"262728def test_await_on_calls():29 t = Template("{{ async_func() + normal_func() }}", enable_async=True)3031 async def async_func():32 return 423334 def normal_func():35 return 233637 async def func():38 return await t.render_async(async_func=async_func, normal_func=normal_func)3940 rv = asyncio.run(func())41 assert rv == "65"424344def test_await_on_calls_normal_render():45 t = Template("{{ async_func() + normal_func() }}", enable_async=True)4647 async def async_func():48 return 424950 def normal_func():51 return 235253 rv = t.render(async_func=async_func, normal_func=normal_func)54 assert rv == "65"555657def test_await_and_macros():58 t = Template(59 "{% macro foo(x) %}[{{ x }}][{{ async_func() }}]{% endmacro %}{{ foo(42) }}",60 enable_async=True,61 )6263 async def async_func():64 return 426566 async def func():67 return await t.render_async(async_func=async_func)6869 rv = asyncio.run(func())70 assert rv == "[42][42]"717273def test_async_blocks():74 t = Template(75 "{% block foo %}<Test>{% endblock %}{{ self.foo() }}",76 enable_async=True,77 autoescape=True,78 )7980 async def func():81 return await t.render_async()8283 rv = asyncio.run(func())84 assert rv == "<Test><Test>"858687def test_async_generate():88 t = Template("{% for x in [1, 2, 3] %}{{ x }}{% endfor %}", enable_async=True)89 rv = list(t.generate())90 assert rv == ["1", "2", "3"]919293def test_async_iteration_in_templates():94 t = Template("{% for x in rng %}{{ x }}{% endfor %}", enable_async=True)9596 async def async_iterator():97 for item in [1, 2, 3]:98 yield item99100 rv = list(t.generate(rng=async_iterator()))101 assert rv == ["1", "2", "3"]102103104def test_async_iteration_in_templates_extended():105 t = Template(106 "{% for x in rng %}{{ loop.index0 }}/{{ x }}{% endfor %}", enable_async=True107 )108 stream = t.generate(rng=auto_aiter(range(1, 4)))109 assert next(stream) == "0"110 assert "".join(stream) == "/11/22/3"111112113@pytest.fixture114def test_env_async():115 env = Environment(116 loader=DictLoader(117 dict(118 module="{% macro test() %}[{{ foo }}|{{ bar }}]{% endmacro %}",119 header="[{{ foo }}|{{ 23 }}]",120 o_printer="({{ o }})",121 )122 ),123 enable_async=True,124 )125 env.globals["bar"] = 23126 return env127128129class TestAsyncImports:130 def test_context_imports(self, test_env_async):131 t = test_env_async.from_string('{% import "module" as m %}{{ m.test() }}')132 assert t.render(foo=42) == "[|23]"133 t = test_env_async.from_string(134 '{% import "module" as m without context %}{{ m.test() }}'135 )136 assert t.render(foo=42) == "[|23]"137 t = test_env_async.from_string(138 '{% import "module" as m with context %}{{ m.test() }}'139 )140 assert t.render(foo=42) == "[42|23]"141 t = test_env_async.from_string('{% from "module" import test %}{{ test() }}')142 assert t.render(foo=42) == "[|23]"143 t = test_env_async.from_string(144 '{% from "module" import test without context %}{{ test() }}'145 )146 assert t.render(foo=42) == "[|23]"147 t = test_env_async.from_string(148 '{% from "module" import test with context %}{{ test() }}'149 )150 assert t.render(foo=42) == "[42|23]"151152 def test_trailing_comma(self, test_env_async):153 test_env_async.from_string('{% from "foo" import bar, baz with context %}')154 test_env_async.from_string('{% from "foo" import bar, baz, with context %}')155 test_env_async.from_string('{% from "foo" import bar, with context %}')156 test_env_async.from_string('{% from "foo" import bar, with, context %}')157 test_env_async.from_string('{% from "foo" import bar, with with context %}')158159 def test_exports(self, test_env_async):160 coro = test_env_async.from_string(161 """162 {% macro toplevel() %}...{% endmacro %}163 {% macro __private() %}...{% endmacro %}164 {% set variable = 42 %}165 {% for item in [1] %}166 {% macro notthere() %}{% endmacro %}167 {% endfor %}168 """169 )._get_default_module_async()170 m = asyncio.run(coro)171 assert asyncio.run(m.toplevel()) == "..."172 assert not hasattr(m, "__missing")173 assert m.variable == 42174 assert not hasattr(m, "notthere")175176 def test_import_with_globals(self, test_env_async):177 t = test_env_async.from_string(178 '{% import "module" as m %}{{ m.test() }}', globals={"foo": 42}179 )180 assert t.render() == "[42|23]"181182 t = test_env_async.from_string('{% import "module" as m %}{{ m.test() }}')183 assert t.render() == "[|23]"184185 def test_import_with_globals_override(self, test_env_async):186 t = test_env_async.from_string(187 '{% set foo = 41 %}{% import "module" as m %}{{ m.test() }}',188 globals={"foo": 42},189 )190 assert t.render() == "[42|23]"191192 def test_from_import_with_globals(self, test_env_async):193 t = test_env_async.from_string(194 '{% from "module" import test %}{{ test() }}',195 globals={"foo": 42},196 )197 assert t.render() == "[42|23]"198199200class TestAsyncIncludes:201 def test_context_include(self, test_env_async):202 t = test_env_async.from_string('{% include "header" %}')203 assert t.render(foo=42) == "[42|23]"204 t = test_env_async.from_string('{% include "header" with context %}')205 assert t.render(foo=42) == "[42|23]"206 t = test_env_async.from_string('{% include "header" without context %}')207 assert t.render(foo=42) == "[|23]"208209 def test_choice_includes(self, test_env_async):210 t = test_env_async.from_string('{% include ["missing", "header"] %}')211 assert t.render(foo=42) == "[42|23]"212213 t = test_env_async.from_string(214 '{% include ["missing", "missing2"] ignore missing %}'215 )216 assert t.render(foo=42) == ""217218 t = test_env_async.from_string('{% include ["missing", "missing2"] %}')219 pytest.raises(TemplateNotFound, t.render)220 with pytest.raises(TemplatesNotFound) as e:221 t.render()222223 assert e.value.templates == ["missing", "missing2"]224 assert e.value.name == "missing2"225226 def test_includes(t, **ctx):227 ctx["foo"] = 42228 assert t.render(ctx) == "[42|23]"229230 t = test_env_async.from_string('{% include ["missing", "header"] %}')231 test_includes(t)232 t = test_env_async.from_string("{% include x %}")233 test_includes(t, x=["missing", "header"])234 t = test_env_async.from_string('{% include [x, "header"] %}')235 test_includes(t, x="missing")236 t = test_env_async.from_string("{% include x %}")237 test_includes(t, x="header")238 t = test_env_async.from_string("{% include x %}")239 test_includes(t, x="header")240 t = test_env_async.from_string("{% include [x] %}")241 test_includes(t, x="header")242243 def test_include_ignoring_missing(self, test_env_async):244 t = test_env_async.from_string('{% include "missing" %}')245 pytest.raises(TemplateNotFound, t.render)246 for extra in "", "with context", "without context":247 t = test_env_async.from_string(248 '{% include "missing" ignore missing ' + extra + " %}"249 )250 assert t.render() == ""251252 def test_context_include_with_overrides(self, test_env_async):253 env = Environment(254 loader=DictLoader(255 dict(256 main="{% for item in [1, 2, 3] %}{% include 'item' %}{% endfor %}",257 item="{{ item }}",258 )259 )260 )261 assert env.get_template("main").render() == "123"262263 def test_unoptimized_scopes(self, test_env_async):264 t = test_env_async.from_string(265 """266 {% macro outer(o) %}267 {% macro inner() %}268 {% include "o_printer" %}269 {% endmacro %}270 {{ inner() }}271 {% endmacro %}272 {{ outer("FOO") }}273 """274 )275 assert t.render().strip() == "(FOO)"276277 def test_unoptimized_scopes_autoescape(self):278 env = Environment(279 loader=DictLoader({"o_printer": "({{ o }})"}),280 autoescape=True,281 enable_async=True,282 )283 t = env.from_string(284 """285 {% macro outer(o) %}286 {% macro inner() %}287 {% include "o_printer" %}288 {% endmacro %}289 {{ inner() }}290 {% endmacro %}291 {{ outer("FOO") }}292 """293 )294 assert t.render().strip() == "(FOO)"295296297class TestAsyncForLoop:298 def test_simple(self, test_env_async):299 tmpl = test_env_async.from_string("{% for item in seq %}{{ item }}{% endfor %}")300 assert tmpl.render(seq=list(range(10))) == "0123456789"301302 def test_else(self, test_env_async):303 tmpl = test_env_async.from_string(304 "{% for item in seq %}XXX{% else %}...{% endfor %}"305 )306 assert tmpl.render() == "..."307308 def test_empty_blocks(self, test_env_async):309 tmpl = test_env_async.from_string(310 "<{% for item in seq %}{% else %}{% endfor %}>"311 )312 assert tmpl.render() == "<>"313314 @pytest.mark.parametrize(315 "transform", [lambda x: x, iter, reversed, lambda x: (i for i in x), auto_aiter]316 )317 def test_context_vars(self, test_env_async, transform):318 t = test_env_async.from_string(319 "{% for item in seq %}{{ loop.index }}|{{ loop.index0 }}"320 "|{{ loop.revindex }}|{{ loop.revindex0 }}|{{ loop.first }}"321 "|{{ loop.last }}|{{ loop.length }}\n{% endfor %}"322 )323 out = t.render(seq=transform([42, 24]))324 assert out == "1|0|2|1|True|False|2\n2|1|1|0|False|True|2\n"325326 def test_cycling(self, test_env_async):327 tmpl = test_env_async.from_string(328 """{% for item in seq %}{{329 loop.cycle('<1>', '<2>') }}{% endfor %}{%330 for item in seq %}{{ loop.cycle(*through) }}{% endfor %}"""331 )332 output = tmpl.render(seq=list(range(4)), through=("<1>", "<2>"))333 assert output == "<1><2>" * 4334335 def test_lookaround(self, test_env_async):336 tmpl = test_env_async.from_string(337 """{% for item in seq -%}338 {{ loop.previtem|default('x') }}-{{ item }}-{{339 loop.nextitem|default('x') }}|340 {%- endfor %}"""341 )342 output = tmpl.render(seq=list(range(4)))343 assert output == "x-0-1|0-1-2|1-2-3|2-3-x|"344345 def test_changed(self, test_env_async):346 tmpl = test_env_async.from_string(347 """{% for item in seq -%}348 {{ loop.changed(item) }},349 {%- endfor %}"""350 )351 output = tmpl.render(seq=[None, None, 1, 2, 2, 3, 4, 4, 4])352 assert output == "True,False,True,True,False,True,True,False,False,"353354 def test_scope(self, test_env_async):355 tmpl = test_env_async.from_string("{% for item in seq %}{% endfor %}{{ item }}")356 output = tmpl.render(seq=list(range(10)))357 assert not output358359 def test_varlen(self, test_env_async):360 def inner():361 yield from range(5)362363 tmpl = test_env_async.from_string(364 "{% for item in iter %}{{ item }}{% endfor %}"365 )366 output = tmpl.render(iter=inner())367 assert output == "01234"368369 def test_noniter(self, test_env_async):370 tmpl = test_env_async.from_string("{% for item in none %}...{% endfor %}")371 pytest.raises(TypeError, tmpl.render)372373 def test_recursive(self, test_env_async):374 tmpl = test_env_async.from_string(375 """{% for item in seq recursive -%}376 [{{ item.a }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]377 {%- endfor %}"""378 )379 assert (380 tmpl.render(381 seq=[382 dict(a=1, b=[dict(a=1), dict(a=2)]),383 dict(a=2, b=[dict(a=1), dict(a=2)]),384 dict(a=3, b=[dict(a="a")]),385 ]386 )387 == "[1<[1][2]>][2<[1][2]>][3<[a]>]"388 )389390 def test_recursive_lookaround(self, test_env_async):391 tmpl = test_env_async.from_string(392 """{% for item in seq recursive -%}393 [{{ loop.previtem.a if loop.previtem is defined else 'x' }}.{{394 item.a }}.{{ loop.nextitem.a if loop.nextitem is defined else 'x'395 }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]396 {%- endfor %}"""397 )398 assert (399 tmpl.render(400 seq=[401 dict(a=1, b=[dict(a=1), dict(a=2)]),402 dict(a=2, b=[dict(a=1), dict(a=2)]),403 dict(a=3, b=[dict(a="a")]),404 ]405 )406 == "[x.1.2<[x.1.2][1.2.x]>][1.2.3<[x.1.2][1.2.x]>][2.3.x<[x.a.x]>]"407 )408409 def test_recursive_depth0(self, test_env_async):410 tmpl = test_env_async.from_string(411 "{% for item in seq recursive %}[{{ loop.depth0 }}:{{ item.a }}"412 "{% if item.b %}<{{ loop(item.b) }}>{% endif %}]{% endfor %}"413 )414 assert (415 tmpl.render(416 seq=[417 dict(a=1, b=[dict(a=1), dict(a=2)]),418 dict(a=2, b=[dict(a=1), dict(a=2)]),419 dict(a=3, b=[dict(a="a")]),420 ]421 )422 == "[0:1<[1:1][1:2]>][0:2<[1:1][1:2]>][0:3<[1:a]>]"423 )424425 def test_recursive_depth(self, test_env_async):426 tmpl = test_env_async.from_string(427 "{% for item in seq recursive %}[{{ loop.depth }}:{{ item.a }}"428 "{% if item.b %}<{{ loop(item.b) }}>{% endif %}]{% endfor %}"429 )430 assert (431 tmpl.render(432 seq=[433 dict(a=1, b=[dict(a=1), dict(a=2)]),434 dict(a=2, b=[dict(a=1), dict(a=2)]),435 dict(a=3, b=[dict(a="a")]),436 ]437 )438 == "[1:1<[2:1][2:2]>][1:2<[2:1][2:2]>][1:3<[2:a]>]"439 )440441 def test_looploop(self, test_env_async):442 tmpl = test_env_async.from_string(443 """{% for row in table %}444 {%- set rowloop = loop -%}445 {% for cell in row -%}446 [{{ rowloop.index }}|{{ loop.index }}]447 {%- endfor %}448 {%- endfor %}"""449 )450 assert tmpl.render(table=["ab", "cd"]) == "[1|1][1|2][2|1][2|2]"451452 def test_reversed_bug(self, test_env_async):453 tmpl = test_env_async.from_string(454 "{% for i in items %}{{ i }}"455 "{% if not loop.last %}"456 ",{% endif %}{% endfor %}"457 )458 assert tmpl.render(items=reversed([3, 2, 1])) == "1,2,3"459460 def test_loop_errors(self, test_env_async):461 tmpl = test_env_async.from_string(462 """{% for item in [1] if loop.index463 == 0 %}...{% endfor %}"""464 )465 pytest.raises(UndefinedError, tmpl.render)466 tmpl = test_env_async.from_string(467 """{% for item in [] %}...{% else468 %}{{ loop }}{% endfor %}"""469 )470 assert tmpl.render() == ""471472 def test_loop_filter(self, test_env_async):473 tmpl = test_env_async.from_string(474 "{% for item in range(10) if item is even %}[{{ item }}]{% endfor %}"475 )476 assert tmpl.render() == "[0][2][4][6][8]"477 tmpl = test_env_async.from_string(478 """479 {%- for item in range(10) if item is even %}[{{480 loop.index }}:{{ item }}]{% endfor %}"""481 )482 assert tmpl.render() == "[1:0][2:2][3:4][4:6][5:8]"483484 def test_scoped_special_var(self, test_env_async):485 t = test_env_async.from_string(486 "{% for s in seq %}[{{ loop.first }}{% for c in s %}"487 "|{{ loop.first }}{% endfor %}]{% endfor %}"488 )489 assert t.render(seq=("ab", "cd")) == "[True|True|False][False|True|False]"490491 def test_scoped_loop_var(self, test_env_async):492 t = test_env_async.from_string(493 "{% for x in seq %}{{ loop.first }}"494 "{% for y in seq %}{% endfor %}{% endfor %}"495 )496 assert t.render(seq="ab") == "TrueFalse"497 t = test_env_async.from_string(498 "{% for x in seq %}{% for y in seq %}"499 "{{ loop.first }}{% endfor %}{% endfor %}"500 )501 assert t.render(seq="ab") == "TrueFalseTrueFalse"502503 def test_recursive_empty_loop_iter(self, test_env_async):504 t = test_env_async.from_string(505 """506 {%- for item in foo recursive -%}{%- endfor -%}507 """508 )509 assert t.render(dict(foo=[])) == ""510511 def test_call_in_loop(self, test_env_async):512 t = test_env_async.from_string(513 """514 {%- macro do_something() -%}515 [{{ caller() }}]516 {%- endmacro %}517518 {%- for i in [1, 2, 3] %}519 {%- call do_something() -%}520 {{ i }}521 {%- endcall %}522 {%- endfor -%}523 """524 )525 assert t.render() == "[1][2][3]"526527 def test_scoping_bug(self, test_env_async):528 t = test_env_async.from_string(529 """530 {%- for item in foo %}...{{ item }}...{% endfor %}531 {%- macro item(a) %}...{{ a }}...{% endmacro %}532 {{- item(2) -}}533 """534 )535 assert t.render(foo=(1,)) == "...1......2..."536537 def test_unpacking(self, test_env_async):538 tmpl = test_env_async.from_string(539 "{% for a, b, c in [[1, 2, 3]] %}{{ a }}|{{ b }}|{{ c }}{% endfor %}"540 )541 assert tmpl.render() == "1|2|3"542543 def test_recursive_loop_filter(self, test_env_async):544 t = test_env_async.from_string(545 """546 <?xml version="1.0" encoding="UTF-8"?>547 <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">548 {%- for page in [site.root] if page.url != this recursive %}549 <url><loc>{{ page.url }}</loc></url>550 {{- loop(page.children) }}551 {%- endfor %}552 </urlset>553 """554 )555 sm = t.render(556 this="/foo",557 site={"root": {"url": "/", "children": [{"url": "/foo"}, {"url": "/bar"}]}},558 )559 lines = [x.strip() for x in sm.splitlines() if x.strip()]560 assert lines == [561 '<?xml version="1.0" encoding="UTF-8"?>',562 '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',563 "<url><loc>/</loc></url>",564 "<url><loc>/bar</loc></url>",565 "</urlset>",566 ]567568 def test_nonrecursive_loop_filter(self, test_env_async):569 t = test_env_async.from_string(570 """571 <?xml version="1.0" encoding="UTF-8"?>572 <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">573 {%- for page in items if page.url != this %}574 <url><loc>{{ page.url }}</loc></url>575 {%- endfor %}576 </urlset>577 """578 )579 sm = t.render(580 this="/foo", items=[{"url": "/"}, {"url": "/foo"}, {"url": "/bar"}]581 )582 lines = [x.strip() for x in sm.splitlines() if x.strip()]583 assert lines == [584 '<?xml version="1.0" encoding="UTF-8"?>',585 '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',586 "<url><loc>/</loc></url>",587 "<url><loc>/bar</loc></url>",588 "</urlset>",589 ]590591 def test_bare_async(self, test_env_async):592 t = test_env_async.from_string('{% extends "header" %}')593 assert t.render(foo=42) == "[42|23]"594595 def test_awaitable_property_slicing(self, test_env_async):596 t = test_env_async.from_string("{% for x in a.b[:1] %}{{ x }}{% endfor %}")597 assert t.render(a=dict(b=[1, 2, 3])) == "1"598599600def test_namespace_awaitable(test_env_async):601 async def _test():602 t = test_env_async.from_string(603 '{% set ns = namespace(foo="Bar") %}{{ ns.foo }}'604 )605 actual = await t.render_async()606 assert actual == "Bar"607608 asyncio.run(_test())609610611def test_chainable_undefined_aiter():612 async def _test():613 t = Template(614 "{% for x in a['b']['c'] %}{{ x }}{% endfor %}",615 enable_async=True,616 undefined=ChainableUndefined,617 )618 rv = await t.render_async(a={})619 assert rv == ""620621 asyncio.run(_test())622623624@pytest.fixture625def async_native_env():626 return NativeEnvironment(enable_async=True)627628629def test_native_async(async_native_env):630 async def _test():631 t = async_native_env.from_string("{{ x }}")632 rv = await t.render_async(x=23)633 assert rv == 23634635 asyncio.run(_test())636637638def test_native_list_async(async_native_env):639 async def _test():640 t = async_native_env.from_string("{{ x }}")641 rv = await t.render_async(x=list(range(3)))642 assert rv == [0, 1, 2]643644 asyncio.run(_test())645646647def test_getitem_after_filter():648 env = Environment(enable_async=True)649 env.filters["add_each"] = lambda v, x: [i + x for i in v]650 t = env.from_string("{{ (a|add_each(2))[1:] }}")651 out = t.render(a=range(3))652 assert out == "[3, 4]"653654655def test_getitem_after_call():656 env = Environment(enable_async=True)657 env.globals["add_each"] = lambda v, x: [i + x for i in v]658 t = env.from_string("{{ add_each(a, 2)[1:] }}")659 out = t.render(a=range(3))660 assert out == "[3, 4]"