Skip to content
Myr

test_api.py

This file

Path

tests/test_api.py

437 lines · 16.7 KiB · Python

Last changed by

Merge pull request #1179 from pallets/undefined-recursionDavid Lordbefore adoption41ed50c

History of this file

Take it

1# -*- coding: utf-8 -*-2import os3import shutil4import tempfile56import pytest78from jinja2 import ChainableUndefined9from jinja2 import DebugUndefined10from jinja2 import DictLoader11from jinja2 import Environment12from jinja2 import is_undefined13from jinja2 import make_logging_undefined14from jinja2 import meta15from jinja2 import StrictUndefined16from jinja2 import Template17from jinja2 import TemplatesNotFound18from jinja2 import Undefined19from jinja2 import UndefinedError20from jinja2.compiler import CodeGenerator21from jinja2.runtime import Context22from jinja2.utils import contextfunction23from jinja2.utils import Cycler24from jinja2.utils import environmentfunction25from jinja2.utils import evalcontextfunction262728class TestExtendedAPI(object):29    def test_item_and_attribute(self, env):30        from jinja2.sandbox import SandboxedEnvironment3132        for env in Environment(), SandboxedEnvironment():33            # the |list is necessary for python334            tmpl = env.from_string("{{ foo.items()|list }}")35            assert tmpl.render(foo={"items": 42}) == "[('items', 42)]"36            tmpl = env.from_string('{{ foo|attr("items")()|list }}')37            assert tmpl.render(foo={"items": 42}) == "[('items', 42)]"38            tmpl = env.from_string('{{ foo["items"] }}')39            assert tmpl.render(foo={"items": 42}) == "42"4041    def test_finalize(self):42        e = Environment(finalize=lambda v: "" if v is None else v)43        t = e.from_string("{% for item in seq %}|{{ item }}{% endfor %}")44        assert t.render(seq=(None, 1, "foo")) == "||1|foo"4546    def test_finalize_constant_expression(self):47        e = Environment(finalize=lambda v: "" if v is None else v)48        t = e.from_string("<{{ none }}>")49        assert t.render() == "<>"5051    def test_no_finalize_template_data(self):52        e = Environment(finalize=lambda v: type(v).__name__)53        t = e.from_string("<{{ value }}>")54        # If template data was finalized, it would print "strintstr".55        assert t.render(value=123) == "<int>"5657    def test_context_finalize(self):58        @contextfunction59        def finalize(context, value):60            return value * context["scale"]6162        e = Environment(finalize=finalize)63        t = e.from_string("{{ value }}")64        assert t.render(value=5, scale=3) == "15"6566    def test_eval_finalize(self):67        @evalcontextfunction68        def finalize(eval_ctx, value):69            return str(eval_ctx.autoescape) + value7071        e = Environment(finalize=finalize, autoescape=True)72        t = e.from_string("{{ value }}")73        assert t.render(value="<script>") == "True&lt;script&gt;"7475    def test_env_autoescape(self):76        @environmentfunction77        def finalize(env, value):78            return " ".join(79                (env.variable_start_string, repr(value), env.variable_end_string)80            )8182        e = Environment(finalize=finalize)83        t = e.from_string("{{ value }}")84        assert t.render(value="hello") == "{{ 'hello' }}"8586    def test_cycler(self, env):87        items = 1, 2, 388        c = Cycler(*items)89        for item in items + items:90            assert c.current == item91            assert next(c) == item92        next(c)93        assert c.current == 294        c.reset()95        assert c.current == 19697    def test_expressions(self, env):98        expr = env.compile_expression("foo")99        assert expr() is None100        assert expr(foo=42) == 42101        expr2 = env.compile_expression("foo", undefined_to_none=False)102        assert is_undefined(expr2())103104        expr = env.compile_expression("42 + foo")105        assert expr(foo=42) == 84106107    def test_template_passthrough(self, env):108        t = Template("Content")109        assert env.get_template(t) is t110        assert env.select_template([t]) is t111        assert env.get_or_select_template([t]) is t112        assert env.get_or_select_template(t) is t113114    def test_get_template_undefined(self, env):115        """Passing Undefined to get/select_template raises an116        UndefinedError or shows the undefined message in the list.117        """118        env.loader = DictLoader({})119        t = Undefined(name="no_name_1")120121        with pytest.raises(UndefinedError):122            env.get_template(t)123124        with pytest.raises(UndefinedError):125            env.get_or_select_template(t)126127        with pytest.raises(UndefinedError):128            env.select_template(t)129130        with pytest.raises(TemplatesNotFound) as exc_info:131            env.select_template([t, "no_name_2"])132133        exc_message = str(exc_info.value)134        assert "'no_name_1' is undefined" in exc_message135        assert "no_name_2" in exc_message136137    def test_autoescape_autoselect(self, env):138        def select_autoescape(name):139            if name is None or "." not in name:140                return False141            return name.endswith(".html")142143        env = Environment(144            autoescape=select_autoescape,145            loader=DictLoader({"test.txt": "{{ foo }}", "test.html": "{{ foo }}"}),146        )147        t = env.get_template("test.txt")148        assert t.render(foo="<foo>") == "<foo>"149        t = env.get_template("test.html")150        assert t.render(foo="<foo>") == "&lt;foo&gt;"151        t = env.from_string("{{ foo }}")152        assert t.render(foo="<foo>") == "<foo>"153154    def test_sandbox_max_range(self, env):155        from jinja2.sandbox import SandboxedEnvironment, MAX_RANGE156157        env = SandboxedEnvironment()158        t = env.from_string("{% for item in range(total) %}{{ item }}{% endfor %}")159160        with pytest.raises(OverflowError):161            t.render(total=MAX_RANGE + 1)162163164class TestMeta(object):165    def test_find_undeclared_variables(self, env):166        ast = env.parse("{% set foo = 42 %}{{ bar + foo }}")167        x = meta.find_undeclared_variables(ast)168        assert x == set(["bar"])169170        ast = env.parse(171            "{% set foo = 42 %}{{ bar + foo }}"172            "{% macro meh(x) %}{{ x }}{% endmacro %}"173            "{% for item in seq %}{{ muh(item) + meh(seq) }}"174            "{% endfor %}"175        )176        x = meta.find_undeclared_variables(ast)177        assert x == set(["bar", "seq", "muh"])178179        ast = env.parse("{% for x in range(5) %}{{ x }}{% endfor %}{{ foo }}")180        x = meta.find_undeclared_variables(ast)181        assert x == set(["foo"])182183    def test_find_refererenced_templates(self, env):184        ast = env.parse('{% extends "layout.html" %}{% include helper %}')185        i = meta.find_referenced_templates(ast)186        assert next(i) == "layout.html"187        assert next(i) is None188        assert list(i) == []189190        ast = env.parse(191            '{% extends "layout.html" %}'192            '{% from "test.html" import a, b as c %}'193            '{% import "meh.html" as meh %}'194            '{% include "muh.html" %}'195        )196        i = meta.find_referenced_templates(ast)197        assert list(i) == ["layout.html", "test.html", "meh.html", "muh.html"]198199    def test_find_included_templates(self, env):200        ast = env.parse('{% include ["foo.html", "bar.html"] %}')201        i = meta.find_referenced_templates(ast)202        assert list(i) == ["foo.html", "bar.html"]203204        ast = env.parse('{% include ("foo.html", "bar.html") %}')205        i = meta.find_referenced_templates(ast)206        assert list(i) == ["foo.html", "bar.html"]207208        ast = env.parse('{% include ["foo.html", "bar.html", foo] %}')209        i = meta.find_referenced_templates(ast)210        assert list(i) == ["foo.html", "bar.html", None]211212        ast = env.parse('{% include ("foo.html", "bar.html", foo) %}')213        i = meta.find_referenced_templates(ast)214        assert list(i) == ["foo.html", "bar.html", None]215216217class TestStreaming(object):218    def test_basic_streaming(self, env):219        t = env.from_string(220            "<ul>{% for item in seq %}<li>{{ loop.index }} - {{ item }}</li>"221            "{%- endfor %}</ul>"222        )223        stream = t.stream(seq=list(range(3)))224        assert next(stream) == "<ul>"225        assert "".join(stream) == "<li>1 - 0</li><li>2 - 1</li><li>3 - 2</li></ul>"226227    def test_buffered_streaming(self, env):228        tmpl = env.from_string(229            "<ul>{% for item in seq %}<li>{{ loop.index }} - {{ item }}</li>"230            "{%- endfor %}</ul>"231        )232        stream = tmpl.stream(seq=list(range(3)))233        stream.enable_buffering(size=3)234        assert next(stream) == u"<ul><li>1"235        assert next(stream) == u" - 0</li>"236237    def test_streaming_behavior(self, env):238        tmpl = env.from_string("")239        stream = tmpl.stream()240        assert not stream.buffered241        stream.enable_buffering(20)242        assert stream.buffered243        stream.disable_buffering()244        assert not stream.buffered245246    def test_dump_stream(self, env):247        tmp = tempfile.mkdtemp()248        try:249            tmpl = env.from_string(u"\u2713")250            stream = tmpl.stream()251            stream.dump(os.path.join(tmp, "dump.txt"), "utf-8")252            with open(os.path.join(tmp, "dump.txt"), "rb") as f:253                assert f.read() == b"\xe2\x9c\x93"254        finally:255            shutil.rmtree(tmp)256257258class TestUndefined(object):259    def test_stopiteration_is_undefined(self):260        def test():261            raise StopIteration()262263        t = Template("A{{ test() }}B")264        assert t.render(test=test) == "AB"265        t = Template("A{{ test().missingattribute }}B")266        pytest.raises(UndefinedError, t.render, test=test)267268    def test_undefined_and_special_attributes(self):269        with pytest.raises(AttributeError):270            Undefined("Foo").__dict__271272    def test_undefined_attribute_error(self):273        # Django's LazyObject turns the __class__ attribute into a274        # property that resolves the wrapped function. If that wrapped275        # function raises an AttributeError, printing the repr of the276        # object in the undefined message would cause a RecursionError.277        class Error(object):278            @property279            def __class__(self):280                raise AttributeError()281282        u = Undefined(obj=Error(), name="hello")283284        with pytest.raises(UndefinedError):285            getattr(u, "recursion", None)286287    def test_logging_undefined(self):288        _messages = []289290        class DebugLogger(object):291            def warning(self, msg, *args):292                _messages.append("W:" + msg % args)293294            def error(self, msg, *args):295                _messages.append("E:" + msg % args)296297        logging_undefined = make_logging_undefined(DebugLogger())298        env = Environment(undefined=logging_undefined)299        assert env.from_string("{{ missing }}").render() == u""300        pytest.raises(UndefinedError, env.from_string("{{ missing.attribute }}").render)301        assert env.from_string("{{ missing|list }}").render() == "[]"302        assert env.from_string("{{ missing is not defined }}").render() == "True"303        assert env.from_string("{{ foo.missing }}").render(foo=42) == ""304        assert env.from_string("{{ not missing }}").render() == "True"305        assert _messages == [306            "W:Template variable warning: missing is undefined",307            "E:Template variable error: 'missing' is undefined",308            "W:Template variable warning: missing is undefined",309            "W:Template variable warning: int object has no attribute missing",310            "W:Template variable warning: missing is undefined",311        ]312313    def test_default_undefined(self):314        env = Environment(undefined=Undefined)315        assert env.from_string("{{ missing }}").render() == u""316        pytest.raises(UndefinedError, env.from_string("{{ missing.attribute }}").render)317        assert env.from_string("{{ missing|list }}").render() == "[]"318        assert env.from_string("{{ missing is not defined }}").render() == "True"319        assert env.from_string("{{ foo.missing }}").render(foo=42) == ""320        assert env.from_string("{{ not missing }}").render() == "True"321        pytest.raises(UndefinedError, env.from_string("{{ missing - 1}}").render)322        und1 = Undefined(name="x")323        und2 = Undefined(name="y")324        assert und1 == und2325        assert und1 != 42326        assert hash(und1) == hash(und2) == hash(Undefined())327        with pytest.raises(AttributeError):328            getattr(Undefined, "__slots__")  # noqa: B009329330    def test_chainable_undefined(self):331        env = Environment(undefined=ChainableUndefined)332        # The following tests are copied from test_default_undefined333        assert env.from_string("{{ missing }}").render() == u""334        assert env.from_string("{{ missing|list }}").render() == "[]"335        assert env.from_string("{{ missing is not defined }}").render() == "True"336        assert env.from_string("{{ foo.missing }}").render(foo=42) == ""337        assert env.from_string("{{ not missing }}").render() == "True"338        pytest.raises(UndefinedError, env.from_string("{{ missing - 1}}").render)339        with pytest.raises(AttributeError):340            getattr(ChainableUndefined, "__slots__")  # noqa: B009341342        # The following tests ensure subclass functionality works as expected343        assert env.from_string('{{ missing.bar["baz"] }}').render() == u""344        assert (345            env.from_string('{{ foo.bar["baz"]._undefined_name }}').render() == u"foo"346        )347        assert (348            env.from_string('{{ foo.bar["baz"]._undefined_name }}').render(foo=42)349            == u"bar"350        )351        assert (352            env.from_string('{{ foo.bar["baz"]._undefined_name }}').render(353                foo={"bar": 42}354            )355            == u"baz"356        )357358    def test_debug_undefined(self):359        env = Environment(undefined=DebugUndefined)360        assert env.from_string("{{ missing }}").render() == "{{ missing }}"361        pytest.raises(UndefinedError, env.from_string("{{ missing.attribute }}").render)362        assert env.from_string("{{ missing|list }}").render() == "[]"363        assert env.from_string("{{ missing is not defined }}").render() == "True"364        assert (365            env.from_string("{{ foo.missing }}").render(foo=42)366            == u"{{ no such element: int object['missing'] }}"367        )368        assert env.from_string("{{ not missing }}").render() == "True"369        undefined_hint = "this is testing undefined hint of DebugUndefined"370        assert (371            str(DebugUndefined(hint=undefined_hint))372            == u"{{ undefined value printed: %s }}" % undefined_hint373        )374        with pytest.raises(AttributeError):375            getattr(DebugUndefined, "__slots__")  # noqa: B009376377    def test_strict_undefined(self):378        env = Environment(undefined=StrictUndefined)379        pytest.raises(UndefinedError, env.from_string("{{ missing }}").render)380        pytest.raises(UndefinedError, env.from_string("{{ missing.attribute }}").render)381        pytest.raises(UndefinedError, env.from_string("{{ missing|list }}").render)382        assert env.from_string("{{ missing is not defined }}").render() == "True"383        pytest.raises(384            UndefinedError, env.from_string("{{ foo.missing }}").render, foo=42385        )386        pytest.raises(UndefinedError, env.from_string("{{ not missing }}").render)387        assert (388            env.from_string('{{ missing|default("default", true) }}').render()389            == "default"390        )391        with pytest.raises(AttributeError):392            getattr(StrictUndefined, "__slots__")  # noqa: B009393        assert env.from_string('{{ "foo" if false }}').render() == ""394395    def test_indexing_gives_undefined(self):396        t = Template("{{ var[42].foo }}")397        pytest.raises(UndefinedError, t.render, var=0)398399    def test_none_gives_proper_error(self):400        with pytest.raises(UndefinedError, match="'None' has no attribute 'split'"):401            Environment().getattr(None, "split")()402403    def test_object_repr(self):404        with pytest.raises(405            UndefinedError, match="'int object' has no attribute 'upper'"406        ):407            Undefined(obj=42, name="upper")()408409410class TestLowLevel(object):411    def test_custom_code_generator(self):412        class CustomCodeGenerator(CodeGenerator):413            def visit_Const(self, node, frame=None):414                # This method is pure nonsense, but works fine for testing...415                if node.value == "foo":416                    self.write(repr("bar"))417                else:418                    super(CustomCodeGenerator, self).visit_Const(node, frame)419420        class CustomEnvironment(Environment):421            code_generator_class = CustomCodeGenerator422423        env = CustomEnvironment()424        tmpl = env.from_string('{% set foo = "foo" %}{{ foo }}')425        assert tmpl.render() == "bar"426427    def test_custom_context(self):428        class CustomContext(Context):429            def resolve_or_missing(self, key):430                return "resolve-" + key431432        class CustomEnvironment(Environment):433            context_class = CustomContext434435        env = CustomEnvironment()436        tmpl = env.from_string("{{ foo }}")437        assert tmpl.render() == "resolve-foo"