Skip to content
Myr

converted unit tests, started rewriting filters

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

--HG-- branch : trunk

authored by Christoph Hack · committed by Christoph Hack · parent 625215e · Browse files · 26 files+137 added−173 removed
This commit

State

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

Diff stats

26 files+137 added−173 removed

  • tests:+44 added−50 removed
  • other:+93 added−123 removed

26 files+137 added−173 removed

modified:jinja2/defaults.py+3 added-1 removed
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""11from jinja2.filters import FILTERS as DEFAULT_FILTERS12from jinja.tests import TESTS as DEFAULT_TESTS13DEFAULT_NAMESPACE = {}13DEFAULT_NAMESPACE = {14 'range': xrange15}161718__all__ = ['DEFAULT_FILTERS', 'DEFAULT_TESTS', 'DEFAULT_NAMESPACE']
modified:jinja2/environment.py+3 added-1 removed
134 unmodified lines
135class Template(object):136 """Represents a template."""137138 def __init__(self, environment, code):139 namespace = {'environment': environment}139 namespace = {140 'environment': environment141 }142 exec code in namespace143 self.environment = environment144 self.name = namespace['filename']145 self.root_render_func = namespace['root']
10 unmodified lines
modified:jinja2/filters.py+71 added-118 removed
13 unmodified lines
14 from operator import itemgetter15except ImportError:16 itemgetter = lambda a: lambda b: b[a]17from urllib import urlencode, quote18from jinja2.utils import escape18from jinja2.utils import escape, pformat19from jinja2.nodes import Undefined20212223_striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)')242526def contextfilter(f):
112 unmodified lines
139 """140 return unicode(s).title()141142141def do_dictsort(case_sensitive=False, by='key'):143def do_dictsort(value, case_sensitive=False, by='key'):144 """145 Sort a dict and yield (key, value) pairs. Because python dicts are146 unsorted you may want to use this function to order them by either147 key or value:
16 unmodified lines
164 pos = 1165 else:166 raise FilterArgumentError('You can only sort by either '167 '"key" or "value"')166 def sort_func(value, env):168 def sort_func(value):169 if isinstance(value, basestring):168 value = env.to_unicode(value)170 value = unicode(value)171 if not case_sensitive:172 value = value.lower()173 return value174173 def wrapped(env, context, value):174 items = value.items()175 items.sort(lambda a, b: cmp(sort_func(a[pos], env),176 sort_func(b[pos], env)))175 items = value.items()176 items.sort(lambda a, b: cmp(sort_func(a[pos]), sort_func(b[pos])))177 return items177 return items178 return wrapped178179180def do_default(value, default_value=u'', boolean=False):181 """
12 unmodified lines
194 .. sourcecode:: jinja195196 {{ ''|default('the string was empty', true) }}197 """199 # XXX: undefined_sigleton200 if (boolean and not value) or value in (env.undefined_singleton, None):198 if (boolean and not value) or isinstance(value, Undefined):199 return default_value200 return value201202
13 unmodified lines
216 """217 return unicode(d).join([unicode(x) for x in value])218219222def do_count():220def do_count(value):221 """222 Return the length of the value. In case if getting an integer or float223 it will convert it into a string an return the length of the new224 string. If the object has no length it will of corse return 0.
5 unmodified lines
230 except TypeError:231 return 0232233236def do_reverse(l):234def do_reverse(value):235 """236 Return a reversed list of the sequence filtered. You can use this237 for example for reverse iteration:238
37 unmodified lines
276 except StopIteration:277 return env.undefined_singleton278279282def do_random():280def do_random(seq):281 """282 Return a random item from the sequence.283 """284 try:
43 unmodified lines
328 import simplejson329 return simplejson.dumps(value)330331334def do_filesizeformat():332def do_filesizeformat(value):333 """334 Format the value like a 'human-readable' file size (i.e. 13 KB, 4.1 MB, 102335 bytes, etc).336 """339 def wrapped(env, context, value):340 # fail silently341 try:342 bytes = float(value)343 except TypeError:344 bytes = 0337 # fail silently338 try:339 bytes = float(value)340 except TypeError:341 bytes = 0342346 if bytes < 1024:347 return "%d Byte%s" % (bytes, bytes != 1 and 's' or '')348 elif bytes < 1024 * 1024:349 return "%.1f KB" % (bytes / 1024)350 elif bytes < 1024 * 1024 * 1024:351 return "%.1f MB" % (bytes / (1024 * 1024))352 return "%.1f GB" % (bytes / (1024 * 1024 * 1024))353 return wrapped343 if bytes < 1024:344 return "%d Byte%s" % (bytes, bytes != 1 and 's' or '')345 elif bytes < 1024 * 1024:346 return "%.1f KB" % (bytes / 1024)347 elif bytes < 1024 * 1024 * 1024:348 return "%.1f MB" % (bytes / (1024 * 1024))349 return "%.1f GB" % (bytes / (1024 * 1024 * 1024))350351352def do_pprint(value, verbose=False):353 """
136 unmodified lines
490 from docutils.core import publish_parts491 parts = publish_parts(source=s, writer_name='html4css1')492 return parts['fragment']493494498def do_int(default=0):495def do_int(value, default=0):496 """497 Convert the value into an integer. If the498 conversion doesn't work it will return ``0``. You can499 override this default using the first parameter.500 """504 def wrapped(env, context, value):501 try:502 return int(value)503 except (TypeError, ValueError):504 try:506 return int(value)505 return int(float(value))506 except (TypeError, ValueError):508 try:509 return int(float(value))510 except (TypeError, ValueError):511 return default507 return default512 return wrapped508509515def do_float(default=0.0):510def do_float(value, default=0.0):511 """512 Convert the value into a floating point number. If the513 conversion doesn't work it will return ``0.0``. You can514 override this default using the first parameter.515 """521 def wrapped(env, context, value):522 try:523 return float(value)524 except (TypeError, ValueError):525 return default516 try:517 return float(value)518 except (TypeError, ValueError):519 return default526 return wrapped520521529def do_string():522def do_string(value):523 """524 Convert the value into an string.525 """533 return lambda e, c, v: e.to_unicode(v)526 return unicode(value)527528536def do_format(*args):529def do_format(value, *args):530 """531 Apply python string formatting on an object:532533 .. sourcecode:: jinja
3 unmodified lines
537538 Note that you cannot use the mapping syntax (``%(name)s``)539 like in python. Use `|dformat` for that.540 """548 def wrapped(env, context, value):549 return env.to_unicode(value) % args541 return unicode(value) % args550 return wrapped542543544def do_dformat(d):545 """
22 unmodified lines
568 """569 return value.strip()570571581def do_capture(name='captured', clean=False):582 """583 Store the value in a variable called ``captured`` or a variable584 with the name provided. Useful for filter blocks:585586 .. sourcecode:: jinja587588 {% filter capture('foo') %}589 ...590 {% endfilter %}591 {{ foo }}592593 This will output "..." two times. One time from the filter block594 and one time from the variable. If you don't want the filter to595 output something you can use it in `clean` mode:596597 .. sourcecode:: jinja598599 {% filter capture('foo', True) %}600 ...601 {% endfilter %}602 {{ foo }}603 """604 if not isinstance(name, basestring):605 raise FilterArgumentError('You can only capture into variables')606 def wrapped(env, context, value):607 context[name] = value608 if clean:609 return TemplateData()610 return value611 return wrapped612613572def do_striptags(value):573 """574 Strip SGML/XML tags and replace adjacent whitespace by one space.575
1 unmodified line
577 """578 return ' '.join(_striptags_re.sub('', value).split())579580623def do_slice(slices, fill_with=None):581def do_slice(value, slices, fill_with=None):582 """583 Slice an iterator and return a list of lists containing584 those items. Useful if you want to create a div containing585 three div tags that represent columns:
14 unmodified lines
600 values on the last iteration.601602 *new in Jinja 1.1*603 """646 def wrapped(env, context, value):647 result = []648 seq = list(value)649 length = len(seq)650 items_per_slice = length // slices651 slices_with_extra = length % slices652 offset = 0653 for slice_number in xrange(slices):654 start = offset + slice_number * items_per_slice655 if slice_number < slices_with_extra:656 offset += 1657 end = offset + (slice_number + 1) * items_per_slice658 tmp = seq[start:end]659 if fill_with is not None and slice_number >= slices_with_extra:660 tmp.append(fill_with)661 result.append(tmp)662 return result604 result = []605 seq = list(value)606 length = len(seq)607 items_per_slice = length // slices608 slices_with_extra = length % slices609 offset = 0610 for slice_number in xrange(slices):611 start = offset + slice_number * items_per_slice612 if slice_number < slices_with_extra:613 offset += 1614 end = offset + (slice_number + 1) * items_per_slice615 tmp = seq[start:end]616 if fill_with is not None and slice_number >= slices_with_extra:617 tmp.append(fill_with)618 result.append(tmp)619 return result663 return wrapped620621666def do_batch(linecount, fill_with=None):622def do_batch(value, linecount, fill_with=None):623 """624 A filter that batches items. It works pretty much like `slice`625 just the other way round. It returns a list of lists with the626 given number of items. If you provide a second parameter this
12 unmodified lines
639 </table>640641 *new in Jinja 1.1*642 """687 def wrapped(env, context, value):688 result = []689 tmp = []690 for item in value:691 if len(tmp) == linecount:643 result = []644 tmp = []645 for item in value:646 if len(tmp) == linecount:692 result.append(tmp)693 tmp = []694 tmp.append(item)695 if tmp:696 if fill_with is not None and len(tmp) < linecount:697 tmp += [fill_with] * (linecount - len(tmp))647 result.append(tmp)699 return result700 return wrapped648 tmp = []649 tmp.append(item)650 if tmp:651 if fill_with is not None and len(tmp) < linecount:652 tmp += [fill_with] * (linecount - len(tmp))653 result.append(tmp)654 return result655656657def do_sum():658 """
182 unmodified lines
841 'string': do_string,842 'urlize': do_urlize,843 'format': do_format,844 'dformat': do_dformat,891 'capture': do_capture,845 'trim': do_trim,846 'striptags': do_striptags,847 'slice': do_slice,848 'batch': do_batch,
8 unmodified lines
modified:jinja2/nodes.py+3 added-3 removed
403 unmodified lines
404 if self.node is obj is None:405 raise Impossible()406 filter = self.environment.filters.get(self.name)407 if filter is None or getattr(filter, 'contextfilter', False):408 raise nodes.Impossible()408 raise Impossible()409 if obj is None:410 obj = self.node.as_const()411 args = [x.as_const() for x in self.args]412 kwargs = dict(x.as_const() for x in self.kwargs)
9 unmodified lines
422 raise Impossible()423 try:424 return filter(obj, *args, **kwargs)425 except:426 raise nodes.Impossible()426 raise Impossible()427428429class Test(Expr):430 """{{ foo is lower }}"""
20 unmodified lines
451 raise Impossible()452 try:453 return obj(*args, **kwargs)454 except:455 raise nodes.Impossible()455 raise Impossible()456457458class Subscript(Expr):459 """{{ foo.bar }} and {{ foo['bar'] }} etc."""
116 unmodified lines
modified:jinja2/utils.py+13 added
17 unmodified lines
18 .replace('&', '&amp;') \19 .replace('>', '&gt;') \20 .replace('<', '&lt;') \21 .replace('"', '&quot;')222324def pformat(obj, verbose=False):25 """26 Prettyprint an object. Either use the `pretty` library or the27 builtin `pprint`.28 """29 try:30 from pretty import pretty31 return pretty(obj, verbose=verbose)32 except ImportError:33 from pprint import pformat34 return pformat(obj)
modified:tests/runtime/bigbench.py+1 added-1 removed
1import jdebug2from time import time3from jinja import Environment3from jinja2 import Environment4tmpl = Environment().from_string('''5<h1>Bigtable</h1>6<table>7{%- for row in table -%}
81 unmodified lines
modified:tests/runtime/bigtable.py+1 added-1 removed
22 unmodified lines
23 have_genshi = True24except ImportError:25 have_genshi = False2627from jinja import Environment27from jinja2 import Environment2829try:30 from django.conf import settings31 settings.configure()
159 unmodified lines
modified:tests/runtime/columntest.py+1 added-1 removed
1import jdebug2from jinja import from_string2from jinja2 import from_string345template = from_string(u'''\6<h1>Unfilled</h1>
51 unmodified lines
modified:tests/runtime/exception.py+2 added-2 removed
1 unmodified line
2import sys3sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..', '..'))45import jdebug6from jinja import Environment, DictLoader7from jinja.exceptions import TemplateNotFound6from jinja2 import Environment, DictLoader7from jinja2.exceptions import TemplateNotFound8from wsgiref.simple_server import make_server910e = Environment(loader=DictLoader({11 '/': u'''
102 unmodified lines
modified:tests/runtime/inheritance.py+3 added-3 removed
1from jinja import Environment, FileSystemLoader1from jinja2 import Environment, FileSystemLoader2e = Environment(loader=FileSystemLoader('templates'))34from jinja.parser import Parser5from jinja.translators.python import PythonTranslator4from jinja2.parser import Parser5from jinja2.translators.python import PythonTranslator67tmpl = e.loader.load('c.html')8print tmpl.render()
modified:tests/runtime/layout.py+3 added-3 removed
1from jinja import Environment, FileSystemLoader1from jinja2 import Environment, FileSystemLoader2e = Environment(loader=FileSystemLoader('templates'))34from jinja.parser import Parser5from jinja.translators.python import PythonTranslator4from jinja2.parser import Parser5from jinja2.translators.python import PythonTranslator67print PythonTranslator(e, e.loader.parse('index.html')).translate()89tmpl = e.loader.load('index.html')
4 unmodified lines
modified:tests/runtime/modglobals.py+1 added-1 removed
1# test file for block super support2import jdebug3from jinja import Environment, DictLoader3from jinja2 import Environment, DictLoader45env = Environment(loader=DictLoader({6 'a': '''\7<title>{{ title|e }}</title>
30 unmodified lines
modified:tests/runtime/strange.py+1 added-1 removed
1import jdebug2from jinja import Environment, DictLoader2from jinja2 import Environment, DictLoader34base_tmpl = """5{% block content %}Default{% endblock %}6"""
51 unmodified lines
modified:tests/runtime/super.py+1 added-1 removed
1# test file for block super support2import jdebug3from jinja import Environment, DictLoader3from jinja2 import Environment, DictLoader45env = Environment(loader=DictLoader({6 'a': '{% block intro %}INTRO{% endblock %}|BEFORE|{% block data %}INNER{% endblock %}|AFTER',7 'b': '{% extends "a" %}{% block data %}({{ super() }}){% endblock %}',
5 unmodified lines
modified:tests/conftest.py+6 added-6 removed
12 unmodified lines
13import sys14sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))1516import py17from jinja import Environment18from jinja.parser import Parser17from jinja2 import Environment18from jinja2.parser import Parser1920try:21 # This code adds support for coverage.py (see22 # http://nedbatchelder.com/code/modules/coverage.html).
1 unmodified line
24 # module globals (of the test modules) named "coverage_modules".2526 import coverage, atexit2728 IGNORED_MODULES = ['jinja._speedups', 'jinja.defaults',29 'jinja.translators']28 IGNORED_MODULES = ['jinja2._speedups', 'jinja2.defaults',29 'jinja2.translators']3031 def report_coverage():32 coverage.stop()33 module_list = [34 mod for name, mod in sys.modules.copy().iteritems() if35 getattr(mod, '__file__', None) and36 name.startswith('jinja.') and36 name.startswith('jinja2.') and37 name not in IGNORED_MODULES38 ]39 module_list.sort()40 coverage.report(module_list)
28 unmodified lines
69 name, None, scope))707172loader = GlobalLoader(globals())73simple_env = Environment(trim_blocks=True, friendly_traceback=False, loader=loader)73simple_env = Environment(trim_blocks=True, loader=loader)747576class MemcacheClient(object):77 """
55 unmodified lines
modified:tests/test_filters.py+2 added-8 removed
13 unmodified lines
14 :license: BSD, see LICENSE for more details.15"""1617CAPITALIZE = '''{{ "foo bar"|capitalize }}'''18CAPTURE = '''{{ "foo"|capture('bar') }}|{{ bar }}'''18CENTER = '''{{ "foo"|center(9) }}'''19DEFAULT = '''{{ missing|default("no") }}|{{ false|default('no') }}|\20{{ false|default('no', true) }}|{{ given|default("no") }}'''21DICTSORT = '''{{ foo|dictsort }}|\
51 unmodified lines
73 tmpl = env.from_string(CAPITALIZE)74 assert tmpl.render() == 'Foo bar'757678def test_capture(env):79 tmpl = env.from_string(CAPTURE)80 assert tmpl.render() == 'foo|foo'818277def test_center(env):78 tmpl = env.from_string(CENTER)79 assert tmpl.render() == ' foo '80
27 unmodified lines
108109def test_escape(env):110 tmpl = env.from_string(ESCAPE)111 out = tmpl.render()118 assert out == '&lt;"&gt;&amp;|&lt;&quot;&gt;&amp;'112 assert out == '&lt;&quot;&gt;&amp;|&lt;&quot;&gt;&amp;'113114115def test_striptags(env):116 tmpl = env.from_string(STRIPTAGS)
67 unmodified lines
184185def test_pprint(env):186 from pprint import pformat187 tmpl = env.from_string(PPRINT)194 data = range(10000)188 data = range(1000)189 assert tmpl.render(data=data) == pformat(data)190191192def test_random(env):
105 unmodified lines
modified:tests/test_i18n.py+1 added-1 removed
4 unmodified lines
56 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8"""9from jinja import Environment, DictLoader9from jinja2 import Environment, DictLoader1011templates = {12 'master.html': '<title>{{ page_title|default(_("missing")) }}</title>'13 '{% block body %}{% endblock %}',
81 unmodified lines
modified:tests/test_inheritance.py+2 added-2 removed
4 unmodified lines
56 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8"""9from jinja import Environment, DictLoader10from jinja.exceptions import TemplateSyntaxError9from jinja2 import Environment, DictLoader10from jinja2.exceptions import TemplateSyntaxError1112LAYOUTTEMPLATE = '''\13|{% block block1 %}block 1 from layout{% endblock %}14|{% block block2 %}block 2 from layout{% endblock %}
104 unmodified lines
modified:tests/test_lexer.py+3 added-3 removed
22 unmodified lines
23 assert tmpl.render() == 'foo|{{ bar }}|{% baz %}'242526def test_balancing():27 from jinja import Environment27 from jinja2 import Environment28 env = Environment('{%', '%}', '${', '}')29 tmpl = env.from_string(BALANCING)30 assert tmpl.render(seq=range(3)) == "{'FOO': 0}{'FOO': 1}{'FOO': 2}"313233def test_comments():34 from jinja import Environment34 from jinja2 import Environment35 env = Environment('<!--', '-->', '{', '}')36 tmpl = env.from_string(COMMENTS)37 assert tmpl.render(seq=range(3)) == ("<ul>\n <li>0</li>\n "38 "<li>1</li>\n <li>2</li>\n</ul>")
11 unmodified lines
50 assert tmpl.render() == u"'foo'|u'b\\xe4r'"515253def test_operators(env):54 from jinja.lexer import operators54 from jinja2.lexer import operators55 for test, expect in operators.iteritems():56 if test in '([{}])':57 continue58 stream = env.lexer.tokenize('{{ %s }}' % test)
2 unmodified lines
modified:tests/test_loaders.py+2 added-2 removed
7 unmodified lines
8"""910import time11import tempfile12from jinja import Environment, loaders13from jinja.exceptions import TemplateNotFound12from jinja2 import Environment, loaders13from jinja2.exceptions import TemplateNotFound141516dict_loader = loaders.DictLoader({17 'justdict.html': 'FOO'
161 unmodified lines
modified:tests/test_macros.py+1 added-1 removed
62 unmodified lines
63 assert tmpl.render() == 'Hello Peter!'646566def test_kwargs_failure(env):67 from jinja.exceptions import TemplateRuntimeError67 from jinja2.exceptions import TemplateRuntimeError68 tmpl = env.from_string(KWARGSFAILURE)69 try:70 tmpl.render()71 except TemplateRuntimeError, e:
43 unmodified lines
modified:tests/test_parser.py+1 added-1 removed
5 unmodified lines
6 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8"""910from jinja import Environment10from jinja2 import Environment1112NO_VARIABLE_BLOCK = '''\13{# i'm a freaking comment #}\14{% if foo %}{% foo %}{% endif %}
79 unmodified lines
modified:tests/test_security.py+1 added-1 removed
4 unmodified lines
56 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8"""9from jinja import Environment9from jinja2 import Environment101112NONLOCALSET = '''\13{% for item in range(10) %}
54 unmodified lines
modified:tests/test_syntax.py+3 added-3 removed
4 unmodified lines
56 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8"""9from jinja import Environment, DictLoader10from jinja.exceptions import TemplateSyntaxError9from jinja2 import Environment, DictLoader10from jinja2.exceptions import TemplateSyntaxError111213CALL = '''{{ foo('a', c='d', e='f', *['b'], **{'g': 'h'}) }}'''14SLICING = '''{{ [1, 2, 3][:] }}|{{ [1, 2, 3][::-1] }}'''
30 unmodified lines
45TRAILINGCOMMA = '''{{ (1, 2,) }}|{{ [1, 2,] }}|{{ {1: 2,} }}|{{ @(1, 2,) }}'''464748def test_call():49 from jinja import Environment49 from jinja2 import Environment50 env = Environment()51 env.globals['foo'] = lambda a, b, c, e, g: a + b + c + e + g52 tmpl = env.from_string(CALL)53 assert tmpl.render() == 'abdfh'
145 unmodified lines
modified:tests/test_undefined.py+3 added-3 removed
5 unmodified lines
6 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8"""910from jinja import Environment11from jinja.exceptions import TemplateRuntimeError12from jinja.datastructure import SilentUndefined, ComplainingUndefined10from jinja2 import Environment11from jinja2.exceptions import TemplateRuntimeError12from jinja2.datastructure import SilentUndefined, ComplainingUndefined131415silent_env = Environment(undefined_singleton=SilentUndefined)16complaining_env = Environment(undefined_singleton=ComplainingUndefined)
51 unmodified lines
modified:tests/test_various.py+5 added-5 removed
4 unmodified lines
56 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8"""9from jinja.exceptions import TemplateSyntaxError9from jinja2.exceptions import TemplateSyntaxError1011KEYWORDS = '''\12{{ with }}13{{ as }}
43 unmodified lines
57 assert tmpl.render() == '{{ FOO }} and {% BAR %}'585960def test_crazy_raw():61 from jinja import Environment61 from jinja2 import Environment62 env = Environment('{', '}', '{', '}')63 tmpl = env.from_string('{raw}{broken foo}{endraw}')64 assert tmpl.render() == '{broken foo}'656667def test_cache_dict():68 from jinja.utils import CacheDict68 from jinja2.utils import CacheDict69 d = CacheDict(3)70 d["a"] = 171 d["b"] = 272 d["c"] = 3
3 unmodified lines
76 assert 'a' in d and 'c' in d and 'd' in d and 'b' not in d777879def test_stringfilter(env):80 from jinja.filters import stringfilter80 from jinja2.filters import stringfilter81 f = stringfilter(lambda f, x: f + x)82 assert f('42')(env, None, 23) == '2342'838485def test_simplefilter(env):86 from jinja.filters import simplefilter86 from jinja2.filters import simplefilter87 f = simplefilter(lambda f, x: f + x)88 assert f(42)(env, None, 23) == 658990
23 unmodified lines