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
Provenance
- Commit
be4ae24- Tree
4456353- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
bd33f11
6 files changed+32 added−56 removed
modified:jinja2/compiler.py+2 added-2 removed
630 unmodified lines631 632 # 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 lines669 self.indent()670 self.writeline('continue')671 self.outdent(2)672 673- self.blockvisit(node.body, loop_frame, force_generator=False)673+ self.blockvisit(node.body, loop_frame, force_generator=True)674 675 if node.else_:676 self.writeline('if l_loop is None:')677 self.indent()375 unmodified linesmodified:jinja2/filters.py+9 added-13 removed
14 unmodified lines15 from operator import itemgetter16 except ImportError:17 itemgetter = lambda a: lambda b: b[a]18 from urllib import urlencode, quote19-from itertools import imap19+from itertools import imap, groupby20 from jinja2.utils import Markup, escape, pformat, urlize, soft_unicode21 from jinja2.runtime import Undefined22 23 83 unmodified lines107 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 lines382 """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 default390 391 392 def do_float(value, default=0.0):393 """Convert the value into a floating point number. If the5 unmodified lines399 except (TypeError, ValueError):400 return default401 402 403-def do_string(value):404- """Convert the value into an string."""405- return soft_unicode(value)406-407-403 def do_format(value, *args, **kwargs):404 """405 Apply python string formatting on an object:406 38 unmodified lines445 446 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 = 0139 unmodified lines593 '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 linesmodified:jinja2/parser.py+1 added-1 removed
479 unmodified lines480 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)485 486 def parse_postfix(self, node):487 while 1:488 token_type = self.stream.current.type202 unmodified linesmodified:jinja2/utils.py+15 added-27 removed
14 unmodified lines15 from functools import update_wrapper16 from itertools import imap17 18 19+_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, ('(', '<', '<'))),23+ '|'.join(imap(re.escape, ('.', ',', ')', '>', '\n', '>')))24+ )25+)26+_simple_email_re = re.compile(r'^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$')27+28+29 def 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 lines35 return s36 37 38 def 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 pretty2 unmodified lines46 from pprint import pformat47 return pformat(obj)48 49 41-_word_split_re = re.compile(r'(\s+)')42-43-_punctuation_re = re.compile(44- '^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$' % (45- '|'.join(imap(re.escape, ('(', '<', '<'))),46- '|'.join(imap(re.escape, ('.', ',', ')', '>', '\n', '>')))47- )48-)49-50-_simple_email_re = re.compile(r'^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$')51-52-50 def 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 lines208 break209 210 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 rv216 217 def get(self, key, default=None):218 """Return an item from the cache dict or `default`"""1 unmodified line220 return self[key]221 return default222 223 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 lines291 return iter(self._queue)292 293 __copy__ = copy294 300- 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 rv295 307-296 # we have to import it down here as the speedups module imports the297 # markup type which is define above.298 try:299 from jinja2._speedups import escape14 unmodified linesmodified:tests/test_filters.py+5 added-5 removed
19 unmodified lines20 {{ false|default('no', true) }}|{{ given|default("no") }}'''21 DICTSORT = '''{{ foo|dictsort }}|\22 {{ foo|dictsort(true) }}|\23 {{ foo|dictsort(false, 'value') }}'''24-BATCH = '''{{ foo|batch(3) }}|{{ foo|batch(3, 'X') }}'''25-SLICE = '''{{ foo|slice(3) }}|{{ foo|slice(3, 'X') }}'''26-ESCAPE = '''{{ '<">&'|escape }}|{{ '<">&'|escape(true) }}'''24+BATCH = '''{{ foo|batch(3)|list }}|{{ foo|batch(3, 'X')|list }}'''25+SLICE = '''{{ foo|slice(3)|list }}|{{ foo|slice(3, 'X')|list }}'''26+ESCAPE = '''{{ '<">&'|escape }}'''27 STRIPTAGS = '''{{ foo|striptags }}'''28 FILESIZEFORMAT = '{{ 100|filesizeformat }}|\29 {{ 1000|filesizeformat }}|\30 {{ 1000000|filesizeformat }}|\9 unmodified lines40 LENGTH = '''{{ "hello world"|length }}'''41 LOWER = '''{{ "FOO"|lower }}'''42 PPRINT = '''{{ data|pprint }}'''43 RANDOM = '''{{ seq|random }}'''44-REVERSE = '''{{ "foobar"|reverse }}|{{ [1, 2, 3]|reverse }}'''44+REVERSE = '''{{ "foobar"|reverse|join }}|{{ [1, 2, 3]|reverse|list }}'''45 STRING = '''{{ range(10)|string }}'''46 TITLE = '''{{ "foo bar"|title }}'''47 TRIM = '''{{ " foo "|trim }}'''48 TRUNCATE = '''{{ data|truncate(15, true, ">>>") }}|\58 unmodified lines107 108 def test_escape(env):109 tmpl = env.from_string(ESCAPE)110 out = tmpl.render()111- assert out == '<">&|<">&'111+ assert out == '<">&'112 113 114 def test_striptags(env):115 tmpl = env.from_string(STRIPTAGS)176 unmodified linesmodified:tests/test_tests.py-8 removed
8 unmodified lines9 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-{{ "foo bar" is matching @/^foo\\s+BAR$/i }}'''13 NUMERIC = '''{{ "43" is numeric }}|{{ "foo" is numeric }}|\14 {{ 42 is numeric }}'''15 ODD = '''{{ 1 is odd }}|{{ 2 is odd }}'''16 SEQUENCE = '''{{ [1, 2, 3] is sequence }}|\18 unmodified lines35 tmpl = env.from_string(LOWER)36 assert tmpl.render() == 'True|False'37 38 42-def test_matching(env):43- tmpl = env.from_string(MATCHING)44- assert tmpl.render() == 'True|False|True'45-46-39 def test_numeric(env):40 tmpl = env.from_string(NUMERIC)41 assert tmpl.render() == 'True|False|True'42 24 unmodified lines