test on trio, fix all missing aclose related warnings (#1960)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Thomas Grainger · committed by GitHub · parent 079e831 · Browse files · 9 files·+238 added−62 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
9 files+238 added−62 removed
- tests:+152 added−37 removed
- other:+86 added−25 removed
Provenance
- Commit
1655128- Tree
bbd9251- Author
Thomas Grainger <tagrain@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
079e831
9 files changed+238 added−62 removed
modified:requirements/docs.txt+1 added-1 removed
13 unmodified lines14 charset-normalizer==3.1.015 # via requests16 docutils==0.20.117 # via sphinx18-idna==3.418+idna==3.619 # via requests20 imagesize==1.4.121 # via sphinx22 jinja2==3.1.239 unmodified linesmodified:requirements/tests.in+1 added
1 pytest2+trio<=0.22.2 # for Python3.7 supportmodified:requirements/tests.txt+18 added-2 removed
1-# SHA1:0eaa389e1fdb3a1917c0f987514bd561be5718ee1+# SHA1:b8d151f902b43c4435188a9d3494fb8d4af071682 #3 # This file is autogenerated by pip-compile-multi4 # To update, run:5 #6 # pip-compile-multi7 #8+attrs==23.2.09+ # via10+ # outcome11+ # trio12 exceptiongroup==1.1.19- # via pytest13+ # via14+ # pytest15+ # trio16+idna==3.617+ # via trio18 iniconfig==2.0.019 # via pytest20+outcome==1.3.0.post021+ # via trio22 packaging==23.123 # via pytest24 pluggy==1.2.025 # via pytest26 pytest==7.4.027 # via -r requirements/tests.in28+sniffio==1.3.129+ # via trio30+sortedcontainers==2.4.031+ # via trio32 tomli==2.0.133 # via pytest34+trio==0.22.235+ # via -r requirements/tests.inmodified:src/jinja2/async_utils.py+20 added-5 removed
4 unmodified lines5 6 from .utils import _PassArg7 from .utils import pass_eval_context8 9+if t.TYPE_CHECKING:10+ import typing_extensions as te11+12 V = t.TypeVar("V")13 14 15 def async_variant(normal_func): # type: ignore53 unmodified lines69 70 return t.cast("V", value)71 72 73+class _IteratorToAsyncIterator(t.Generic[V]):74+ def __init__(self, iterator: "t.Iterator[V]"):75+ self._iterator = iterator76+77+ def __aiter__(self) -> "te.Self":78+ return self79+80+ async def __anext__(self) -> V:81+ try:82+ return next(self._iterator)83+ except StopIteration as e:84+ raise StopAsyncIteration(e.value) from e85+86+70-async def auto_aiter(87+def auto_aiter(88 iterable: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",89 ) -> "t.AsyncIterator[V]":90 if hasattr(iterable, "__aiter__"):74- async for item in t.cast("t.AsyncIterable[V]", iterable):75- yield item91+ return iterable.__aiter__()92 else:77- for item in iterable:78- yield item93+ return _IteratorToAsyncIterator(iter(iterable))94 95 96 async def auto_to_list(97 value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",2 unmodified linesmodified:src/jinja2/compiler.py+30 added-14 removed
900 unmodified lines901 self.indent()902 if not self.environment.is_async:903 self.writeline("yield from parent_template.root_render_func(context)")904 else:905- self.writeline(906- "async for event in parent_template.root_render_func(context):"907- )905+ self.writeline("agen = parent_template.root_render_func(context)")906+ self.writeline("try:")907 self.indent()908+ self.writeline("async for event in agen:")909+ self.indent()910 self.writeline("yield event")911 self.outdent()912+ self.outdent()913+ self.writeline("finally: await agen.aclose()")914 self.outdent(1 + (not self.has_known_extends))915 916 # at this point we now have the blocks collected and can visit them too.917 for name, block in self.blocks.items():61 unmodified lines979 self.writeline(980 f"yield from context.blocks[{node.name!r}][0]({context})", node981 )982 else:983+ self.writeline(f"gen = context.blocks[{node.name!r}][0]({context})")984+ self.writeline("try:")985+ self.indent()986 self.writeline(981- f"{self.choose_async()}for event in"982- f" context.blocks[{node.name!r}][0]({context}):",987+ f"{self.choose_async()}for event in gen:",988 node,989 )990 self.indent()991 self.simple_write("event", frame)992 self.outdent()993+ self.outdent()994+ self.writeline(995+ f"finally: {self.choose_async('await gen.aclose()', 'gen.close()')}"996+ )997 998 self.outdent(level)999 1000 def visit_Extends(self, node: nodes.Extends, frame: Frame) -> None:64 unmodified lines1065 self.outdent()1066 self.writeline("else:")1067 self.indent()1068 1060- skip_event_yield = False1069+ def loop_body() -> None:1070+ self.indent()1071+ self.simple_write("event", frame)1072+ self.outdent()1073+1074 if node.with_context:1075 self.writeline(1063- f"{self.choose_async()}for event in template.root_render_func("1076+ f"gen = template.root_render_func("1077 "template.new_context(context.get_all(), True,"1065- f" {self.dump_local_context(frame)})):"1078+ f" {self.dump_local_context(frame)}))"1079 )1080+ self.writeline("try:")1081+ self.indent()1082+ self.writeline(f"{self.choose_async()}for event in gen:")1083+ loop_body()1084+ self.outdent()1085+ self.writeline(1086+ f"finally: {self.choose_async('await gen.aclose()', 'gen.close()')}"1087+ )1088 elif self.environment.is_async:1089 self.writeline(1090 "for event in (await template._get_default_module_async())"1091 "._body_stream:"1092 )1093+ loop_body()1094 else:1095 self.writeline("yield from template._get_default_module()._body_stream")1074- skip_event_yield = True1096 1076- if not skip_event_yield:1077- self.indent()1078- self.simple_write("event", frame)1079- self.outdent()1080-1097 if node.ignore_missing:1098 self.outdent()1099 1100 def _import_common(876 unmodified linesmodified:src/jinja2/environment.py+9 added-3 removed
1344 unmodified lines1345 yield self.environment.handle_exception()1346 1347 async def generate_async(1348 self, *args: t.Any, **kwargs: t.Any1349- ) -> t.AsyncIterator[str]:1349+ ) -> t.AsyncGenerator[str, object]:1350 """An async version of :meth:`generate`. Works very similarly but1351 returns an async iterator instead.1352 """1353 if not self.environment.is_async:3 unmodified lines1357 1358 ctx = self.new_context(dict(*args, **kwargs))1359 1360 try:1361+ agen = self.root_render_func(ctx)1362+ try:1361- async for event in self.root_render_func(ctx): # type: ignore1362- yield event1363+ async for event in agen: # type: ignore1364+ yield event1365+ finally:1366+ # we can't use async with aclosing(...) because that's only1367+ # in 3.10+1368+ await agen.aclose() # type: ignore1369 except Exception:1370 yield self.environment.handle_exception()1371 1372 def new_context(297 unmodified linesmodified:tests/test_async_filters.py+54 added-13 removed
1+import asyncio2+import contextlib3 from collections import namedtuple4 5 import pytest6+import trio7 from markupsafe import Markup8 9 from jinja2 import Environment10 from jinja2.async_utils import auto_aiter17 unmodified lines28 def env_async():29 return Environment(enable_async=True)30 31 32+def _asyncio_run(async_fn, *args):33+ return asyncio.run(async_fn(*args))34+35+36+@pytest.fixture(params=[_asyncio_run, trio.run], ids=["asyncio", "trio"])37+def run_async_fn(request):38+ return request.param39+40+41+@contextlib.asynccontextmanager42+async def closing_factory():43+ async with contextlib.AsyncExitStack() as stack:44+45+ def closing(maybe_agen):46+ try:47+ aclose = maybe_agen.aclose48+ except AttributeError:49+ pass50+ else:51+ stack.push_async_callback(aclose)52+ return maybe_agen53+54+ yield closing55+56+57 @mark_dualiter("foo", lambda: range(10))30-def test_first(env_async, foo):31- tmpl = env_async.from_string("{{ foo()|first }}")32- out = tmpl.render(foo=foo)58+def test_first(env_async, foo, run_async_fn):59+ async def test():60+ async with closing_factory() as closing:61+ tmpl = env_async.from_string("{{ closing(foo())|first }}")62+ return await tmpl.render_async(foo=foo, closing=closing)63+64+ out = run_async_fn(test)65 assert out == "0"66 67 68 @mark_dualiter(207 unmodified lines276 "[[0, 1, 2, 3], [4, 5, 6, 'X'], [7, 8, 9, 'X']]"277 )278 279 248-def test_custom_async_filter(env_async):280+def test_custom_async_filter(env_async, run_async_fn):281 async def customfilter(val):282 return str(val)283 252- env_async.filters["customfilter"] = customfilter253- tmpl = env_async.from_string("{{ 'static'|customfilter }} {{ arg|customfilter }}")254- out = tmpl.render(arg="dynamic")284+ async def test():285+ env_async.filters["customfilter"] = customfilter286+ tmpl = env_async.from_string(287+ "{{ 'static'|customfilter }} {{ arg|customfilter }}"288+ )289+ return await tmpl.render_async(arg="dynamic")290+291+ out = run_async_fn(test)292 assert out == "static dynamic"293 294 295 @mark_dualiter("items", lambda: range(10))259-def test_custom_async_iteratable_filter(env_async, items):296+def test_custom_async_iteratable_filter(env_async, items, run_async_fn):297 async def customfilter(iterable):298 items = []299 async for item in auto_aiter(iterable):300 items.append(str(item))301 if len(items) == 3:302 break303 return ",".join(items)304 305+ async def test():306+ async with closing_factory() as closing:268- env_async.filters["customfilter"] = customfilter269- tmpl = env_async.from_string(270- "{{ items()|customfilter }} .. {{ [3, 4, 5, 6]|customfilter }}"271- )272- out = tmpl.render(items=items)307+ env_async.filters["customfilter"] = customfilter308+ tmpl = env_async.from_string(309+ "{{ closing(items())|customfilter }} .. {{ [3, 4, 5, 6]|customfilter }}"310+ )311+ return await tmpl.render_async(items=items, closing=closing)312+313+ out = run_async_fn(test)314 assert out == "0,1,2 .. 3,4,5"modified:tests/test_async.py+98 added-24 removed
1 import asyncio2 3 import pytest4+import trio5 6 from jinja2 import ChainableUndefined7 from jinja2 import DictLoader8 from jinja2 import Environment4 unmodified lines13 from jinja2.exceptions import UndefinedError14 from jinja2.nativetypes import NativeEnvironment15 16 16-def test_basic_async():17+def _asyncio_run(async_fn, *args):18+ return asyncio.run(async_fn(*args))19+20+21+@pytest.fixture(params=[_asyncio_run, trio.run], ids=["asyncio", "trio"])22+def run_async_fn(request):23+ return request.param24+25+26+def test_basic_async(run_async_fn):27 t = Template(28 "{% for item in [1, 2, 3] %}[{{ item }}]{% endfor %}", enable_async=True29 )30 31 async def func():32 return await t.render_async()33 24- rv = asyncio.run(func())34+ rv = run_async_fn(func)35 assert rv == "[1][2][3]"36 37 28-def test_await_on_calls():38+def test_await_on_calls(run_async_fn):39 t = Template("{{ async_func() + normal_func() }}", enable_async=True)40 41 async def async_func():42 return 423 unmodified lines46 47 async def func():48 return await t.render_async(async_func=async_func, normal_func=normal_func)49 40- rv = asyncio.run(func())50+ rv = run_async_fn(func)51 assert rv == "65"52 53 54 def test_await_on_calls_normal_render():8 unmodified lines63 rv = t.render(async_func=async_func, normal_func=normal_func)64 assert rv == "65"65 66 57-def test_await_and_macros():67+def test_await_and_macros(run_async_fn):68 t = Template(69 "{% macro foo(x) %}[{{ x }}][{{ async_func() }}]{% endmacro %}{{ foo(42) }}",70 enable_async=True,71 )3 unmodified lines75 76 async def func():77 return await t.render_async(async_func=async_func)78 69- rv = asyncio.run(func())79+ rv = run_async_fn(func)80 assert rv == "[42][42]"81 82 73-def test_async_blocks():83+def test_async_blocks(run_async_fn):84 t = Template(85 "{% block foo %}<Test>{% endblock %}{{ self.foo() }}",86 enable_async=True,87 autoescape=True,1 unmodified line89 90 async def func():91 return await t.render_async()92 83- rv = asyncio.run(func())93+ rv = run_async_fn(func)94 assert rv == "<Test><Test>"95 96 97 def test_async_generate():67 unmodified lines165 test_env_async.from_string('{% from "foo" import bar, with context %}')166 test_env_async.from_string('{% from "foo" import bar, with, context %}')167 test_env_async.from_string('{% from "foo" import bar, with with context %}')168 159- def test_exports(self, test_env_async):160- coro = test_env_async.from_string(169+ def test_exports(self, test_env_async, run_async_fn):170+ coro_fn = test_env_async.from_string(171 """172 {% macro toplevel() %}...{% endmacro %}173 {% macro __private() %}...{% endmacro %}174 {% set variable = 42 %}175 {% for item in [1] %}176 {% macro notthere() %}{% endmacro %}177 {% endfor %}178 """169- )._get_default_module_async()170- m = asyncio.run(coro)171- assert asyncio.run(m.toplevel()) == "..."179+ )._get_default_module_async180+ m = run_async_fn(coro_fn)181+ assert run_async_fn(m.toplevel) == "..."182 assert not hasattr(m, "__missing")183 assert m.variable == 42184 assert not hasattr(m, "notthere")185 280 unmodified lines466 ",{% endif %}{% endfor %}"467 )468 assert tmpl.render(items=reversed([3, 2, 1])) == "1,2,3"469 460- def test_loop_errors(self, test_env_async):470+ def test_loop_errors(self, test_env_async, run_async_fn):471 tmpl = test_env_async.from_string(472 """{% for item in [1] if loop.index473 == 0 %}...{% endfor %}"""474 )465- pytest.raises(UndefinedError, tmpl.render)475+ with pytest.raises(UndefinedError):476+ run_async_fn(tmpl.render_async)477+478 tmpl = test_env_async.from_string(479 """{% for item in [] %}...{% else480 %}{{ loop }}{% endfor %}"""481 )470- assert tmpl.render() == ""482+ assert run_async_fn(tmpl.render_async) == ""483 484 def test_loop_filter(self, test_env_async):485 tmpl = test_env_async.from_string(486 "{% for item in range(10) if item is even %}[{{ item }}]{% endfor %}"121 unmodified lines608 t = test_env_async.from_string("{% for x in a.b[:1] %}{{ x }}{% endfor %}")609 assert t.render(a=dict(b=[1, 2, 3])) == "1"610 611 600-def test_namespace_awaitable(test_env_async):612+def test_namespace_awaitable(test_env_async, run_async_fn):613 async def _test():614 t = test_env_async.from_string(615 '{% set ns = namespace(foo="Bar") %}{{ ns.foo }}'616 )617 actual = await t.render_async()618 assert actual == "Bar"619 608- asyncio.run(_test())620+ run_async_fn(_test)621 622 611-def test_chainable_undefined_aiter():623+def test_chainable_undefined_aiter(run_async_fn):624 async def _test():625 t = Template(626 "{% for x in a['b']['c'] %}{{ x }}{% endfor %}",627 enable_async=True,1 unmodified line629 )630 rv = await t.render_async(a={})631 assert rv == ""632 621- asyncio.run(_test())633+ run_async_fn(_test)634 635 636 @pytest.fixture637 def async_native_env():638 return NativeEnvironment(enable_async=True)639 640 629-def test_native_async(async_native_env):641+def test_native_async(async_native_env, run_async_fn):642 async def _test():643 t = async_native_env.from_string("{{ x }}")644 rv = await t.render_async(x=23)645 assert rv == 23646 635- asyncio.run(_test())647+ run_async_fn(_test)648 649 638-def test_native_list_async(async_native_env):650+def test_native_list_async(async_native_env, run_async_fn):651 async def _test():652 t = async_native_env.from_string("{{ x }}")653 rv = await t.render_async(x=list(range(3)))654 assert rv == [0, 1, 2]655 644- asyncio.run(_test())656+ run_async_fn(_test)657 658 659 def test_getitem_after_filter():660 env = Environment(enable_async=True)8 unmodified lines669 env.globals["add_each"] = lambda v, x: [i + x for i in v]670 t = env.from_string("{{ add_each(a, 2)[1:] }}")671 out = t.render(a=range(3))672 assert out == "[3, 4]"673+674+675+def test_basic_generate_async(run_async_fn):676+ t = Template(677+ "{% for item in [1, 2, 3] %}[{{ item }}]{% endfor %}", enable_async=True678+ )679+680+ async def func():681+ agen = t.generate_async()682+ try:683+ return await agen.__anext__()684+ finally:685+ await agen.aclose()686+687+ rv = run_async_fn(func)688+ assert rv == "["689+690+691+def test_include_generate_async(run_async_fn, test_env_async):692+ t = test_env_async.from_string('{% include "header" %}')693+694+ async def func():695+ agen = t.generate_async()696+ try:697+ return await agen.__anext__()698+ finally:699+ await agen.aclose()700+701+ rv = run_async_fn(func)702+ assert rv == "["703+704+705+def test_blocks_generate_async(run_async_fn):706+ t = Template(707+ "{% block foo %}<Test>{% endblock %}{{ self.foo() }}",708+ enable_async=True,709+ autoescape=True,710+ )711+712+ async def func():713+ agen = t.generate_async()714+ try:715+ return await agen.__anext__()716+ finally:717+ await agen.aclose()718+719+ rv = run_async_fn(func)720+ assert rv == "<Test>"721+722+723+def test_async_extend(run_async_fn, test_env_async):724+ t = test_env_async.from_string('{% extends "header" %}')725+726+ async def func():727+ agen = t.generate_async()728+ try:729+ return await agen.__anext__()730+ finally:731+ await agen.aclose()732+733+ rv = run_async_fn(func)734+ assert rv == "["modified:CHANGES.rst+7 added
5 unmodified lines6 Unreleased7 8 - Calling sync ``render`` for an async template uses ``asyncio.run``.9 :pr:`1952`10+- Avoid unclosed ``auto_aiter`` warnings. :pr:`1960`11+- Return an ``aclose``-able ``AsyncGenerator`` from12+ ``Template.generate_async``. :pr:`1960`13+- Avoid leaving ``root_render_func()`` unclosed in14+ ``Template.generate_async``. :pr:`1960`15+- Avoid leaving async generators unclosed in blocks, includes and extends.16+ :pr:`1960`17 18 19 Version 3.1.420 -------------994 unmodified lines