Skip to content
Myr

[svn] added jinja doctests and fixed problem with i18n strings in requirements

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 aa5adfa · Browse files · 10 files+456 added−41 removed
This commit

State

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

Diff stats

10 files+456 added−41 removed

  • tests:+400 added−0 removed
  • other:+56 added−41 removed

10 files+456 added−41 removed

modified:jinja/translators/python.py+5 added-4 removed
302 unmodified lines
303 ' ctx_pop = context.pop\n' % node.filename304 ]305306 # we have requirements? add them here.307 body_lines = []308 if requirements:309 for n in requirements:309 lines.append(self.handle_node(n))310 body_lines.append(self.handle_node(n))311312 # the template body312 body_lines = [self.handle_node(n) for n in node]313 body_lines.extend([self.handle_node(n) for n in node])314315 # add translation helpers if required316 if self.require_translations:317 lines.append(
61 unmodified lines
379 self.indention += 1380 nodeinfo = self.nodeinfo(node.body)381 if nodeinfo:382 write(nodeinfo)382 buf.append(self.handle_node(node.body))383 buf.append(self.handle_node(node.body) or self.indent('pass'))384 self.indention -= 1385386 # else part of loop387 if node.else_:
1 unmodified line
389 self.indention += 1390 nodeinfo = self.nodeinfo(node.else_)391 if nodeinfo:392 write(nodeinfo)392 buf.append(self.handle_node(node.else_))393 buf.append(self.handle_node(node.else_) or self.indent('pass'))394 self.indention -= 1395396 # call recursive for loop!397 if node.recursive:
496 unmodified lines
modified:jinja/datastructure.py+8 added-5 removed
242 unmodified lines
243244 iterated = property(lambda s: s._stack[-1]['index'] > -1)245 index0 = property(lambda s: s._stack[-1]['index'])246 index = property(lambda s: s._stack[-1]['index'] + 1)247 revindex0 = property(lambda s: s._stack[-1]['length'] - s._stack[-1]['index'] - 1)248 revindex = property(lambda s: s._stack[-1]['length'] - s._stack[-1]['index'])247 revindex0 = property(lambda s: s._stack[-1]['length'] -248 s._stack[-1]['index'] - 1)249 revindex = property(lambda s: s._stack[-1]['length'] -250 s._stack[-1]['index'])251 length = property(lambda s: s._stack[-1]['length'])250 even = property(lambda s: s._stack[-1]['index'] % 2 == 0)251 odd = property(lambda s: s._stack[-1]['index'] % 2 == 1)252 even = property(lambda s: s._stack[-1]['index'] % 2 == 1)253 odd = property(lambda s: s._stack[-1]['index'] % 2 == 0)254 first = property(lambda s: s._stack[-1]['index'] == 0)253 last = property(lambda s: s._stack[-1]['index'] == s._stack[-1]['length'] - 1)255 last = property(lambda s: s._stack[-1]['index'] ==256 s._stack[-1]['length'] - 1)257258 def __iter__(self):259 s = self._stack[-1]260 for idx, item in enumerate(s['seq']):
113 unmodified lines
modified:jinja/filters.py+21 added-20 removed
107 unmodified lines
108 return escape(s, attribute)109do_escape = stringfilter(do_escape)110111112def do_addslashes(s):113 """114 Add backslashes in front of special characters to s. This method115 might be useful if you try to fill javascript strings. Also have116 a look at the `jsonencode` filter.117 """118 return s.encode('utf-8').encode('string-escape').decode('utf-8')119do_addslashes = stringfilter(do_addslashes)120121112def do_capitalize(s):113 """114 Capitalize a value. The first character will be uppercase, all others115 lowercase.
69 unmodified lines
185186 {{ ''|default('the string was empty', true) }}187 """188 def wrapped(env, context, value):199 if (boolean and not v) or v in (Undefined, None):189 if (boolean and not value) or value in (Undefined, None):190 return default_value201 return v191 return value192 return wrapped203do_default = stringfilter(do_default)193194195def do_join(d=u''):196 """
312 unmodified lines
509 return s510do_rst = stringfilter(do_rst)511512524def do_int():513def do_int(default=0):514 """526 Convert the value into an integer.515 Convert the value into an integer. If the516 conversion doesn't work it will return ``0``. You can517 override this default using the first parameter.518 """519 def wrapped(env, context, value):520 try:529 return int(value)521 return int(value)522 except (TypeError, ValueError):523 try:524 return int(float(value))525 except (TypeError, ValueError):526 return default527 return wrapped528529533def do_float():530def do_float(default=0.0):531 """535 Convert the value into a floating point number.532 Convert the value into a floating point number. If the533 conversion doesn't work it will return ``0.0``. You can534 override this default using the first parameter.535 """536 def wrapped(env, context, value):537 try:538 return float(value)538 return float(value)539 except (TypeError, ValueError):540 return default541 return wrapped542543544def do_string():
8 unmodified lines
553 'upper': do_upper,554 'lower': do_lower,555 'escape': do_escape,556 'e': do_escape,555 'addslashes': do_addslashes,557 'capitalize': do_capitalize,558 'title': do_title,559 'default': do_default,560 'join': do_join,
26 unmodified lines
modified:jinja/tests.py+10 added-12 removed
10 unmodified lines
11import re12from jinja.datastructure import Undefined131415number_re = re.compile(r'^-?\d+(\.\d+)$')15number_re = re.compile(r'^-?\d+(\.\d+)?$')1617regex_type = type(number_re)1819
66 unmodified lines
86 return wrapped878889def test_matching(regex):90 """91 Test if the variable matches the regular expression92 given. If the regular expression is a string additional93 slashes are automatically added, if it's a compiled regex94 it's used without any modifications:90 r"""91 Test if the variable matches the regular expression given. Note that92 you have to escape special chars using *two* backslashes, these are93 *not* raw strings.9495 .. sourcecode:: jinja9698 {% if var is matching('\d+$') %}97 {% if var is matching('^\\d+$') %}98 var looks like a number99 {% else %}100 var doesn't really look like a number101 {% endif %}102 """103 if isinstance(regex, unicode):105 regex = re.compile(regex.encode('unicode-escape'), re.U)106 elif isinstance(regex, unicode):107 regex = re.compile(regex.encode('string-escape'))104 regex = re.compile(regex, re.U)105 elif isinstance(regex, str):106 regex = re.compile(regex)107 elif type(regex) is not regex_type:108 regex = None109 def wrapped(environment, context, value):110 if regex is None:111 return False113 else:114 return regex.match(value)112 return regex.search(value) is not None113 return wrapped114115TESTS = {116 'odd': test_odd,
8 unmodified lines
added:tests/conftest.py+55 added
1# -*- coding: utf-8 -*-2"""3 conftest4 ~~~~~~~~56 Configure py.test for support stuff.78 :copyright: 2007 by Armin Ronacher, Alexander Schremmer.9 :license: BSD, see LICENSE for more details.10"""1112import os13import sys14sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))1516import py17from inspect import isclass18from jinja import Environment192021simple_env = Environment(trim_blocks=True)222324class Module(py.test.collect.Module):2526 def __init__(self, *args, **kwargs):27 self.env = simple_env28 super(Module, self).__init__(*args, **kwargs)2930 def join(self, name):31 obj = getattr(self.obj, name)32 if isclass(obj):33 return JinjaClassCollector(name, parent=self)34 elif hasattr(obj, 'func_code'):35 return JinjaTestFunction(name, parent=self)363738class JinjaTestFunction(py.test.collect.Function):3940 def execute(self, target, *args):41 co = target.func_code42 if 'env' in co.co_varnames[:co.co_argcount]:43 target(self.parent.env, *args)44 else:45 target(*args)464748class JinjaClassCollector(py.test.collect.Class):4950 Function = JinjaTestFunction5152 def setup(self):53 cls = self.obj54 cls.env = self.parent.env55 super(JinjaClassCollector, self).setup()
added:tests/test_filters.py+191 added
1# -*- coding: utf-8 -*-2"""3 unit test for the filters4 ~~~~~~~~~~~~~~~~~~~~~~~~~56 Missing tests:78 - wordcount9 - rst10 - markdown11 - textile1213 :copyright: 2007 by Armin Ronacher.14 :license: BSD, see LICENSE for more details.15"""1617CAPITALIZE = '''{{ "foo bar"|capitalize }}'''18CENTER = '''{{ "foo"|center(9) }}'''19DEFAULT = '''{{ missing|default("no") }}|{{ false|default('no') }}|\20{{ false|default('no', true) }}|{{ given|default("no") }}'''21DICTSORT = '''{{ foo|dictsort }}|\22{{ foo|dictsort(true) }}|\23{{ foo|dictsort(false, 'value') }}'''24ESCAPE = '''{{ '<">&'|escape }}|{{ '<">&'|escape(true) }}'''25FILESIZEFORMAT = '{{ 100|filesizeformat }}|\26{{ 1000|filesizeformat }}|\27{{ 1000000|filesizeformat }}|\28{{ 1000000000|filesizeformat }}|\29{{ 1000000000000|filesizeformat }}'30FIRST = '''{{ foo|first }}'''31FLOAT = '''{{ "42"|float }}|{{ "ajsghasjgd"|float }}|{{ "32.32"|float }}'''32INDENT = '''{{ foo|indent(2) }}|{{ foo|indent(2, true) }}'''33INT = '''{{ "42"|int }}|{{ "ajsghasjgd"|int }}|{{ "32.32"|int }}'''34JOIN = '''{{ [1, 2, 3]|join("|") }}'''35LAST = '''{{ foo|last }}'''36LENGTH = '''{{ "hello world"|length }}'''37LOWER = '''{{ "FOO"|lower }}'''38PPRINT = '''{{ data|pprint }}'''39RANDOM = '''{{ seq|random }}'''40REVERSE = '''{{ "foobar"|reverse }}|{{ [1, 2, 3]|reverse }}'''41STRING = '''{{ range(10)|string }}'''42TITLE = '''{{ "foo bar"|title }}'''43TRUNCATE = '''{{ data|truncate(15, true, ">>>") }}|\44{{ data|truncate(15, false, ">>>") }}|\45{{ smalldata|truncate(15) }}'''46UPPER = '''{{ "foo"|upper }}'''47URLENCODE = '''{{ "f#b"|urlencode }}'''48URLIZE = '''{{ "foo http://www.example.com/ bar"|urlize }}'''49WORDCOUNT = '''{{ "foo bar baz"|wordcount }}'''505152def test_capitalize(env):53 tmpl = env.from_string(CAPITALIZE)54 assert tmpl.render() == 'Foo bar'555657def test_center(env):58 tmpl = env.from_string(CENTER)59 assert tmpl.render() == ' foo '606162def test_default(env):63 tmpl = env.from_string(DEFAULT)64 assert tmpl.render(given='yes') == 'no|False|no|yes'656667def test_dictsort(env):68 tmpl = env.from_string(DICTSORT)69 out = tmpl.render(foo={"a": 0, "b": 1, "c": 2, "A": 3})70 assert out == ("[('a', 0), ('A', 3), ('b', 1), ('c', 2)]|"71 "[('A', 3), ('a', 0), ('b', 1), ('c', 2)]|"72 "[('a', 0), ('b', 1), ('c', 2), ('A', 3)]")737475def test_escape(env):76 tmpl = env.from_string(ESCAPE)77 out = tmpl.render()78 assert out == '&lt;"&gt;&amp;|&lt;&quot;&gt;&amp;'798081def test_filesizeformat(env):82 tmpl = env.from_string(FILESIZEFORMAT)83 out = tmpl.render()84 assert out == '100 Bytes|1000 Bytes|976.6 KB|953.7 MB|931.3 GB'858687def test_first(env):88 tmpl = env.from_string(FIRST)89 out = tmpl.render(foo=range(10))90 assert out == '0'919293def test_float(env):94 tmpl = env.from_string(FLOAT)95 out = tmpl.render()96 assert out == '42.0|0.0|32.32'979899def test_indent(env):100 tmpl = env.from_string(INDENT)101 text = '\n'.join([' '.join(['foo', 'bar'] * 2)] * 2)102 out = tmpl.render(foo=text)103 assert out == 'foo bar foo bar\n foo bar foo bar| ' \104 'foo bar foo bar\n foo bar foo bar'105106107def test_int(env):108 tmpl = env.from_string(INT)109 out = tmpl.render()110 assert out == '42|0|32'111112113def test_join(env):114 tmpl = env.from_string(JOIN)115 out = tmpl.render()116 assert out == '1|2|3'117118119def test_last(env):120 tmpl = env.from_string(LAST)121 out = tmpl.render(foo=range(10))122 assert out == '9'123124125def test_length(env):126 tmpl = env.from_string(LENGTH)127 out = tmpl.render()128 assert out == '11'129130131def test_lower(env):132 tmpl = env.from_string(LOWER)133 out = tmpl.render()134 assert out == 'foo'135136137def test_pprint(env):138 from pprint import pformat139 tmpl = env.from_string(PPRINT)140 data = range(10000)141 assert tmpl.render(data=data) == pformat(data)142143144def test_random(env):145 tmpl = env.from_string(RANDOM)146 seq = range(100)147 for _ in range(10):148 assert int(tmpl.render(seq=seq)) in seq149150151def test_reverse(env):152 tmpl = env.from_string(REVERSE)153 assert tmpl.render() == 'raboof|[3, 2, 1]'154155156def test_string(env):157 tmpl = env.from_string(STRING)158 assert tmpl.render(foo=range(10)) == str(range(10))159160161def test_title(env):162 tmpl = env.from_string(TITLE)163 assert tmpl.render() == "Foo Bar"164165166def test_truncate(env):167 tmpl = env.from_string(TRUNCATE)168 out = tmpl.render(data='foobar baz bar' * 1000,169 smalldata='foobar baz bar')170 assert out == 'foobar baz barf>>>|foobar baz >>>|foobar baz bar'171172173def test_upper(env):174 tmpl = env.from_string(UPPER)175 assert tmpl.render() == 'FOO'176177178def test_urlencode(env):179 tmpl = env.from_string(URLENCODE)180 assert tmpl.render() == 'f%23b'181182183def test_urlize(env):184 tmpl = env.from_string(URLIZE)185 assert tmpl.render() == 'foo <a href="http://www.example.com/">'\186 'http://www.example.com/</a> bar'187188189def test_wordcount(env):190 tmpl = env.from_string(WORDCOUNT)191 assert tmpl.render() == '3'
added:tests/test_forloop.py+65 added
1# -*- coding: utf-8 -*-2"""3 unit test for loop functions4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~56 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8"""910SIMPLE = '''{% for item in seq %}{{ item }}{% endfor %}'''11ELSE = '''{% for item in seq %}XXX{% else %}...{% endfor %}'''12EMPTYBLOCKS = '''<{% for item in seq %}{% else %}{% endfor %}>'''13CONTEXTVARS = '''{% for item in seq %}\14{{ loop.index }}|{{ loop.index0 }}|{{ loop.revindex }}|{{15 loop.revindex0 }}|{{ loop.first }}|{{ loop.last }}|{{16 loop.even }}|{{ loop.odd }}|{{ loop.length }}###{% endfor %}'''17CYCLING = '''{% for item in seq %}{% cycle '<1>', '<2>' %}{% endfor %}\18{% for item in seq %}{% cycle through %}{% endfor %}'''19SCOPE = '''{% for item in seq %}{% endfor %}{{ item }}'''202122def test_simple(env):23 tmpl = env.from_string(SIMPLE)24 assert tmpl.render(seq=range(10)) == '0123456789'252627def test_else(env):28 tmpl = env.from_string(ELSE)29 assert tmpl.render() == '...'303132def test_empty_blocks(env):33 tmpl = env.from_string(EMPTYBLOCKS)34 assert tmpl.render() == '<>'353637def test_context_vars(env):38 tmpl = env.from_string(CONTEXTVARS)39 one, two, _ = tmpl.render(seq=[0, 1]).split('###')40 (one_index, one_index0, one_revindex, one_revindex0, one_first,41 one_last, one_even, one_odd, one_length) = one.split('|')42 (two_index, two_index0, two_revindex, two_revindex0, two_first,43 two_last, two_even, two_odd, two_length) = two.split('|')4445 assert int(one_index) == 1 and int(two_index) == 246 assert int(one_index0) == 0 and int(two_index0) == 147 assert int(one_revindex) == 2 and int(two_revindex) == 148 assert int(one_revindex0) == 1 and int(two_revindex0) == 049 assert one_first == 'True' and two_first == 'False'50 assert one_last == 'False' and two_last == 'True'51 assert one_even == 'False' and two_even == 'True'52 assert one_odd == 'True' and two_odd == 'False'53 assert one_length == two_length == '2'545556def test_cycling(env):57 tmpl = env.from_string(CYCLING)58 output = tmpl.render(seq=range(4), through=('<1>', '<2>'))59 assert output == '<1><2>' * 4606162def test_scope(env):63 tmpl = env.from_string(SCOPE)64 output = tmpl.render(seq=range(10))65 assert not output
added:tests/test_ifcondition.py+27 added
1# -*- coding: utf-8 -*-2"""3 unit test for if conditions4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~56 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8"""910SIMPLE = '''{% if true %}...{% endif %}'''11ELIF = '''{% if false %}XXX{% elif true %}...{% else %}XXX{% endif %}'''12ELSE = '''{% if false %}XXX{% else %}...{% endif %}'''131415def test_simple(env):16 tmpl = env.from_string(SIMPLE)17 assert tmpl.render() == '...'181920def test_elif(env):21 tmpl = env.from_string(ELIF)22 assert tmpl.render() == '...'232425def test_else(env):26 tmpl = env.from_string(ELSE)27 assert tmpl.render() == '...'
added:tests/test_tests.py+62 added
1# -*- coding: utf-8 -*-2"""3 unit test for the test functions4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~56 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8"""910DEFINED = '''{{ missing is defined }}|{{ true is defined }}'''11EVEN = '''{{ 1 is even }}|{{ 2 is even }}'''12LOWER = '''{{ "foo" is lower }}|{{ "FOO" is lower }}'''13MATCHING = '''{{ "42" is matching('^\\d+$') }}|\14{{ "foo" is matching('^\\d+$') }}'''15NUMERIC = '''{{ "43" is numeric }}|{{ "foo" is numeric }}|\16{{ 42 is numeric }}'''17ODD = '''{{ 1 is odd }}|{{ 2 is odd }}'''18SEQUENCE = '''{{ [1, 2, 3] is sequence }}|\19{{ "foo" is sequence }}|\20{{ 42 is sequence }}'''21UPPER = '''{{ "FOO" is upper }}|{{ "foo" is upper }}'''222324def test_defined(env):25 tmpl = env.from_string(DEFINED)26 assert tmpl.render() == 'False|True'272829def test_even(env):30 tmpl = env.from_string(EVEN)31 assert tmpl.render() == 'False|True'323334def test_lower(env):35 tmpl = env.from_string(LOWER)36 assert tmpl.render() == 'True|False'373839def test_matching(env):40 tmpl = env.from_string(MATCHING)41 assert tmpl.render() == 'True|False'424344def test_numeric(env):45 tmpl = env.from_string(NUMERIC)46 assert tmpl.render() == 'True|False|True'474849def test_odd(env):50 tmpl = env.from_string(ODD)51 assert tmpl.render() == 'True|False'525354def test_sequence(env):55 tmpl = env.from_string(SEQUENCE)56 assert tmpl.render() == 'True|True|False'575859def test_upper(env):60 tmpl = env.from_string(UPPER)61 assert tmpl.render() == 'True|False'62
added:Makefile+12 added
1#2# Jinja Makefile3# ~~~~~~~~~~~~~~4#5# Shortcuts for various tasks.6#7# :copyright: 2007 by Armin Ronacher.8# :license: BSD, see LICENSE for more details.9#1011test:12 @(cd tests; py.test $(TESTS))