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
Provenance
- Commit
63d7324- Tree
6bf8ab1- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
f61ffbf
4 files changed+156 added−25 removed
modified:jinja2/asyncsupport.py+1 added-9 removed
62 unmodified lines63 self._module = rv = await self.make_module_async()64 return rv65 66 67-@internalcode68-def get_default_module_impl(self):69- if self.environment._async:70- return self._get_default_module_async()71- return self._get_default_module()72-73-67 def wrap_default_module(original_default_module):68 @internalcode69 def _get_default_module(self):70 if self.environment._async:5 unmodified lines76 77 async 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)83 84 3 unmodified lines88 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_async93 94 95 def patch_runtime():13 unmodified linesmodified:jinja2/compiler.py+13 added-5 removed
969 unmodified lines970 self.outdent()971 self.writeline('else:')972 self.indent()973 974- 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:')986 987 self.indent()988 self.simple_write('event', frame)989 self.outdent()15 unmodified lines1005 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 lines1023 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()')1031 1032 var_names = []1033 discarded_names = []1034 for name in node.names:691 unmodified linesmodified:jinja2/environment.py-4 removed
1040 unmodified lines1041 return self._module1042 self._module = rv = self.make_module()1043 return rv1044 1045- # 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_module1048-1045 @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 access179 unmodified linesmodified:tests/test_async.py+142 added-7 removed
1 import pytest2 import asyncio3 4-from jinja2 import Template4+from jinja2 import Template, Environment, DictLoader5 from jinja2.utils import have_async_gen6+from jinja2.exceptions import TemplateNotFound, TemplatesNotFound7 8 8-def run(func):9+def run(coro):10 loop = asyncio.get_event_loop()10- return loop.run_until_complete(func())11+ return loop.run_until_complete(coro)12 13 14 @pytest.mark.skipif(not have_async_gen, reason='No async generators')15 def test_basic_async():1 unmodified line17 enable_async=True)18 async def func():19 return await t.render_async()20 20- rv = run(func)21+ rv = run(func())22 assert rv == '[1][2][3]'23 24 25 @pytest.mark.skipif(not have_async_gen, reason='No async generators')12 unmodified lines38 async_func=async_func,39 normal_func=normal_func40 )41 41- rv = run(func)42+ rv = run(func())43 assert rv == '65'44 45 46 @pytest.mark.skipif(not have_async_gen, reason='No async generators')25 unmodified lines72 73 async def func():74 return await t.render_async(async_func=async_func)75 75- rv = run(func)76+ rv = run(func())77 assert rv == '[42][42]'78 79 80 @pytest.mark.skipif(not have_async_gen, reason='No async generators')2 unmodified lines83 enable_async=True, autoescape=True)84 async def func():85 return await t.render_async()86 86- rv = run(func)87+ rv = run(func())88 assert rv == '<Test><Test>'89+90+91+@pytest.fixture92+def 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 env100+101+102+@pytest.mark.imports103+class TestAsyncImports(object):104+105+ 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]'126+127+ 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 %}')133+134+ 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')147+148+149+@pytest.mark.imports150+@pytest.mark.includes151+class TestAsyncIncludes(object):152+153+ 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]'160+161+ 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]'164+165+ t = test_env_async.from_string(166+ '{% include ["missing", "missing2"] ignore missing %}'167+ )168+ assert t.render(foo=42) == ''169+170+ 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'179+180+ def test_includes(t, **ctx):181+ ctx['foo'] = 42182+ assert t.render(ctx) == '[42|23]'183+184+ 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')196+197+ 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() == ''204+205+ 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"211+212+ 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)'