Skip to content
Myr

Added tests for async functionality with imports and includes

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Armin Ronacher · committed by Armin Ronacher · parent f61ffbf · Browse files · 4 files+156 added−25 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

4 files+156 added−25 removed

  • tests:+142 added−7 removed
  • other:+14 added−18 removed

4 files+156 added−25 removed

modified:jinja2/asyncsupport.py+1 added-9 removed
62 unmodified lines
63 self._module = rv = await self.make_module_async()64 return rv656667@internalcode68def get_default_module_impl(self):69 if self.environment._async:70 return self._get_default_module_async()71 return self._get_default_module()727367def wrap_default_module(original_default_module):68 @internalcode69 def _get_default_module(self):70 if self.environment._async:
5 unmodified lines
7677async def make_module_async(self, vars=None, shared=False, locals=None):78 context = self.new_context(vars, shared, locals)79 body_stream = []87 async for item in template.root_render_func(context):80 async for item in self.root_render_func(context):81 body_stream.append(item)82 return TemplateModule(self, context, body_stream)8384
3 unmodified lines
88 Template.render = wrap_render_func(Template.render)89 Template._get_default_module = wrap_default_module(90 Template._get_default_module)91 Template._get_default_module_async = get_default_module_async99 Template._get_default_module_impl = get_default_module_impl92 Template.make_module_async = make_module_async939495def patch_runtime():
13 unmodified lines
modified:jinja2/compiler.py+13 added-5 removed
969 unmodified lines
970 self.outdent()971 self.writeline('else:')972 self.indent()973974 loop = self.environment._async and 'async for' or 'for'974 if node.with_context:975 loop = self.environment._async and 'async for' or 'for'976 self.writeline('%s event in template.root_render_func('977 'template.new_context(context.parent, True, '978 'locals())):' % loop)979 elif self.environment._async:980 self.writeline('for event in (await '981 'template._get_default_module_async())'982 '._body_stream:')983 else:980 self.writeline('%s event in template._get_default_module_impl()'981 '._body_stream:' % loop)984 self.writeline('for event in template._get_default_module()'985 '._body_stream:')986987 self.indent()988 self.simple_write('event', frame)989 self.outdent()
15 unmodified lines
1005 self.write(', %r).' % self.name)1006 if node.with_context:1007 self.write('make_module%s(context.parent, True, locals())'1008 % (self.environment._async and '_async' or ''))1009 elif self.environment._async:1010 self.write('_get_default_module_async()')1011 else:1006 self.write('_get_default_module_impl()')1012 self.write('_get_default_module()')1013 if frame.toplevel and not node.target.startswith('_'):1014 self.writeline('context.exported_vars.discard(%r)' % node.target)1015 frame.assigned_names.add(node.target)1016
6 unmodified lines
1023 self.write(', %r).' % self.name)1024 if node.with_context:1025 self.write('make_module%s(context.parent, True)'1026 % (self.environment._async and '_async' or ''))1027 elif self.environment._async:1028 self.write('_get_default_module_async()')1029 else:1022 self.write('_get_default_module_impl()')1030 self.write('_get_default_module()')10311032 var_names = []1033 discarded_names = []1034 for name in node.names:
691 unmodified lines
modified:jinja2/environment.py-4 removed
1040 unmodified lines
1041 return self._module1042 self._module = rv = self.make_module()1043 return rv10441045 # This is what the compiler dispatches to from generated code. It1046 # might get swapped out by the async support1047 _get_default_module_impl = _get_default_module10481045 @property1046 def module(self):1047 """The template as module. This is used for imports in the1048 template runtime but is also useful if one wants to access
179 unmodified lines
modified:tests/test_async.py+142 added-7 removed
1import pytest2import asyncio34from jinja2 import Template4from jinja2 import Template, Environment, DictLoader5from jinja2.utils import have_async_gen6from jinja2.exceptions import TemplateNotFound, TemplatesNotFound788def run(func):9def run(coro):10 loop = asyncio.get_event_loop()10 return loop.run_until_complete(func())11 return loop.run_until_complete(coro)121314@pytest.mark.skipif(not have_async_gen, reason='No async generators')15def test_basic_async():
1 unmodified line
17 enable_async=True)18 async def func():19 return await t.render_async()2020 rv = run(func)21 rv = run(func())22 assert rv == '[1][2][3]'232425@pytest.mark.skipif(not have_async_gen, reason='No async generators')
12 unmodified lines
38 async_func=async_func,39 normal_func=normal_func40 )4141 rv = run(func)42 rv = run(func())43 assert rv == '65'444546@pytest.mark.skipif(not have_async_gen, reason='No async generators')
25 unmodified lines
7273 async def func():74 return await t.render_async(async_func=async_func)7575 rv = run(func)76 rv = run(func())77 assert rv == '[42][42]'787980@pytest.mark.skipif(not have_async_gen, reason='No async generators')
2 unmodified lines
83 enable_async=True, autoescape=True)84 async def func():85 return await t.render_async()8686 rv = run(func)87 rv = run(func())88 assert rv == '<Test><Test>'899091@pytest.fixture92def test_env_async():93 env = Environment(loader=DictLoader(dict(94 module='{% macro test() %}[{{ foo }}|{{ bar }}]{% endmacro %}',95 header='[{{ foo }}|{{ 23 }}]',96 o_printer='({{ o }})'97 )), enable_async=True)98 env.globals['bar'] = 2399 return env100101102@pytest.mark.imports103class TestAsyncImports(object):104105 def test_context_imports(self, test_env_async):106 t = test_env_async.from_string('{% import "module" as m %}{{ m.test() }}')107 assert t.render(foo=42) == '[|23]'108 t = test_env_async.from_string(109 '{% import "module" as m without context %}{{ m.test() }}'110 )111 assert t.render(foo=42) == '[|23]'112 t = test_env_async.from_string(113 '{% import "module" as m with context %}{{ m.test() }}'114 )115 assert t.render(foo=42) == '[42|23]'116 t = test_env_async.from_string('{% from "module" import test %}{{ test() }}')117 assert t.render(foo=42) == '[|23]'118 t = test_env_async.from_string(119 '{% from "module" import test without context %}{{ test() }}'120 )121 assert t.render(foo=42) == '[|23]'122 t = test_env_async.from_string(123 '{% from "module" import test with context %}{{ test() }}'124 )125 assert t.render(foo=42) == '[42|23]'126127 def test_trailing_comma(self, test_env_async):128 test_env_async.from_string('{% from "foo" import bar, baz with context %}')129 test_env_async.from_string('{% from "foo" import bar, baz, with context %}')130 test_env_async.from_string('{% from "foo" import bar, with context %}')131 test_env_async.from_string('{% from "foo" import bar, with, context %}')132 test_env_async.from_string('{% from "foo" import bar, with with context %}')133134 def test_exports(self, test_env_async):135 m = run(test_env_async.from_string('''136 {% macro toplevel() %}...{% endmacro %}137 {% macro __private() %}...{% endmacro %}138 {% set variable = 42 %}139 {% for item in [1] %}140 {% macro notthere() %}{% endmacro %}141 {% endfor %}142 ''')._get_default_module_async())143 assert run(m.toplevel()) == '...'144 assert not hasattr(m, '__missing')145 assert m.variable == 42146 assert not hasattr(m, 'notthere')147148149@pytest.mark.imports150@pytest.mark.includes151class TestAsyncIncludes(object):152153 def test_context_include(self, test_env_async):154 t = test_env_async.from_string('{% include "header" %}')155 assert t.render(foo=42) == '[42|23]'156 t = test_env_async.from_string('{% include "header" with context %}')157 assert t.render(foo=42) == '[42|23]'158 t = test_env_async.from_string('{% include "header" without context %}')159 assert t.render(foo=42) == '[|23]'160161 def test_choice_includes(self, test_env_async):162 t = test_env_async.from_string('{% include ["missing", "header"] %}')163 assert t.render(foo=42) == '[42|23]'164165 t = test_env_async.from_string(166 '{% include ["missing", "missing2"] ignore missing %}'167 )168 assert t.render(foo=42) == ''169170 t = test_env_async.from_string('{% include ["missing", "missing2"] %}')171 pytest.raises(TemplateNotFound, t.render)172 try:173 t.render()174 except TemplatesNotFound as e:175 assert e.templates == ['missing', 'missing2']176 assert e.name == 'missing2'177 else:178 assert False, 'thou shalt raise'179180 def test_includes(t, **ctx):181 ctx['foo'] = 42182 assert t.render(ctx) == '[42|23]'183184 t = test_env_async.from_string('{% include ["missing", "header"] %}')185 test_includes(t)186 t = test_env_async.from_string('{% include x %}')187 test_includes(t, x=['missing', 'header'])188 t = test_env_async.from_string('{% include [x, "header"] %}')189 test_includes(t, x='missing')190 t = test_env_async.from_string('{% include x %}')191 test_includes(t, x='header')192 t = test_env_async.from_string('{% include x %}')193 test_includes(t, x='header')194 t = test_env_async.from_string('{% include [x] %}')195 test_includes(t, x='header')196197 def test_include_ignoring_missing(self, test_env_async):198 t = test_env_async.from_string('{% include "missing" %}')199 pytest.raises(TemplateNotFound, t.render)200 for extra in '', 'with context', 'without context':201 t = test_env_async.from_string('{% include "missing" ignore missing ' +202 extra + ' %}')203 assert t.render() == ''204205 def test_context_include_with_overrides(self, test_env_async):206 env = Environment(loader=DictLoader(dict(207 main="{% for item in [1, 2, 3] %}{% include 'item' %}{% endfor %}",208 item="{{ item }}"209 )))210 assert env.get_template("main").render() == "123"211212 def test_unoptimized_scopes(self, test_env_async):213 t = test_env_async.from_string("""214 {% macro outer(o) %}215 {% macro inner() %}216 {% include "o_printer" %}217 {% endmacro %}218 {{ inner() }}219 {% endmacro %}220 {{ outer("FOO") }}221 """)222 assert t.render().strip() == '(FOO)'