Skip to content
Myr

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

9 files+238 added−62 removed

modified:requirements/docs.txt+1 added-1 removed
13 unmodified lines
14charset-normalizer==3.1.015 # via requests16docutils==0.20.117 # via sphinx18idna==3.418idna==3.619 # via requests20imagesize==1.4.121 # via sphinx22jinja2==3.1.2
39 unmodified lines
modified:requirements/tests.in+1 added
1pytest2trio<=0.22.2 # for Python3.7 support
modified: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#8attrs==23.2.09 # via10 # outcome11 # trio12exceptiongroup==1.1.19 # via pytest13 # via14 # pytest15 # trio16idna==3.617 # via trio18iniconfig==2.0.019 # via pytest20outcome==1.3.0.post021 # via trio22packaging==23.123 # via pytest24pluggy==1.2.025 # via pytest26pytest==7.4.027 # via -r requirements/tests.in28sniffio==1.3.129 # via trio30sortedcontainers==2.4.031 # via trio32tomli==2.0.133 # via pytest34trio==0.22.235 # via -r requirements/tests.in
modified:src/jinja2/async_utils.py+20 added-5 removed
4 unmodified lines
56from .utils import _PassArg7from .utils import pass_eval_context89if t.TYPE_CHECKING:10 import typing_extensions as te1112V = t.TypeVar("V")131415def async_variant(normal_func): # type: ignore
53 unmodified lines
6970 return t.cast("V", value)717273class _IteratorToAsyncIterator(t.Generic[V]):74 def __init__(self, iterator: "t.Iterator[V]"):75 self._iterator = iterator7677 def __aiter__(self) -> "te.Self":78 return self7980 async def __anext__(self) -> V:81 try:82 return next(self._iterator)83 except StopIteration as e:84 raise StopAsyncIteration(e.value) from e858670async def auto_aiter(87def 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))949596async def auto_to_list(97 value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
2 unmodified lines
modified:src/jinja2/compiler.py+30 added-14 removed
900 unmodified lines
901 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))915916 # at this point we now have the blocks collected and can visit them too.917 for name, block in self.blocks.items():
61 unmodified lines
979 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 )997998 self.outdent(level)9991000 def visit_Extends(self, node: nodes.Extends, frame: Frame) -> None:
64 unmodified lines
1065 self.outdent()1066 self.writeline("else:")1067 self.indent()10681060 skip_event_yield = False1069 def loop_body() -> None:1070 self.indent()1071 self.simple_write("event", frame)1072 self.outdent()10731074 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 = True10961076 if not skip_event_yield:1077 self.indent()1078 self.simple_write("event", frame)1079 self.outdent()10801097 if node.ignore_missing:1098 self.outdent()10991100 def _import_common(
876 unmodified lines
modified:src/jinja2/environment.py+9 added-3 removed
1344 unmodified lines
1345 yield self.environment.handle_exception()13461347 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 lines
13571358 ctx = self.new_context(dict(*args, **kwargs))13591360 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()13711372 def new_context(
297 unmodified lines
modified:tests/test_async_filters.py+54 added-13 removed
1import asyncio2import contextlib3from collections import namedtuple45import pytest6import trio7from markupsafe import Markup89from jinja2 import Environment10from jinja2.async_utils import auto_aiter
17 unmodified lines
28def env_async():29 return Environment(enable_async=True)303132def _asyncio_run(async_fn, *args):33 return asyncio.run(async_fn(*args))343536@pytest.fixture(params=[_asyncio_run, trio.run], ids=["asyncio", "trio"])37def run_async_fn(request):38 return request.param394041@contextlib.asynccontextmanager42async def closing_factory():43 async with contextlib.AsyncExitStack() as stack:4445 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_agen5354 yield closing555657@mark_dualiter("foo", lambda: range(10))30def test_first(env_async, foo):31 tmpl = env_async.from_string("{{ foo()|first }}")32 out = tmpl.render(foo=foo)58def 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)6364 out = run_async_fn(test)65 assert out == "0"666768@mark_dualiter(
207 unmodified lines
276 "[[0, 1, 2, 3], [4, 5, 6, 'X'], [7, 8, 9, 'X']]"277 )278279248def test_custom_async_filter(env_async):280def test_custom_async_filter(env_async, run_async_fn):281 async def customfilter(val):282 return str(val)283252 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")290291 out = run_async_fn(test)292 assert out == "static dynamic"293294295@mark_dualiter("items", lambda: range(10))259def test_custom_async_iteratable_filter(env_async, items):296def 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)304305 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)312313 out = run_async_fn(test)314 assert out == "0,1,2 .. 3,4,5"
modified:tests/test_async.py+98 added-24 removed
1import asyncio23import pytest4import trio56from jinja2 import ChainableUndefined7from jinja2 import DictLoader8from jinja2 import Environment
4 unmodified lines
13from jinja2.exceptions import UndefinedError14from jinja2.nativetypes import NativeEnvironment151616def test_basic_async():17def _asyncio_run(async_fn, *args):18 return asyncio.run(async_fn(*args))192021@pytest.fixture(params=[_asyncio_run, trio.run], ids=["asyncio", "trio"])22def run_async_fn(request):23 return request.param242526def test_basic_async(run_async_fn):27 t = Template(28 "{% for item in [1, 2, 3] %}[{{ item }}]{% endfor %}", enable_async=True29 )3031 async def func():32 return await t.render_async()3324 rv = asyncio.run(func())34 rv = run_async_fn(func)35 assert rv == "[1][2][3]"363728def test_await_on_calls():38def test_await_on_calls(run_async_fn):39 t = Template("{{ async_func() + normal_func() }}", enable_async=True)4041 async def async_func():42 return 42
3 unmodified lines
4647 async def func():48 return await t.render_async(async_func=async_func, normal_func=normal_func)4940 rv = asyncio.run(func())50 rv = run_async_fn(func)51 assert rv == "65"525354def test_await_on_calls_normal_render():
8 unmodified lines
63 rv = t.render(async_func=async_func, normal_func=normal_func)64 assert rv == "65"656657def test_await_and_macros():67def 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 lines
7576 async def func():77 return await t.render_async(async_func=async_func)7869 rv = asyncio.run(func())79 rv = run_async_fn(func)80 assert rv == "[42][42]"818273def test_async_blocks():83def 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 line
8990 async def func():91 return await t.render_async()9283 rv = asyncio.run(func())93 rv = run_async_fn(func)94 assert rv == "<Test><Test>"959697def test_async_generate():
67 unmodified lines
165 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 %}')168159 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 lines
466 ",{% endif %}{% endfor %}"467 )468 assert tmpl.render(items=reversed([3, 2, 1])) == "1,2,3"469460 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)477478 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) == ""483484 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 lines
608 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"610611600def test_namespace_awaitable(test_env_async):612def 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"619608 asyncio.run(_test())620 run_async_fn(_test)621622611def test_chainable_undefined_aiter():623def 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 line
629 )630 rv = await t.render_async(a={})631 assert rv == ""632621 asyncio.run(_test())633 run_async_fn(_test)634635636@pytest.fixture637def async_native_env():638 return NativeEnvironment(enable_async=True)639640629def test_native_async(async_native_env):641def 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 == 23646635 asyncio.run(_test())647 run_async_fn(_test)648649638def test_native_list_async(async_native_env):650def 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]655644 asyncio.run(_test())656 run_async_fn(_test)657658659def test_getitem_after_filter():660 env = Environment(enable_async=True)
8 unmodified lines
669 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]"673674675def test_basic_generate_async(run_async_fn):676 t = Template(677 "{% for item in [1, 2, 3] %}[{{ item }}]{% endfor %}", enable_async=True678 )679680 async def func():681 agen = t.generate_async()682 try:683 return await agen.__anext__()684 finally:685 await agen.aclose()686687 rv = run_async_fn(func)688 assert rv == "["689690691def test_include_generate_async(run_async_fn, test_env_async):692 t = test_env_async.from_string('{% include "header" %}')693694 async def func():695 agen = t.generate_async()696 try:697 return await agen.__anext__()698 finally:699 await agen.aclose()700701 rv = run_async_fn(func)702 assert rv == "["703704705def 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 )711712 async def func():713 agen = t.generate_async()714 try:715 return await agen.__anext__()716 finally:717 await agen.aclose()718719 rv = run_async_fn(func)720 assert rv == "<Test>"721722723def test_async_extend(run_async_fn, test_env_async):724 t = test_env_async.from_string('{% extends "header" %}')725726 async def func():727 agen = t.generate_async()728 try:729 return await agen.__anext__()730 finally:731 await agen.aclose()732733 rv = run_async_fn(func)734 assert rv == "["
modified:CHANGES.rst+7 added
5 unmodified lines
6Unreleased78- 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`171819Version 3.1.420-------------
994 unmodified lines