Skip to content
Myr

test_api.py

This file

Path

tests/test_api.py

434 lines · 16.6 KiB · Python

Last changed by

Merge remote-tracking branch 'origin/3.0.x'David Lordbefore adoption35c69e9

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 SandboxedEnvironment, MAX_RANGE154155        env = SandboxedEnvironment()156        t = env.from_string("{% for item in range(total) %}{{ item }}{% endfor %}")157158        with pytest.raises(OverflowError):159            t.render(total=MAX_RANGE + 1)160161162class TestMeta:163    def test_find_undeclared_variables(self, env):164        ast = env.parse("{% set foo = 42 %}{{ bar + foo }}")165        x = meta.find_undeclared_variables(ast)166        assert x == {"bar"}167168        ast = env.parse(169            "{% set foo = 42 %}{{ bar + foo }}"170            "{% macro meh(x) %}{{ x }}{% endmacro %}"171            "{% for item in seq %}{{ muh(item) + meh(seq) }}"172            "{% endfor %}"173        )174        x = meta.find_undeclared_variables(ast)175        assert x == {"bar", "seq", "muh"}176177        ast = env.parse("{% for x in range(5) %}{{ x }}{% endfor %}{{ foo }}")178        x = meta.find_undeclared_variables(ast)179        assert x == {"foo"}180181    def test_find_refererenced_templates(self, env):182        ast = env.parse('{% extends "layout.html" %}{% include helper %}')183        i = meta.find_referenced_templates(ast)184        assert next(i) == "layout.html"185        assert next(i) is None186        assert list(i) == []187188        ast = env.parse(189            '{% extends "layout.html" %}'190            '{% from "test.html" import a, b as c %}'191            '{% import "meh.html" as meh %}'192            '{% include "muh.html" %}'193        )194        i = meta.find_referenced_templates(ast)195        assert list(i) == ["layout.html", "test.html", "meh.html", "muh.html"]196197    def test_find_included_templates(self, env):198        ast = env.parse('{% include ["foo.html", "bar.html"] %}')199        i = meta.find_referenced_templates(ast)200        assert list(i) == ["foo.html", "bar.html"]201202        ast = env.parse('{% include ("foo.html", "bar.html") %}')203        i = meta.find_referenced_templates(ast)204        assert list(i) == ["foo.html", "bar.html"]205206        ast = env.parse('{% include ["foo.html", "bar.html", foo] %}')207        i = meta.find_referenced_templates(ast)208        assert list(i) == ["foo.html", "bar.html", None]209210        ast = env.parse('{% include ("foo.html", "bar.html", foo) %}')211        i = meta.find_referenced_templates(ast)212        assert list(i) == ["foo.html", "bar.html", None]213214215class TestStreaming:216    def test_basic_streaming(self, env):217        t = env.from_string(218            "<ul>{% for item in seq %}<li>{{ loop.index }} - {{ item }}</li>"219            "{%- endfor %}</ul>"220        )221        stream = t.stream(seq=list(range(3)))222        assert next(stream) == "<ul>"223        assert "".join(stream) == "<li>1 - 0</li><li>2 - 1</li><li>3 - 2</li></ul>"224225    def test_buffered_streaming(self, env):226        tmpl = env.from_string(227            "<ul>{% for item in seq %}<li>{{ loop.index }} - {{ item }}</li>"228            "{%- endfor %}</ul>"229        )230        stream = tmpl.stream(seq=list(range(3)))231        stream.enable_buffering(size=3)232        assert next(stream) == "<ul><li>1"233        assert next(stream) == " - 0</li>"234235    def test_streaming_behavior(self, env):236        tmpl = env.from_string("")237        stream = tmpl.stream()238        assert not stream.buffered239        stream.enable_buffering(20)240        assert stream.buffered241        stream.disable_buffering()242        assert not stream.buffered243244    def test_dump_stream(self, env):245        tmp = Path(tempfile.mkdtemp())246        try:247            tmpl = env.from_string("\u2713")248            stream = tmpl.stream()249            stream.dump(str(tmp / "dump.txt"), "utf-8")250            assert (tmp / "dump.txt").read_bytes() == b"\xe2\x9c\x93"251        finally:252            shutil.rmtree(tmp)253254255class TestUndefined:256    def test_stopiteration_is_undefined(self):257        def test():258            raise StopIteration()259260        t = Template("A{{ test() }}B")261        assert t.render(test=test) == "AB"262        t = Template("A{{ test().missingattribute }}B")263        pytest.raises(UndefinedError, t.render, test=test)264265    def test_undefined_and_special_attributes(self):266        with pytest.raises(AttributeError):267            Undefined("Foo").__dict__268269    def test_undefined_attribute_error(self):270        # Django's LazyObject turns the __class__ attribute into a271        # property that resolves the wrapped function. If that wrapped272        # function raises an AttributeError, printing the repr of the273        # object in the undefined message would cause a RecursionError.274        class Error:275            @property  # type: ignore276            def __class__(self):277                raise AttributeError()278279        u = Undefined(obj=Error(), name="hello")280281        with pytest.raises(UndefinedError):282            getattr(u, "recursion", None)283284    def test_logging_undefined(self):285        _messages = []286287        class DebugLogger:288            def warning(self, msg, *args):289                _messages.append("W:" + msg % args)290291            def error(self, msg, *args):292                _messages.append("E:" + msg % args)293294        logging_undefined = make_logging_undefined(DebugLogger())295        env = Environment(undefined=logging_undefined)296        assert env.from_string("{{ missing }}").render() == ""297        pytest.raises(UndefinedError, env.from_string("{{ missing.attribute }}").render)298        assert env.from_string("{{ missing|list }}").render() == "[]"299        assert env.from_string("{{ missing is not defined }}").render() == "True"300        assert env.from_string("{{ foo.missing }}").render(foo=42) == ""301        assert env.from_string("{{ not missing }}").render() == "True"302        assert _messages == [303            "W:Template variable warning: 'missing' is undefined",304            "E:Template variable error: 'missing' is undefined",305            "W:Template variable warning: 'missing' is undefined",306            "W:Template variable warning: 'int object' has no attribute 'missing'",307            "W:Template variable warning: 'missing' is undefined",308        ]309310    def test_default_undefined(self):311        env = Environment(undefined=Undefined)312        assert env.from_string("{{ missing }}").render() == ""313        pytest.raises(UndefinedError, env.from_string("{{ missing.attribute }}").render)314        assert env.from_string("{{ missing|list }}").render() == "[]"315        assert env.from_string("{{ missing is not defined }}").render() == "True"316        assert env.from_string("{{ foo.missing }}").render(foo=42) == ""317        assert env.from_string("{{ not missing }}").render() == "True"318        pytest.raises(UndefinedError, env.from_string("{{ missing - 1}}").render)319        assert env.from_string("{{ 'foo' in missing }}").render() == "False"320        und1 = Undefined(name="x")321        und2 = Undefined(name="y")322        assert und1 == und2323        assert und1 != 42324        assert hash(und1) == hash(und2) == hash(Undefined())325        with pytest.raises(AttributeError):326            getattr(Undefined, "__slots__")  # noqa: B009327328    def test_chainable_undefined(self):329        env = Environment(undefined=ChainableUndefined)330        # The following tests are copied from test_default_undefined331        assert env.from_string("{{ missing }}").render() == ""332        assert env.from_string("{{ missing|list }}").render() == "[]"333        assert env.from_string("{{ missing is not defined }}").render() == "True"334        assert env.from_string("{{ foo.missing }}").render(foo=42) == ""335        assert env.from_string("{{ not missing }}").render() == "True"336        pytest.raises(UndefinedError, env.from_string("{{ missing - 1}}").render)337        with pytest.raises(AttributeError):338            getattr(ChainableUndefined, "__slots__")  # noqa: B009339340        # The following tests ensure subclass functionality works as expected341        assert env.from_string('{{ missing.bar["baz"] }}').render() == ""342        assert env.from_string('{{ foo.bar["baz"]._undefined_name }}').render() == "foo"343        assert (344            env.from_string('{{ foo.bar["baz"]._undefined_name }}').render(foo=42)345            == "bar"346        )347        assert (348            env.from_string('{{ foo.bar["baz"]._undefined_name }}').render(349                foo={"bar": 42}350            )351            == "baz"352        )353354    def test_debug_undefined(self):355        env = Environment(undefined=DebugUndefined)356        assert env.from_string("{{ missing }}").render() == "{{ missing }}"357        pytest.raises(UndefinedError, env.from_string("{{ missing.attribute }}").render)358        assert env.from_string("{{ missing|list }}").render() == "[]"359        assert env.from_string("{{ missing is not defined }}").render() == "True"360        assert (361            env.from_string("{{ foo.missing }}").render(foo=42)362            == "{{ no such element: int object['missing'] }}"363        )364        assert env.from_string("{{ not missing }}").render() == "True"365        undefined_hint = "this is testing undefined hint of DebugUndefined"366        assert (367            str(DebugUndefined(hint=undefined_hint))368            == f"{{{{ undefined value printed: {undefined_hint} }}}}"369        )370        with pytest.raises(AttributeError):371            getattr(DebugUndefined, "__slots__")  # noqa: B009372373    def test_strict_undefined(self):374        env = Environment(undefined=StrictUndefined)375        pytest.raises(UndefinedError, env.from_string("{{ missing }}").render)376        pytest.raises(UndefinedError, env.from_string("{{ missing.attribute }}").render)377        pytest.raises(UndefinedError, env.from_string("{{ missing|list }}").render)378        pytest.raises(UndefinedError, env.from_string("{{ 'foo' in missing }}").render)379        assert env.from_string("{{ missing is not defined }}").render() == "True"380        pytest.raises(381            UndefinedError, env.from_string("{{ foo.missing }}").render, foo=42382        )383        pytest.raises(UndefinedError, env.from_string("{{ not missing }}").render)384        assert (385            env.from_string('{{ missing|default("default", true) }}').render()386            == "default"387        )388        with pytest.raises(AttributeError):389            getattr(StrictUndefined, "__slots__")  # noqa: B009390        assert env.from_string('{{ "foo" if false }}').render() == ""391392    def test_indexing_gives_undefined(self):393        t = Template("{{ var[42].foo }}")394        pytest.raises(UndefinedError, t.render, var=0)395396    def test_none_gives_proper_error(self):397        with pytest.raises(UndefinedError, match="'None' has no attribute 'split'"):398            Environment().getattr(None, "split")()399400    def test_object_repr(self):401        with pytest.raises(402            UndefinedError, match="'int object' has no attribute 'upper'"403        ):404            Undefined(obj=42, name="upper")()405406407class TestLowLevel:408    def test_custom_code_generator(self):409        class CustomCodeGenerator(CodeGenerator):410            def visit_Const(self, node, frame=None):411                # This method is pure nonsense, but works fine for testing...412                if node.value == "foo":413                    self.write(repr("bar"))414                else:415                    super().visit_Const(node, frame)416417        class CustomEnvironment(Environment):418            code_generator_class = CustomCodeGenerator419420        env = CustomEnvironment()421        tmpl = env.from_string('{% set foo = "foo" %}{{ foo }}')422        assert tmpl.render() == "bar"423424    def test_custom_context(self):425        class CustomContext(Context):426            def resolve_or_missing(self, key):427                return "resolve-" + key428429        class CustomEnvironment(Environment):430            context_class = CustomContext431432        env = CustomEnvironment()433        tmpl = env.from_string("{{ foo }}")434        assert tmpl.render() == "resolve-foo"