1 # -*- coding: utf-8 -*-
3 unit test for the imports and includes
4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
6 :copyright: (c) 2009 by the Jinja Team.
7 :license: BSD, see LICENSE for more details.
9 from py.test import raises
10 from jinja2 import Environment, DictLoader
11 from jinja2.exceptions import TemplateNotFound
14 test_env = Environment(loader=DictLoader(dict(
15 module='{% macro test() %}[{{ foo }}|{{ bar }}]{% endmacro %}',
16 header='[{{ foo }}|{{ 23 }}]',
19 test_env.globals['bar'] = 23
22 def test_context_imports():
23 t = test_env.from_string('{% import "module" as m %}{{ m.test() }}')
24 assert t.render(foo=42) == '[|23]'
25 t = test_env.from_string('{% import "module" as m without context %}{{ m.test() }}')
26 assert t.render(foo=42) == '[|23]'
27 t = test_env.from_string('{% import "module" as m with context %}{{ m.test() }}')
28 assert t.render(foo=42) == '[42|23]'
29 t = test_env.from_string('{% from "module" import test %}{{ test() }}')
30 assert t.render(foo=42) == '[|23]'
31 t = test_env.from_string('{% from "module" import test without context %}{{ test() }}')
32 assert t.render(foo=42) == '[|23]'
33 t = test_env.from_string('{% from "module" import test with context %}{{ test() }}')
34 assert t.render(foo=42) == '[42|23]'
37 def test_context_include():
38 t = test_env.from_string('{% include "header" %}')
39 assert t.render(foo=42) == '[42|23]'
40 t = test_env.from_string('{% include "header" with context %}')
41 assert t.render(foo=42) == '[42|23]'
42 t = test_env.from_string('{% include "header" without context %}')
43 assert t.render(foo=42) == '[|23]'
46 def test_include_ignoring_missing():
47 t = test_env.from_string('{% include "missing" %}')
48 raises(TemplateNotFound, t.render)
49 for extra in '', 'with context', 'without context':
50 t = test_env.from_string('{% include "missing" ignore missing ' +
52 assert t.render() == ''
55 def test_context_include_with_overrides():
56 env = Environment(loader=DictLoader(dict(
57 main="{% for item in [1, 2, 3] %}{% include 'item' %}{% endfor %}",
60 assert env.get_template("main").render() == "123"
63 def test_trailing_comma():
64 test_env.from_string('{% from "foo" import bar, baz with context %}')
65 test_env.from_string('{% from "foo" import bar, baz, with context %}')
66 test_env.from_string('{% from "foo" import bar, with context %}')
67 test_env.from_string('{% from "foo" import bar, with, context %}')
68 test_env.from_string('{% from "foo" import bar, with with context %}')
72 m = test_env.from_string('''
73 {% macro toplevel() %}...{% endmacro %}
74 {% macro __private() %}...{% endmacro %}
75 {% set variable = 42 %}
77 {% macro notthere() %}{% endmacro %}
80 assert m.toplevel() == '...'
81 assert not hasattr(m, '__missing')
82 assert m.variable == 42
83 assert not hasattr(m, 'notthere')
86 def test_unoptimized_scopes():
87 t = test_env.from_string("""
90 {% include "o_printer" %}
96 assert t.render().strip() == '(FOO)'