Fixed a broken unittest and fixed a bug that required multiple tests to be put into...
[jinja2.git] / tests / test_various.py
1 # -*- coding: utf-8 -*-
2 """
3     unit test for various things
4     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
5
6     :copyright: 2007 by Armin Ronacher.
7     :license: BSD, see LICENSE for more details.
8 """
9 import gc
10 from py.test import raises
11 from jinja2 import escape
12 from jinja2.exceptions import TemplateSyntaxError
13
14
15 UNPACKING = '''{% for a, b, c in [[1, 2, 3]] %}{{ a }}|{{ b }}|{{ c }}{% endfor %}'''
16 RAW = '''{% raw %}{{ FOO }} and {% BAR %}{% endraw %}'''
17 CONST = '''{{ true }}|{{ false }}|{{ none }}|\
18 {{ none is defined }}|{{ missing is defined }}'''
19 LOCALSET = '''{% set foo = 0 %}\
20 {% for item in [1, 2] %}{% set foo = 1 %}{% endfor %}\
21 {{ foo }}'''
22 CONSTASS1 = '''{% set true = 42 %}'''
23 CONSTASS2 = '''{% for none in seq %}{% endfor %}'''
24
25
26 def test_unpacking(env):
27     tmpl = env.from_string(UNPACKING)
28     assert tmpl.render() == '1|2|3'
29
30
31 def test_raw(env):
32     tmpl = env.from_string(RAW)
33     assert tmpl.render() == '{{ FOO }} and {% BAR %}'
34
35
36 def test_const(env):
37     tmpl = env.from_string(CONST)
38     assert tmpl.render() == 'True|False|None|True|False'
39
40
41 def test_const_assign(env):
42     for tmpl in CONSTASS1, CONSTASS2:
43         raises(TemplateSyntaxError, env.from_string, tmpl)
44
45
46 def test_localset(env):
47     tmpl = env.from_string(LOCALSET)
48     assert tmpl.render() == '0'
49
50
51 def test_markup_leaks():
52     counts = set()
53     for count in xrange(20):
54         for item in xrange(1000):
55             escape("foo")
56             escape("<foo>")
57             escape(u"foo")
58             escape(u"<foo>")
59         counts.add(len(gc.get_objects()))
60     assert len(counts) == 1, 'ouch, c extension seems to leak objects'
61
62
63 def test_item_and_attribute():
64     from jinja2 import Environment
65     from jinja2.sandbox import SandboxedEnvironment
66
67     for env in Environment(), SandboxedEnvironment():
68         tmpl = env.from_string('{{ foo.items() }}')
69         assert tmpl.render(foo={'items': 42}) == "[('items', 42)]"
70         tmpl = env.from_string('{{ foo|attr("items")() }}')
71         assert tmpl.render(foo={'items': 42}) == "[('items', 42)]"
72         tmpl = env.from_string('{{ foo["items"] }}')
73         assert tmpl.render(foo={'items': 42}) == '42'