[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
Provenance
- Commit
ab45b84- Tree
e3eefdb- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
aa5adfa
10 files changed+456 added−41 removed
modified:jinja/translators/python.py+5 added-4 removed
302 unmodified lines303 ' ctx_pop = context.pop\n' % node.filename304 ]305 306 # 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))311 312 # 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])314 315 # add translation helpers if required316 if self.require_translations:317 lines.append(61 unmodified lines379 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 -= 1385 386 # else part of loop387 if node.else_:1 unmodified line389 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 -= 1395 396 # call recursive for loop!397 if node.recursive:496 unmodified linesmodified:jinja/datastructure.py+8 added-5 removed
242 unmodified lines243 244 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)257 258 def __iter__(self):259 s = self._stack[-1]260 for idx, item in enumerate(s['seq']):113 unmodified linesmodified:jinja/filters.py+21 added-20 removed
107 unmodified lines108 return escape(s, attribute)109 do_escape = stringfilter(do_escape)110 111 112-def 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')119-do_addslashes = stringfilter(do_addslashes)120-121-112 def do_capitalize(s):113 """114 Capitalize a value. The first character will be uppercase, all others115 lowercase.69 unmodified lines185 186 {{ ''|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 wrapped203-do_default = stringfilter(do_default)193 194 195 def do_join(d=u''):196 """312 unmodified lines509 return s510 do_rst = stringfilter(do_rst)511 512 524-def do_int():513+def 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 wrapped528 529 533-def do_float():530+def 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 wrapped542 543 544 def do_string():8 unmodified lines553 '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 linesmodified:jinja/tests.py+10 added-12 removed
10 unmodified lines11 import re12 from jinja.datastructure import Undefined13 14 15-number_re = re.compile(r'^-?\d+(\.\d+)$')15+number_re = re.compile(r'^-?\d+(\.\d+)?$')16 17 regex_type = type(number_re)18 19 66 unmodified lines86 return wrapped87 88 89 def 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.94 95 .. sourcecode:: jinja96 98- {% 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 wrapped114 115 TESTS = {116 'odd': test_odd,8 unmodified linesadded:tests/conftest.py+55 added
1+# -*- coding: utf-8 -*-2+"""3+ conftest4+ ~~~~~~~~5+6+ Configure py.test for support stuff.7+8+ :copyright: 2007 by Armin Ronacher, Alexander Schremmer.9+ :license: BSD, see LICENSE for more details.10+"""11+12+import os13+import sys14+sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))15+16+import py17+from inspect import isclass18+from jinja import Environment19+20+21+simple_env = Environment(trim_blocks=True)22+23+24+class Module(py.test.collect.Module):25+26+ def __init__(self, *args, **kwargs):27+ self.env = simple_env28+ super(Module, self).__init__(*args, **kwargs)29+30+ 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)36+37+38+class JinjaTestFunction(py.test.collect.Function):39+40+ 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)46+47+48+class JinjaClassCollector(py.test.collect.Class):49+50+ Function = JinjaTestFunction51+52+ 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+ ~~~~~~~~~~~~~~~~~~~~~~~~~5+6+ Missing tests:7+8+ - wordcount9+ - rst10+ - markdown11+ - textile12+13+ :copyright: 2007 by Armin Ronacher.14+ :license: BSD, see LICENSE for more details.15+"""16+17+CAPITALIZE = '''{{ "foo bar"|capitalize }}'''18+CENTER = '''{{ "foo"|center(9) }}'''19+DEFAULT = '''{{ missing|default("no") }}|{{ false|default('no') }}|\20+{{ false|default('no', true) }}|{{ given|default("no") }}'''21+DICTSORT = '''{{ foo|dictsort }}|\22+{{ foo|dictsort(true) }}|\23+{{ foo|dictsort(false, 'value') }}'''24+ESCAPE = '''{{ '<">&'|escape }}|{{ '<">&'|escape(true) }}'''25+FILESIZEFORMAT = '{{ 100|filesizeformat }}|\26+{{ 1000|filesizeformat }}|\27+{{ 1000000|filesizeformat }}|\28+{{ 1000000000|filesizeformat }}|\29+{{ 1000000000000|filesizeformat }}'30+FIRST = '''{{ foo|first }}'''31+FLOAT = '''{{ "42"|float }}|{{ "ajsghasjgd"|float }}|{{ "32.32"|float }}'''32+INDENT = '''{{ foo|indent(2) }}|{{ foo|indent(2, true) }}'''33+INT = '''{{ "42"|int }}|{{ "ajsghasjgd"|int }}|{{ "32.32"|int }}'''34+JOIN = '''{{ [1, 2, 3]|join("|") }}'''35+LAST = '''{{ foo|last }}'''36+LENGTH = '''{{ "hello world"|length }}'''37+LOWER = '''{{ "FOO"|lower }}'''38+PPRINT = '''{{ data|pprint }}'''39+RANDOM = '''{{ seq|random }}'''40+REVERSE = '''{{ "foobar"|reverse }}|{{ [1, 2, 3]|reverse }}'''41+STRING = '''{{ range(10)|string }}'''42+TITLE = '''{{ "foo bar"|title }}'''43+TRUNCATE = '''{{ data|truncate(15, true, ">>>") }}|\44+{{ data|truncate(15, false, ">>>") }}|\45+{{ smalldata|truncate(15) }}'''46+UPPER = '''{{ "foo"|upper }}'''47+URLENCODE = '''{{ "f#b"|urlencode }}'''48+URLIZE = '''{{ "foo http://www.example.com/ bar"|urlize }}'''49+WORDCOUNT = '''{{ "foo bar baz"|wordcount }}'''50+51+52+def test_capitalize(env):53+ tmpl = env.from_string(CAPITALIZE)54+ assert tmpl.render() == 'Foo bar'55+56+57+def test_center(env):58+ tmpl = env.from_string(CENTER)59+ assert tmpl.render() == ' foo '60+61+62+def test_default(env):63+ tmpl = env.from_string(DEFAULT)64+ assert tmpl.render(given='yes') == 'no|False|no|yes'65+66+67+def 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)]")73+74+75+def test_escape(env):76+ tmpl = env.from_string(ESCAPE)77+ out = tmpl.render()78+ assert out == '<">&|<">&'79+80+81+def 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'85+86+87+def test_first(env):88+ tmpl = env.from_string(FIRST)89+ out = tmpl.render(foo=range(10))90+ assert out == '0'91+92+93+def test_float(env):94+ tmpl = env.from_string(FLOAT)95+ out = tmpl.render()96+ assert out == '42.0|0.0|32.32'97+98+99+def 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'105+106+107+def test_int(env):108+ tmpl = env.from_string(INT)109+ out = tmpl.render()110+ assert out == '42|0|32'111+112+113+def test_join(env):114+ tmpl = env.from_string(JOIN)115+ out = tmpl.render()116+ assert out == '1|2|3'117+118+119+def test_last(env):120+ tmpl = env.from_string(LAST)121+ out = tmpl.render(foo=range(10))122+ assert out == '9'123+124+125+def test_length(env):126+ tmpl = env.from_string(LENGTH)127+ out = tmpl.render()128+ assert out == '11'129+130+131+def test_lower(env):132+ tmpl = env.from_string(LOWER)133+ out = tmpl.render()134+ assert out == 'foo'135+136+137+def 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)142+143+144+def 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 seq149+150+151+def test_reverse(env):152+ tmpl = env.from_string(REVERSE)153+ assert tmpl.render() == 'raboof|[3, 2, 1]'154+155+156+def test_string(env):157+ tmpl = env.from_string(STRING)158+ assert tmpl.render(foo=range(10)) == str(range(10))159+160+161+def test_title(env):162+ tmpl = env.from_string(TITLE)163+ assert tmpl.render() == "Foo Bar"164+165+166+def 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'171+172+173+def test_upper(env):174+ tmpl = env.from_string(UPPER)175+ assert tmpl.render() == 'FOO'176+177+178+def test_urlencode(env):179+ tmpl = env.from_string(URLENCODE)180+ assert tmpl.render() == 'f%23b'181+182+183+def 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'187+188+189+def 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+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~5+6+ :copyright: 2007 by Armin Ronacher.7+ :license: BSD, see LICENSE for more details.8+"""9+10+SIMPLE = '''{% for item in seq %}{{ item }}{% endfor %}'''11+ELSE = '''{% for item in seq %}XXX{% else %}...{% endfor %}'''12+EMPTYBLOCKS = '''<{% for item in seq %}{% else %}{% endfor %}>'''13+CONTEXTVARS = '''{% 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 %}'''17+CYCLING = '''{% for item in seq %}{% cycle '<1>', '<2>' %}{% endfor %}\18+{% for item in seq %}{% cycle through %}{% endfor %}'''19+SCOPE = '''{% for item in seq %}{% endfor %}{{ item }}'''20+21+22+def test_simple(env):23+ tmpl = env.from_string(SIMPLE)24+ assert tmpl.render(seq=range(10)) == '0123456789'25+26+27+def test_else(env):28+ tmpl = env.from_string(ELSE)29+ assert tmpl.render() == '...'30+31+32+def test_empty_blocks(env):33+ tmpl = env.from_string(EMPTYBLOCKS)34+ assert tmpl.render() == '<>'35+36+37+def 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('|')44+45+ 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'54+55+56+def test_cycling(env):57+ tmpl = env.from_string(CYCLING)58+ output = tmpl.render(seq=range(4), through=('<1>', '<2>'))59+ assert output == '<1><2>' * 460+61+62+def test_scope(env):63+ tmpl = env.from_string(SCOPE)64+ output = tmpl.render(seq=range(10))65+ assert not outputadded:tests/test_ifcondition.py+27 added
1+# -*- coding: utf-8 -*-2+"""3+ unit test for if conditions4+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~5+6+ :copyright: 2007 by Armin Ronacher.7+ :license: BSD, see LICENSE for more details.8+"""9+10+SIMPLE = '''{% if true %}...{% endif %}'''11+ELIF = '''{% if false %}XXX{% elif true %}...{% else %}XXX{% endif %}'''12+ELSE = '''{% if false %}XXX{% else %}...{% endif %}'''13+14+15+def test_simple(env):16+ tmpl = env.from_string(SIMPLE)17+ assert tmpl.render() == '...'18+19+20+def test_elif(env):21+ tmpl = env.from_string(ELIF)22+ assert tmpl.render() == '...'23+24+25+def 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+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~5+6+ :copyright: 2007 by Armin Ronacher.7+ :license: BSD, see LICENSE for more details.8+"""9+10+DEFINED = '''{{ missing is defined }}|{{ true is defined }}'''11+EVEN = '''{{ 1 is even }}|{{ 2 is even }}'''12+LOWER = '''{{ "foo" is lower }}|{{ "FOO" is lower }}'''13+MATCHING = '''{{ "42" is matching('^\\d+$') }}|\14+{{ "foo" is matching('^\\d+$') }}'''15+NUMERIC = '''{{ "43" is numeric }}|{{ "foo" is numeric }}|\16+{{ 42 is numeric }}'''17+ODD = '''{{ 1 is odd }}|{{ 2 is odd }}'''18+SEQUENCE = '''{{ [1, 2, 3] is sequence }}|\19+{{ "foo" is sequence }}|\20+{{ 42 is sequence }}'''21+UPPER = '''{{ "FOO" is upper }}|{{ "foo" is upper }}'''22+23+24+def test_defined(env):25+ tmpl = env.from_string(DEFINED)26+ assert tmpl.render() == 'False|True'27+28+29+def test_even(env):30+ tmpl = env.from_string(EVEN)31+ assert tmpl.render() == 'False|True'32+33+34+def test_lower(env):35+ tmpl = env.from_string(LOWER)36+ assert tmpl.render() == 'True|False'37+38+39+def test_matching(env):40+ tmpl = env.from_string(MATCHING)41+ assert tmpl.render() == 'True|False'42+43+44+def test_numeric(env):45+ tmpl = env.from_string(NUMERIC)46+ assert tmpl.render() == 'True|False|True'47+48+49+def test_odd(env):50+ tmpl = env.from_string(ODD)51+ assert tmpl.render() == 'True|False'52+53+54+def test_sequence(env):55+ tmpl = env.from_string(SEQUENCE)56+ assert tmpl.render() == 'True|True|False'57+58+59+def 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+#10+11+test:12+ @(cd tests; py.test $(TESTS))