Skip to content
Myr

fixed a few bugs from the 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 bd33f11 · Browse files · 6 files+32 added−56 removed
This commit

State

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

Diff stats

6 files+32 added−56 removed

  • tests:+5 added−13 removed
  • other:+27 added−43 removed

6 files+32 added−56 removed

modified:jinja2/compiler.py+2 added-2 removed
630 unmodified lines
631632 # the expression pointing to the parent loop. We make the633 # undefined a bit more debug friendly at the same time.634 parent_loop = 'loop' in aliases and aliases['loop'] \635 or "environment.undefined('loop', extra=%r)" % \635 or "environment.undefined(%r)" % "'loop' is undefined. " \636 'the filter section of a loop as well as the ' \637 'else block doesn\'t have access to the special ' \638 "'loop' variable of the current loop. Because " \639 'there is no parent loop it\'s undefined.'
29 unmodified lines
669 self.indent()670 self.writeline('continue')671 self.outdent(2)672673 self.blockvisit(node.body, loop_frame, force_generator=False)673 self.blockvisit(node.body, loop_frame, force_generator=True)674675 if node.else_:676 self.writeline('if l_loop is None:')677 self.indent()
375 unmodified lines
modified:jinja2/filters.py+9 added-13 removed
14 unmodified lines
15 from operator import itemgetter16except ImportError:17 itemgetter = lambda a: lambda b: b[a]18from urllib import urlencode, quote19from itertools import imap19from itertools import imap, groupby20from jinja2.utils import Markup, escape, pformat, urlize, soft_unicode21from jinja2.runtime import Undefined2223
83 unmodified lines
107 raise TypeError('a dict is required')108 result = []109 for key, value in d.iteritems():110 if value is not None and not isinstance(value, Undefined):111 result.append(u'%s="%s"' % (112 escape(env.to_unicode(key)),113 escape(env.to_unicode(value), True)114 ))111 result.append(u'%s="%s"' % (escape(key), escape(value)))112 rv = u' '.join(113 u'%s="%s"' % (escape(key), escape(value))114 for key, value in d.iteritems()115 if value is not None and not isinstance(value, Undefined)
266 unmodified lines
382 """383 try:384 return int(value)385 except (TypeError, ValueError):386 try:387 return int(float(value))388 except (TypeError, ValueError):389 return default389 return default390391392def do_float(value, default=0.0):393 """Convert the value into a floating point number. If the
5 unmodified lines
399 except (TypeError, ValueError):400 return default401402403def do_string(value):404 """Convert the value into an string."""405 return soft_unicode(value)406407403def do_format(value, *args, **kwargs):404 """405 Apply python string formatting on an object:406
38 unmodified lines
445446 If you pass it a second argument it's used to fill missing447 values on the last iteration.448 """454 seq = list(seq)449 seq = list(value)450 length = len(seq)451 items_per_slice = length // slices452 slices_with_extra = length % slices453 offset = 0
139 unmodified lines
593 'wordwrap': do_wordwrap,594 'wordcount': do_wordcount,595 'int': do_int,596 'float': do_float,602 'string': do_string,597 'string': soft_unicode,598 'list': list,599 'urlize': do_urlize,600 'format': do_format,601 'trim': do_trim,602 'striptags': do_striptags,
9 unmodified lines
modified:jinja2/parser.py+1 added-1 removed
479 unmodified lines
480 self.stream.expect('colon')481 value = self.parse_expression()482 items.append(nodes.Pair(key, value, lineno=key.lineno))483 self.stream.expect('rbrace')484 return nodes.Dict(items, token.lineno, self.filename)484 return nodes.Dict(items, lineno=token.lineno)485486 def parse_postfix(self, node):487 while 1:488 token_type = self.stream.current.type
202 unmodified lines
modified:jinja2/utils.py+15 added-27 removed
14 unmodified lines
15from functools import update_wrapper16from itertools import imap171819_word_split_re = re.compile(r'(\s+)')20_punctuation_re = re.compile(21 '^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$' % (22 '|'.join(imap(re.escape, ('(', '<', '&lt;'))),23 '|'.join(imap(re.escape, ('.', ',', ')', '>', '\n', '&gt;')))24 )25)26_simple_email_re = re.compile(r'^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$')272829def soft_unicode(s):30 """Make a string unicode if it isn't already. That way a markup31 string is not converted back to unicode.32 """
2 unmodified lines
35 return s363738def pformat(obj, verbose=False):29 """30 Prettyprint an object. Either use the `pretty` library or the39 """Prettyprint an object. Either use the `pretty` library or the40 builtin `pprint`.41 """42 try:43 from pretty import pretty
2 unmodified lines
46 from pprint import pformat47 return pformat(obj)484941_word_split_re = re.compile(r'(\s+)')4243_punctuation_re = re.compile(44 '^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$' % (45 '|'.join(imap(re.escape, ('(', '<', '&lt;'))),46 '|'.join(imap(re.escape, ('.', ',', ')', '>', '\n', '&gt;')))47 )48)4950_simple_email_re = re.compile(r'^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$')515250def urlize(text, trim_url_limit=None, nofollow=False):54 """55 Converts any URLs in text into clickable links. Works on http://,51 """Converts any URLs in text into clickable links. Works on http://,52 https:// and www. links. Links can have trailing punctuation (periods,53 commas, close-parens) and leading punctuation (opening parens) and54 it'll still do the right thing.55
152 unmodified lines
208 break209210 def copy(self):211 """Return an shallow copy of the instance."""216 rv = LRUCache(self.capacity)212 rv = self.__class__(self.capacity)213 rv._mapping.update(self._mapping)218 rv._queue = self._queue[:]214 rv._queue = deque(self._queue)215 return rv216217 def get(self, key, default=None):218 """Return an item from the cache dict or `default`"""
1 unmodified line
220 return self[key]221 return default222223 def setdefault(self, key, default=None):228 """229 Set `default` if the key is not in the cache otherwise224 """Set `default` if the key is not in the cache otherwise225 leave unchanged. Return the value of this key.226 """227 if key in self:228 return self[key]
62 unmodified lines
291 return iter(self._queue)292293 __copy__ = copy294300 def __deepcopy__(self):301 """Return a deep copy of the LRU Cache"""302 rv = LRUCache(self.capacity)303 rv._mapping = deepcopy(self._mapping)304 rv._queue = deepcopy(self._queue)305 return rv295307296# we have to import it down here as the speedups module imports the297# markup type which is define above.298try:299 from jinja2._speedups import escape
14 unmodified lines
modified:tests/test_filters.py+5 added-5 removed
19 unmodified lines
20{{ false|default('no', true) }}|{{ given|default("no") }}'''21DICTSORT = '''{{ foo|dictsort }}|\22{{ foo|dictsort(true) }}|\23{{ foo|dictsort(false, 'value') }}'''24BATCH = '''{{ foo|batch(3) }}|{{ foo|batch(3, 'X') }}'''25SLICE = '''{{ foo|slice(3) }}|{{ foo|slice(3, 'X') }}'''26ESCAPE = '''{{ '<">&'|escape }}|{{ '<">&'|escape(true) }}'''24BATCH = '''{{ foo|batch(3)|list }}|{{ foo|batch(3, 'X')|list }}'''25SLICE = '''{{ foo|slice(3)|list }}|{{ foo|slice(3, 'X')|list }}'''26ESCAPE = '''{{ '<">&'|escape }}'''27STRIPTAGS = '''{{ foo|striptags }}'''28FILESIZEFORMAT = '{{ 100|filesizeformat }}|\29{{ 1000|filesizeformat }}|\30{{ 1000000|filesizeformat }}|\
9 unmodified lines
40LENGTH = '''{{ "hello world"|length }}'''41LOWER = '''{{ "FOO"|lower }}'''42PPRINT = '''{{ data|pprint }}'''43RANDOM = '''{{ seq|random }}'''44REVERSE = '''{{ "foobar"|reverse }}|{{ [1, 2, 3]|reverse }}'''44REVERSE = '''{{ "foobar"|reverse|join }}|{{ [1, 2, 3]|reverse|list }}'''45STRING = '''{{ range(10)|string }}'''46TITLE = '''{{ "foo bar"|title }}'''47TRIM = '''{{ " foo "|trim }}'''48TRUNCATE = '''{{ data|truncate(15, true, ">>>") }}|\
58 unmodified lines
107108def test_escape(env):109 tmpl = env.from_string(ESCAPE)110 out = tmpl.render()111 assert out == '&lt;&quot;&gt;&amp;|&lt;&quot;&gt;&amp;'111 assert out == '&lt;&quot;&gt;&amp;'112113114def test_striptags(env):115 tmpl = env.from_string(STRIPTAGS)
176 unmodified lines
modified:tests/test_tests.py-8 removed
8 unmodified lines
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+$') }}|\15{{ "foo bar" is matching @/^foo\\s+BAR$/i }}'''13NUMERIC = '''{{ "43" is numeric }}|{{ "foo" is numeric }}|\14{{ 42 is numeric }}'''15ODD = '''{{ 1 is odd }}|{{ 2 is odd }}'''16SEQUENCE = '''{{ [1, 2, 3] is sequence }}|\
18 unmodified lines
35 tmpl = env.from_string(LOWER)36 assert tmpl.render() == 'True|False'373842def test_matching(env):43 tmpl = env.from_string(MATCHING)44 assert tmpl.render() == 'True|False|True'454639def test_numeric(env):40 tmpl = env.from_string(NUMERIC)41 assert tmpl.render() == 'True|False|True'42
24 unmodified lines