Skip to content
Myr

test_async.py

This file

Path

tests/test_async.py

720 lines · 23.2 KiB · Python

Last changed by

Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74

History of this file

Take it

1import pytest23from jinja2 import ChainableUndefined4from jinja2 import DictLoader5from jinja2 import Environment6from jinja2 import Template7from jinja2.async_utils import auto_aiter8from jinja2.exceptions import TemplateNotFound9from jinja2.exceptions import TemplatesNotFound10from jinja2.exceptions import UndefinedError11from jinja2.nativetypes import NativeEnvironment121314def test_basic_async(run_async_fn):15    t = Template(16        "{% for item in [1, 2, 3] %}[{{ item }}]{% endfor %}", enable_async=True17    )1819    async def func():20        return await t.render_async()2122    rv = run_async_fn(func)23    assert rv == "[1][2][3]"242526def test_await_on_calls(run_async_fn):27    t = Template("{{ async_func() + normal_func() }}", 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(async_func=async_func, normal_func=normal_func)3738    rv = run_async_fn(func)39    assert rv == "65"404142def test_await_on_calls_normal_render():43    t = Template("{{ async_func() + normal_func() }}", enable_async=True)4445    async def async_func():46        return 424748    def normal_func():49        return 235051    rv = t.render(async_func=async_func, normal_func=normal_func)52    assert rv == "65"535455def test_await_and_macros(run_async_fn):56    t = Template(57        "{% macro foo(x) %}[{{ x }}][{{ async_func() }}]{% endmacro %}{{ foo(42) }}",58        enable_async=True,59    )6061    async def async_func():62        return 426364    async def func():65        return await t.render_async(async_func=async_func)6667    rv = run_async_fn(func)68    assert rv == "[42][42]"697071def test_async_blocks(run_async_fn):72    t = Template(73        "{% block foo %}<Test>{% endblock %}{{ self.foo() }}",74        enable_async=True,75        autoescape=True,76    )7778    async def func():79        return await t.render_async()8081    rv = run_async_fn(func)82    assert rv == "<Test><Test>"838485def test_async_generate():86    t = Template("{% for x in [1, 2, 3] %}{{ x }}{% endfor %}", enable_async=True)87    rv = list(t.generate())88    assert rv == ["1", "2", "3"]899091def test_async_iteration_in_templates():92    t = Template("{% for x in rng %}{{ x }}{% endfor %}", enable_async=True)9394    async def async_iterator():95        for item in [1, 2, 3]:96            yield item9798    rv = list(t.generate(rng=async_iterator()))99    assert rv == ["1", "2", "3"]100101102def test_async_iteration_in_templates_extended():103    t = Template(104        "{% for x in rng %}{{ loop.index0 }}/{{ x }}{% endfor %}", enable_async=True105    )106    stream = t.generate(rng=auto_aiter(range(1, 4)))107    assert next(stream) == "0"108    assert "".join(stream) == "/11/22/3"109110111@pytest.fixture112def test_env_async():113    env = Environment(114        loader=DictLoader(115            dict(116                module="{% macro test() %}[{{ foo }}|{{ bar }}]{% endmacro %}",117                header="[{{ foo }}|{{ 23 }}]",118                o_printer="({{ o }})",119            )120        ),121        enable_async=True,122    )123    env.globals["bar"] = 23124    return env125126127class TestAsyncImports:128    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, run_async_fn):158        coro_fn = test_env_async.from_string(159            """160            {% macro toplevel() %}...{% endmacro %}161            {% macro __private() %}...{% endmacro %}162            {% set variable = 42 %}163            {% for item in [1] %}164                {% macro notthere() %}{% endmacro %}165            {% endfor %}166            """167        )._get_default_module_async168        m = run_async_fn(coro_fn)169        assert run_async_fn(m.toplevel) == "..."170        assert not hasattr(m, "__missing")171        assert m.variable == 42172        assert not hasattr(m, "notthere")173174    def test_import_with_globals(self, test_env_async):175        t = test_env_async.from_string(176            '{% import "module" as m %}{{ m.test() }}', globals={"foo": 42}177        )178        assert t.render() == "[42|23]"179180        t = test_env_async.from_string('{% import "module" as m %}{{ m.test() }}')181        assert t.render() == "[|23]"182183    def test_import_with_globals_override(self, test_env_async):184        t = test_env_async.from_string(185            '{% set foo = 41 %}{% import "module" as m %}{{ m.test() }}',186            globals={"foo": 42},187        )188        assert t.render() == "[42|23]"189190    def test_from_import_with_globals(self, test_env_async):191        t = test_env_async.from_string(192            '{% from "module" import test %}{{ test() }}',193            globals={"foo": 42},194        )195        assert t.render() == "[42|23]"196197198class TestAsyncIncludes:199    def test_context_include(self, test_env_async):200        t = test_env_async.from_string('{% include "header" %}')201        assert t.render(foo=42) == "[42|23]"202        t = test_env_async.from_string('{% include "header" with context %}')203        assert t.render(foo=42) == "[42|23]"204        t = test_env_async.from_string('{% include "header" without context %}')205        assert t.render(foo=42) == "[|23]"206207    def test_choice_includes(self, test_env_async):208        t = test_env_async.from_string('{% include ["missing", "header"] %}')209        assert t.render(foo=42) == "[42|23]"210211        t = test_env_async.from_string(212            '{% include ["missing", "missing2"] ignore missing %}'213        )214        assert t.render(foo=42) == ""215216        t = test_env_async.from_string('{% include ["missing", "missing2"] %}')217        pytest.raises(TemplateNotFound, t.render)218        with pytest.raises(TemplatesNotFound) as e:219            t.render()220221        assert e.value.templates == ["missing", "missing2"]222        assert e.value.name == "missing2"223224        def test_includes(t, **ctx):225            ctx["foo"] = 42226            assert t.render(ctx) == "[42|23]"227228        t = test_env_async.from_string('{% include ["missing", "header"] %}')229        test_includes(t)230        t = test_env_async.from_string("{% include x %}")231        test_includes(t, x=["missing", "header"])232        t = test_env_async.from_string('{% include [x, "header"] %}')233        test_includes(t, x="missing")234        t = test_env_async.from_string("{% include x %}")235        test_includes(t, x="header")236        t = test_env_async.from_string("{% include x %}")237        test_includes(t, x="header")238        t = test_env_async.from_string("{% include [x] %}")239        test_includes(t, x="header")240241    def test_include_ignoring_missing(self, test_env_async):242        t = test_env_async.from_string('{% include "missing" %}')243        pytest.raises(TemplateNotFound, t.render)244        for extra in "", "with context", "without context":245            t = test_env_async.from_string(246                '{% include "missing" ignore missing ' + extra + " %}"247            )248            assert t.render() == ""249250    def test_context_include_with_overrides(self, test_env_async):251        env = Environment(252            loader=DictLoader(253                dict(254                    main="{% for item in [1, 2, 3] %}{% include 'item' %}{% endfor %}",255                    item="{{ item }}",256                )257            )258        )259        assert env.get_template("main").render() == "123"260261    def test_unoptimized_scopes(self, test_env_async):262        t = test_env_async.from_string(263            """264            {% macro outer(o) %}265            {% macro inner() %}266            {% include "o_printer" %}267            {% endmacro %}268            {{ inner() }}269            {% endmacro %}270            {{ outer("FOO") }}271        """272        )273        assert t.render().strip() == "(FOO)"274275    def test_unoptimized_scopes_autoescape(self):276        env = Environment(277            loader=DictLoader({"o_printer": "({{ o }})"}),278            autoescape=True,279            enable_async=True,280        )281        t = env.from_string(282            """283            {% macro outer(o) %}284            {% macro inner() %}285            {% include "o_printer" %}286            {% endmacro %}287            {{ inner() }}288            {% endmacro %}289            {{ outer("FOO") }}290        """291        )292        assert t.render().strip() == "(FOO)"293294295class TestAsyncForLoop:296    def test_simple(self, test_env_async):297        tmpl = test_env_async.from_string("{% for item in seq %}{{ item }}{% endfor %}")298        assert tmpl.render(seq=list(range(10))) == "0123456789"299300    def test_else(self, test_env_async):301        tmpl = test_env_async.from_string(302            "{% for item in seq %}XXX{% else %}...{% endfor %}"303        )304        assert tmpl.render() == "..."305306    def test_empty_blocks(self, test_env_async):307        tmpl = test_env_async.from_string(308            "<{% for item in seq %}{% else %}{% endfor %}>"309        )310        assert tmpl.render() == "<>"311312    @pytest.mark.parametrize(313        "transform", [lambda x: x, iter, reversed, lambda x: (i for i in x), auto_aiter]314    )315    def test_context_vars(self, test_env_async, transform):316        t = test_env_async.from_string(317            "{% for item in seq %}{{ loop.index }}|{{ loop.index0 }}"318            "|{{ loop.revindex }}|{{ loop.revindex0 }}|{{ loop.first }}"319            "|{{ loop.last }}|{{ loop.length }}\n{% endfor %}"320        )321        out = t.render(seq=transform([42, 24]))322        assert out == "1|0|2|1|True|False|2\n2|1|1|0|False|True|2\n"323324    def test_cycling(self, test_env_async):325        tmpl = test_env_async.from_string(326            """{% for item in seq %}{{327            loop.cycle('<1>', '<2>') }}{% endfor %}{%328            for item in seq %}{{ loop.cycle(*through) }}{% endfor %}"""329        )330        output = tmpl.render(seq=list(range(4)), through=("<1>", "<2>"))331        assert output == "<1><2>" * 4332333    def test_lookaround(self, test_env_async):334        tmpl = test_env_async.from_string(335            """{% for item in seq -%}336            {{ loop.previtem|default('x') }}-{{ item }}-{{337            loop.nextitem|default('x') }}|338        {%- endfor %}"""339        )340        output = tmpl.render(seq=list(range(4)))341        assert output == "x-0-1|0-1-2|1-2-3|2-3-x|"342343    def test_changed(self, test_env_async):344        tmpl = test_env_async.from_string(345            """{% for item in seq -%}346            {{ loop.changed(item) }},347        {%- endfor %}"""348        )349        output = tmpl.render(seq=[None, None, 1, 2, 2, 3, 4, 4, 4])350        assert output == "True,False,True,True,False,True,True,False,False,"351352    def test_scope(self, test_env_async):353        tmpl = test_env_async.from_string("{% for item in seq %}{% endfor %}{{ item }}")354        output = tmpl.render(seq=list(range(10)))355        assert not output356357    def test_varlen(self, test_env_async):358        def inner():359            yield from range(5)360361        tmpl = test_env_async.from_string(362            "{% for item in iter %}{{ item }}{% endfor %}"363        )364        output = tmpl.render(iter=inner())365        assert output == "01234"366367    def test_noniter(self, test_env_async):368        tmpl = test_env_async.from_string("{% for item in none %}...{% endfor %}")369        pytest.raises(TypeError, tmpl.render)370371    def test_recursive(self, test_env_async):372        tmpl = test_env_async.from_string(373            """{% for item in seq recursive -%}374            [{{ item.a }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]375        {%- endfor %}"""376        )377        assert (378            tmpl.render(379                seq=[380                    dict(a=1, b=[dict(a=1), dict(a=2)]),381                    dict(a=2, b=[dict(a=1), dict(a=2)]),382                    dict(a=3, b=[dict(a="a")]),383                ]384            )385            == "[1<[1][2]>][2<[1][2]>][3<[a]>]"386        )387388    def test_recursive_lookaround(self, test_env_async):389        tmpl = test_env_async.from_string(390            """{% for item in seq recursive -%}391            [{{ loop.previtem.a if loop.previtem is defined else 'x' }}.{{392            item.a }}.{{ loop.nextitem.a if loop.nextitem is defined else 'x'393            }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]394        {%- endfor %}"""395        )396        assert (397            tmpl.render(398                seq=[399                    dict(a=1, b=[dict(a=1), dict(a=2)]),400                    dict(a=2, b=[dict(a=1), dict(a=2)]),401                    dict(a=3, b=[dict(a="a")]),402                ]403            )404            == "[x.1.2<[x.1.2][1.2.x]>][1.2.3<[x.1.2][1.2.x]>][2.3.x<[x.a.x]>]"405        )406407    def test_recursive_depth0(self, test_env_async):408        tmpl = test_env_async.from_string(409            "{% for item in seq recursive %}[{{ loop.depth0 }}:{{ item.a }}"410            "{% if item.b %}<{{ loop(item.b) }}>{% endif %}]{% endfor %}"411        )412        assert (413            tmpl.render(414                seq=[415                    dict(a=1, b=[dict(a=1), dict(a=2)]),416                    dict(a=2, b=[dict(a=1), dict(a=2)]),417                    dict(a=3, b=[dict(a="a")]),418                ]419            )420            == "[0:1<[1:1][1:2]>][0:2<[1:1][1:2]>][0:3<[1:a]>]"421        )422423    def test_recursive_depth(self, test_env_async):424        tmpl = test_env_async.from_string(425            "{% for item in seq recursive %}[{{ loop.depth }}:{{ item.a }}"426            "{% if item.b %}<{{ loop(item.b) }}>{% endif %}]{% endfor %}"427        )428        assert (429            tmpl.render(430                seq=[431                    dict(a=1, b=[dict(a=1), dict(a=2)]),432                    dict(a=2, b=[dict(a=1), dict(a=2)]),433                    dict(a=3, b=[dict(a="a")]),434                ]435            )436            == "[1:1<[2:1][2:2]>][1:2<[2:1][2:2]>][1:3<[2:a]>]"437        )438439    def test_looploop(self, test_env_async):440        tmpl = test_env_async.from_string(441            """{% for row in table %}442            {%- set rowloop = loop -%}443            {% for cell in row -%}444                [{{ rowloop.index }}|{{ loop.index }}]445            {%- endfor %}446        {%- endfor %}"""447        )448        assert tmpl.render(table=["ab", "cd"]) == "[1|1][1|2][2|1][2|2]"449450    def test_reversed_bug(self, test_env_async):451        tmpl = test_env_async.from_string(452            "{% for i in items %}{{ i }}{% if not loop.last %},{% endif %}{% endfor %}"453        )454        assert tmpl.render(items=reversed([3, 2, 1])) == "1,2,3"455456    def test_loop_errors(self, test_env_async, run_async_fn):457        tmpl = test_env_async.from_string(458            """{% for item in [1] if loop.index459                                      == 0 %}...{% endfor %}"""460        )461        with pytest.raises(UndefinedError):462            run_async_fn(tmpl.render_async)463464        tmpl = test_env_async.from_string(465            """{% for item in [] %}...{% else466            %}{{ loop }}{% endfor %}"""467        )468        assert run_async_fn(tmpl.render_async) == ""469470    def test_loop_filter(self, test_env_async):471        tmpl = test_env_async.from_string(472            "{% for item in range(10) if item is even %}[{{ item }}]{% endfor %}"473        )474        assert tmpl.render() == "[0][2][4][6][8]"475        tmpl = test_env_async.from_string(476            """477            {%- for item in range(10) if item is even %}[{{478                loop.index }}:{{ item }}]{% endfor %}"""479        )480        assert tmpl.render() == "[1:0][2:2][3:4][4:6][5:8]"481482    def test_scoped_special_var(self, test_env_async):483        t = test_env_async.from_string(484            "{% for s in seq %}[{{ loop.first }}{% for c in s %}"485            "|{{ loop.first }}{% endfor %}]{% endfor %}"486        )487        assert t.render(seq=("ab", "cd")) == "[True|True|False][False|True|False]"488489    def test_scoped_loop_var(self, test_env_async):490        t = test_env_async.from_string(491            "{% for x in seq %}{{ loop.first }}"492            "{% for y in seq %}{% endfor %}{% endfor %}"493        )494        assert t.render(seq="ab") == "TrueFalse"495        t = test_env_async.from_string(496            "{% for x in seq %}{% for y in seq %}"497            "{{ loop.first }}{% endfor %}{% endfor %}"498        )499        assert t.render(seq="ab") == "TrueFalseTrueFalse"500501    def test_recursive_empty_loop_iter(self, test_env_async):502        t = test_env_async.from_string(503            """504        {%- for item in foo recursive -%}{%- endfor -%}505        """506        )507        assert t.render(dict(foo=[])) == ""508509    def test_call_in_loop(self, test_env_async):510        t = test_env_async.from_string(511            """512        {%- macro do_something() -%}513            [{{ caller() }}]514        {%- endmacro %}515516        {%- for i in [1, 2, 3] %}517            {%- call do_something() -%}518                {{ i }}519            {%- endcall %}520        {%- endfor -%}521        """522        )523        assert t.render() == "[1][2][3]"524525    def test_scoping_bug(self, test_env_async):526        t = test_env_async.from_string(527            """528        {%- for item in foo %}...{{ item }}...{% endfor %}529        {%- macro item(a) %}...{{ a }}...{% endmacro %}530        {{- item(2) -}}531        """532        )533        assert t.render(foo=(1,)) == "...1......2..."534535    def test_unpacking(self, test_env_async):536        tmpl = test_env_async.from_string(537            "{% for a, b, c in [[1, 2, 3]] %}{{ a }}|{{ b }}|{{ c }}{% endfor %}"538        )539        assert tmpl.render() == "1|2|3"540541    def test_recursive_loop_filter(self, test_env_async):542        t = test_env_async.from_string(543            """544        <?xml version="1.0" encoding="UTF-8"?>545        <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">546          {%- for page in [site.root] if page.url != this recursive %}547          <url><loc>{{ page.url }}</loc></url>548          {{- loop(page.children) }}549          {%- endfor %}550        </urlset>551        """552        )553        sm = t.render(554            this="/foo",555            site={"root": {"url": "/", "children": [{"url": "/foo"}, {"url": "/bar"}]}},556        )557        lines = [x.strip() for x in sm.splitlines() if x.strip()]558        assert lines == [559            '<?xml version="1.0" encoding="UTF-8"?>',560            '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',561            "<url><loc>/</loc></url>",562            "<url><loc>/bar</loc></url>",563            "</urlset>",564        ]565566    def test_nonrecursive_loop_filter(self, test_env_async):567        t = test_env_async.from_string(568            """569        <?xml version="1.0" encoding="UTF-8"?>570        <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">571          {%- for page in items if page.url != this %}572          <url><loc>{{ page.url }}</loc></url>573          {%- endfor %}574        </urlset>575        """576        )577        sm = t.render(578            this="/foo", items=[{"url": "/"}, {"url": "/foo"}, {"url": "/bar"}]579        )580        lines = [x.strip() for x in sm.splitlines() if x.strip()]581        assert lines == [582            '<?xml version="1.0" encoding="UTF-8"?>',583            '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',584            "<url><loc>/</loc></url>",585            "<url><loc>/bar</loc></url>",586            "</urlset>",587        ]588589    def test_bare_async(self, test_env_async):590        t = test_env_async.from_string('{% extends "header" %}')591        assert t.render(foo=42) == "[42|23]"592593    def test_awaitable_property_slicing(self, test_env_async):594        t = test_env_async.from_string("{% for x in a.b[:1] %}{{ x }}{% endfor %}")595        assert t.render(a=dict(b=[1, 2, 3])) == "1"596597598def test_namespace_awaitable(test_env_async, run_async_fn):599    async def _test():600        t = test_env_async.from_string(601            '{% set ns = namespace(foo="Bar") %}{{ ns.foo }}'602        )603        actual = await t.render_async()604        assert actual == "Bar"605606    run_async_fn(_test)607608609def test_chainable_undefined_aiter(run_async_fn):610    async def _test():611        t = Template(612            "{% for x in a['b']['c'] %}{{ x }}{% endfor %}",613            enable_async=True,614            undefined=ChainableUndefined,615        )616        rv = await t.render_async(a={})617        assert rv == ""618619    run_async_fn(_test)620621622@pytest.fixture623def async_native_env():624    return NativeEnvironment(enable_async=True)625626627def test_native_async(async_native_env, run_async_fn):628    async def _test():629        t = async_native_env.from_string("{{ x }}")630        rv = await t.render_async(x=23)631        assert rv == 23632633    run_async_fn(_test)634635636def test_native_list_async(async_native_env, run_async_fn):637    async def _test():638        t = async_native_env.from_string("{{ x }}")639        rv = await t.render_async(x=list(range(3)))640        assert rv == [0, 1, 2]641642    run_async_fn(_test)643644645def test_getitem_after_filter():646    env = Environment(enable_async=True)647    env.filters["add_each"] = lambda v, x: [i + x for i in v]648    t = env.from_string("{{ (a|add_each(2))[1:] }}")649    out = t.render(a=range(3))650    assert out == "[3, 4]"651652653def test_getitem_after_call():654    env = Environment(enable_async=True)655    env.globals["add_each"] = lambda v, x: [i + x for i in v]656    t = env.from_string("{{ add_each(a, 2)[1:] }}")657    out = t.render(a=range(3))658    assert out == "[3, 4]"659660661def test_basic_generate_async(run_async_fn):662    t = Template(663        "{% for item in [1, 2, 3] %}[{{ item }}]{% endfor %}", enable_async=True664    )665666    async def func():667        agen = t.generate_async()668        try:669            return await agen.__anext__()670        finally:671            await agen.aclose()672673    rv = run_async_fn(func)674    assert rv == "["675676677def test_include_generate_async(run_async_fn, test_env_async):678    t = test_env_async.from_string('{% include "header" %}')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_blocks_generate_async(run_async_fn):692    t = Template(693        "{% block foo %}<Test>{% endblock %}{{ self.foo() }}",694        enable_async=True,695        autoescape=True,696    )697698    async def func():699        agen = t.generate_async()700        try:701            return await agen.__anext__()702        finally:703            await agen.aclose()704705    rv = run_async_fn(func)706    assert rv == "<Test>"707708709def test_async_extend(run_async_fn, test_env_async):710    t = test_env_async.from_string('{% extends "header" %}')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 == "["