# -*- coding: utf-8 -*- import os import shutil import tempfile import pytest from jinja2 import ChainableUndefined from jinja2 import DebugUndefined from jinja2 import DictLoader from jinja2 import Environment from jinja2 import is_undefined from jinja2 import make_logging_undefined from jinja2 import meta from jinja2 import StrictUndefined from jinja2 import Template from jinja2 import TemplatesNotFound from jinja2 import Undefined from jinja2 import UndefinedError from jinja2.compiler import CodeGenerator from jinja2.runtime import Context from jinja2.utils import contextfunction from jinja2.utils import Cycler from jinja2.utils import environmentfunction from jinja2.utils import evalcontextfunction class TestExtendedAPI(object): def test_item_and_attribute(self, env): from jinja2.sandbox import SandboxedEnvironment for env in Environment(), SandboxedEnvironment(): # the |list is necessary for python3 tmpl = env.from_string("{{ foo.items()|list }}") assert tmpl.render(foo={"items": 42}) == "[('items', 42)]" tmpl = env.from_string('{{ foo|attr("items")()|list }}') assert tmpl.render(foo={"items": 42}) == "[('items', 42)]" tmpl = env.from_string('{{ foo["items"] }}') assert tmpl.render(foo={"items": 42}) == "42" def test_finalize(self): e = Environment(finalize=lambda v: "" if v is None else v) t = e.from_string("{% for item in seq %}|{{ item }}{% endfor %}") assert t.render(seq=(None, 1, "foo")) == "||1|foo" def test_finalize_constant_expression(self): e = Environment(finalize=lambda v: "" if v is None else v) t = e.from_string("<{{ none }}>") assert t.render() == "<>" def test_no_finalize_template_data(self): e = Environment(finalize=lambda v: type(v).__name__) t = e.from_string("<{{ value }}>") # If template data was finalized, it would print "strintstr". assert t.render(value=123) == "" def test_context_finalize(self): @contextfunction def finalize(context, value): return value * context["scale"] e = Environment(finalize=finalize) t = e.from_string("{{ value }}") assert t.render(value=5, scale=3) == "15" def test_eval_finalize(self): @evalcontextfunction def finalize(eval_ctx, value): return str(eval_ctx.autoescape) + value e = Environment(finalize=finalize, autoescape=True) t = e.from_string("{{ value }}") assert t.render(value="