Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

Removed old testsuite.

--HG--
branch : trunk
  • Loading branch information...
commit b36ddc9a97c3f17b8f728707f0e61ec6cb49d148 1 parent 9d8ff9e
@mitsuhiko authored
View
6 Makefile
@@ -1,8 +1,4 @@
test:
- nosetests --with-doctest jinja2 tests
-
-2to3:
- rm -rf build/lib
- python3 setup.py build
+ python setup.py test
.PHONY: test
View
0  tests/loaderres/__init__.py
No changes.
View
3  tests/loaderres/templates/broken.html
@@ -1,3 +0,0 @@
-Before
-{{ fail() }}
-After
View
1  tests/loaderres/templates/foo/test.html
@@ -1 +0,0 @@
-FOO
View
4 tests/loaderres/templates/syntaxerror.html
@@ -1,4 +0,0 @@
-Foo
-{% for item in broken %}
- ...
-{% endif %}
View
1  tests/loaderres/templates/test.html
@@ -1 +0,0 @@
-BAR
View
51 tests/test_debug.py
@@ -1,51 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- Test debug interface
- ~~~~~~~~~~~~~~~~~~~~
-
- Tests the traceback rewriter.
-
- :copyright: (c) 2009 by the Jinja Team.
- :license: BSD.
-"""
-from jinja2 import Environment
-from test_loaders import filesystem_loader
-
-env = Environment(loader=filesystem_loader)
-
-
-def test_runtime_error():
- '''
->>> tmpl = env.get_template('broken.html')
->>> tmpl.render(fail=lambda: 1 / 0)
-Traceback (most recent call last):
- File "loaderres/templates/broken.html", line 2, in top-level template code
- {{ fail() }}
- File "<doctest test_runtime_error[1]>", line 1, in <lambda>
- tmpl.render(fail=lambda: 1 / 0)
-ZeroDivisionError: integer division or modulo by zero
-'''
-
-
-def test_syntax_error():
- '''
->>> tmpl = env.get_template('syntaxerror.html')
-Traceback (most recent call last):
- ...
- File "tests/loaderres/templates/syntaxerror.html", line 4, in template
- {% endif %}
-TemplateSyntaxError: Encountered unknown tag 'endif'. Jinja was looking for the following tags: 'endfor' or 'else'. The innermost block that needs to be closed is 'for'.
-'''
-
-
-def test_regular_syntax_error():
- '''
->>> from jinja2.exceptions import TemplateSyntaxError
->>> raise TemplateSyntaxError('wtf', 42)
-Traceback (most recent call last):
- ...
- File "<doctest test_regular_syntax_error[1]>", line 1, in <module>
- raise TemplateSyntaxError('wtf', 42)
-TemplateSyntaxError: wtf
- line 42
-'''
View
173 tests/test_ext.py
@@ -1,173 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- unit test for some extensions
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
- :copyright: (c) 2009 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-import re
-from jinja2 import Environment, nodes
-from jinja2.ext import Extension
-from jinja2.lexer import Token, count_newlines
-
-
-importable_object = 23
-
-
-_gettext_re = re.compile(r'_\((.*?)\)(?s)')
-
-
-class TestExtension(Extension):
- tags = set(['test'])
- ext_attr = 42
-
- def parse(self, parser):
- return nodes.Output([self.call_method('_dump', [
- nodes.EnvironmentAttribute('sandboxed'),
- self.attr('ext_attr'),
- nodes.ImportedName(__name__ + '.importable_object'),
- nodes.ContextReference()
- ])]).set_lineno(parser.stream.next().lineno)
-
- def _dump(self, sandboxed, ext_attr, imported_object, context):
- return '%s|%s|%s|%s' % (
- sandboxed,
- ext_attr,
- imported_object,
- context.blocks
- )
-
-
-class PreprocessorExtension(Extension):
-
- def preprocess(self, source, name, filename=None):
- return source.replace('[[TEST]]', '({{ foo }})')
-
-
-class StreamFilterExtension(Extension):
-
- def filter_stream(self, stream):
- for token in stream:
- if token.type == 'data':
- for t in self.interpolate(token):
- yield t
- else:
- yield token
-
- def interpolate(self, token):
- pos = 0
- end = len(token.value)
- lineno = token.lineno
- while 1:
- match = _gettext_re.search(token.value, pos)
- if match is None:
- break
- value = token.value[pos:match.start()]
- if value:
- yield Token(lineno, 'data', value)
- lineno += count_newlines(token.value)
- yield Token(lineno, 'variable_begin', None)
- yield Token(lineno, 'name', 'gettext')
- yield Token(lineno, 'lparen', None)
- yield Token(lineno, 'string', match.group(1))
- yield Token(lineno, 'rparen', None)
- yield Token(lineno, 'variable_end', None)
- pos = match.end()
- if pos < end:
- yield Token(lineno, 'data', token.value[pos:])
-
-
-def test_loop_controls():
- env = Environment(extensions=['jinja2.ext.loopcontrols'])
-
- tmpl = env.from_string('''
- {%- for item in [1, 2, 3, 4] %}
- {%- if item % 2 == 0 %}{% continue %}{% endif -%}
- {{ item }}
- {%- endfor %}''')
- assert tmpl.render() == '13'
-
- tmpl = env.from_string('''
- {%- for item in [1, 2, 3, 4] %}
- {%- if item > 2 %}{% break %}{% endif -%}
- {{ item }}
- {%- endfor %}''')
- assert tmpl.render() == '12'
-
-
-def test_do():
- env = Environment(extensions=['jinja2.ext.do'])
- tmpl = env.from_string('''
- {%- set items = [] %}
- {%- for char in "foo" %}
- {%- do items.append(loop.index0 ~ char) %}
- {%- endfor %}{{ items|join(', ') }}''')
- assert tmpl.render() == '0f, 1o, 2o'
-
-
-def test_with():
- env = Environment(extensions=['jinja2.ext.with_'])
- tmpl = env.from_string('''\
- {% with a=42, b=23 -%}
- {{ a }} = {{ b }}
- {% endwith -%}
- {{ a }} = {{ b }}\
- ''')
- assert [x.strip() for x in tmpl.render(a=1, b=2).splitlines()] \
- == ['42 = 23', '1 = 2']
-
-
-def test_extension_nodes():
- env = Environment(extensions=[TestExtension])
- tmpl = env.from_string('{% test %}')
- assert tmpl.render() == 'False|42|23|{}'
-
-
-def test_identifier():
- assert TestExtension.identifier == __name__ + '.TestExtension'
-
-
-def test_rebinding():
- original = Environment(extensions=[TestExtension])
- overlay = original.overlay()
- for env in original, overlay:
- for ext in env.extensions.itervalues():
- assert ext.environment is env
-
-
-def test_preprocessor_extension():
- env = Environment(extensions=[PreprocessorExtension])
- tmpl = env.from_string('{[[TEST]]}')
- assert tmpl.render(foo=42) == '{(42)}'
-
-
-def test_streamfilter_extension():
- env = Environment(extensions=[StreamFilterExtension])
- env.globals['gettext'] = lambda x: x.upper()
- tmpl = env.from_string('Foo _(bar) Baz')
- out = tmpl.render()
- assert out == 'Foo BAR Baz'
-
-
-class WithExtension(Extension):
- tags = frozenset(['with'])
-
- def parse(self, parser):
- lineno = parser.stream.next().lineno
- value = parser.parse_expression()
- parser.stream.expect('name:as')
- name = parser.stream.expect('name')
-
- body = parser.parse_statements(['name:endwith'], drop_needle=True)
- body.insert(0, nodes.Assign(nodes.Name(name.value, 'store'), value))
- return nodes.Scope(body)
-
-
-def test_with_extension():
- env = Environment(extensions=[WithExtension])
- t = env.from_string('{{ a }}{% with 2 as a %}{{ a }}{% endwith %}{{ a }}')
- assert t.render(a=1) == '121'
-
- t = env.from_string('{% with 2 as a %}{{ a }}{% endwith %}{{ a }}')
- assert t.render(a=3) == '23'
View
328 tests/test_filters.py
@@ -1,328 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- unit test for the filters
- ~~~~~~~~~~~~~~~~~~~~~~~~~
-
- :copyright: (c) 2009 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-from jinja2 import Markup, Environment
-
-env = Environment()
-
-
-CAPITALIZE = '''{{ "foo bar"|capitalize }}'''
-CENTER = '''{{ "foo"|center(9) }}'''
-DEFAULT = '''{{ missing|default("no") }}|{{ false|default('no') }}|\
-{{ false|default('no', true) }}|{{ given|default("no") }}'''
-DICTSORT = '''{{ foo|dictsort }}|\
-{{ foo|dictsort(true) }}|\
-{{ foo|dictsort(false, 'value') }}'''
-BATCH = '''{{ foo|batch(3)|list }}|{{ foo|batch(3, 'X')|list }}'''
-SLICE = '''{{ foo|slice(3)|list }}|{{ foo|slice(3, 'X')|list }}'''
-ESCAPE = '''{{ '<">&'|escape }}'''
-STRIPTAGS = '''{{ foo|striptags }}'''
-FILESIZEFORMAT = '{{ 100|filesizeformat }}|\
-{{ 1000|filesizeformat }}|\
-{{ 1000000|filesizeformat }}|\
-{{ 1000000000|filesizeformat }}|\
-{{ 1000000000000|filesizeformat }}|\
-{{ 100|filesizeformat(true) }}|\
-{{ 1000|filesizeformat(true) }}|\
-{{ 1000000|filesizeformat(true) }}|\
-{{ 1000000000|filesizeformat(true) }}|\
-{{ 1000000000000|filesizeformat(true) }}'
-FIRST = '''{{ foo|first }}'''
-FLOAT = '''{{ "42"|float }}|{{ "ajsghasjgd"|float }}|{{ "32.32"|float }}'''
-FORMAT = '''{{ "%s|%s"|format("a", "b") }}'''
-INDENT = '''{{ foo|indent(2) }}|{{ foo|indent(2, true) }}'''
-INT = '''{{ "42"|int }}|{{ "ajsghasjgd"|int }}|{{ "32.32"|int }}'''
-JOIN = '''{{ [1, 2, 3]|join("|") }}'''
-LAST = '''{{ foo|last }}'''
-LENGTH = '''{{ "hello world"|length }}'''
-LOWER = '''{{ "FOO"|lower }}'''
-PPRINT = '''{{ data|pprint }}'''
-RANDOM = '''{{ seq|random }}'''
-REVERSE = '''{{ "foobar"|reverse|join }}|{{ [1, 2, 3]|reverse|list }}'''
-STRING = '''{{ range(10)|string }}'''
-TITLE = '''{{ "foo bar"|title }}'''
-TRIM = '''{{ " foo "|trim }}'''
-TRUNCATE = '''{{ data|truncate(15, true, ">>>") }}|\
-{{ data|truncate(15, false, ">>>") }}|\
-{{ smalldata|truncate(15) }}'''
-UPPER = '''{{ "foo"|upper }}'''
-URLIZE = '''{{ "foo http://www.example.com/ bar"|urlize }}'''
-WORDCOUNT = '''{{ "foo bar baz"|wordcount }}'''
-BLOCK = '''{% filter lower|escape %}<HEHE>{% endfilter %}'''
-CHAINING = '''{{ ['<foo>', '<bar>']|first|upper|escape }}'''
-SUM = '''{{ [1, 2, 3, 4, 5, 6]|sum }}'''
-ABS = '''{{ -1|abs }}|{{ 1|abs }}'''
-ROUND = '''{{ 2.7|round }}|{{ 2.1|round }}|\
-{{ 2.1234|round(2, 'floor') }}|{{ 2.1|round(0, 'ceil') }}'''
-XMLATTR = '''{{ {'foo': 42, 'bar': 23, 'fish': none,
-'spam': missing, 'blub:blub': '<?>'}|xmlattr }}'''
-SORT1 = '''{{ [2, 3, 1]|sort }}|{{ [2, 3, 1]|sort(true) }}'''
-GROUPBY = '''{% for grouper, list in [{'foo': 1, 'bar': 2},
- {'foo': 2, 'bar': 3},
- {'foo': 1, 'bar': 1},
- {'foo': 3, 'bar': 4}]|groupby('foo') -%}
-{{ grouper }}: {{ list|join(', ') }}
-{% endfor %}'''
-FILTERTAG = '''{% filter upper|replace('FOO', 'foo') %}foobar{% endfilter %}'''
-SORT2 = '''{{ ['foo', 'Bar', 'blah']|sort }}'''
-
-
-def test_capitalize():
- tmpl = env.from_string(CAPITALIZE)
- assert tmpl.render() == 'Foo bar'
-
-
-def test_center():
- tmpl = env.from_string(CENTER)
- assert tmpl.render() == ' foo '
-
-
-def test_default():
- tmpl = env.from_string(DEFAULT)
- assert tmpl.render(given='yes') == 'no|False|no|yes'
-
-
-def test_dictsort():
- tmpl = env.from_string(DICTSORT)
- out = tmpl.render(foo={"aa": 0, "b": 1, "c": 2, "AB": 3})
- assert out == ("[('aa', 0), ('AB', 3), ('b', 1), ('c', 2)]|"
- "[('AB', 3), ('aa', 0), ('b', 1), ('c', 2)]|"
- "[('aa', 0), ('b', 1), ('c', 2), ('AB', 3)]")
-
-
-def test_batch():
- tmpl = env.from_string(BATCH)
- out = tmpl.render(foo=range(10))
- assert out == ("[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]|"
- "[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 'X', 'X']]")
-
-
-def test_slice():
- tmpl = env.from_string(SLICE)
- out = tmpl.render(foo=range(10))
- assert out == ("[[0, 1, 2, 3], [4, 5, 6], [7, 8, 9]]|"
- "[[0, 1, 2, 3], [4, 5, 6, 'X'], [7, 8, 9, 'X']]")
-
-
-def test_escape():
- tmpl = env.from_string(ESCAPE)
- out = tmpl.render()
- assert out == '&lt;&#34;&gt;&amp;'
-
-
-def test_striptags():
- tmpl = env.from_string(STRIPTAGS)
- out = tmpl.render(foo=' <p>just a small \n <a href="#">'
- 'example</a> link</p>\n<p>to a webpage</p> '
- '<!-- <p>and some commented stuff</p> -->')
- assert out == 'just a small example link to a webpage'
-
-
-def test_filesizeformat():
- tmpl = env.from_string(FILESIZEFORMAT)
- out = tmpl.render()
- assert out == (
- '100 Bytes|1.0 KB|1.0 MB|1.0 GB|1000.0 GB|'
- '100 Bytes|1000 Bytes|976.6 KiB|953.7 MiB|931.3 GiB'
- )
-
-
-def test_first():
- tmpl = env.from_string(FIRST)
- out = tmpl.render(foo=range(10))
- assert out == '0'
-
-
-def test_float():
- tmpl = env.from_string(FLOAT)
- out = tmpl.render()
- assert out == '42.0|0.0|32.32'
-
-
-def test_format():
- tmpl = env.from_string(FORMAT)
- out = tmpl.render()
- assert out == 'a|b'
-
-
-def test_indent():
- tmpl = env.from_string(INDENT)
- text = '\n'.join([' '.join(['foo', 'bar'] * 2)] * 2)
- out = tmpl.render(foo=text)
- assert out == ('foo bar foo bar\n foo bar foo bar| '
- 'foo bar foo bar\n foo bar foo bar')
-
-
-def test_int():
- tmpl = env.from_string(INT)
- out = tmpl.render()
- assert out == '42|0|32'
-
-
-def test_join():
- tmpl = env.from_string(JOIN)
- out = tmpl.render()
- assert out == '1|2|3'
-
- env2 = Environment(autoescape=True)
- tmpl = env2.from_string('{{ ["<foo>", "<span>foo</span>"|safe]|join }}')
- assert tmpl.render() == '&lt;foo&gt;<span>foo</span>'
-
-
-def test_last():
- tmpl = env.from_string(LAST)
- out = tmpl.render(foo=range(10))
- assert out == '9'
-
-
-def test_length():
- tmpl = env.from_string(LENGTH)
- out = tmpl.render()
- assert out == '11'
-
-
-def test_lower():
- tmpl = env.from_string(LOWER)
- out = tmpl.render()
- assert out == 'foo'
-
-
-def test_pprint():
- from pprint import pformat
- tmpl = env.from_string(PPRINT)
- data = range(1000)
- assert tmpl.render(data=data) == pformat(data)
-
-
-def test_random():
- tmpl = env.from_string(RANDOM)
- seq = range(100)
- for _ in range(10):
- assert int(tmpl.render(seq=seq)) in seq
-
-
-def test_reverse():
- tmpl = env.from_string(REVERSE)
- assert tmpl.render() == 'raboof|[3, 2, 1]'
-
-
-def test_string():
- tmpl = env.from_string(STRING)
- assert tmpl.render(foo=range(10)) == unicode(xrange(10))
-
-
-def test_title():
- tmpl = env.from_string(TITLE)
- assert tmpl.render() == "Foo Bar"
-
-
-def test_truncate():
- tmpl = env.from_string(TRUNCATE)
- out = tmpl.render(data='foobar baz bar' * 1000,
- smalldata='foobar baz bar')
- assert out == 'foobar baz barf>>>|foobar baz >>>|foobar baz bar'
-
-
-def test_upper():
- tmpl = env.from_string(UPPER)
- assert tmpl.render() == 'FOO'
-
-
-def test_urlize():
- tmpl = env.from_string(URLIZE)
- assert tmpl.render() == 'foo <a href="http://www.example.com/">'\
- 'http://www.example.com/</a> bar'
-
-
-def test_wordcount():
- tmpl = env.from_string(WORDCOUNT)
- assert tmpl.render() == '3'
-
-
-def test_block():
- tmpl = env.from_string(BLOCK)
- assert tmpl.render() == '&lt;hehe&gt;'
-
-
-def test_chaining():
- tmpl = env.from_string(CHAINING)
- assert tmpl.render() == '&lt;FOO&gt;'
-
-
-def test_sum():
- tmpl = env.from_string(SUM)
- assert tmpl.render() == '21'
-
-
-def test_abs():
- tmpl = env.from_string(ABS)
- return tmpl.render() == '1|1'
-
-
-def test_round():
- tmpl = env.from_string(ROUND)
- return tmpl.render() == '3.0|2.0|2.1|3.0'
-
-
-def test_xmlattr():
- tmpl = env.from_string(XMLATTR)
- out = tmpl.render().split()
- assert len(out) == 3
- assert 'foo="42"' in out
- assert 'bar="23"' in out
- assert 'blub:blub="&lt;?&gt;"' in out
-
-
-def test_sort1():
- tmpl = env.from_string(SORT1)
- assert tmpl.render() == '[1, 2, 3]|[3, 2, 1]'
-
-
-def test_groupby():
- tmpl = env.from_string(GROUPBY)
- assert tmpl.render().splitlines() == [
- "1: {'foo': 1, 'bar': 2}, {'foo': 1, 'bar': 1}",
- "2: {'foo': 2, 'bar': 3}",
- "3: {'foo': 3, 'bar': 4}"
- ]
-
-
-def test_filtertag():
- tmpl = env.from_string(FILTERTAG)
- assert tmpl.render() == 'fooBAR'
-
-
-def test_replace():
- env = Environment()
- tmpl = env.from_string('{{ string|replace("o", 42) }}')
- assert tmpl.render(string='<foo>') == '<f4242>'
-
- env = Environment(autoescape=True)
- tmpl = env.from_string('{{ string|replace("o", 42) }}')
- assert tmpl.render(string='<foo>') == '&lt;f4242&gt;'
- tmpl = env.from_string('{{ string|replace("<", 42) }}')
- assert tmpl.render(string='<foo>') == '42foo&gt;'
- tmpl = env.from_string('{{ string|replace("o", ">x<") }}')
- assert tmpl.render(string=Markup('foo')) == 'f&gt;x&lt;&gt;x&lt;'
-
-
-def test_forceescape():
- tmpl = env.from_string('{{ x|forceescape }}')
- assert tmpl.render(x=Markup('<div />')) == u'&lt;div /&gt;'
-
-
-def test_safe():
- env = Environment(autoescape=True)
- tmpl = env.from_string('{{ "<div>foo</div>"|safe }}')
- assert tmpl.render() == '<div>foo</div>'
- tmpl = env.from_string('{{ "<div>foo</div>" }}')
- assert tmpl.render() == '&lt;div&gt;foo&lt;/div&gt;'
-
-
-def test_sort2():
- assert env.from_string(SORT2).render() == "['Bar', 'blah', 'foo']"
View
190 tests/test_forloop.py
@@ -1,190 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- unit test for loop functions
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
- :copyright: (c) 2009 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-from jinja2 import Environment
-from jinja2.exceptions import UndefinedError, TemplateSyntaxError
-
-from nose.tools import assert_raises
-
-env = Environment()
-
-
-SIMPLE = '''{% for item in seq %}{{ item }}{% endfor %}'''
-ELSE = '''{% for item in seq %}XXX{% else %}...{% endfor %}'''
-EMPTYBLOCKS = '''<{% for item in seq %}{% else %}{% endfor %}>'''
-CONTEXTVARS = '''{% for item in seq %}\
-{{ loop.index }}|{{ loop.index0 }}|{{ loop.revindex }}|{{
- loop.revindex0 }}|{{ loop.first }}|{{ loop.last }}|{{
- loop.length }}###{% endfor %}'''
-CYCLING = '''{% for item in seq %}{{ loop.cycle('<1>', '<2>') }}{% endfor %}\
-{% for item in seq %}{{ loop.cycle(*through) }}{% endfor %}'''
-SCOPE = '''{% for item in seq %}{% endfor %}{{ item }}'''
-VARLEN = '''{% for item in iter %}{{ item }}{% endfor %}'''
-NONITER = '''{% for item in none %}...{% endfor %}'''
-RECURSIVE = '''{% for item in seq recursive -%}
- [{{ item.a }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]
-{%- endfor %}'''
-LOOPLOOP = '''{% for row in table %}
- {%- set rowloop = loop -%}
- {% for cell in row -%}
- [{{ rowloop.index }}|{{ loop.index }}]
- {%- endfor %}
-{%- endfor %}'''
-LOOPERROR1 = '''\
-{% for item in [1] if loop.index == 0 %}...{% endfor %}'''
-LOOPERROR2 = '''\
-{% for item in [] %}...{% else %}{{ loop }}{% endfor %}'''
-LOOPFILTER = '''\
-{% for item in range(10) if item is even %}[{{ item }}]{% endfor %}'''
-EXTENDEDLOOPFILTER = '''\
-{% for item in range(10) if item is even %}[{{ loop.index
-}}:{{ item }}]{% endfor %}'''
-LOOPUNASSIGNABLE = '''\
-{% for loop in seq %}...{% endfor %}'''
-
-
-def test_simple():
- tmpl = env.from_string(SIMPLE)
- assert tmpl.render(seq=range(10)) == '0123456789'
-
-
-def test_else():
- tmpl = env.from_string(ELSE)
- assert tmpl.render() == '...'
-
-
-def test_empty_blocks():
- tmpl = env.from_string(EMPTYBLOCKS)
- assert tmpl.render() == '<>'
-
-
-def test_context_vars():
- tmpl = env.from_string(CONTEXTVARS)
- one, two, _ = tmpl.render(seq=[0, 1]).split('###')
- (one_index, one_index0, one_revindex, one_revindex0, one_first,
- one_last, one_length) = one.split('|')
- (two_index, two_index0, two_revindex, two_revindex0, two_first,
- two_last, two_length) = two.split('|')
-
- assert int(one_index) == 1 and int(two_index) == 2
- assert int(one_index0) == 0 and int(two_index0) == 1
- assert int(one_revindex) == 2 and int(two_revindex) == 1
- assert int(one_revindex0) == 1 and int(two_revindex0) == 0
- assert one_first == 'True' and two_first == 'False'
- assert one_last == 'False' and two_last == 'True'
- assert one_length == two_length == '2'
-
-
-def test_cycling():
- tmpl = env.from_string(CYCLING)
- output = tmpl.render(seq=range(4), through=('<1>', '<2>'))
- assert output == '<1><2>' * 4
-
-
-def test_scope():
- tmpl = env.from_string(SCOPE)
- output = tmpl.render(seq=range(10))
- assert not output
-
-
-def test_varlen():
- def inner():
- for item in range(5):
- yield item
- tmpl = env.from_string(VARLEN)
- output = tmpl.render(iter=inner())
- assert output == '01234'
-
-
-def test_noniter():
- tmpl = env.from_string(NONITER)
- assert_raises(TypeError, tmpl.render)
-
-
-def test_recursive():
- tmpl = env.from_string(RECURSIVE)
- assert tmpl.render(seq=[
- dict(a=1, b=[dict(a=1), dict(a=2)]),
- dict(a=2, b=[dict(a=1), dict(a=2)]),
- dict(a=3, b=[dict(a='a')])
- ]) == '[1<[1][2]>][2<[1][2]>][3<[a]>]'
-
-
-def test_looploop():
- tmpl = env.from_string(LOOPLOOP)
- assert tmpl.render(table=['ab', 'cd']) == '[1|1][1|2][2|1][2|2]'
-
-
-def test_reversed_bug():
- tmpl = env.from_string('{% for i in items %}{{ i }}{% if not loop.last %}'
- ',{% endif %}{% endfor %}')
- assert tmpl.render(items=reversed([3, 2, 1])) == '1,2,3'
-
-
-def test_loop_errors():
- tmpl = env.from_string(LOOPERROR1)
- assert_raises(UndefinedError, tmpl.render)
- tmpl = env.from_string(LOOPERROR2)
- assert tmpl.render() == ''
-
-
-def test_loop_filter():
- tmpl = env.from_string(LOOPFILTER)
- assert tmpl.render() == '[0][2][4][6][8]'
- tmpl = env.from_string(EXTENDEDLOOPFILTER)
- assert tmpl.render() == '[1:0][2:2][3:4][4:6][5:8]'
-
-
-def test_loop_unassignable():
- assert_raises(TemplateSyntaxError, env.from_string, LOOPUNASSIGNABLE)
-
-
-def test_scoped_special_var():
- t = env.from_string('{% for s in seq %}[{{ loop.first }}{% for c in s %}'
- '|{{ loop.first }}{% endfor %}]{% endfor %}')
- assert t.render(seq=('ab', 'cd')) == '[True|True|False][False|True|False]'
-
-
-def test_scoped_loop_var():
- t = env.from_string('{% for x in seq %}{{ loop.first }}'
- '{% for y in seq %}{% endfor %}{% endfor %}')
- assert t.render(seq='ab') == 'TrueFalse'
- t = env.from_string('{% for x in seq %}{% for y in seq %}'
- '{{ loop.first }}{% endfor %}{% endfor %}')
- assert t.render(seq='ab') == 'TrueFalseTrueFalse'
-
-
-def test_recursive_empty_loop_iter():
- t = env.from_string('''
- {%- for item in foo recursive -%}{%- endfor -%}
- ''')
- assert t.render(dict(foo=[])) == ''
-
-
-def test_call_in_loop():
- t = env.from_string('''
- {%- macro do_something() -%}
- [{{ caller() }}]
- {%- endmacro %}
-
- {%- for i in [1, 2, 3] %}
- {%- call do_something() -%}
- {{ i }}
- {%- endcall %}
- {%- endfor -%}
- ''')
- assert t.render() == '[1][2][3]'
-
-
-def test_scoping_bug():
- t = env.from_string('''
- {%- for item in foo %}...{{ item }}...{% endfor %}
- {%- macro item(a) %}...{{ a }}...{% endmacro %}
- {{- item(2) -}}
- ''')
- assert t.render(foo=(1,)) == '...1......2...'
View
73 tests/test_heavy.py
@@ -1,73 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- Heavy tests
- ~~~~~~~~~~~
-
- The tests in this module test complex Jinja2 situations to ensure
- corner cases (unfortunately mostly undocumented scoping behavior)
- does not change between versions.
-
- :copyright: Copyright 2009 by the Jinja Team.
- :license: BSD.
-"""
-from jinja2 import Environment
-env = Environment()
-
-
-def test_assigned_scoping():
- t = env.from_string('''
- {%- for item in (1, 2, 3, 4) -%}
- [{{ item }}]
- {%- endfor %}
- {{- item -}}
- ''')
- assert t.render(item=42) == '[1][2][3][4]42'
-
- t = env.from_string('''
- {%- for item in (1, 2, 3, 4) -%}
- [{{ item }}]
- {%- endfor %}
- {%- set item = 42 %}
- {{- item -}}
- ''')
- assert t.render() == '[1][2][3][4]42'
-
- t = env.from_string('''
- {%- set item = 42 %}
- {%- for item in (1, 2, 3, 4) -%}
- [{{ item }}]
- {%- endfor %}
- {{- item -}}
- ''')
- assert t.render() == '[1][2][3][4]42'
-
-
-def test_closure_scoping():
- t = env.from_string('''
- {%- set wrapper = "<FOO>" %}
- {%- for item in (1, 2, 3, 4) %}
- {%- macro wrapper() %}[{{ item }}]{% endmacro %}
- {{- wrapper() }}
- {%- endfor %}
- {{- wrapper -}}
- ''')
- assert t.render() == '[1][2][3][4]<FOO>'
-
- t = env.from_string('''
- {%- for item in (1, 2, 3, 4) %}
- {%- macro wrapper() %}[{{ item }}]{% endmacro %}
- {{- wrapper() }}
- {%- endfor %}
- {%- set wrapper = "<FOO>" %}
- {{- wrapper -}}
- ''')
- assert t.render() == '[1][2][3][4]<FOO>'
-
- t = env.from_string('''
- {%- for item in (1, 2, 3, 4) %}
- {%- macro wrapper() %}[{{ item }}]{% endmacro %}
- {{- wrapper() }}
- {%- endfor %}
- {{- wrapper -}}
- ''')
- assert t.render(wrapper=23) == '[1][2][3][4]23'
View
114 tests/test_i18n.py
@@ -1,114 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- unit test for the i18n functions
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
- :copyright: (c) 2009 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-from jinja2 import Environment, DictLoader, contextfunction
-from jinja2.exceptions import TemplateAssertionError
-
-from nose.tools import assert_raises
-
-templates = {
- 'master.html': '<title>{{ page_title|default(_("missing")) }}</title>'
- '{% block body %}{% endblock %}',
- 'child.html': '{% extends "master.html" %}{% block body %}'
- '{% trans %}watch out{% endtrans %}{% endblock %}',
- 'plural.html': '{% trans user_count %}One user online{% pluralize %}'
- '{{ user_count }} users online{% endtrans %}',
- 'stringformat.html': '{{ _("User: %d")|format(user_count) }}'
-}
-
-
-languages = {
- 'de': {
- 'missing': 'fehlend',
- 'watch out': 'pass auf',
- 'One user online': 'Ein Benutzer online',
- '%(user_count)s users online': '%(user_count)s Benutzer online',
- 'User: %d': 'Benutzer: %d'
- }
-}
-
-
-@contextfunction
-def gettext(context, string):
- language = context.get('LANGUAGE', 'en')
- return languages.get(language, {}).get(string, string)
-
-
-@contextfunction
-def ngettext(context, s, p, n):
- language = context.get('LANGUAGE', 'en')
- if n != 1:
- return languages.get(language, {}).get(p, p)
- return languages.get(language, {}).get(s, s)
-
-
-i18n_env = Environment(
- loader=DictLoader(templates),
- extensions=['jinja2.ext.i18n']
-)
-i18n_env.globals.update({
- '_': gettext,
- 'gettext': gettext,
- 'ngettext': ngettext
-})
-
-
-def test_trans():
- tmpl = i18n_env.get_template('child.html')
- assert tmpl.render(LANGUAGE='de') == '<title>fehlend</title>pass auf'
-
-
-def test_trans_plural():
- tmpl = i18n_env.get_template('plural.html')
- assert tmpl.render(LANGUAGE='de', user_count=1) == 'Ein Benutzer online'
- assert tmpl.render(LANGUAGE='de', user_count=2) == '2 Benutzer online'
-
-
-def test_complex_plural():
- tmpl = i18n_env.from_string('{% trans foo=42, count=2 %}{{ count }} item{% '
- 'pluralize count %}{{ count }} items{% endtrans %}')
- assert tmpl.render() == '2 items'
- assert_raises(TemplateAssertionError, i18n_env.from_string,
- '{% trans foo %}...{% pluralize bar %}...{% endtrans %}')
-
-
-def test_trans_stringformatting():
- tmpl = i18n_env.get_template('stringformat.html')
- assert tmpl.render(LANGUAGE='de', user_count=5) == 'Benutzer: 5'
-
-
-def test_extract():
- from jinja2.ext import babel_extract
- from StringIO import StringIO
- source = StringIO('''
- {{ gettext('Hello World') }}
- {% trans %}Hello World{% endtrans %}
- {% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %}
- ''')
- assert list(babel_extract(source, ('gettext', 'ngettext', '_'), [], {})) == [
- (2, 'gettext', u'Hello World', []),
- (3, 'gettext', u'Hello World', []),
- (4, 'ngettext', (u'%(users)s user', u'%(users)s users', None), [])
- ]
-
-
-def test_comment_extract():
- from jinja2.ext import babel_extract
- from StringIO import StringIO
- source = StringIO('''
- {# trans first #}
- {{ gettext('Hello World') }}
- {% trans %}Hello World{% endtrans %}{# trans second #}
- {#: third #}
- {% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %}
- ''')
- assert list(babel_extract(source, ('gettext', 'ngettext', '_'), ['trans', ':'], {})) == [
- (3, 'gettext', u'Hello World', ['first']),
- (4, 'gettext', u'Hello World', ['second']),
- (6, 'ngettext', (u'%(users)s user', u'%(users)s users', None), ['third'])
- ]
View
50 tests/test_ifcondition.py
@@ -1,50 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- unit test for if conditions
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
- :copyright: (c) 2009 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-
-from jinja2 import Environment
-env = Environment()
-
-
-SIMPLE = '''{% if true %}...{% endif %}'''
-ELIF = '''{% if false %}XXX{% elif true %}...{% else %}XXX{% endif %}'''
-ELSE = '''{% if false %}XXX{% else %}...{% endif %}'''
-EMPTY = '''[{% if true %}{% else %}{% endif %}]'''
-
-
-def test_simple():
- tmpl = env.from_string(SIMPLE)
- assert tmpl.render() == '...'
-
-
-def test_elif():
- tmpl = env.from_string(ELIF)
- assert tmpl.render() == '...'
-
-
-def test_else():
- tmpl = env.from_string(ELSE)
- assert tmpl.render() == '...'
-
-
-def test_empty():
- tmpl = env.from_string(EMPTY)
- assert tmpl.render() == '[]'
-
-
-def test_complete():
- tmpl = env.from_string('{% if a %}A{% elif b %}B{% elif c == d %}'
- 'C{% else %}D{% endif %}')
- assert tmpl.render(a=0, b=False, c=42, d=42.0) == 'C'
-
-
-def test_no_scope():
- tmpl = env.from_string('{% if a %}{% set foo = 1 %}{% endif %}{{ foo }}')
- assert tmpl.render(a=True) == '1'
- tmpl = env.from_string('{% if true %}{% set foo = 1 %}{% endif %}{{ foo }}')
- assert tmpl.render() == '1'
View
132 tests/test_imports.py
@@ -1,132 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- unit test for the imports and includes
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
- :copyright: (c) 2009 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-from jinja2 import Environment, DictLoader
-from jinja2.exceptions import TemplateNotFound, TemplatesNotFound
-
-from nose.tools import assert_raises
-
-
-test_env = Environment(loader=DictLoader(dict(
- module='{% macro test() %}[{{ foo }}|{{ bar }}]{% endmacro %}',
- header='[{{ foo }}|{{ 23 }}]',
- o_printer='({{ o }})'
-)))
-test_env.globals['bar'] = 23
-
-
-def test_context_imports():
- t = test_env.from_string('{% import "module" as m %}{{ m.test() }}')
- assert t.render(foo=42) == '[|23]'
- t = test_env.from_string('{% import "module" as m without context %}{{ m.test() }}')
- assert t.render(foo=42) == '[|23]'
- t = test_env.from_string('{% import "module" as m with context %}{{ m.test() }}')
- assert t.render(foo=42) == '[42|23]'
- t = test_env.from_string('{% from "module" import test %}{{ test() }}')
- assert t.render(foo=42) == '[|23]'
- t = test_env.from_string('{% from "module" import test without context %}{{ test() }}')
- assert t.render(foo=42) == '[|23]'
- t = test_env.from_string('{% from "module" import test with context %}{{ test() }}')
- assert t.render(foo=42) == '[42|23]'
-
-
-def test_context_include():
- t = test_env.from_string('{% include "header" %}')
- assert t.render(foo=42) == '[42|23]'
- t = test_env.from_string('{% include "header" with context %}')
- assert t.render(foo=42) == '[42|23]'
- t = test_env.from_string('{% include "header" without context %}')
- assert t.render(foo=42) == '[|23]'
-
-
-def test_choice_includes():
- t = test_env.from_string('{% include ["missing", "header"] %}')
- assert t.render(foo=42) == '[42|23]'
-
- t = test_env.from_string('{% include ["missing", "missing2"] ignore missing %}')
- assert t.render(foo=42) == ''
-
- t = test_env.from_string('{% include ["missing", "missing2"] %}')
- assert_raises(TemplateNotFound, t.render)
- try:
- t.render()
- except TemplatesNotFound, e:
- assert e.templates == ['missing', 'missing2']
- assert e.name == 'missing2'
- else:
- assert False, 'thou shalt raise'
-
- def test_includes(t, **ctx):
- ctx['foo'] = 42
- assert t.render(ctx) == '[42|23]'
-
- t = test_env.from_string('{% include ["missing", "header"] %}')
- test_includes(t)
- t = test_env.from_string('{% include x %}')
- test_includes(t, x=['missing', 'header'])
- t = test_env.from_string('{% include [x, "header"] %}')
- test_includes(t, x='missing')
- t = test_env.from_string('{% include x %}')
- test_includes(t, x='header')
- t = test_env.from_string('{% include x %}')
- test_includes(t, x='header')
- t = test_env.from_string('{% include [x] %}')
- test_includes(t, x='header')
-
-
-def test_include_ignoring_missing():
- t = test_env.from_string('{% include "missing" %}')
- assert_raises(TemplateNotFound, t.render)
- for extra in '', 'with context', 'without context':
- t = test_env.from_string('{% include "missing" ignore missing ' +
- extra + ' %}')
- assert t.render() == ''
-
-
-def test_context_include_with_overrides():
- env = Environment(loader=DictLoader(dict(
- main="{% for item in [1, 2, 3] %}{% include 'item' %}{% endfor %}",
- item="{{ item }}"
- )))
- assert env.get_template("main").render() == "123"
-
-
-def test_trailing_comma():
- test_env.from_string('{% from "foo" import bar, baz with context %}')
- test_env.from_string('{% from "foo" import bar, baz, with context %}')
- test_env.from_string('{% from "foo" import bar, with context %}')
- test_env.from_string('{% from "foo" import bar, with, context %}')
- test_env.from_string('{% from "foo" import bar, with with context %}')
-
-
-def test_exports():
- m = test_env.from_string('''
- {% macro toplevel() %}...{% endmacro %}
- {% macro __private() %}...{% endmacro %}
- {% set variable = 42 %}
- {% for item in [1] %}
- {% macro notthere() %}{% endmacro %}
- {% endfor %}
- ''').module
- assert m.toplevel() == '...'
- assert not hasattr(m, '__missing')
- assert m.variable == 42
- assert not hasattr(m, 'notthere')
-
-
-def test_unoptimized_scopes():
- t = test_env.from_string("""
- {% macro outer(o) %}
- {% macro inner() %}
- {% include "o_printer" %}
- {% endmacro %}
- {{ inner() }}
- {% endmacro %}
- {{ outer("FOO") }}
- """)
- assert t.render().strip() == '(FOO)'
View
197 tests/test_inheritance.py
@@ -1,197 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- unit test for the inheritance
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
- :copyright: (c) 2009 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-
-from jinja2 import Environment, DictLoader
-from jinja2.exceptions import TemplateSyntaxError
-
-
-LAYOUTTEMPLATE = '''\
-|{% block block1 %}block 1 from layout{% endblock %}
-|{% block block2 %}block 2 from layout{% endblock %}
-|{% block block3 %}
-{% block block4 %}nested block 4 from layout{% endblock %}
-{% endblock %}|'''
-
-LEVEL1TEMPLATE = '''\
-{% extends "layout" %}
-{% block block1 %}block 1 from level1{% endblock %}'''
-
-LEVEL2TEMPLATE = '''\
-{% extends "level1" %}
-{% block block2 %}{% block block5 %}nested block 5 from level2{%
-endblock %}{% endblock %}'''
-
-LEVEL3TEMPLATE = '''\
-{% extends "level2" %}
-{% block block5 %}block 5 from level3{% endblock %}
-{% block block4 %}block 4 from level3{% endblock %}
-'''
-
-LEVEL4TEMPLATE = '''\
-{% extends "level3" %}
-{% block block3 %}block 3 from level4{% endblock %}
-'''
-
-WORKINGTEMPLATE = '''\
-{% extends "layout" %}
-{% block block1 %}
- {% if false %}
- {% block block2 %}
- this should workd
- {% endblock %}
- {% endif %}
-{% endblock %}
-'''
-
-env = Environment(loader=DictLoader({
- 'layout': LAYOUTTEMPLATE,
- 'level1': LEVEL1TEMPLATE,
- 'level2': LEVEL2TEMPLATE,
- 'level3': LEVEL3TEMPLATE,
- 'level4': LEVEL4TEMPLATE,
- 'working': WORKINGTEMPLATE
-}), trim_blocks=True)
-
-def test_layout():
- tmpl = env.get_template('layout')
- assert tmpl.render() == ('|block 1 from layout|block 2 from '
- 'layout|nested block 4 from layout|')
-
-
-def test_level1():
- tmpl = env.get_template('level1')
- assert tmpl.render() == ('|block 1 from level1|block 2 from '
- 'layout|nested block 4 from layout|')
-
-
-def test_level2():
- tmpl = env.get_template('level2')
- assert tmpl.render() == ('|block 1 from level1|nested block 5 from '
- 'level2|nested block 4 from layout|')
-
-
-def test_level3():
- tmpl = env.get_template('level3')
- assert tmpl.render() == ('|block 1 from level1|block 5 from level3|'
- 'block 4 from level3|')
-
-
-def test_level4():
- tmpl = env.get_template('level4')
- assert tmpl.render() == ('|block 1 from level1|block 5 from '
- 'level3|block 3 from level4|')
-
-
-def test_super():
- env = Environment(loader=DictLoader({
- 'a': '{% block intro %}INTRO{% endblock %}|'
- 'BEFORE|{% block data %}INNER{% endblock %}|AFTER',
- 'b': '{% extends "a" %}{% block data %}({{ '
- 'super() }}){% endblock %}',
- 'c': '{% extends "b" %}{% block intro %}--{{ '
- 'super() }}--{% endblock %}\n{% block data '
- '%}[{{ super() }}]{% endblock %}'
- }))
- tmpl = env.get_template('c')
- assert tmpl.render() == '--INTRO--|BEFORE|[(INNER)]|AFTER'
-
-
-def test_working():
- tmpl = env.get_template('working')
-
-
-def test_reuse_blocks():
- tmpl = env.from_string('{{ self.foo() }}|{% block foo %}42{% endblock %}|{{ self.foo() }}')
- assert tmpl.render() == '42|42|42'
-
-
-def test_preserve_blocks():
- env = Environment(loader=DictLoader({
- 'a': '{% if false %}{% block x %}A{% endblock %}{% endif %}{{ self.x() }}',
- 'b': '{% extends "a" %}{% block x %}B{{ super() }}{% endblock %}'
- }))
- tmpl = env.get_template('b')
- assert tmpl.render() == 'BA'
-
-
-def test_dynamic_inheritance():
- env = Environment(loader=DictLoader({
- 'master1': 'MASTER1{% block x %}{% endblock %}',
- 'master2': 'MASTER2{% block x %}{% endblock %}',
- 'child': '{% extends master %}{% block x %}CHILD{% endblock %}'
- }))
- tmpl = env.get_template('child')
- for m in range(1, 3):
- assert tmpl.render(master='master%d' % m) == 'MASTER%dCHILD' % m
-
-
-def test_multi_inheritance():
- env = Environment(loader=DictLoader({
- 'master1': 'MASTER1{% block x %}{% endblock %}',
- 'master2': 'MASTER2{% block x %}{% endblock %}',
- 'child': '''{% if master %}{% extends master %}{% else %}{% extends
- 'master1' %}{% endif %}{% block x %}CHILD{% endblock %}'''
- }))
- tmpl = env.get_template('child')
- assert tmpl.render(master='master2') == 'MASTER2CHILD'
- assert tmpl.render(master='master1') == 'MASTER1CHILD'
- assert tmpl.render() == 'MASTER1CHILD'
-
-
-def test_fixed_macro_scoping_bug():
- assert Environment(loader=DictLoader({
- 'test.html': '''\
- {% extends 'details.html' %}
-
- {% macro my_macro() %}
- my_macro
- {% endmacro %}
-
- {% block inner_box %}
- {{ my_macro() }}
- {% endblock %}
- ''',
- 'details.html': '''\
- {% extends 'standard.html' %}
-
- {% macro my_macro() %}
- my_macro
- {% endmacro %}
-
- {% block content %}
- {% block outer_box %}
- outer_box
- {% block inner_box %}
- inner_box
- {% endblock %}
- {% endblock %}
- {% endblock %}
- ''',
- 'standard.html': '''
- {% block content %}&nbsp;{% endblock %}
- '''
- })).get_template("test.html").render().split() == [u'outer_box', u'my_macro']
-
-
-def test_scoped_block():
- env = Environment(loader=DictLoader({
- 'master.html': '{% for item in seq %}[{% block item scoped %}'
- '{% endblock %}]{% endfor %}'
- }))
- t = env.from_string('{% extends "master.html" %}{% block item %}{{ item }}{% endblock %}')
- assert t.render(seq=range(5)) == '[0][1][2][3][4]'
-
-
-def test_super_in_scoped_block():
- env = Environment(loader=DictLoader({
- 'master.html': '{% for item in seq %}[{% block item scoped %}'
- '{{ item }}{% endblock %}]{% endfor %}'
- }))
- t = env.from_string('{% extends "master.html" %}{% block item %}{{ super() }}|{{ item * 2 }}{% endblock %}')
- assert t.render(seq=range(5)) == '[0|0][1|2][2|4][3|6][4|8]'
View
73 tests/test_lexer.py
@@ -1,73 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- unit test for the lexer
- ~~~~~~~~~~~~~~~~~~~~~~~
-
- :copyright: (c) 2009 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-from jinja2 import Environment
-
-env = Environment()
-
-
-RAW = '{% raw %}foo{% endraw %}|{%raw%}{{ bar }}|{% baz %}{% endraw %}'
-BALANCING = '''{% for item in seq %}${{'foo': item}|upper}{% endfor %}'''
-COMMENTS = '''\
-<ul>
-<!--- for item in seq -->
- <li>{item}</li>
-<!--- endfor -->
-</ul>'''
-BYTEFALLBACK = u'''{{ 'foo'|pprint }}|{{ 'bär'|pprint }}'''
-
-
-def test_raw():
- tmpl = env.from_string(RAW)
- assert tmpl.render() == 'foo|{{ bar }}|{% baz %}'
-
-
-def test_balancing():
- from jinja2 import Environment
- env = Environment('{%', '%}', '${', '}')
- tmpl = env.from_string(BALANCING)
- assert tmpl.render(seq=range(3)) == "{'FOO': 0}{'FOO': 1}{'FOO': 2}"
-
-
-def test_comments():
- from jinja2 import Environment
- env = Environment('<!--', '-->', '{', '}')
- tmpl = env.from_string(COMMENTS)
- assert tmpl.render(seq=range(3)) == ("<ul>\n <li>0</li>\n "
- "<li>1</li>\n <li>2</li>\n</ul>")
-
-
-def test_string_escapes():
- for char in u'\0', u'\u2668', u'\xe4', u'\t', u'\r', u'\n':
- tmpl = env.from_string('{{ %s }}' % repr(char)[1:])
- assert tmpl.render() == char
- assert env.from_string('{{ "\N{HOT SPRINGS}" }}').render() == u'\u2668'
-
-
-def test_bytefallback():
- tmpl = env.from_string(BYTEFALLBACK)
- assert tmpl.render() == u"'foo'|u'b\\xe4r'"
-
-
-def test_operators():
- from jinja2.lexer import operators
- for test, expect in operators.iteritems():
- if test in '([{}])':
- continue
- stream = env.lexer.tokenize('{{ %s }}' % test)
- stream.next()
- assert stream.current.type == expect
-
-
-def test_normalizing():
- from jinja2 import Environment
- for seq in '\r', '\r\n', '\n':
- env = Environment(newline_sequence=seq)
- tmpl = env.from_string('1\n2\r\n3\n4\n')
- result = tmpl.render()
- assert result.replace(seq, 'X') == '1X2X3X4'
View
112 tests/test_loaders.py
@@ -1,112 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- unit test for the loaders
- ~~~~~~~~~~~~~~~~~~~~~~~~~
-
- :copyright: (c) 2009 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-
-import os
-import time
-import tempfile
-from jinja2 import Environment, loaders
-from jinja2.loaders import split_template_path
-from jinja2.exceptions import TemplateNotFound
-
-from nose.tools import assert_raises
-
-
-dict_loader = loaders.DictLoader({
- 'justdict.html': 'FOO'
-})
-package_loader = loaders.PackageLoader('loaderres', 'templates')
-filesystem_loader = loaders.FileSystemLoader('tests/loaderres/templates')
-function_loader = loaders.FunctionLoader({'justfunction.html': 'FOO'}.get)
-choice_loader = loaders.ChoiceLoader([dict_loader, package_loader])
-prefix_loader = loaders.PrefixLoader({
- 'a': filesystem_loader,
- 'b': dict_loader
-})
-
-
-def test_dict_loader():
- env = Environment(loader=dict_loader)
- tmpl = env.get_template('justdict.html')
- assert tmpl.render().strip() == 'FOO'
- assert_raises(TemplateNotFound, env.get_template, 'missing.html')
-
-
-def test_package_loader():
- env = Environment(loader=package_loader)
- tmpl = env.get_template('test.html')
- assert tmpl.render().strip() == 'BAR'
- assert_raises(TemplateNotFound, env.get_template, 'missing.html')
-
-
-def test_filesystem_loader():
- env = Environment(loader=filesystem_loader)
- tmpl = env.get_template('test.html')
- assert tmpl.render().strip() == 'BAR'
- tmpl = env.get_template('foo/test.html')
- assert tmpl.render().strip() == 'FOO'
- assert_raises(TemplateNotFound, env.get_template, 'missing.html')
-
-
-def test_choice_loader():
- env = Environment(loader=choice_loader)
- tmpl = env.get_template('justdict.html')
- assert tmpl.render().strip() == 'FOO'
- tmpl = env.get_template('test.html')
- assert tmpl.render().strip() == 'BAR'
- assert_raises(TemplateNotFound, env.get_template, 'missing.html')
-
-
-def test_function_loader():
- env = Environment(loader=function_loader)
- tmpl = env.get_template('justfunction.html')
- assert tmpl.render().strip() == 'FOO'
- assert_raises(TemplateNotFound, env.get_template, 'missing.html')
-
-
-def test_prefix_loader():
- env = Environment(loader=prefix_loader)
- tmpl = env.get_template('a/test.html')
- assert tmpl.render().strip() == 'BAR'
- tmpl = env.get_template('b/justdict.html')
- assert tmpl.render().strip() == 'FOO'
- assert_raises(TemplateNotFound, env.get_template, 'missing')
-
-
-def test_caching():
- changed = False
- class TestLoader(loaders.BaseLoader):
- def get_source(self, environment, template):
- return u'foo', None, lambda: not changed
- env = Environment(loader=TestLoader(), cache_size=-1)
- tmpl = env.get_template('template')
- assert tmpl is env.get_template('template')
- changed = True
- assert tmpl is not env.get_template('template')
- changed = False
-
- env = Environment(loader=TestLoader(), cache_size=0)
- assert env.get_template('template') \
- is not env.get_template('template')
-
- env = Environment(loader=TestLoader(), cache_size=2)
- t1 = env.get_template('one')
- t2 = env.get_template('two')
- print env.cache
- assert t2 is env.get_template('two')
- assert t1 is env.get_template('one')
- t3 = env.get_template('three')
- assert 'one' in env.cache
- assert 'two' not in env.cache
- assert 'three' in env.cache
-
-
-def test_split_template_path():
- assert split_template_path('foo/bar') == ['foo', 'bar']
- assert split_template_path('./foo/bar') == ['foo', 'bar']
- assert_raises(TemplateNotFound, split_template_path, '../foo')
View
39 tests/test_lrucache.py
@@ -1,39 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- Tests the LRUCache
- ~~~~~~~~~~~~~~~~~~
-
- This module tests the LRU Cache
-
- :copyright: (c) 2009 by the Jinja Team.
- :license: BSD.
-"""
-import thread
-import time
-import random
-import pickle
-from jinja2.utils import LRUCache
-
-
-def test_simple():
- d = LRUCache(3)
- d["a"] = 1
- d["b"] = 2
- d["c"] = 3
- d["a"]
- d["d"] = 4
- assert len(d) == 3
- assert 'a' in d and 'c' in d and 'd' in d and 'b' not in d
-
-
-def test_pickleable():
- cache = LRUCache(2)
- cache["foo"] = 42
- cache["bar"] = 23
- cache["foo"]
-
- for protocol in range(3):
- copy = pickle.loads(pickle.dumps(cache, protocol))
- assert copy.capacity == cache.capacity
- assert copy._mapping == cache._mapping
- assert copy._queue == cache._queue
View
112 tests/test_macros.py
@@ -1,112 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- unit test for the macros
- ~~~~~~~~~~~~~~~~~~~~~~~~
-
- :copyright: (c) 2009 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-
-from jinja2 import Environment, DictLoader
-
-env = Environment(trim_blocks=True)
-
-
-SIMPLE = '''\
-{% macro say_hello(name) %}Hello {{ name }}!{% endmacro %}
-{{ say_hello('Peter') }}\
-'''
-
-SCOPING = '''\
-{% macro level1(data1) %}
-{% macro level2(data2) %}{{ data1 }}|{{ data2 }}{% endmacro %}
-{{ level2('bar') }}{% endmacro %}
-{{ level1('foo') }}\
-'''
-
-ARGUMENTS = '''\
-{% macro m(a, b, c='c', d='d') %}{{ a }}|{{ b }}|{{ c }}|{{ d }}{% endmacro %}
-{{ m() }}|{{ m('a') }}|{{ m('a', 'b') }}|{{ m(1, 2, 3) }}\
-'''
-
-VARARGS = '''\
-{% macro test() %}{{ varargs|join('|') }}{% endmacro %}\
-{{ test(1, 2, 3) }}\
-'''
-
-SIMPLECALL = '''\
-{% macro test() %}[[{{ caller() }}]]{% endmacro %}\
-{% call test() %}data{% endcall %}\
-'''
-
-COMPLEXCALL = '''\
-{% macro test() %}[[{{ caller('data') }}]]{% endmacro %}\
-{% call(data) test() %}{{ data }}{% endcall %}\
-'''
-
-CALLERUNDEFINED = '''\
-{% set caller = 42 %}\
-{% macro test() %}{{ caller is not defined }}{% endmacro %}\
-{{ test() }}\
-'''
-
-INCLUDETEMPLATE = '''{% macro test(foo) %}[{{ foo }}]{% endmacro %}'''
-
-
-def test_simple():
- tmpl = env.from_string(SIMPLE)
- assert tmpl.render() == 'Hello Peter!'
-
-
-def test_scoping():
- tmpl = env.from_string(SCOPING)
- assert tmpl.render() == 'foo|bar'
-
-
-def test_arguments():
- tmpl = env.from_string(ARGUMENTS)
- assert tmpl.render() == '||c|d|a||c|d|a|b|c|d|1|2|3|d'
-
-
-def test_varargs():
- tmpl = env.from_string(VARARGS)
- assert tmpl.render() == '1|2|3'
-
-
-def test_simple_call():
- tmpl = env.from_string(SIMPLECALL)
- assert tmpl.render() == '[[data]]'
-
-
-def test_complex_call():
- tmpl = env.from_string(COMPLEXCALL)
- assert tmpl.render() == '[[data]]'
-
-
-def test_caller_undefined():
- tmpl = env.from_string(CALLERUNDEFINED)
- assert tmpl.render() == 'True'
-
-
-def test_include():
- env = Environment(loader=DictLoader({'include': INCLUDETEMPLATE}))
- tmpl = env.from_string('{% from "include" import test %}{{ test("foo") }}')
- assert tmpl.render() == '[foo]'
-
-
-def test_macro_api():
- tmpl = env.from_string('{% macro foo(a, b) %}{% endmacro %}'
- '{% macro bar() %}{{ varargs }}{{ kwargs }}{% endmacro %}'
- '{% macro baz() %}{{ caller() }}{% endmacro %}')
- assert tmpl.module.foo.arguments == ('a', 'b')
- assert tmpl.module.foo.defaults == ()
- assert tmpl.module.foo.name == 'foo'
- assert not tmpl.module.foo.caller
- assert not tmpl.module.foo.catch_kwargs
- assert not tmpl.module.foo.catch_varargs
- assert tmpl.module.bar.arguments == ()
- assert tmpl.module.bar.defaults == ()
- assert not tmpl.module.bar.caller
- assert tmpl.module.bar.catch_kwargs
- assert tmpl.module.bar.catch_varargs
- assert tmpl.module.baz.caller
View
57 tests/test_meta.py
@@ -1,57 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- unit test for the meta module
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
- :copyright: (c) 2009 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-from jinja2 import Environment, meta
-
-
-def test_find_undeclared_variables():
- env = Environment()
- ast = env.parse('{% set foo = 42 %}{{ bar + foo }}')
- x = meta.find_undeclared_variables(ast)
- assert x == set(['bar'])
-
- ast = env.parse('{% set foo = 42 %}{{ bar + foo }}'
- '{% macro meh(x) %}{{ x }}{% endmacro %}'
- '{% for item in seq %}{{ muh(item) + meh(seq) }}{% endfor %}')
- x = meta.find_undeclared_variables(ast)
- assert x == set(['bar', 'seq', 'muh'])
-
-
-def test_find_refererenced_templates():
- env = Environment()
- ast = env.parse('{% extends "layout.html" %}{% include helper %}')
- i = meta.find_referenced_templates(ast)
- assert i.next() == 'layout.html'
- assert i.next() is None
- assert list(i) == []
-
- ast = env.parse('{% extends "layout.html" %}'
- '{% from "test.html" import a, b as c %}'
- '{% import "meh.html" as meh %}'
- '{% include "muh.html" %}')
- i = meta.find_referenced_templates(ast)
- assert list(i) == ['layout.html', 'test.html', 'meh.html', 'muh.html']
-
-
-def test_find_included_templates():
- env = Environment()
- ast = env.parse('{% include ["foo.html", "bar.html"] %}')
- i = meta.find_referenced_templates(ast)
- assert list(i) == ['foo.html', 'bar.html']
-
- ast = env.parse('{% include ("foo.html", "bar.html") %}')
- i = meta.find_referenced_templates(ast)
- assert list(i) == ['foo.html', 'bar.html']
-
- ast = env.parse('{% include ["foo.html", "bar.html", foo] %}')
- i = meta.find_referenced_templates(ast)
- assert list(i) == ['foo.html', 'bar.html', None]
-
- ast = env.parse('{% include ("foo.html", "bar.html", foo) %}')
- i = meta.find_referenced_templates(ast)
- assert list(i) == ['foo.html', 'bar.html', None]
View
183 tests/test_old_bugs.py
@@ -1,183 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- Tests for old bugs
- ~~~~~~~~~~~~~~~~~~
-
- Unittest that test situations caused by various older bugs.
-
- :copyright: (c) 2009 by the Jinja Team.
- :license: BSD.
-"""
-from jinja2 import Template, Environment, DictLoader, TemplateSyntaxError, \
- TemplateNotFound, PrefixLoader
-
-env = Environment()
-
-from nose import SkipTest
-from nose.tools import assert_raises
-
-
-def test_keyword_folding():
- env = Environment()
- env.filters['testing'] = lambda value, some: value + some
- assert env.from_string("{{ 'test'|testing(some='stuff') }}") \
- .render() == 'teststuff'
-
-
-def test_extends_output_bugs():
- env = Environment(loader=DictLoader({
- 'parent.html': '(({% block title %}{% endblock %}))'
- }))
-
- t = env.from_string('{% if expr %}{% extends "parent.html" %}{% endif %}'
- '[[{% block title %}title{% endblock %}]]'
- '{% for item in [1, 2, 3] %}({{ item }}){% endfor %}')
- assert t.render(expr=False) == '[[title]](1)(2)(3)'
- assert t.render(expr=True) == '((title))'
-
-
-def test_urlize_filter_escaping():
- tmpl = env.from_string('{{ "http://www.example.org/<foo"|urlize }}')
- assert tmpl.render() == '<a href="http://www.example.org/&lt;foo">http://www.example.org/&lt;foo</a>'
-
-
-def test_loop_call_loop():
- tmpl = env.from_string('''
-
- {% macro test() %}
- {{ caller() }}
- {% endmacro %}
-
- {% for num1 in range(5) %}
- {% call test() %}
- {% for num2 in range(10) %}
- {{ loop.index }}
- {% endfor %}
- {% endcall %}
- {% endfor %}
-
- ''')
-
- assert tmpl.render().split() == map(unicode, range(1, 11)) * 5
-
-
-def test_weird_inline_comment():
- env = Environment(line_statement_prefix='%')
- assert_raises(TemplateSyntaxError, env.from_string,
- '% for item in seq {# missing #}\n...% endfor')
-
-
-def test_old_macro_loop_scoping_bug():
- tmpl = env.from_string('{% for i in (1, 2) %}{{ i }}{% endfor %}'
- '{% macro i() %}3{% endmacro %}{{ i() }}')
- assert tmpl.render() == '123'
-
-
-def test_partial_conditional_assignments():
- tmpl = env.from_string('{% if b %}{% set a = 42 %}{% endif %}{{ a }}')
- assert tmpl.render(a=23) == '23'
- assert tmpl.render(b=True) == '42'
-
-
-def test_stacked_locals_scoping_bug():
- env = Environment(line_statement_prefix='#')
- t = env.from_string('''\
-# for j in [1, 2]:
-# set x = 1
-# for i in [1, 2]:
-# print x
-# if i % 2 == 0:
-# set x = x + 1
-# endif
-# endfor
-# endfor
-# if a
-# print 'A'
-# elif b
-# print 'B'
-# elif c == d
-# print 'C'
-# else
-# print 'D'
-# endif
-''')
- assert t.render(a=0, b=False, c=42, d=42.0) == '1111C'
-
-
-def test_call_with_args():
- t = Template("""{% macro dump_users(users) -%}
- <ul>
- {%- for user in users -%}
- <li><p>{{ user.username|e }}</p>{{ caller(user) }}</li>
- {%- endfor -%}
- </ul>
- {%- endmacro -%}
-
- {% call(user) dump_users(list_of_user) -%}
- <dl>
- <dl>Realname</dl>
- <dd>{{ user.realname|e }}</dd>
- <dl>Description</dl>
- <dd>{{ user.description }}</dd>
- </dl>
- {% endcall %}""")
-
- assert [x.strip() for x in t.render(list_of_user=[{
- 'username':'apo',
- 'realname':'something else',
- 'description':'test'
- }]).splitlines()] == [
- u'<ul><li><p>apo</p><dl>',
- u'<dl>Realname</dl>',
- u'<dd>something else</dd>',
- u'<dl>Description</dl>',
- u'<dd>test</dd>',
- u'</dl>',
- u'</li></ul>'
- ]
-
-
-def test_empty_if_condition_fails():
- assert_raises(TemplateSyntaxError, Template, '{% if %}....{% endif %}')
- assert_raises(TemplateSyntaxError, Template, '{% if foo %}...{% elif %}...{% endif %}')
- assert_raises(TemplateSyntaxError, Template, '{% for x in %}..{% endfor %}')
-
-
-def test_recursive_loop_bug():
- tpl1 = Template("""
- {% for p in foo recursive%}
- {{p.bar}}
- {% for f in p.fields recursive%}
- {{f.baz}}
- {{p.bar}}
- {% if f.rec %}
- {{ loop(f.sub) }}
- {% endif %}
- {% endfor %}
- {% endfor %}
- """)
-
- tpl2 = Template("""
- {% for p in foo%}
- {{p.bar}}
- {% for f in p.fields recursive%}
- {{f.baz}}
- {{p.bar}}
- {% if f.rec %}
- {{ loop(f.sub) }}
- {% endif %}
- {% endfor %}
- {% endfor %}
- """)
-
-
-def test_correct_prefix_loader_name():
- env = Environment(loader=PrefixLoader({
- 'foo': DictLoader({})
- }))
- try:
- env.get_template('foo/bar.html')
- except TemplateNotFound, e:
- assert e.name == 'foo/bar.html'
- else:
- assert False, 'expected error here'
View
146 tests/test_parser.py
@@ -1,146 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- unit test for the parser
- ~~~~~~~~~~~~~~~~~~~~~~~~
-
- :copyright: (c) 2009 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-from jinja2 import Environment, Template, TemplateSyntaxError
-
-env = Environment()
-
-
-PHP_SYNTAX = '''\
-<!-- I'm a comment, I'm not interesting -->\
-<? for item in seq -?>
- <?= item ?>
-<?- endfor ?>'''
-
-ERB_SYNTAX = '''\
-<%# I'm a comment, I'm not interesting %>\
-<% for item in seq -%>
- <%= item %>
-<%- endfor %>'''
-
-COMMENT_SYNTAX = '''\
-<!--# I'm a comment, I'm not interesting -->\
-<!-- for item in seq --->
- ${item}
-<!--- endfor -->'''
-
-MAKO_SYNTAX = '''\
-<%# regular comment %>
-% for item in seq:
- ${item}
-% endfor'''
-
-MAKO_SYNTAX_LINECOMMENTS = '''\
-<%# regular comment %>
-% for item in seq:
- ${item} ## the rest of the stuff
-% endfor'''
-
-BALANCING = '''{{{'foo':'bar'}.foo}}'''
-
-STARTCOMMENT = '''{# foo comment
-and bar comment #}
-{% macro blub() %}foo{% endmacro %}
-{{ blub() }}'''
-
-LINE_SYNTAX_PRIORITY1 = '''\
-/* ignore me.
- I'm a multiline comment */
-## for item in seq:
-* ${item} # this is just extra stuff
-## endfor
-'''
-
-LINE_SYNTAX_PRIORITY2 = '''\
-/* ignore me.
- I'm a multiline comment */
-# for item in seq:
-* ${item} ## this is just extra stuff
- ## extra stuff i just want to ignore
-# endfor
-'''
-
-
-def test_php_syntax():
- env = Environment('<?', '?>', '<?=', '?>', '<!--', '-->')
- tmpl = env.from_string(PHP_SYNTAX)
- assert tmpl.render(seq=range(5)) == '01234'
-
-
-def test_erb_syntax():
- env = Environment('<%', '%>', '<%=', '%>', '<%#', '%>')
- tmpl = env.from_string(ERB_SYNTAX)
- assert tmpl.render(seq=range(5)) == '01234'
-
-
-def test_comment_syntax():
- env = Environment('<!--', '-->', '${', '}', '<!--#', '-->')
- tmpl = env.from_string(COMMENT_SYNTAX)
- assert tmpl.render(seq=range(5)) == '01234'
-
-
-def test_balancing():
- tmpl = env.from_string(BALANCING)
- assert tmpl.render() == 'bar'
-
-
-def test_start_comment():
- tmpl = env.from_string(STARTCOMMENT)
- assert tmpl.render().strip() == 'foo'
-
-
-def test_line_syntax():
- env = Environment('<%', '%>', '${', '}', '<%#', '%>', '%')
- tmpl = env.from_string(MAKO_SYNTAX)
- assert [int(x.strip()) for x in tmpl.render(seq=range(5)).split()] == \
- range(5)
-
- env = Environment('<%', '%>', '${', '}', '<%#', '%>', '%', '##')
- tmpl = env.from_string(MAKO_SYNTAX_LINECOMMENTS)
- assert [int(x.strip()) for x in tmpl.render(seq=range(5)).split()] == \
- range(5)
-
-
-def test_line_syntax_priority():
- # XXX: why is the whitespace there in front of the newline?
- env = Environment('{%', '%}', '${', '}', '/*', '*/', '##', '#')
- tmpl = env.from_string(LINE_SYNTAX_PRIORITY1)
- assert tmpl.render(seq=[1, 2]).strip() == '* 1\n* 2'
- env = Environment('{%', '%}', '${', '}', '/*', '*/', '#', '##')
- tmpl = env.from_string(LINE_SYNTAX_PRIORITY2)
- assert tmpl.render(seq=[1, 2]).strip() == '* 1\n\n* 2'
-
-
-def test_error_messages():
- def assert_error(code, expected):
- try:
- Template(code)
- except TemplateSyntaxError, e:
- assert str(e) == expected, 'unexpected error message'
- else:
- assert False, 'that was suposed to be an error'
-
- assert_error('{% for item in seq %}...{% endif %}',
- "Encountered unknown tag 'endif'. Jinja was looking "
- "for the following tags: 'endfor' or 'else'. The "
- "innermost block that needs to be closed is 'for'.")
- assert_error('{% if foo %}{% for item in seq %}...{% endfor %}{% endfor %}',
- "Encountered unknown tag 'endfor'. Jinja was looking for "
- "the following tags: 'elif' or 'else' or 'endif'. The "
- "innermost block that needs to be closed is 'if'.")
- assert_error('{% if foo %}',
- "Unexpected end of template. Jinja was looking for the "
- "following tags: 'elif' or 'else' or 'endif'. The "
- "innermost block that needs to be closed is 'if'.")
- assert_error('{% for item in seq %}',
- "Unexpected end of template. Jinja was looking for the "
- "following tags: 'endfor' or 'else'. The innermost block "
- "that needs to be closed is 'for'.")
- assert_error('{% block foo-bar-baz %}',
- "Block names in Jinja have to be valid Python identifiers "
- "and may not contain hypens, use an underscore instead.")
View
141 tests/test_security.py
@@ -1,141 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- unit test for security features
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
- :copyright: (c) 2009 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-from jinja2 import Environment
-from jinja2.sandbox import SandboxedEnvironment, \
- ImmutableSandboxedEnvironment, unsafe
-from jinja2 import Markup, escape
-from jinja2.exceptions import SecurityError, TemplateSyntaxError
-
-
-from nose.tools import assert_raises
-
-class PrivateStuff(object):
-
- def bar(self):
- return 23
-
- @unsafe
- def foo(self):
- return 42
-
- def __repr__(self):
- return 'PrivateStuff'
-
-
-class PublicStuff(object):
- bar = lambda self: 23
- _foo = lambda self: 42
-
- def __repr__(self):
- return 'PublicStuff'
-
-
-def test_unsafe():
- '''
->>> env = SandboxedEnvironment()
->>> env.from_string("{{ foo.foo() }}").render(foo=PrivateStuff())
-Traceback (most recent call last):
- ...
-SecurityError: <bound method PrivateStuff.foo of PrivateStuff> is not safely callable
->>> env.from_string("{{ foo.bar() }}").render(foo=PrivateStuff())
-u'23'
-
->>> env.from_string("{{ foo._foo() }}").render(foo=PublicStuff())
-Traceback (most recent call last):
- ...
-SecurityError: access to attribute '_foo' of 'PublicStuff' object is unsafe.
->>> env.from_string("{{ foo.bar() }}").render(foo=PublicStuff())
-u'23'
-
->>> env.from_string("{{ foo.__class__ }}").render(foo=42)
-u''
->>> env.from_string("{{ foo.func_code }}").render(foo=lambda:None)
-u''
->>> env.from_string("{{ foo.__class__.__subclasses__() }}").render(foo=42)
-Traceback (most recent call last):
- ...
-SecurityError: access to attribute '__class__' of 'int' object is unsafe.
-'''
-
-
-def test_restricted():
- env = SandboxedEnvironment()
- assert_raises(TemplateSyntaxError, env.from_string,
- "{% for item.attribute in seq %}...{% endfor %}")
- assert_raises(TemplateSyntaxError, env.from_string,
- "{% for foo, bar.baz in seq %}...{% endfor %}")
-
-
-def test_immutable_environment():
- '''
->>> env = ImmutableSandboxedEnvironment()
->>> env.from_string('{{ [].append(23) }}').render()
-Traceback (most recent call last):
- ...
-SecurityError: access to attribute 'append' of 'list' object is unsafe.
->>> env.from_string('{{ {1:2}.clear() }}').render()
-Traceback (most recent call last):
- ...
-SecurityError: access to attribute 'clear' of 'dict' object is unsafe.
-'''
-
-
-def test_markup_operations():
- # adding two strings should escape the unsafe one
- unsafe = '<script type="application/x-some-script">alert("foo");</script>'
- safe = Markup('<em>username</em>')
- assert unsafe + safe == unicode(escape(unsafe)) + unicode(safe)
-
- # string interpolations are safe to use too
- assert Markup('<em>%s</em>') % '<bad user>' == \
- '<em>&lt;bad user&gt;</em>'
- assert Markup('<em>%(username)s</em>') % {
- 'username': '<bad user>'
- } == '<em>&lt;bad user&gt;</em>'
-
- # an escaped object is markup too
- assert type(Markup('foo') + 'bar') is Markup
-
- # and it implements __html__ by returning itself
- x = Markup("foo")
- assert x.__html__() is x
-
- # it also knows how to treat __html__ objects
- class Foo(object):
- def __html__(self):
- return '<em>awesome</em>'
- def __unicode__(self):
- return 'awesome'
- assert Markup(Foo()) == '<em>awesome</em>'
- assert Markup('<strong>%s</strong>') % Foo() == \
- '<strong><em>awesome</em></strong>'
-
- # escaping and unescaping
- assert escape('"<>&\'') == '&#34;&lt;&gt;&amp;&#39;'
- assert Markup("<em>Foo &amp; Bar</em>").striptags() == "Foo & Bar"
- assert Markup("&lt;test&gt;").unescape() == "<test>"
-
-
-def test_template_data():
- env = Environment(autoescape=True)
- t = env.from_string('{% macro say_hello(name) %}'
- '<p>Hello {{ name }}!</p>{% endmacro %}'
- '{{ say_hello("<blink>foo</blink>") }}')
- escaped_out = '<p>Hello &lt;blink&gt;foo&lt;/blink&gt;!</p>'
- assert t.render() == escaped_out
- assert unicode(t.module) == escaped_out
- assert escape(t.module) == escaped_out
- assert t.module.say_hello('<blink>foo</blink>') == escaped_out
- assert escape(t.module.say_hello('<blink>foo</blink>')) == escaped_out
-
-
-def test_attr_filter():
- env = SandboxedEnvironment()
- tmpl = env.from_string('{{ 42|attr("__class__")|attr("__subclasses__")() }}')
- assert_raises(SecurityError, tmpl.render)
View
57 tests/test_streaming.py
@@ -1,57 +0,0 @@
-# -*- coding: utf-8 -*-
-"""
- unit test for streaming interface
- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
-
- :copyright: (c) 2009 by the Jinja Team.
- :license: BSD, see LICENSE for more details.
-"""
-
-from jinja2 import Environment
-env = Environment()
-
-
-def test_basic_streaming():
- r"""
->>> tmpl = env.from_string("<ul>{% for item in seq %}<li>{{ loop.index "
-... "}} - {{ item }}</li>{%- endfor %}</ul>")
->>> stream = tmpl.stream(seq=range(4))
->>> stream.next()
-u'<ul>'
->>> stream.next()
-u'<li>1 - 0</li>'
->>> stream.next()
-u'<li>2 - 1</li>'
->>> stream.next()
-u'<li>3 - 2</li>'
->>> stream.next()
-u'<li>4 - 3</li>'
->>> stream.next()
-u'</ul>'
-"""
-
-def test_buffered_streaming():
- r"""
->>> tmpl = env.from_string("<ul>{% for item in seq %}<li>{{ loop.index "
-... "}} - {{ item }}</li>{%- endfor %}</ul>")
->>> stream = tmpl.stream(seq=range(4))
->>> stream.enable_buffering(size=3)
->>> stream.next()
-u'<ul><li>1 - 0</li><li>2 - 1</li>'
->>> stream.next()
-u'<li>3 - 2</li><li>4 - 3</li></ul>'
-"""