test_async.py
This file
Path
tests/test_async.py
591 lines · 19.6 KiB · Python
Last changed by
Merge pull request #1181 from bartfeenstra/async-namespaceDavid Lordbefore adoption786867a
History of this fileTake it
1import asyncio23import pytest45from jinja2 import DictLoader6from jinja2 import Environment7from jinja2 import Template8from jinja2.asyncsupport import auto_aiter9from jinja2.exceptions import TemplateNotFound10from jinja2.exceptions import TemplatesNotFound11from jinja2.exceptions import UndefinedError121314def run(coro):15 loop = asyncio.get_event_loop()16 return loop.run_until_complete(coro)171819def test_basic_async():20 t = Template(21 "{% for item in [1, 2, 3] %}[{{ item }}]{% endfor %}", enable_async=True22 )2324 async def func():25 return await t.render_async()2627 rv = run(func())28 assert rv == "[1][2][3]"293031def test_await_on_calls():32 t = Template("{{ async_func() + normal_func() }}", enable_async=True)3334 async def async_func():35 return 423637 def normal_func():38 return 233940 async def func():41 return await t.render_async(async_func=async_func, normal_func=normal_func)4243 rv = run(func())44 assert rv == "65"454647def test_await_on_calls_normal_render():48 t = Template("{{ async_func() + normal_func() }}", enable_async=True)4950 async def async_func():51 return 425253 def normal_func():54 return 235556 rv = t.render(async_func=async_func, normal_func=normal_func)5758 assert rv == "65"596061def test_await_and_macros():62 t = Template(63 "{% macro foo(x) %}[{{ x }}][{{ async_func() }}]{% endmacro %}{{ foo(42) }}",64 enable_async=True,65 )6667 async def async_func():68 return 426970 async def func():71 return await t.render_async(async_func=async_func)7273 rv = run(func())74 assert rv == "[42][42]"757677def test_async_blocks():78 t = Template(79 "{% block foo %}<Test>{% endblock %}{{ self.foo() }}",80 enable_async=True,81 autoescape=True,82 )8384 async def func():85 return await t.render_async()8687 rv = run(func())88 assert rv == "<Test><Test>"899091def test_async_generate():92 t = Template("{% for x in [1, 2, 3] %}{{ x }}{% endfor %}", enable_async=True)93 rv = list(t.generate())94 assert rv == ["1", "2", "3"]959697def test_async_iteration_in_templates():98 t = Template("{% for x in rng %}{{ x }}{% endfor %}", enable_async=True)99100 async def async_iterator():101 for item in [1, 2, 3]:102 yield item103104 rv = list(t.generate(rng=async_iterator()))105 assert rv == ["1", "2", "3"]106107108def test_async_iteration_in_templates_extended():109 t = Template(110 "{% for x in rng %}{{ loop.index0 }}/{{ x }}{% endfor %}", enable_async=True111 )112 stream = t.generate(rng=auto_aiter(range(1, 4)))113 assert next(stream) == "0"114 assert "".join(stream) == "/11/22/3"115116117@pytest.fixture118def test_env_async():119 env = Environment(120 loader=DictLoader(121 dict(122 module="{% macro test() %}[{{ foo }}|{{ bar }}]{% endmacro %}",123 header="[{{ foo }}|{{ 23 }}]",124 o_printer="({{ o }})",125 )126 ),127 enable_async=True,128 )129 env.globals["bar"] = 23130 return env131132133class TestAsyncImports(object):134 def test_context_imports(self, test_env_async):135 t = test_env_async.from_string('{% import "module" as m %}{{ m.test() }}')136 assert t.render(foo=42) == "[|23]"137 t = test_env_async.from_string(138 '{% import "module" as m without context %}{{ m.test() }}'139 )140 assert t.render(foo=42) == "[|23]"141 t = test_env_async.from_string(142 '{% import "module" as m with context %}{{ m.test() }}'143 )144 assert t.render(foo=42) == "[42|23]"145 t = test_env_async.from_string('{% from "module" import test %}{{ test() }}')146 assert t.render(foo=42) == "[|23]"147 t = test_env_async.from_string(148 '{% from "module" import test without context %}{{ test() }}'149 )150 assert t.render(foo=42) == "[|23]"151 t = test_env_async.from_string(152 '{% from "module" import test with context %}{{ test() }}'153 )154 assert t.render(foo=42) == "[42|23]"155156 def test_trailing_comma(self, test_env_async):157 test_env_async.from_string('{% from "foo" import bar, baz with context %}')158 test_env_async.from_string('{% from "foo" import bar, baz, with context %}')159 test_env_async.from_string('{% from "foo" import bar, with context %}')160 test_env_async.from_string('{% from "foo" import bar, with, context %}')161 test_env_async.from_string('{% from "foo" import bar, with with context %}')162163 def test_exports(self, test_env_async):164 m = run(165 test_env_async.from_string(166 """167 {% macro toplevel() %}...{% endmacro %}168 {% macro __private() %}...{% endmacro %}169 {% set variable = 42 %}170 {% for item in [1] %}171 {% macro notthere() %}{% endmacro %}172 {% endfor %}173 """174 )._get_default_module_async()175 )176 assert run(m.toplevel()) == "..."177 assert not hasattr(m, "__missing")178 assert m.variable == 42179 assert not hasattr(m, "notthere")180181182class TestAsyncIncludes(object):183 def test_context_include(self, test_env_async):184 t = test_env_async.from_string('{% include "header" %}')185 assert t.render(foo=42) == "[42|23]"186 t = test_env_async.from_string('{% include "header" with context %}')187 assert t.render(foo=42) == "[42|23]"188 t = test_env_async.from_string('{% include "header" without context %}')189 assert t.render(foo=42) == "[|23]"190191 def test_choice_includes(self, test_env_async):192 t = test_env_async.from_string('{% include ["missing", "header"] %}')193 assert t.render(foo=42) == "[42|23]"194195 t = test_env_async.from_string(196 '{% include ["missing", "missing2"] ignore missing %}'197 )198 assert t.render(foo=42) == ""199200 t = test_env_async.from_string('{% include ["missing", "missing2"] %}')201 pytest.raises(TemplateNotFound, t.render)202 with pytest.raises(TemplatesNotFound) as e:203 t.render()204205 assert e.value.templates == ["missing", "missing2"]206 assert e.value.name == "missing2"207208 def test_includes(t, **ctx):209 ctx["foo"] = 42210 assert t.render(ctx) == "[42|23]"211212 t = test_env_async.from_string('{% include ["missing", "header"] %}')213 test_includes(t)214 t = test_env_async.from_string("{% include x %}")215 test_includes(t, x=["missing", "header"])216 t = test_env_async.from_string('{% include [x, "header"] %}')217 test_includes(t, x="missing")218 t = test_env_async.from_string("{% include x %}")219 test_includes(t, x="header")220 t = test_env_async.from_string("{% include x %}")221 test_includes(t, x="header")222 t = test_env_async.from_string("{% include [x] %}")223 test_includes(t, x="header")224225 def test_include_ignoring_missing(self, test_env_async):226 t = test_env_async.from_string('{% include "missing" %}')227 pytest.raises(TemplateNotFound, t.render)228 for extra in "", "with context", "without context":229 t = test_env_async.from_string(230 '{% include "missing" ignore missing ' + extra + " %}"231 )232 assert t.render() == ""233234 def test_context_include_with_overrides(self, test_env_async):235 env = Environment(236 loader=DictLoader(237 dict(238 main="{% for item in [1, 2, 3] %}{% include 'item' %}{% endfor %}",239 item="{{ item }}",240 )241 )242 )243 assert env.get_template("main").render() == "123"244245 def test_unoptimized_scopes(self, test_env_async):246 t = test_env_async.from_string(247 """248 {% macro outer(o) %}249 {% macro inner() %}250 {% include "o_printer" %}251 {% endmacro %}252 {{ inner() }}253 {% endmacro %}254 {{ outer("FOO") }}255 """256 )257 assert t.render().strip() == "(FOO)"258259 def test_unoptimized_scopes_autoescape(self):260 env = Environment(261 loader=DictLoader(dict(o_printer="({{ o }})",)),262 autoescape=True,263 enable_async=True,264 )265 t = env.from_string(266 """267 {% macro outer(o) %}268 {% macro inner() %}269 {% include "o_printer" %}270 {% endmacro %}271 {{ inner() }}272 {% endmacro %}273 {{ outer("FOO") }}274 """275 )276 assert t.render().strip() == "(FOO)"277278279class TestAsyncForLoop(object):280 def test_simple(self, test_env_async):281 tmpl = test_env_async.from_string("{% for item in seq %}{{ item }}{% endfor %}")282 assert tmpl.render(seq=list(range(10))) == "0123456789"283284 def test_else(self, test_env_async):285 tmpl = test_env_async.from_string(286 "{% for item in seq %}XXX{% else %}...{% endfor %}"287 )288 assert tmpl.render() == "..."289290 def test_empty_blocks(self, test_env_async):291 tmpl = test_env_async.from_string(292 "<{% for item in seq %}{% else %}{% endfor %}>"293 )294 assert tmpl.render() == "<>"295296 @pytest.mark.parametrize(297 "transform", [lambda x: x, iter, reversed, lambda x: (i for i in x), auto_aiter]298 )299 def test_context_vars(self, test_env_async, transform):300 t = test_env_async.from_string(301 "{% for item in seq %}{{ loop.index }}|{{ loop.index0 }}"302 "|{{ loop.revindex }}|{{ loop.revindex0 }}|{{ loop.first }}"303 "|{{ loop.last }}|{{ loop.length }}\n{% endfor %}"304 )305 out = t.render(seq=transform([42, 24]))306 assert out == "1|0|2|1|True|False|2\n2|1|1|0|False|True|2\n"307308 def test_cycling(self, test_env_async):309 tmpl = test_env_async.from_string(310 """{% for item in seq %}{{311 loop.cycle('<1>', '<2>') }}{% endfor %}{%312 for item in seq %}{{ loop.cycle(*through) }}{% endfor %}"""313 )314 output = tmpl.render(seq=list(range(4)), through=("<1>", "<2>"))315 assert output == "<1><2>" * 4316317 def test_lookaround(self, test_env_async):318 tmpl = test_env_async.from_string(319 """{% for item in seq -%}320 {{ loop.previtem|default('x') }}-{{ item }}-{{321 loop.nextitem|default('x') }}|322 {%- endfor %}"""323 )324 output = tmpl.render(seq=list(range(4)))325 assert output == "x-0-1|0-1-2|1-2-3|2-3-x|"326327 def test_changed(self, test_env_async):328 tmpl = test_env_async.from_string(329 """{% for item in seq -%}330 {{ loop.changed(item) }},331 {%- endfor %}"""332 )333 output = tmpl.render(seq=[None, None, 1, 2, 2, 3, 4, 4, 4])334 assert output == "True,False,True,True,False,True,True,False,False,"335336 def test_scope(self, test_env_async):337 tmpl = test_env_async.from_string("{% for item in seq %}{% endfor %}{{ item }}")338 output = tmpl.render(seq=list(range(10)))339 assert not output340341 def test_varlen(self, test_env_async):342 def inner():343 for item in range(5):344 yield item345346 tmpl = test_env_async.from_string(347 "{% for item in iter %}{{ item }}{% endfor %}"348 )349 output = tmpl.render(iter=inner())350 assert output == "01234"351352 def test_noniter(self, test_env_async):353 tmpl = test_env_async.from_string("{% for item in none %}...{% endfor %}")354 pytest.raises(TypeError, tmpl.render)355356 def test_recursive(self, test_env_async):357 tmpl = test_env_async.from_string(358 """{% for item in seq recursive -%}359 [{{ item.a }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]360 {%- endfor %}"""361 )362 assert (363 tmpl.render(364 seq=[365 dict(a=1, b=[dict(a=1), dict(a=2)]),366 dict(a=2, b=[dict(a=1), dict(a=2)]),367 dict(a=3, b=[dict(a="a")]),368 ]369 )370 == "[1<[1][2]>][2<[1][2]>][3<[a]>]"371 )372373 def test_recursive_lookaround(self, test_env_async):374 tmpl = test_env_async.from_string(375 """{% for item in seq recursive -%}376 [{{ loop.previtem.a if loop.previtem is defined else 'x' }}.{{377 item.a }}.{{ loop.nextitem.a if loop.nextitem is defined else 'x'378 }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]379 {%- endfor %}"""380 )381 assert (382 tmpl.render(383 seq=[384 dict(a=1, b=[dict(a=1), dict(a=2)]),385 dict(a=2, b=[dict(a=1), dict(a=2)]),386 dict(a=3, b=[dict(a="a")]),387 ]388 )389 == "[x.1.2<[x.1.2][1.2.x]>][1.2.3<[x.1.2][1.2.x]>][2.3.x<[x.a.x]>]"390 )391392 def test_recursive_depth0(self, test_env_async):393 tmpl = test_env_async.from_string(394 "{% for item in seq recursive %}[{{ loop.depth0 }}:{{ item.a }}"395 "{% if item.b %}<{{ loop(item.b) }}>{% endif %}]{% endfor %}"396 )397 assert (398 tmpl.render(399 seq=[400 dict(a=1, b=[dict(a=1), dict(a=2)]),401 dict(a=2, b=[dict(a=1), dict(a=2)]),402 dict(a=3, b=[dict(a="a")]),403 ]404 )405 == "[0:1<[1:1][1:2]>][0:2<[1:1][1:2]>][0:3<[1:a]>]"406 )407408 def test_recursive_depth(self, test_env_async):409 tmpl = test_env_async.from_string(410 "{% for item in seq recursive %}[{{ loop.depth }}:{{ item.a }}"411 "{% if item.b %}<{{ loop(item.b) }}>{% endif %}]{% endfor %}"412 )413 assert (414 tmpl.render(415 seq=[416 dict(a=1, b=[dict(a=1), dict(a=2)]),417 dict(a=2, b=[dict(a=1), dict(a=2)]),418 dict(a=3, b=[dict(a="a")]),419 ]420 )421 == "[1:1<[2:1][2:2]>][1:2<[2:1][2:2]>][1:3<[2:a]>]"422 )423424 def test_looploop(self, test_env_async):425 tmpl = test_env_async.from_string(426 """{% for row in table %}427 {%- set rowloop = loop -%}428 {% for cell in row -%}429 [{{ rowloop.index }}|{{ loop.index }}]430 {%- endfor %}431 {%- endfor %}"""432 )433 assert tmpl.render(table=["ab", "cd"]) == "[1|1][1|2][2|1][2|2]"434435 def test_reversed_bug(self, test_env_async):436 tmpl = test_env_async.from_string(437 "{% for i in items %}{{ i }}"438 "{% if not loop.last %}"439 ",{% endif %}{% endfor %}"440 )441 assert tmpl.render(items=reversed([3, 2, 1])) == "1,2,3"442443 def test_loop_errors(self, test_env_async):444 tmpl = test_env_async.from_string(445 """{% for item in [1] if loop.index446 == 0 %}...{% endfor %}"""447 )448 pytest.raises(UndefinedError, tmpl.render)449 tmpl = test_env_async.from_string(450 """{% for item in [] %}...{% else451 %}{{ loop }}{% endfor %}"""452 )453 assert tmpl.render() == ""454455 def test_loop_filter(self, test_env_async):456 tmpl = test_env_async.from_string(457 "{% for item in range(10) if item is even %}[{{ item }}]{% endfor %}"458 )459 assert tmpl.render() == "[0][2][4][6][8]"460 tmpl = test_env_async.from_string(461 """462 {%- for item in range(10) if item is even %}[{{463 loop.index }}:{{ item }}]{% endfor %}"""464 )465 assert tmpl.render() == "[1:0][2:2][3:4][4:6][5:8]"466467 def test_scoped_special_var(self, test_env_async):468 t = test_env_async.from_string(469 "{% for s in seq %}[{{ loop.first }}{% for c in s %}"470 "|{{ loop.first }}{% endfor %}]{% endfor %}"471 )472 assert t.render(seq=("ab", "cd")) == "[True|True|False][False|True|False]"473474 def test_scoped_loop_var(self, test_env_async):475 t = test_env_async.from_string(476 "{% for x in seq %}{{ loop.first }}"477 "{% for y in seq %}{% endfor %}{% endfor %}"478 )479 assert t.render(seq="ab") == "TrueFalse"480 t = test_env_async.from_string(481 "{% for x in seq %}{% for y in seq %}"482 "{{ loop.first }}{% endfor %}{% endfor %}"483 )484 assert t.render(seq="ab") == "TrueFalseTrueFalse"485486 def test_recursive_empty_loop_iter(self, test_env_async):487 t = test_env_async.from_string(488 """489 {%- for item in foo recursive -%}{%- endfor -%}490 """491 )492 assert t.render(dict(foo=[])) == ""493494 def test_call_in_loop(self, test_env_async):495 t = test_env_async.from_string(496 """497 {%- macro do_something() -%}498 [{{ caller() }}]499 {%- endmacro %}500501 {%- for i in [1, 2, 3] %}502 {%- call do_something() -%}503 {{ i }}504 {%- endcall %}505 {%- endfor -%}506 """507 )508 assert t.render() == "[1][2][3]"509510 def test_scoping_bug(self, test_env_async):511 t = test_env_async.from_string(512 """513 {%- for item in foo %}...{{ item }}...{% endfor %}514 {%- macro item(a) %}...{{ a }}...{% endmacro %}515 {{- item(2) -}}516 """517 )518 assert t.render(foo=(1,)) == "...1......2..."519520 def test_unpacking(self, test_env_async):521 tmpl = test_env_async.from_string(522 "{% for a, b, c in [[1, 2, 3]] %}{{ a }}|{{ b }}|{{ c }}{% endfor %}"523 )524 assert tmpl.render() == "1|2|3"525526 def test_recursive_loop_filter(self, test_env_async):527 t = test_env_async.from_string(528 """529 <?xml version="1.0" encoding="UTF-8"?>530 <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">531 {%- for page in [site.root] if page.url != this recursive %}532 <url><loc>{{ page.url }}</loc></url>533 {{- loop(page.children) }}534 {%- endfor %}535 </urlset>536 """537 )538 sm = t.render(539 this="/foo",540 site={"root": {"url": "/", "children": [{"url": "/foo"}, {"url": "/bar"}]}},541 )542 lines = [x.strip() for x in sm.splitlines() if x.strip()]543 assert lines == [544 '<?xml version="1.0" encoding="UTF-8"?>',545 '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',546 "<url><loc>/</loc></url>",547 "<url><loc>/bar</loc></url>",548 "</urlset>",549 ]550551 def test_nonrecursive_loop_filter(self, test_env_async):552 t = test_env_async.from_string(553 """554 <?xml version="1.0" encoding="UTF-8"?>555 <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">556 {%- for page in items if page.url != this %}557 <url><loc>{{ page.url }}</loc></url>558 {%- endfor %}559 </urlset>560 """561 )562 sm = t.render(563 this="/foo", items=[{"url": "/"}, {"url": "/foo"}, {"url": "/bar"}]564 )565 lines = [x.strip() for x in sm.splitlines() if x.strip()]566 assert lines == [567 '<?xml version="1.0" encoding="UTF-8"?>',568 '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',569 "<url><loc>/</loc></url>",570 "<url><loc>/bar</loc></url>",571 "</urlset>",572 ]573574 def test_bare_async(self, test_env_async):575 t = test_env_async.from_string('{% extends "header" %}')576 assert t.render(foo=42) == "[42|23]"577578 def test_awaitable_property_slicing(self, test_env_async):579 t = test_env_async.from_string("{% for x in a.b[:1] %}{{ x }}{% endfor %}")580 assert t.render(a=dict(b=[1, 2, 3])) == "1"581582583def test_namespace_awaitable(test_env_async):584 async def _test():585 t = test_env_async.from_string(586 '{% set ns = namespace(foo="Bar") %}{{ ns.foo }}'587 )588 actual = await t.render_async()589 assert actual == "Bar"590591 run(_test())