Skip to content
Myr

test_api.py

This file

Path

tests/test_api.py

435 lines · 16.5 KiB · Python

Last changed by

Merge branch 'stable'David Lordbefore adoption6aeab5d

History of this file

Take it

1import shutil2import tempfile3from pathlib import Path45import pytest67from jinja2 import ChainableUndefined8from jinja2 import DebugUndefined9from jinja2 import DictLoader10from jinja2 import Environment11from jinja2 import is_undefined12from jinja2 import make_logging_undefined13from jinja2 import meta14from jinja2 import StrictUndefined15from jinja2 import Template16from jinja2 import TemplatesNotFound17from jinja2 import Undefined18from jinja2 import UndefinedError19from jinja2.compiler import CodeGenerator20from jinja2.runtime import Context21from jinja2.utils import Cycler22from jinja2.utils import pass_context23from jinja2.utils import pass_environment24from jinja2.utils import pass_eval_context252627class TestExtendedAPI:28    def test_item_and_attribute(self, env):29        from jinja2.sandbox import SandboxedEnvironment3031        for env in Environment(), SandboxedEnvironment():32            tmpl = env.from_string("{{ foo.items()|list }}")33            assert tmpl.render(foo={"items": 42}) == "[('items', 42)]"34            tmpl = env.from_string('{{ foo|attr("items")()|list }}')35            assert tmpl.render(foo={"items": 42}) == "[('items', 42)]"36            tmpl = env.from_string('{{ foo["items"] }}')37            assert tmpl.render(foo={"items": 42}) == "42"3839    def test_finalize(self):40        e = Environment(finalize=lambda v: "" if v is None else v)41        t = e.from_string("{% for item in seq %}|{{ item }}{% endfor %}")42        assert t.render(seq=(None, 1, "foo")) == "||1|foo"4344    def test_finalize_constant_expression(self):45        e = Environment(finalize=lambda v: "" if v is None else v)46        t = e.from_string("<{{ none }}>")47        assert t.render() == "<>"4849    def test_no_finalize_template_data(self):50        e = Environment(finalize=lambda v: type(v).__name__)51        t = e.from_string("<{{ value }}>")52        # If template data was finalized, it would print "strintstr".53        assert t.render(value=123) == "<int>"5455    def test_context_finalize(self):56        @pass_context57        def finalize(context, value):58            return value * context["scale"]5960        e = Environment(finalize=finalize)61        t = e.from_string("{{ value }}")62        assert t.render(value=5, scale=3) == "15"6364    def test_eval_finalize(self):65        @pass_eval_context66        def finalize(eval_ctx, value):67            return str(eval_ctx.autoescape) + value6869        e = Environment(finalize=finalize, autoescape=True)70        t = e.from_string("{{ value }}")71        assert t.render(value="<script>") == "True&lt;script&gt;"7273    def test_env_autoescape(self):74        @pass_environment75        def finalize(env, value):76            return " ".join(77                (env.variable_start_string, repr(value), env.variable_end_string)78            )7980        e = Environment(finalize=finalize)81        t = e.from_string("{{ value }}")82        assert t.render(value="hello") == "{{ 'hello' }}"8384    def test_cycler(self, env):85        items = 1, 2, 386        c = Cycler(*items)87        for item in items + items:88            assert c.current == item89            assert next(c) == item90        next(c)91        assert c.current == 292        c.reset()93        assert c.current == 19495    def test_expressions(self, env):96        expr = env.compile_expression("foo")97        assert expr() is None98        assert expr(foo=42) == 4299        expr2 = env.compile_expression("foo", undefined_to_none=False)100        assert is_undefined(expr2())101102        expr = env.compile_expression("42 + foo")103        assert expr(foo=42) == 84104105    def test_template_passthrough(self, env):106        t = Template("Content")107        assert env.get_template(t) is t108        assert env.select_template([t]) is t109        assert env.get_or_select_template([t]) is t110        assert env.get_or_select_template(t) is t111112    def test_get_template_undefined(self, env):113        """Passing Undefined to get/select_template raises an114        UndefinedError or shows the undefined message in the list.115        """116        env.loader = DictLoader({})117        t = Undefined(name="no_name_1")118119        with pytest.raises(UndefinedError):120            env.get_template(t)121122        with pytest.raises(UndefinedError):123            env.get_or_select_template(t)124125        with pytest.raises(UndefinedError):126            env.select_template(t)127128        with pytest.raises(TemplatesNotFound) as exc_info:129            env.select_template([t, "no_name_2"])130131        exc_message = str(exc_info.value)132        assert "'no_name_1' is undefined" in exc_message133        assert "no_name_2" in exc_message134135    def test_autoescape_autoselect(self, env):136        def select_autoescape(name):137            if name is None or "." not in name:138                return False139            return name.endswith(".html")140141        env = Environment(142            autoescape=select_autoescape,143            loader=DictLoader({"test.txt": "{{ foo }}", "test.html": "{{ foo }}"}),144        )145        t = env.get_template("test.txt")146        assert t.render(foo="<foo>") == "<foo>"147        t = env.get_template("test.html")148        assert t.render(foo="<foo>") == "&lt;foo&gt;"149        t = env.from_string("{{ foo }}")150        assert t.render(foo="<foo>") == "<foo>"151152    def test_sandbox_max_range(self, env):153        from jinja2.sandbox import MAX_RANGE154        from jinja2.sandbox import SandboxedEnvironment155156        env = SandboxedEnvironment()157        t = env.from_string("{% for item in range(total) %}{{ item }}{% endfor %}")158159        with pytest.raises(OverflowError):160            t.render(total=MAX_RANGE + 1)161162163class TestMeta:164    def test_find_undeclared_variables(self, env):165        ast = env.parse("{% set foo = 42 %}{{ bar + foo }}")166        x = meta.find_undeclared_variables(ast)167        assert x == {"bar"}168169        ast = env.parse(170            "{% set foo = 42 %}{{ bar + foo }}"171            "{% macro meh(x) %}{{ x }}{% endmacro %}"172            "{% for item in seq %}{{ muh(item) + meh(seq) }}"173            "{% endfor %}"174        )175        x = meta.find_undeclared_variables(ast)176        assert x == {"bar", "seq", "muh"}177178        ast = env.parse("{% for x in range(5) %}{{ x }}{% endfor %}{{ foo }}")179        x = meta.find_undeclared_variables(ast)180        assert x == {"foo"}181182    def test_find_refererenced_templates(self, env):183        ast = env.parse('{% extends "layout.html" %}{% include helper %}')184        i = meta.find_referenced_templates(ast)185        assert next(i) == "layout.html"186        assert next(i) is None187        assert list(i) == []188189        ast = env.parse(190            '{% extends "layout.html" %}'191            '{% from "test.html" import a, b as c %}'192            '{% import "meh.html" as meh %}'193            '{% include "muh.html" %}'194        )195        i = meta.find_referenced_templates(ast)196        assert list(i) == ["layout.html", "test.html", "meh.html", "muh.html"]197198    def test_find_included_templates(self, env):199        ast = env.parse('{% include ["foo.html", "bar.html"] %}')200        i = meta.find_referenced_templates(ast)201        assert list(i) == ["foo.html", "bar.html"]202203        ast = env.parse('{% include ("foo.html", "bar.html") %}')204        i = meta.find_referenced_templates(ast)205        assert list(i) == ["foo.html", "bar.html"]206207        ast = env.parse('{% include ["foo.html", "bar.html", foo] %}')208        i = meta.find_referenced_templates(ast)209        assert list(i) == ["foo.html", "bar.html", None]210211        ast = env.parse('{% include ("foo.html", "bar.html", foo) %}')212        i = meta.find_referenced_templates(ast)213        assert list(i) == ["foo.html", "bar.html", None]214215216class TestStreaming:217    def test_basic_streaming(self, env):218        t = env.from_string(219            "<ul>{% for item in seq %}<li>{{ loop.index }} - {{ item }}</li>"220            "{%- endfor %}</ul>"221        )222        stream = t.stream(seq=list(range(3)))223        assert next(stream) == "<ul>"224        assert "".join(stream) == "<li>1 - 0</li><li>2 - 1</li><li>3 - 2</li></ul>"225226    def test_buffered_streaming(self, env):227        tmpl = env.from_string(228            "<ul>{% for item in seq %}<li>{{ loop.index }} - {{ item }}</li>"229            "{%- endfor %}</ul>"230        )231        stream = tmpl.stream(seq=list(range(3)))232        stream.enable_buffering(size=3)233        assert next(stream) == "<ul><li>1"234        assert next(stream) == " - 0</li>"235236    def test_streaming_behavior(self, env):237        tmpl = env.from_string("")238        stream = tmpl.stream()239        assert not stream.buffered240        stream.enable_buffering(20)241        assert stream.buffered242        stream.disable_buffering()243        assert not stream.buffered244245    def test_dump_stream(self, env):246        tmp = Path(tempfile.mkdtemp())247        try:248            tmpl = env.from_string("\u2713")249            stream = tmpl.stream()250            stream.dump(str(tmp / "dump.txt"), "utf-8")251            assert (tmp / "dump.txt").read_bytes() == b"\xe2\x9c\x93"252        finally:253            shutil.rmtree(tmp)254255256class TestUndefined:257    def test_stopiteration_is_undefined(self):258        def test():259            raise StopIteration()260261        t = Template("A{{ test() }}B")262        assert t.render(test=test) == "AB"263        t = Template("A{{ test().missingattribute }}B")264        pytest.raises(UndefinedError, t.render, test=test)265266    def test_undefined_and_special_attributes(self):267        with pytest.raises(AttributeError):268            Undefined("Foo").__dict__  # noqa B018269270    def test_undefined_attribute_error(self):271        # Django's LazyObject turns the __class__ attribute into a272        # property that resolves the wrapped function. If that wrapped273        # function raises an AttributeError, printing the repr of the274        # object in the undefined message would cause a RecursionError.275        class Error:276            @property  # type: ignore277            def __class__(self):278                raise AttributeError()279280        u = Undefined(obj=Error(), name="hello")281282        with pytest.raises(UndefinedError):283            getattr(u, "recursion", None)284285    def test_logging_undefined(self):286        _messages = []287288        class DebugLogger:289            def warning(self, msg, *args):290                _messages.append("W:" + msg % args)291292            def error(self, msg, *args):293                _messages.append("E:" + msg % args)294295        logging_undefined = make_logging_undefined(DebugLogger())296        env = Environment(undefined=logging_undefined)297        assert env.from_string("{{ missing }}").render() == ""298        pytest.raises(UndefinedError, env.from_string("{{ missing.attribute }}").render)299        assert env.from_string("{{ missing|list }}").render() == "[]"300        assert env.from_string("{{ missing is not defined }}").render() == "True"301        assert env.from_string("{{ foo.missing }}").render(foo=42) == ""302        assert env.from_string("{{ not missing }}").render() == "True"303        assert _messages == [304            "W:Template variable warning: 'missing' is undefined",305            "E:Template variable error: 'missing' is undefined",306            "W:Template variable warning: 'missing' is undefined",307            "W:Template variable warning: 'int object' has no attribute 'missing'",308            "W:Template variable warning: 'missing' is undefined",309        ]310311    def test_default_undefined(self):312        env = Environment(undefined=Undefined)313        assert env.from_string("{{ missing }}").render() == ""314        pytest.raises(UndefinedError, env.from_string("{{ missing.attribute }}").render)315        assert env.from_string("{{ missing|list }}").render() == "[]"316        assert env.from_string("{{ missing is not defined }}").render() == "True"317        assert env.from_string("{{ foo.missing }}").render(foo=42) == ""318        assert env.from_string("{{ not missing }}").render() == "True"319        pytest.raises(UndefinedError, env.from_string("{{ missing - 1}}").render)320        assert env.from_string("{{ 'foo' in missing }}").render() == "False"321        und1 = Undefined(name="x")322        und2 = Undefined(name="y")323        assert und1 == und2324        assert und1 != 42325        assert hash(und1) == hash(und2) == hash(Undefined())326327    def test_chainable_undefined(self):328        env = Environment(undefined=ChainableUndefined)329        # The following tests are copied from test_default_undefined330        assert env.from_string("{{ missing }}").render() == ""331        assert env.from_string("{{ missing|list }}").render() == "[]"332        assert env.from_string("{{ missing is not defined }}").render() == "True"333        assert env.from_string("{{ foo.missing }}").render(foo=42) == ""334        assert env.from_string("{{ not missing }}").render() == "True"335        pytest.raises(UndefinedError, env.from_string("{{ missing - 1}}").render)336337        # The following tests ensure subclass functionality works as expected338        assert env.from_string('{{ missing.bar["baz"] }}').render() == ""339        assert env.from_string('{{ foo.bar["baz"]._undefined_name }}').render() == "foo"340        assert (341            env.from_string('{{ foo.bar["baz"]._undefined_name }}').render(foo=42)342            == "bar"343        )344        assert (345            env.from_string('{{ foo.bar["baz"]._undefined_name }}').render(346                foo={"bar": 42}347            )348            == "baz"349        )350351    def test_debug_undefined(self):352        env = Environment(undefined=DebugUndefined)353        assert env.from_string("{{ missing }}").render() == "{{ missing }}"354        pytest.raises(UndefinedError, env.from_string("{{ missing.attribute }}").render)355        assert env.from_string("{{ missing|list }}").render() == "[]"356        assert env.from_string("{{ missing is not defined }}").render() == "True"357        assert (358            env.from_string("{{ foo.missing }}").render(foo=42)359            == "{{ no such element: int object['missing'] }}"360        )361        assert env.from_string("{{ not missing }}").render() == "True"362        undefined_hint = "this is testing undefined hint of DebugUndefined"363        assert (364            str(DebugUndefined(hint=undefined_hint))365            == f"{{{{ undefined value printed: {undefined_hint} }}}}"366        )367368    def test_strict_undefined(self):369        env = Environment(undefined=StrictUndefined)370        pytest.raises(UndefinedError, env.from_string("{{ missing }}").render)371        pytest.raises(UndefinedError, env.from_string("{{ missing.attribute }}").render)372        pytest.raises(UndefinedError, env.from_string("{{ missing|list }}").render)373        pytest.raises(UndefinedError, env.from_string("{{ 'foo' in missing }}").render)374        assert env.from_string("{{ missing is not defined }}").render() == "True"375        pytest.raises(376            UndefinedError, env.from_string("{{ foo.missing }}").render, foo=42377        )378        pytest.raises(UndefinedError, env.from_string("{{ not missing }}").render)379        assert (380            env.from_string('{{ missing|default("default", true) }}').render()381            == "default"382        )383        assert env.from_string('{{ "foo" if false }}').render() == ""384385    def test_indexing_gives_undefined(self):386        t = Template("{{ var[42].foo }}")387        pytest.raises(UndefinedError, t.render, var=0)388389    def test_none_gives_proper_error(self):390        with pytest.raises(UndefinedError, match="'None' has no attribute 'split'"):391            Environment().getattr(None, "split")()392393    def test_object_repr(self):394        with pytest.raises(395            UndefinedError, match="'int object' has no attribute 'upper'"396        ):397            Undefined(obj=42, name="upper")()398399400class TestLowLevel:401    def test_custom_code_generator(self):402        class CustomCodeGenerator(CodeGenerator):403            def visit_Const(self, node, frame=None):404                # This method is pure nonsense, but works fine for testing...405                if node.value == "foo":406                    self.write(repr("bar"))407                else:408                    super().visit_Const(node, frame)409410        class CustomEnvironment(Environment):411            code_generator_class = CustomCodeGenerator412413        env = CustomEnvironment()414        tmpl = env.from_string('{% set foo = "foo" %}{{ foo }}')415        assert tmpl.render() == "bar"416417    def test_custom_context(self):418        class CustomContext(Context):419            def resolve_or_missing(self, key):420                return "resolve-" + key421422        class CustomEnvironment(Environment):423            context_class = CustomContext424425        env = CustomEnvironment()426        tmpl = env.from_string("{{ foo }}")427        assert tmpl.render() == "resolve-foo"428429430def test_overlay_enable_async(env):431    assert not env.is_async432    assert not env.overlay().is_async433    env_async = env.overlay(enable_async=True)434    assert env_async.is_async435    assert not env_async.overlay(enable_async=False).is_async