[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
Provenance
- Commit
ecc051b- Tree
89408eb- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
2f613d0
12 files changed+140 added−28 removed
modified:docs/src/altsyntax.txt+3 added-2 removed
40 unmodified lines41 An example template then looks like this:42 43 .. sourcecode:: rhtml44 45- <%# 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 <% endfor %>12 unmodified lines62 env = Environment('<!--', '-->', '${', '}', '<!--#', '-->')63 64 .. sourcecode:: html65 66- <!--# 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 lines97 This now allows smarty like templates:98 99 .. sourcecode:: smarty100 101+ {* 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 linesmodified:jinja/translators/python.py+3 added-6 removed
1000 unmodified lines1001 """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 lines1208 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 lines64 def __copy__(self):65 return self66 __deepcopy__ = __copy__67 68+ def __repr__(self):69+ return 'Undefined'70+71 def __reduce__(self):72 raise TypeError('undefined objects have to provide a __reduce__')73 74 527 unmodified linesmodified:jinja/lexer.py+2 added-2 removed
49 unmodified lines50 '+', '-', '**', '*', '//', '/', '%',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 ]]))57 58 # set of used keywords215 unmodified lines274 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 matched91 unmodified linesmodified:jinja/parser.py+3 added-3 removed
351 unmodified lines352 '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 lines368 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 lines469 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 this347 unmodified linesmodified:jinja/utils.py+5 added-3 removed
61 unmodified lines62 sorted = sorted63 except 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 rv70 71 #: function types72 callable_types = (FunctionType, MethodType)388 unmodified lines461 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 lines479 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 linesmodified:tests/test_parser.py+7 added
38 unmodified lines39 {for item in seq-}40 {item}41 {-endfor}'''42 43+BALANCING = '''{{{'foo':'bar'}.foo}}'''44 45+46 def 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 lines75 def test_smarty_syntax():76 env = Environment('{', '}', '{', '}', '{*', '*}')77 tmpl = env.from_string(SMARTY_SYNTAX)78 assert tmpl.render(seq=range(5)) == '01234'79+80+81+def test_balancing(env):82+ tmpl = env.from_string(BALANCING)83+ assert tmpl.render() == 'bar'modified:tests/test_security.py+4 added
42 unmodified lines43 >>> env.from_string("{% for item.attribute in seq %}...{% endfor %}")44 Traceback (most recent call last):45 ...46 TemplateSyntaxError: can't assign to expression. (line 1)47+>>> env.from_string("{% for foo, bar.baz in seq %}...{% endfor %}")48+Traceback (most recent call last):49+ ...50+TemplateSyntaxError: 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+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~5+6+ :copyright: 2007 by Armin Ronacher.7+ :license: BSD, see LICENSE for more details.8+"""9+10+CALL = '''{{ foo('a', c='d', e='f', *['b'], **{'g': 'h'}) }}'''11+SLICING = '''{{ [1, 2, 3][:] }}|{{ [1, 2, 3][::-1] }}'''12+ATTR = '''{{ foo.bar }}|{{ foo['bar'] }}'''13+SUBSCRIPT = '''{{ foo[0] }}|{{ foo[-1] }}'''14+KEYATTR = '''{{ {'items': 'foo'}.items }}|{{ {}.items() }}'''15+TUPLE = '''{{ () }}'''16+MATH = '''{{ (1 + 1 * 2) - 3 / 2 }}|{{ 2**3 }}'''17+DIV = '''{{ 3 // 2 }}|{{ 3 / 2 }}|{{ 3 % 2 }}'''18+UNARY = '''{{ +3 }}|{{ -3 }}'''19+COMPARE = '''{{ 1 > 0 }}|{{ 1 >= 1 }}|{{ 2 < 3 }}|{{ 2 == 2 }}|{{ 1 <= 1 }}'''20+LITERALS = '''{{ [] }}|{{ {} }}|{{ '' }}'''21+BOOL = '''{{ true and false }}|{{ false or true }}|{{ not false }}'''22+23+24+def 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'30+31+32+def test_slicing(env):33+ tmpl = env.from_string(SLICING)34+ assert tmpl.render() == '[1, 2, 3]|[3, 2, 1]'35+36+37+def test_attr(env):38+ tmpl = env.from_string(ATTR)39+ assert tmpl.render(foo={'bar': 42}) == '42|42'40+41+42+def test_subscript(env):43+ tmpl = env.from_string(SUBSCRIPT)44+ assert tmpl.render(foo=[0, 1, 2]) == '0|2'45+46+47+def test_keyattr(env):48+ tmpl = env.from_string(KEYATTR)49+ assert tmpl.render() == 'foo|[]'50+51+52+def test_tuple(env):53+ tmpl = env.from_string(TUPLE)54+ assert tmpl.render() == '[]'55+56+57+def test_math(env):58+ tmpl = env.from_string(MATH)59+ assert tmpl.render() == '1.5|8'60+61+62+def test_div(env):63+ tmpl = env.from_string(DIV)64+ assert tmpl.render() == '1|1.5|1'65+66+67+def test_unary(env):68+ tmpl = env.from_string(UNARY)69+ assert tmpl.render() == '3|-3'70+71+72+def test_compare(env):73+ tmpl = env.from_string(COMPARE)74+ assert tmpl.render() == 'True|True|True|True|True'75+76+77+def test_literals(env):78+ tmpl = env.from_string(LITERALS)79+ assert tmpl.render() == '[]|{}|'80+81+82+def 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 lines5 6 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8 """9+from jinja.exceptions import TemplateSyntaxError10 11 KEYWORDS = '''\12 {{ with }}13 {{ as }}17 unmodified lines31 {{ finally }}'''32 LIGHTKW = '''{{ call }}'''33 UNPACKING = '''{% for a, b, c in [[1, 2, 3]] %}{{ a }}|{{ b }}|{{ c }}{% endfor %}'''34 RAW = '''{% raw %}{{ FOO }} and {% BAR %}{% endraw %}'''34-CALL = '''{{ foo('a', c='d', e='f', *['b'], **{'g': 'h'}) }}'''35+CONST = '''{{ true }}|{{ false }}|{{ none }}|{{ undefined }}|\36+{{ none is defined }}|{{ undefined is defined }}'''37+CONSTASS1 = '''{% set true = 42 %}'''38+CONSTASS2 = '''{% for undefined in seq %}{% endfor %}'''39 40+41 def test_keywords(env):42 env.from_string(KEYWORDS)43 44 29 unmodified lines74 assert len(d) == 375 assert 'a' in d and 'c' in d and 'd' in d and 'b' not in d76 77 73-def 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'79-80-78 def 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 lines84 def test_simplefilter(env):85 from jinja.filters import simplefilter86 f = simplefilter(lambda f, x: f + x)87 assert f(42)(env, None, 23) == 6588+89+90+def test_const(env):91+ tmpl = env.from_string(CONST)92+ assert tmpl.render() == 'True|False|||True|False'93+94+95+def 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 line2 ===============3 4 Version 1.15 -----------6-(codename to be selected, release date unknown)6+(codename: sinka, released Jun 1, 2007)7 8 - blocks now support ``{{ super() }}`` to render the parent output.9 10 - debugging system improved, smaller filesize for the cached files.98 unmodified lines109 - added `simplefilter` decorator.110 111 - improved ChoiceLoader error reporting (thanks to Bryan McLemore)112 113+- fixed extended slicing114 115+116 Version 1.0117 -----------116-(released Mar 23, 2007)118+(codename: siyutusan, released Mar 23, 2007)119 120 - Initial releasemodified:setup.py+1 added-1 removed
43 unmodified lines44 45 46 setup(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