Skip to content
Myr

test_async.py

This file

Path

tests/test_async.py

418 lines · 15.4 KiB · Python

Last changed by

Make tests pass on older python versions againArmin Ronacherbefore adoption7265e6f

History of this file

Take it

Initial support for async renderingArmin Ronacherbefore adoptionb11056d

lines 1–3why, one step back
1import pytest
2import asyncio3

Added tests for async functionality with imports and includesArmin Ronacherbefore adoption63d7324

line 4why, one step back
4from jinja2 import Template, Environment, DictLoader

Initial support for async renderingArmin Ronacherbefore adoptionb11056d

line 5why, one step back
5from jinja2.utils import have_async_gen

Support the same set of loop functions for async modeArmin Ronacherbefore adoptionacab87a

lines 6–7why, one step back
6from jinja2.exceptions import TemplateNotFound, TemplatesNotFound, \
7 UndefinedError

Initial support for async renderingArmin Ronacherbefore adoptionb11056d

lines 8–9why, one step back
8
9

Added tests for async functionality with imports and includesArmin Ronacherbefore adoption63d7324

line 10why, one step back
10def run(coro):

Initial support for async renderingArmin Ronacherbefore adoptionb11056d

line 11why, one step back
11 loop = asyncio.get_event_loop()

Added tests for async functionality with imports and includesArmin Ronacherbefore adoption63d7324

line 12why, one step back
12 return loop.run_until_complete(coro)

Initial support for async renderingArmin Ronacherbefore adoptionb11056d

lines 13–20why, one step back
13
1415def test_basic_async():16 t = Template('{% for item in [1, 2, 3] %}[{{ item }}]{% endfor %}',17 enable_async=True)18 async def func():19 return await t.render_async()20

Added tests for async functionality with imports and includesArmin Ronacherbefore adoption63d7324

line 21why, one step back
21 rv = run(func())

Initial support for async renderingArmin Ronacherbefore adoptionb11056d

line 22why, one step back
22 assert rv == '[1][2][3]'

Automatically await on function calls if necessaryArmin Ronacherbefore adoptiond1b8f08

lines 23–40why, one step back
23
2425def test_await_on_calls():26 t = Template('{{ async_func() + normal_func() }}',27 enable_async=True)2829 async def async_func():30 return 423132 def normal_func():33 return 233435 async def func():36 return await t.render_async(37 async_func=async_func,38 normal_func=normal_func39 )40

Added tests for async functionality with imports and includesArmin Ronacherbefore adoption63d7324

line 41why, one step back
41 rv = run(func())

Automatically await on function calls if necessaryArmin Ronacherbefore adoptiond1b8f08

line 42why, one step back
42 assert rv == '65'

Added test for macro async supportArmin Ronacherbefore adoption9853794

lines 43–44why, one step back
43
44

Restore original render func for non async usageArmin Ronacherbefore adoption7c90534

lines 45–62why, one step back
45def test_await_on_calls_normal_render():
46 t = Template('{{ async_func() + normal_func() }}',47 enable_async=True)4849 async def async_func():50 return 425152 def normal_func():53 return 235455 rv = t.render(56 async_func=async_func,57 normal_func=normal_func58 )5960 assert rv == '65'6162

Added test for macro async supportArmin Ronacherbefore adoption9853794

line 63why, one step back
63def test_await_and_macros():

Improved async testArmin Ronacherbefore adoption6298972

lines 64–65why, one step back
64 t = Template('{% macro foo(x) %}[{{ x }}][{{ async_func() }}]'
65 '{% endmacro %}{{ foo(42) }}', enable_async=True)

Added test for macro async supportArmin Ronacherbefore adoption9853794

line 66why, one step back
66

Improved async testArmin Ronacherbefore adoption6298972

lines 67–69why, one step back
67 async def async_func():
68 return 4269

Added test for macro async supportArmin Ronacherbefore adoption9853794

line 70why, one step back
70 async def func():

Improved async testArmin Ronacherbefore adoption6298972

line 71why, one step back
71 return await t.render_async(async_func=async_func)

Added test for macro async supportArmin Ronacherbefore adoption9853794

line 72why, one step back
72

Added tests for async functionality with imports and includesArmin Ronacherbefore adoption63d7324

line 73why, one step back
73 rv = run(func())

Improved async testArmin Ronacherbefore adoption6298972

line 74why, one step back
74 assert rv == '[42][42]'

Basic async support for blocksArmin Ronacherbefore adoption2b4d44b

lines 75–82why, one step back
75
7677def test_async_blocks():78 t = Template('{% block foo %}<Test>{% endblock %}{{ self.foo() }}',79 enable_async=True, autoescape=True)80 async def func():81 return await t.render_async()82

Added tests for async functionality with imports and includesArmin Ronacherbefore adoption63d7324

line 83why, one step back
83 rv = run(func())

Basic async support for blocksArmin Ronacherbefore adoption2b4d44b

line 84why, one step back
84 assert rv == '<Test><Test>'

Added tests for async functionality with imports and includesArmin Ronacherbefore adoption63d7324

lines 85–86why, one step back
85
86

Wrap generate to support async modeArmin Ronacherbefore adoption3e6992f

lines 87–93why, one step back
87def test_async_generate():
88 t = Template('{% for x in [1, 2, 3] %}{{ x }}{% endfor %}',89 enable_async=True)90 rv = list(t.generate())91 assert rv == ['1', '2', '3']9293

Added support for async loop contextArmin Ronacherbefore adoptiond4e14fc

line 94why, one step back
94def test_async_iteration_in_templates():

Added basic support for async iterArmin Ronacherbefore adoptionaa188fd

lines 95–101why, one step back
95 t = Template('{% for x in rng %}{{ x }}{% endfor %}',
96 enable_async=True)97 async def async_iterator():98 for item in [1, 2, 3]:99 yield item100 rv = list(t.generate(rng=async_iterator()))101 assert rv == ['1', '2', '3']

Added support for async loop contextArmin Ronacherbefore adoptiond4e14fc

lines 102–111why, one step back
102
103104def test_async_iteration_in_templates_extended():105 t = Template('{% for x in rng %}{{ loop.index0 }}/{{ x }}{% endfor %}',106 enable_async=True)107 async def async_iterator():108 for item in [1, 2, 3]:109 yield item110 rv = list(t.generate(rng=async_iterator()))111 assert rv == ['0/1', '1/2', '2/3']

Added basic support for async iterArmin Ronacherbefore adoptionaa188fd

lines 112–113why, one step back
112
113

Added tests for async functionality with imports and includesArmin Ronacherbefore adoption63d7324

lines 114–245why, one step back
114@pytest.fixture
115def test_env_async():116 env = Environment(loader=DictLoader(dict(117 module='{% macro test() %}[{{ foo }}|{{ bar }}]{% endmacro %}',118 header='[{{ foo }}|{{ 23 }}]',119 o_printer='({{ o }})'120 )), enable_async=True)121 env.globals['bar'] = 23122 return env123124125@pytest.mark.imports126class TestAsyncImports(object):127128 def test_context_imports(self, test_env_async):129 t = test_env_async.from_string('{% import "module" as m %}{{ m.test() }}')130 assert t.render(foo=42) == '[|23]'131 t = test_env_async.from_string(132 '{% import "module" as m without context %}{{ m.test() }}'133 )134 assert t.render(foo=42) == '[|23]'135 t = test_env_async.from_string(136 '{% import "module" as m with context %}{{ m.test() }}'137 )138 assert t.render(foo=42) == '[42|23]'139 t = test_env_async.from_string('{% from "module" import test %}{{ test() }}')140 assert t.render(foo=42) == '[|23]'141 t = test_env_async.from_string(142 '{% from "module" import test without context %}{{ test() }}'143 )144 assert t.render(foo=42) == '[|23]'145 t = test_env_async.from_string(146 '{% from "module" import test with context %}{{ test() }}'147 )148 assert t.render(foo=42) == '[42|23]'149150 def test_trailing_comma(self, test_env_async):151 test_env_async.from_string('{% from "foo" import bar, baz with context %}')152 test_env_async.from_string('{% from "foo" import bar, baz, with context %}')153 test_env_async.from_string('{% from "foo" import bar, with context %}')154 test_env_async.from_string('{% from "foo" import bar, with, context %}')155 test_env_async.from_string('{% from "foo" import bar, with with context %}')156157 def test_exports(self, test_env_async):158 m = run(test_env_async.from_string('''159 {% macro toplevel() %}...{% endmacro %}160 {% macro __private() %}...{% endmacro %}161 {% set variable = 42 %}162 {% for item in [1] %}163 {% macro notthere() %}{% endmacro %}164 {% endfor %}165 ''')._get_default_module_async())166 assert run(m.toplevel()) == '...'167 assert not hasattr(m, '__missing')168 assert m.variable == 42169 assert not hasattr(m, 'notthere')170171172@pytest.mark.imports173@pytest.mark.includes174class TestAsyncIncludes(object):175176 def test_context_include(self, test_env_async):177 t = test_env_async.from_string('{% include "header" %}')178 assert t.render(foo=42) == '[42|23]'179 t = test_env_async.from_string('{% include "header" with context %}')180 assert t.render(foo=42) == '[42|23]'181 t = test_env_async.from_string('{% include "header" without context %}')182 assert t.render(foo=42) == '[|23]'183184 def test_choice_includes(self, test_env_async):185 t = test_env_async.from_string('{% include ["missing", "header"] %}')186 assert t.render(foo=42) == '[42|23]'187188 t = test_env_async.from_string(189 '{% include ["missing", "missing2"] ignore missing %}'190 )191 assert t.render(foo=42) == ''192193 t = test_env_async.from_string('{% include ["missing", "missing2"] %}')194 pytest.raises(TemplateNotFound, t.render)195 try:196 t.render()197 except TemplatesNotFound as e:198 assert e.templates == ['missing', 'missing2']199 assert e.name == 'missing2'200 else:201 assert False, 'thou shalt raise'202203 def test_includes(t, **ctx):204 ctx['foo'] = 42205 assert t.render(ctx) == '[42|23]'206207 t = test_env_async.from_string('{% include ["missing", "header"] %}')208 test_includes(t)209 t = test_env_async.from_string('{% include x %}')210 test_includes(t, x=['missing', 'header'])211 t = test_env_async.from_string('{% include [x, "header"] %}')212 test_includes(t, x='missing')213 t = test_env_async.from_string('{% include x %}')214 test_includes(t, x='header')215 t = test_env_async.from_string('{% include x %}')216 test_includes(t, x='header')217 t = test_env_async.from_string('{% include [x] %}')218 test_includes(t, x='header')219220 def test_include_ignoring_missing(self, test_env_async):221 t = test_env_async.from_string('{% include "missing" %}')222 pytest.raises(TemplateNotFound, t.render)223 for extra in '', 'with context', 'without context':224 t = test_env_async.from_string('{% include "missing" ignore missing ' +225 extra + ' %}')226 assert t.render() == ''227228 def test_context_include_with_overrides(self, test_env_async):229 env = Environment(loader=DictLoader(dict(230 main="{% for item in [1, 2, 3] %}{% include 'item' %}{% endfor %}",231 item="{{ item }}"232 )))233 assert env.get_template("main").render() == "123"234235 def test_unoptimized_scopes(self, test_env_async):236 t = test_env_async.from_string("""237 {% macro outer(o) %}238 {% macro inner() %}239 {% include "o_printer" %}240 {% endmacro %}241 {{ inner() }}242 {% endmacro %}243 {{ outer("FOO") }}244 """)245 assert t.render().strip() == '(FOO)'

Support the same set of loop functions for async modeArmin Ronacherbefore adoptionacab87a

lines 246–418why, one step back
246
247248@pytest.mark.core_tags249@pytest.mark.for_loop250class TestAsyncForLoop(object):251252 def test_simple(self, test_env_async):253 tmpl = test_env_async.from_string('{% for item in seq %}{{ item }}{% endfor %}')254 assert tmpl.render(seq=list(range(10))) == '0123456789'255256 def test_else(self, test_env_async):257 tmpl = test_env_async.from_string(258 '{% for item in seq %}XXX{% else %}...{% endfor %}')259 assert tmpl.render() == '...'260261 def test_empty_blocks(self, test_env_async):262 tmpl = test_env_async.from_string('<{% for item in seq %}{% else %}{% endfor %}>')263 assert tmpl.render() == '<>'264265 def test_context_vars(self, test_env_async):266 slist = [42, 24]267 for seq in [slist, iter(slist), reversed(slist), (_ for _ in slist)]:268 tmpl = test_env_async.from_string('''{% for item in seq -%}269 {{ loop.index }}|{{ loop.index0 }}|{{ loop.revindex }}|{{270 loop.revindex0 }}|{{ loop.first }}|{{ loop.last }}|{{271 loop.length }}###{% endfor %}''')272 one, two, _ = tmpl.render(seq=seq).split('###')273 (one_index, one_index0, one_revindex, one_revindex0, one_first,274 one_last, one_length) = one.split('|')275 (two_index, two_index0, two_revindex, two_revindex0, two_first,276 two_last, two_length) = two.split('|')277278 assert int(one_index) == 1 and int(two_index) == 2279 assert int(one_index0) == 0 and int(two_index0) == 1280 assert int(one_revindex) == 2 and int(two_revindex) == 1281 assert int(one_revindex0) == 1 and int(two_revindex0) == 0282 assert one_first == 'True' and two_first == 'False'283 assert one_last == 'False' and two_last == 'True'284 assert one_length == two_length == '2'285286 def test_cycling(self, test_env_async):287 tmpl = test_env_async.from_string('''{% for item in seq %}{{288 loop.cycle('<1>', '<2>') }}{% endfor %}{%289 for item in seq %}{{ loop.cycle(*through) }}{% endfor %}''')290 output = tmpl.render(seq=list(range(4)), through=('<1>', '<2>'))291 assert output == '<1><2>' * 4292293 def test_scope(self, test_env_async):294 tmpl = test_env_async.from_string('{% for item in seq %}{% endfor %}{{ item }}')295 output = tmpl.render(seq=list(range(10)))296 assert not output297298 def test_varlen(self, test_env_async):299 def inner():300 for item in range(5):301 yield item302 tmpl = test_env_async.from_string('{% for item in iter %}{{ item }}{% endfor %}')303 output = tmpl.render(iter=inner())304 assert output == '01234'305306 def test_noniter(self, test_env_async):307 tmpl = test_env_async.from_string('{% for item in none %}...{% endfor %}')308 pytest.raises(TypeError, tmpl.render)309310 def test_recursive(self, test_env_async):311 tmpl = test_env_async.from_string('''{% for item in seq recursive -%}312 [{{ item.a }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]313 {%- endfor %}''')314 assert tmpl.render(seq=[315 dict(a=1, b=[dict(a=1), dict(a=2)]),316 dict(a=2, b=[dict(a=1), dict(a=2)]),317 dict(a=3, b=[dict(a='a')])318 ]) == '[1<[1][2]>][2<[1][2]>][3<[a]>]'319320 def test_recursive_depth0(self, test_env_async):321 tmpl = test_env_async.from_string('''{% for item in seq recursive -%}322 [{{ loop.depth0 }}:{{ item.a }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]323 {%- endfor %}''')324 assert tmpl.render(seq=[325 dict(a=1, b=[dict(a=1), dict(a=2)]),326 dict(a=2, b=[dict(a=1), dict(a=2)]),327 dict(a=3, b=[dict(a='a')])328 ]) == '[0:1<[1:1][1:2]>][0:2<[1:1][1:2]>][0:3<[1:a]>]'329330 def test_recursive_depth(self, test_env_async):331 tmpl = test_env_async.from_string('''{% for item in seq recursive -%}332 [{{ loop.depth }}:{{ item.a }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]333 {%- endfor %}''')334 assert tmpl.render(seq=[335 dict(a=1, b=[dict(a=1), dict(a=2)]),336 dict(a=2, b=[dict(a=1), dict(a=2)]),337 dict(a=3, b=[dict(a='a')])338 ]) == '[1:1<[2:1][2:2]>][1:2<[2:1][2:2]>][1:3<[2:a]>]'339340 def test_looploop(self, test_env_async):341 tmpl = test_env_async.from_string('''{% for row in table %}342 {%- set rowloop = loop -%}343 {% for cell in row -%}344 [{{ rowloop.index }}|{{ loop.index }}]345 {%- endfor %}346 {%- endfor %}''')347 assert tmpl.render(table=['ab', 'cd']) == '[1|1][1|2][2|1][2|2]'348349 def test_reversed_bug(self, test_env_async):350 tmpl = test_env_async.from_string('{% for i in items %}{{ i }}'351 '{% if not loop.last %}'352 ',{% endif %}{% endfor %}')353 assert tmpl.render(items=reversed([3, 2, 1])) == '1,2,3'354355 def test_loop_errors(self, test_env_async):356 tmpl = test_env_async.from_string('''{% for item in [1] if loop.index357 == 0 %}...{% endfor %}''')358 pytest.raises(UndefinedError, tmpl.render)359 tmpl = test_env_async.from_string('''{% for item in [] %}...{% else360 %}{{ loop }}{% endfor %}''')361 assert tmpl.render() == ''362363 def test_loop_filter(self, test_env_async):364 tmpl = test_env_async.from_string('{% for item in range(10) if item '365 'is even %}[{{ item }}]{% endfor %}')366 assert tmpl.render() == '[0][2][4][6][8]'367 tmpl = test_env_async.from_string('''368 {%- for item in range(10) if item is even %}[{{369 loop.index }}:{{ item }}]{% endfor %}''')370 assert tmpl.render() == '[1:0][2:2][3:4][4:6][5:8]'371372 def test_scoped_special_var(self, test_env_async):373 t = test_env_async.from_string(374 '{% for s in seq %}[{{ loop.first }}{% for c in s %}'375 '|{{ loop.first }}{% endfor %}]{% endfor %}')376 assert t.render(seq=('ab', 'cd')) \377 == '[True|True|False][False|True|False]'378379 def test_scoped_loop_var(self, test_env_async):380 t = test_env_async.from_string('{% for x in seq %}{{ loop.first }}'381 '{% for y in seq %}{% endfor %}{% endfor %}')382 assert t.render(seq='ab') == 'TrueFalse'383 t = test_env_async.from_string('{% for x in seq %}{% for y in seq %}'384 '{{ loop.first }}{% endfor %}{% endfor %}')385 assert t.render(seq='ab') == 'TrueFalseTrueFalse'386387 def test_recursive_empty_loop_iter(self, test_env_async):388 t = test_env_async.from_string('''389 {%- for item in foo recursive -%}{%- endfor -%}390 ''')391 assert t.render(dict(foo=[])) == ''392393 def test_call_in_loop(self, test_env_async):394 t = test_env_async.from_string('''395 {%- macro do_something() -%}396 [{{ caller() }}]397 {%- endmacro %}398399 {%- for i in [1, 2, 3] %}400 {%- call do_something() -%}401 {{ i }}402 {%- endcall %}403 {%- endfor -%}404 ''')405 assert t.render() == '[1][2][3]'406407 def test_scoping_bug(self, test_env_async):408 t = test_env_async.from_string('''409 {%- for item in foo %}...{{ item }}...{% endfor %}410 {%- macro item(a) %}...{{ a }}...{% endmacro %}411 {{- item(2) -}}412 ''')413 assert t.render(foo=(1,)) == '...1......2...'414415 def test_unpacking(self, test_env_async):416 tmpl = test_env_async.from_string('{% for a, b, c in [[1, 2, 3]] %}'417 '{{ a }}|{{ b }}|{{ c }}{% endfor %}')418 assert tmpl.render() == '1|2|3'