Skip to content
Myr

[svn] added some more jinja unittests

Before adoption: this commit came in with the history the project adopted, so no landing records it.

--HG-- branch : trunk

authored by Armin Ronacher · committed by Armin Ronacher · parent 2f613d0 · Browse files · 12 files+140 added−28 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

12 files+140 added−28 removed

  • tests:+116 added−9 removed
  • other:+24 added−19 removed

12 files+140 added−28 removed

modified:docs/src/altsyntax.txt+3 added-2 removed
40 unmodified lines
41An example template then looks like this:4243.. sourcecode:: rhtml4445 <%# example eruby like configuration for jinja %>45 <%# example eruby like configuration for Jinja %>46 <ul>47 <% for item in seq %>48 <li><%= item %></li>49 <% end‭for %>
12 unmodified lines
62 env = Environment('<!--', '-->', '${', '}', '<!--#', '-->')6364.. sourcecode:: html6566 <!--# example eruby like configuration for jinja -->66 <!--# example SGML comment configuration for Jinja -->67 <ul>68 <!-- for item in seq -->69 <li>${item}</li>70 <!-- endfor -->
26 unmodified lines
97This now allows smarty like templates:9899.. sourcecode:: smarty100101 {* example smarty-like configuration for Jinja *}102 {if something == 42}103 Something is the answer to all questions and stuff like that.104 {else}105 Something is {something}.
4 unmodified lines
modified:jinja/translators/python.py+3 added-6 removed
1000 unmodified lines
1001 """1002 Handle variable based attribute access foo['bar'].1003 """1004 if len(node.subs) != 1:1005 raise TemplateSyntaxError('attribute access requires one argument',1006 node.lineno,1005 raise TemplateSyntaxError('attribute access requires one '1006 'argument', node.lineno,1007 node.filename)1008 assert node.flags != 'OP_DELETE', 'wtf? do we support that?'1009 if node.subs[0].__class__ is ast.Sliceobj:1010 return '%s%s' % (
197 unmodified lines
1208 def handle_sliceobj(self, node):1209 """1210 Extended Slice access.1211 """1212 args = []1213 for n in node.nodes:1214 args.append(self.handle_node(n))1215 return '[%s]' % ':'.join(args)1212 return '[%s]' % ':'.join([self.handle_node(n) for n in node.nodes])
modified:jinja/datastructure.py+3 added
63 unmodified lines
64 def __copy__(self):65 return self66 __deepcopy__ = __copy__6768 def __repr__(self):69 return 'Undefined'7071 def __reduce__(self):72 raise TypeError('undefined objects have to provide a __reduce__')7374
527 unmodified lines
modified:jinja/lexer.py+2 added-2 removed
49 unmodified lines
50 '+', '-', '**', '*', '//', '/', '%',51 # braces and parenthesis52 '[', ']', '(', ')', '{', '}',53 # attribute access and comparison / logical operators54 '.', ':', ',', '|', '==', '<', '>', '<=', '>=', '!=', '=',54 '.', ':', ',', '|', '==', '<=', '>=', '<', '>', '!=', '=',55 ur'or\b', ur'and\b', ur'not\b', ur'in\b', ur'is\b'56]]))5758# set of used keywords
215 unmodified lines
274 if g:275 lineno += g.count('\n')276 continue277 # failure group278 elif isinstance(token, Failure):278 elif token.__class__ is Failure:279 raise token(lineno, filename)280 # bygroup is a bit more complex, in that case we281 # yield for the current token the first named282 # group that matched
91 unmodified lines
modified:jinja/parser.py+3 added-3 removed
351 unmodified lines
352 'translation variable blocks.',353 lineno, self.filename)354 # plural name without trailing "_"? that's a keyword355 if not name.endswith('_'):356 raise TemplateSyntaxError('illegal use of keyword \'%s\' as'356 raise TemplateSyntaxError('illegal use of keyword \'%s\' as '357 'identifier in translatable block.'358 % name, lineno, self.filename)359 name = name[:-1]360 if name not in replacements:
7 unmodified lines
368 if next_token != 'variable_end' and not \369 (self.no_variable_block and next_token == 'block_end'):370 raise TemplateSyntaxError('you cannot use variable '371 'expressions inside translatable '372 'tags. apply filters in the'372 'tags. apply filters in the '373 'trans header.', lineno,374 self.filename)375 buf.append('%%(%s)s' % name)376
92 unmodified lines
469 block_name)470 continue471 block_name = block_name[:-1]472 raise TemplateSyntaxError('unknown directive'473 "'%s'" % block_name,473 " '%s'" % block_name,474 lineno,475 self.filename)476 # we have something different and are in the477 # special no_variable_block mode. process this
347 unmodified lines
modified:jinja/utils.py+5 added-3 removed
61 unmodified lines
62 sorted = sorted63except NameError:64 def sorted(seq, reverse=False):65 rv = list(seq)66 rv.sort(reverse=reverse)66 rv.sort()67 if reverse:68 rv.reverse()69 return rv7071#: function types72callable_types = (FunctionType, MethodType)
388 unmodified lines
461 result = []462 for name, f in filters:463 if f in strip:464 continue463 doc = '\n'.join(' ' + x for x in (getdoc(f) or '').splitlines())465 doc = '\n'.join([' ' + x for x in (getdoc(f) or '').splitlines()])466 result.append('`%s`\n\n%s' % (name, doc))467 return '\n\n'.join(result)468 filters.jinja_context_callable = True469
9 unmodified lines
479 result = []480 for name, f in tests:481 if f in strip:482 continue481 doc = '\n'.join(' ' + x for x in (getdoc(f) or '').splitlines())483 doc = '\n'.join([' ' + x for x in (getdoc(f) or '').splitlines()])484 result.append('`%s`\n\n%s' % (name, doc))485 return '\n\n'.join(result)486 tests.jinja_context_callable = True487
214 unmodified lines
modified:tests/test_parser.py+7 added
38 unmodified lines
39{for item in seq-}40 {item}41{-endfor}'''4243BALANCING = '''{{{'foo':'bar'}.foo}}'''444546def test_no_variable_block():47 env = Environment('{%', '%}', None, None)48 tmpl = env.from_string(NO_VARIABLE_BLOCK)49 assert tmpl.render(foo=42, seq=range(2)).splitlines() == [
25 unmodified lines
75def test_smarty_syntax():76 env = Environment('{', '}', '{', '}', '{*', '*}')77 tmpl = env.from_string(SMARTY_SYNTAX)78 assert tmpl.render(seq=range(5)) == '01234'798081def test_balancing(env):82 tmpl = env.from_string(BALANCING)83 assert tmpl.render() == 'bar'
modified:tests/test_security.py+4 added
42 unmodified lines
43>>> env.from_string("{% for item.attribute in seq %}...{% endfor %}")44Traceback (most recent call last):45 ...46TemplateSyntaxError: can't assign to expression. (line 1)47>>> env.from_string("{% for foo, bar.baz in seq %}...{% endfor %}")48Traceback (most recent call last):49 ...50TemplateSyntaxError: can't assign to expression. (line 1)51'''
added:tests/test_syntax.py+84 added
1# -*- coding: utf-8 -*-2"""3 unit test for expression syntax4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~56 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8"""910CALL = '''{{ foo('a', c='d', e='f', *['b'], **{'g': 'h'}) }}'''11SLICING = '''{{ [1, 2, 3][:] }}|{{ [1, 2, 3][::-1] }}'''12ATTR = '''{{ foo.bar }}|{{ foo['bar'] }}'''13SUBSCRIPT = '''{{ foo[0] }}|{{ foo[-1] }}'''14KEYATTR = '''{{ {'items': 'foo'}.items }}|{{ {}.items() }}'''15TUPLE = '''{{ () }}'''16MATH = '''{{ (1 + 1 * 2) - 3 / 2 }}|{{ 2**3 }}'''17DIV = '''{{ 3 // 2 }}|{{ 3 / 2 }}|{{ 3 % 2 }}'''18UNARY = '''{{ +3 }}|{{ -3 }}'''19COMPARE = '''{{ 1 > 0 }}|{{ 1 >= 1 }}|{{ 2 < 3 }}|{{ 2 == 2 }}|{{ 1 <= 1 }}'''20LITERALS = '''{{ [] }}|{{ {} }}|{{ '' }}'''21BOOL = '''{{ true and false }}|{{ false or true }}|{{ not false }}'''222324def test_call():25 from jinja import Environment26 env = Environment()27 env.globals['foo'] = lambda a, b, c, e, g: a + b + c + e + g28 tmpl = env.from_string(CALL)29 assert tmpl.render() == 'abdfh'303132def test_slicing(env):33 tmpl = env.from_string(SLICING)34 assert tmpl.render() == '[1, 2, 3]|[3, 2, 1]'353637def test_attr(env):38 tmpl = env.from_string(ATTR)39 assert tmpl.render(foo={'bar': 42}) == '42|42'404142def test_subscript(env):43 tmpl = env.from_string(SUBSCRIPT)44 assert tmpl.render(foo=[0, 1, 2]) == '0|2'454647def test_keyattr(env):48 tmpl = env.from_string(KEYATTR)49 assert tmpl.render() == 'foo|[]'505152def test_tuple(env):53 tmpl = env.from_string(TUPLE)54 assert tmpl.render() == '[]'555657def test_math(env):58 tmpl = env.from_string(MATH)59 assert tmpl.render() == '1.5|8'606162def test_div(env):63 tmpl = env.from_string(DIV)64 assert tmpl.render() == '1|1.5|1'656667def test_unary(env):68 tmpl = env.from_string(UNARY)69 assert tmpl.render() == '3|-3'707172def test_compare(env):73 tmpl = env.from_string(COMPARE)74 assert tmpl.render() == 'True|True|True|True|True'757677def test_literals(env):78 tmpl = env.from_string(LITERALS)79 assert tmpl.render() == '[]|{}|'808182def test_bool(env):83 tmpl = env.from_string(BOOL)84 assert tmpl.render() == 'False|True|True'
modified:tests/test_various.py+21 added-9 removed
4 unmodified lines
56 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8"""9from jinja.exceptions import TemplateSyntaxError1011KEYWORDS = '''\12{{ with }}13{{ as }}
17 unmodified lines
31{{ finally }}'''32LIGHTKW = '''{{ call }}'''33UNPACKING = '''{% for a, b, c in [[1, 2, 3]] %}{{ a }}|{{ b }}|{{ c }}{% endfor %}'''34RAW = '''{% raw %}{{ FOO }} and {% BAR %}{% endraw %}'''34CALL = '''{{ foo('a', c='d', e='f', *['b'], **{'g': 'h'}) }}'''35CONST = '''{{ true }}|{{ false }}|{{ none }}|{{ undefined }}|\36{{ none is defined }}|{{ undefined is defined }}'''37CONSTASS1 = '''{% set true = 42 %}'''38CONSTASS2 = '''{% for undefined in seq %}{% endfor %}'''394041def test_keywords(env):42 env.from_string(KEYWORDS)4344
29 unmodified lines
74 assert len(d) == 375 assert 'a' in d and 'c' in d and 'd' in d and 'b' not in d767773def test_call():74 from jinja import Environment75 env = Environment()76 env.globals['foo'] = lambda a, b, c, e, g: a + b + c + e + g77 tmpl = env.from_string(CALL)78 assert tmpl.render() == 'abdfh'798078def test_stringfilter(env):79 from jinja.filters import stringfilter80 f = stringfilter(lambda f, x: f + x)81 assert f('42')(env, None, 23) == '2342'
2 unmodified lines
84def test_simplefilter(env):85 from jinja.filters import simplefilter86 f = simplefilter(lambda f, x: f + x)87 assert f(42)(env, None, 23) == 65888990def test_const(env):91 tmpl = env.from_string(CONST)92 assert tmpl.render() == 'True|False|||True|False'939495def test_const_assign(env):96 for tmpl in CONSTASS1, CONSTASS2:97 try:98 env.from_string(tmpl)99 except TemplateSyntaxError:100 pass101 else:102 raise AssertionError('expected syntax error')
modified:CHANGES+4 added-2 removed
1 unmodified line
2===============34Version 1.15-----------6(codename to be selected, release date unknown)6(codename: sinka, released Jun 1, 2007)78- blocks now support ``{{ super() }}`` to render the parent output.910- debugging system improved, smaller filesize for the cached files.
98 unmodified lines
109- added `simplefilter` decorator.110111- improved ChoiceLoader error reporting (thanks to Bryan McLemore)112113- fixed extended slicing114115116Version 1.0117-----------116(released Mar 23, 2007)118(codename: siyutusan, released Mar 23, 2007)119120- Initial release
modified:setup.py+1 added-1 removed
43 unmodified lines
444546setup(47 name = 'Jinja',48 version = '1.0',48 version = '1.1',49 url = 'http://jinja.pocoo.org/',50 license = 'BSD',51 author = 'Armin Ronacher',52 author_email = 'armin.ronacher@active-4.com',
38 unmodified lines