Skip to content
Myr

[svn] added many new tests to jinja

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 25d3322 · Browse files · 19 files+414 added−71 removed
This commit

State

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

Diff stats

19 files+414 added−71 removed

  • tests:+309 added−9 removed
  • other:+105 added−62 removed

19 files+414 added−71 removed

modified:docs/src/altsyntax.txt+5 added-2 removed
44 unmodified lines
45 <%# example eruby like configuration for jinja %>46 <ul>47 <% for item in seq %>48 <li><%= item %></li>49 <% endfor %>49 <% end‭for %>50 </ul>515253SGML Comment Syntax
27 unmodified lines
81Jinja 1.1 or higher.828384Block / Variable Tag Unification85--------------------------------85================================8687If variable end and start tags are `None` or look the same as block tags and88you're running Jinja 1.1 or later the parser will switch into the89`no_comment_block` mode. In that mode it will try to match something as block
12 unmodified lines
102 Something is the answer to all questions and stuff like that.103 {else}104 Something is {something}.105 {endif}106107This feature however can cause strange looking templates because there is no108visible difference between blocks and variables.
modified:docs/src/designerdoc.txt+5 added-6 removed
417 unmodified lines
418419 `and`, `block`, `cycle`, `elif`, `else`, `endblock`, `endfilter`,420 `endfor`, `endif`, `endmacro`, `endraw`, `endtrans`, `extends`, `filter`,421 `for`, `if`, `in`, `include`, `is`, `macro`, `not`, `or`, `pluralize`,422 `print`, `raw`, `recursive`, `set`, `trans`422 `print`, `raw`, `recursive`, `set`, `trans`, `call`*, `endcall`*,423424keywords marked with `*` can be used until Jinja 1.3 as identifiers because425they were introduced after the Jinja 1.0 release and can cause backwards426compatiblity problems otherwise. You should not use them any more.427428If you want to use such a name you have to prefix or suffix it or use429alternative names:430431.. sourcecode:: jinja
1 unmodified line
433 {% for macro_ in macros %}434 {{ macro_('foo') }}435 {% endfor %}436433If future Jinja releases add new keywords those will be "light" keywords which434means that they won't raise an error for several releases but yield warnings435on the application side. But it's very unlikely that new keywords will be436added.437438438Bleeding Edge439=============440441Here are some features documented that are new in the SVN version and might
58 unmodified lines
modified:docs/src/devrecipies.txt+6 added-5 removed
21 unmodified lines
22 from jinja import Environment2324 class AutoEnvironment(Environment):2526 def autorender(self):27 return self.render(sys._getframe(1).f_locals)26 def autorender(self, template):27 tmpl = self.get_template(template)28 return tmpl.render(sys._getframe(1).f_locals)2930You can use it now like this:3132.. sourcecode:: python3333 foo_tmpl = env.get_template('foo.html')3434 def foo():35 seq = range(10)36 foo = "blub"38 return foo_tmpl.autorender()37 return env.autorender('foo.html')3839In the template you can now access the local variables `seq` and `foo`.
modified:docs/src/objects.txt+24 added
47 unmodified lines
48from the template it should return the content of the context as simple html49template. Of course you can modify the context too. For more informations about50the context object have a look at the `context object`_ documentation.5152The new ``{% call %}`` tag that exists with Jinja 1.1 onwards can not only53be used with Jinja macros but also with Python functions. If a template54designers uses the ``{% call %}`` tag to call a function provided by the55application Jinja will call this function with a keyword argument called56`caller` which points to a `function`. If you call this function (optionally57with keyword arguments that appear in the context) you get a string back58that was the content of that block. This should explain this:5960.. sourcecode:: python6162 def make_dialog(title, caller=None):63 body = ''64 if caller:65 body = caller(title=title)66 return '<div class="dialog"><h2>%s</h2>%s</div>' % (title, body)6768This can be used like this in the template now:6970.. sourcecode:: html+jinja7172 {% call make_dialog('Dialog Title') %}73 This is the body of the dialog entitled "{{ title }}".74 {% endcall %}7576Deferred Values77===============7879You can pass functions to the template that are called to provide values at
74 unmodified lines
modified:docs/generate.py+1 added-1 removed
258 unmodified lines
259260def handle_file(filename, fp, dst, preproc):261 now = datetime.now()262 title = os.path.basename(filename)[:-4]263 content = fp.read()263 content = fp.read().decode('utf-8')264 suffix = not preproc and '.html' or ''265 parts = generate_documentation(content, (lambda x: './%s%s' % (x, suffix)))266 result = file(os.path.join(dst, title + '.html'), 'w')267 c = dict(parts)
32 unmodified lines
modified:jinja/translators/python.py+13 added-27 removed
421 unmodified lines
422 node = parent423424 # handle requirements code425 if requirements:426 requirement_lines = [427 'def bootstrap(context):',428 ' ctx_push = context.push',429 ' ctx_pop = context.pop'430 ]426 requirement_lines = ['def bootstrap(context):']427 has_requirements = False428 for n in requirements:429 requirement_lines.append(self.handle_node(n))430 requirement_lines.append(' if 0: yield None\n')
16 unmodified lines
447 # blocks with data448 if data:449 block_lines.extend([450 'def %s(context):' % func_name,455 ' ctx_push = context.push',456 ' ctx_pop = context.pop',451 self.indent(self.nodeinfo(item, True)),452 data,453 ' if 0: yield None\n'454 ])
29 unmodified lines
484 '%s\n\n'485 '# Name for disabled debugging\n'486 '__name__ = %r\n\n'487 'def generate(context):\n'494 ' assert environment is context.environment\n'495 ' ctx_push = context.push\n'496 ' ctx_pop = context.pop' % (488 ' assert environment is context.environment' % (489 '\n'.join([490 '%s = environment.%s' % (item, item) for item in491 ['get_attribute', 'perform_test', 'apply_filters',492 'call_function', 'call_function_simple', 'finish_var',
68 unmodified lines
561 def handle_template_text(self, node):562 """563 Handle data around nodes.564 """573 # if we have a ascii only string we go with the574 # bytestring. otherwise we go with the unicode object575 try:576 data = str(node.text)577 except UnicodeError:578 data = node.text565 return self.indent(self.nodeinfo(node)) + '\n' +\580 self.indent('yield %r' % data)566 self.indent('yield %r' % node.text)567568 def handle_dynamic_text(self, node):569 """570 Like `handle_template_text` but for nodes of the type
34 unmodified lines
605 self.used_data_structures.add('LoopContext')606 buf = []607 write = lambda x: buf.append(self.indent(x))608 write(self.nodeinfo(node))623 write('ctx_push()')609 write('context.push()')610611 # recursive loops612 if node.recursive:613 write('def loop(seq):')
39 unmodified lines
653 self.indention += 1654 write('yield item')655 self.indention -= 1656671 write('ctx_pop()')657 write('context.pop()')658 return '\n'.join(buf)659660 def handle_if_condition(self, node):661 """
124 unmodified lines
786 arg_items.append('\'caller\': kw.pop(\'caller\', undefined_singleton)')787 if varargs_init:788 arg_items.append(varargs_init)789804 write('ctx_push({%s})' % ',\n '.join([790 write('context.push({%s})' % ',\n '.join([791 idx and self.indent(item) or item for idx, item792 in enumerate(arg_items)793 ]))794
8 unmodified lines
803 write(self.nodeinfo(node.body))804 data = self.handle_node(node.body)805 if data:806 buf.append(data)821 write('ctx_pop()')807 write('context.pop()')808 write('if 0: yield None')809 self.indention -= 1810 buf.append(self.indent('context[%r] = buffereater(macro)' %811 node.name))
9 unmodified lines
821 write = lambda x: buf.append(self.indent(x))822823 write('def call(**kwargs):')824 self.indention += 1839 write('ctx_push(kwargs)')825 write('context.push(kwargs)')826 data = self.handle_node(node.body)827 if data:828 buf.append(data)843 write('ctx_pop()')829 write('context.pop()')830 write('if 0: yield None')831 self.indention -= 1832 write('yield ' + self.handle_call_func(node.expr,833 {'caller': 'buffereater(call)'}))
21 unmodified lines
855 buf = []856 write = lambda x: buf.append(self.indent(x))857 write('def filtered():')858 self.indention += 1873 write('ctx_push()')859 write('context.push()')860 write(self.nodeinfo(node.body))861 data = self.handle_node(node.body)862 if data:863 buf.append(data)878 write('ctx_pop()')864 write('context.pop()')865 write('if 0: yield None')866 self.indention -= 1867 write('yield %s' % self.filter('buffereater(filtered)()',868 node.filters))
14 unmodified lines
883 buf = []884 write = lambda x: buf.append(self.indent(x))885886 write(self.nodeinfo(node))901 write('ctx_push({\'super\': SuperBlock(%r, blocks, %r, context)})' % (887 write('context.push({\'super\': SuperBlock(%r, blocks, %r, context)})' % (888 str(node.name),889 level890 ))891 write(self.nodeinfo(node.body))892 buf.append(rv)907 write('ctx_pop()')893 write('context.pop()')894 return '\n'.join(buf)895896 def handle_include(self, node):897 """
331 unmodified lines
modified:jinja/_native.py+28 added-11 removed
12 unmodified lines
13 :copyright: 2007 by Armin Ronacher.14 :license: BSD, see LICENSE for more details.15"""16from jinja.datastructure import Deferred, Undefined17try:18 from collections import deque19except ImportError:20 class deque(list):21 """22 Minimal subclass of list that provides the deque23 interface used by the native `BaseContext`.24 """2526 def appendleft(self, item):27 list.insert(self, 0, item)2829 def popleft(self):30 return list.pop(self, 0)313233class BaseContext(object):3435 def __init__(self, undefined_singleton, globals, initial):36 self._undefined_singleton = undefined_singleton37 self.current = current = {}24 self.stack = [globals, initial, current]25 self._push = self.stack.append26 self._pop = self.stack.pop38 self._stack = deque([current, initial, globals])39 self.globals = globals40 self.initial = initial4142 self._push = self._stack.appendleft43 self._pop = self._stack.popleft4445 def stack(self):46 return list(self._stack)[::-1]47 stack = property(stack)4849 def pop(self):50 """51 Pop the last layer from the stack and return it.52 """53 rv = self._pop()35 self.current = self.stack[-1]54 self.current = self._stack[0]55 return rv5657 def push(self, data=None):58 """40 Push one layer to the stack. Layer must be a dict or omitted.59 Push one layer to the stack and return it. Layer must be60 a dict or omitted.61 """62 data = data or {}63 self._push(data)44 self.current = self.stack[-1]64 self.current = self._stack[0]65 return data6667 def __getitem__(self, name):68 """69 Resolve one item. Restrict the access to internal variables70 such as ``'::cycle1'``. Resolve deferreds.71 """72 if not name.startswith('::'):53 # because the stack is usually quite small we better54 # use [::-1] which is faster than reversed() in such55 # a situation.56 for d in self.stack[::-1]:73 for d in self._stack:74 if name in d:75 rv = d[name]76 if rv.__class__ is Deferred:77 rv = rv(self, name)
21 unmodified lines
99 def __contains__(self, name):100 """101 Check if the context contains a given variable.102 """86 for layer in self.stack:103 for layer in self._stack:104 if name in layer:105 return True106 return False
modified:jinja/datastructure.py+1 added-1 removed
545 unmodified lines
546 """547548 def __init__(self, gen):549 self._gen = gen550 self._next = gen._next550 self._next = gen.next551 self.buffered = False552553 def disable_buffering(self):554 """
40 unmodified lines
modified:jinja/lexer.py+1 added-1 removed
62 unmodified lines
63keywords = set(['and', 'block', 'cycle', 'elif', 'else', 'endblock',64 'endfilter', 'endfor', 'endif', 'endmacro', 'endraw',65 'endtrans', 'extends', 'filter', 'for', 'if', 'in',66 'include', 'is', 'macro', 'not', 'or', 'pluralize', 'raw',67 'recursive', 'set', 'trans', 'print', 'call', 'endcall'])67 'recursive', 'set', 'trans', 'print'])686970class Failure(object):71 """
301 unmodified lines
modified:jinja/loaders.py+12 added-5 removed
60 unmodified lines
61 self.available = False62 else:63 self.available = True6465 def __getattr__(self, name):66 """67 Not found attributes are redirected to the loader68 """69 return getattr(self.loader, name)7071 def get_source(self, name, parent=None):72 """Retrieve the sourcecode of a template."""73 # just ascii chars are allowed as template names74 name = str(name)
266 unmodified lines
341 template loader in the same folder. Defaults342 to ``package_name + '/' + package_path``.343 *New in Jinja 1.1*344 =================== =================================================345346 Important note: If you're using an application that is inside of an347 egg never set `auto_reload` to `True`. The egg resource manager will348 automatically export files to the file system and touch them so that349 you not only end up with additional temporary files but also an automatic350 reload each time you load a template.351 """352353 def __init__(self, package_name, package_path, use_memcache=False,354 memcache_size=40, cache_folder=None, auto_reload=True,
3 unmodified lines
358 self.package_name = package_name359 self.package_path = package_path360 if cache_salt is None:361 cache_salt = package_name + '/' + package_path350 # if we have an loader we probably retrieved it from an egg351 # file. In that case don't use the auto_reload!352 if auto_reload and getattr(__import__(package_name, '', '', ['']),353 '__loader__', None) is not None:354 auto_reload = False362 CachedLoaderMixin.__init__(self, use_memcache, memcache_size,363 cache_folder, auto_reload, cache_salt)364365 def get_source(self, environment, name, parent):
153 unmodified lines
modified:jinja/parser.py+4 added-2 removed
39 unmodified lines
40switch_if = StateTest.expect_name('else', 'elif', 'endif')41end_of_if = StateTest.expect_name('endif')42end_of_filter = StateTest.expect_name('endfilter')43end_of_macro = StateTest.expect_name('endmacro')44end_of_call = StateTest.expect_name('endcall')44end_of_call = StateTest.expect_name('endcall_')45end_of_block_tag = StateTest.expect_name('endblock')46end_of_trans = StateTest.expect_name('endtrans')4748
4 unmodified lines
53 Transforms sourcecode into an abstract syntax tree.54 """5556 def __init__(self, environment, source, filename=None):57 #XXX: with Jinja 1.3 call becomes a keyword. Add it also58 # to the lexer.py file.59 self.environment = environment60 if isinstance(source, str):61 source = source.decode(environment.template_charset, 'ignore')62 if isinstance(filename, unicode):
16 unmodified lines
79 'set': self.handle_set_directive,80 'filter': self.handle_filter_directive,81 'print': self.handle_print_directive,82 'macro': self.handle_macro_directive,81 'call': self.handle_call_directive,83 'call_': self.handle_call_directive,84 'block': self.handle_block_directive,85 'extends': self.handle_extends_directive,86 'include': self.handle_include_directive,87 'trans': self.handle_trans_directive
742 unmodified lines
modified:tests/runtime/bigtable.py+19 added-5 removed
11 unmodified lines
12import timeit13import jdebug14from StringIO import StringIO1516try:16from genshi.builder import tag17from genshi.template import MarkupTemplate17 from genshi.builder import tag18 from genshi.template import MarkupTemplate19 have_genshi = True20except ImportError:21 have_genshi = False2223from jinja import Environment2425try:
10 unmodified lines
36 have_kid = True37except ImportError:38 have_kid = False3940try:36from Cheetah.Template import Template as CheetahTemplate41 from Cheetah.Template import Template as CheetahTemplate42 have_cheetah = True43except ImportError:44 have_cheetah = False4546try:47 from mako.template import Template as MakoTemplate48 have_mako = True
2 unmodified lines
5152table = [dict(zip('abcdefghij', map(unicode,range(1, 11))))53 for x in range(1000)]5455if have_genshi:47genshi_tmpl = MarkupTemplate("""56 genshi_tmpl = MarkupTemplate("""57<table xmlns:py="http://genshi.edgewall.org/">58<tr py:for="row in table">59<td py:for="c in row.values()" py:content="c"/>60</tr>
25 unmodified lines
86{% endfor %}87</table>88''')8990if have_cheetah:81cheetah_tmpl = CheetahTemplate('''91 cheetah_tmpl = CheetahTemplate('''92<table>93#for $row in $table94<tr>95#for $col in $row.values()
29 unmodified lines
125 jinja_tmpl.render(table=table)126127def test_genshi():128 """Genshi Templates"""129 if not have_genshi:130 return131 stream = genshi_tmpl.generate(table=table)132 stream.render('html', strip_whitespace=False)133134def test_kid():
4 unmodified lines
139 kid_tmpl.serialize(output="html")140141def test_cheetah():142 """Cheetah Templates"""143 if not have_cheetah:144 return145 cheetah_tmpl.respond()146147def test_mako():148 """Mako Templates"""
38 unmodified lines
modified:tests/conftest.py+56 added-4 removed
15 unmodified lines
16import py17from jinja import Environment18from jinja.parser import Parser1920try:21 # This code adds support for coverage.py (see22 # http://nedbatchelder.com/code/modules/coverage.html).23 # It prints a coverage report for the modules specified in all24 # module globals (of the test modules) named "coverage_modules".2526 import coverage, atexit2728 IGNORED_MODULES = ['jinja._speedups', 'jinja.defaults',29 'jinja.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.') and37 name not in IGNORED_MODULES38 ]39 module_list.sort()40 coverage.report(module_list)4142 def callback(option, opt_str, value, parser):43 atexit.register(report_coverage)44 coverage.erase()45 coverage.start()4647 py.test.config.addoptions('Test options', py.test.config.Option('-C',48 '--coverage', action='callback', callback=callback,49 help='Output information about code coverage (slow!)'))5051except ImportError:52 coverage = None535455class GlobalLoader(object):5657 def __init__(self, scope):58 self.scope = scope
19 unmodified lines
78 def __init__(self, *args, **kwargs):79 self.env = simple_env80 super(Module, self).__init__(*args, **kwargs)8148 def join(self, name):49 obj = getattr(self.obj, name)50 if hasattr(obj, 'func_code'):51 return JinjaTestFunction(name, parent=self)82 def makeitem(self, name, obj, usefilters=True):83 if name.startswith('test_'):84 if hasattr(obj, 'func_code'):85 return JinjaTestFunction(name, parent=self)86 elif isinstance(obj, basestring):87 return JinjaDocTest(name, parent=self)888990class JinjaTestFunction(py.test.collect.Function):91
3 unmodified lines
95 if 'env' in co.co_varnames[:co.co_argcount]:96 target(self.parent.env, *args)97 else:98 target(*args)99100101class JinjaDocTest(py.test.collect.Item):102103 def run(self):104 mod = py.std.types.ModuleType(self.name)105 mod.__doc__ = self.obj106 self.execute(mod)107108 def execute(self, mod):109 mod.env = self.parent.env110 mod.MODULE = self.parent.obj111 failed, tot = py.compat.doctest.testmod(mod, verbose=True)112 if failed:113 py.test.fail('doctest %s: %s failed out of %s' % (114 self.fspath, failed, tot))
modified:tests/test_loaders.py+60 added
5 unmodified lines
6 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8"""910import time11import tempfile12from jinja import Environment, loaders13from jinja.exceptions import TemplateNotFound1415
9 unmodified lines
2526choice_loader = loaders.ChoiceLoader([dict_loader, package_loader])272829class FakeLoader(loaders.BaseLoader):30 local_attr = 42313233def test_dict_loader():34 env = Environment(loader=dict_loader)35 tmpl = env.get_template('justdict.html')36 assert tmpl.render().strip() == 'FOO'
52 unmodified lines
89 except TemplateNotFound:90 pass91 else:92 raise AssertionError('expected template exception')939495def test_loader_redirect():96 env = Environment(loader=FakeLoader())97 assert env.loader.local_attr == 4298 assert env.loader.get_source99 assert env.loader.load100101102class MemcacheTestingLoader(loaders.CachedLoaderMixin, loaders.BaseLoader):103104 def __init__(self, enable):105 loaders.CachedLoaderMixin.__init__(self, enable, 40, None, True, 'foo')106 self.times = {}107 self.idx = 0108109 def touch(self, name):110 self.times[name] = time.time()111112 def get_source(self, environment, name, parent):113 self.touch(name)114 self.idx += 1115 return 'Template %s (%d)' % (name, self.idx)116117 def check_source_changed(self, environment, name):118 if name in self.times:119 return self.times[name]120 return -1121122123memcache_env = Environment(loader=MemcacheTestingLoader(True))124no_memcache_env = Environment(loader=MemcacheTestingLoader(False))125126127test_memcaching = r'''128>>> not_caching = MODULE.no_memcache_env.loader129>>> caching = MODULE.memcache_env.loader130>>> touch = caching.touch131132>>> tmpl1 = not_caching.load('test.html')133>>> tmpl2 = not_caching.load('test.html')134>>> tmpl1 == tmpl2135False136137>>> tmpl1 = caching.load('test.html')138>>> tmpl2 = caching.load('test.html')139>>> tmpl1 == tmpl2140True141142>>> touch('test.html')143>>> tmpl2 = caching.load('test.html')144>>> tmpl1 == tmpl2145False146'''
added:tests/test_parser.py+76 added
1# -*- coding: utf-8 -*-2"""3 unit test for the parser4 ~~~~~~~~~~~~~~~~~~~~~~~~56 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8"""910from jinja import Environment1112NO_VARIABLE_BLOCK = '''\13{# i'm a freaking comment #}\14{% if foo %}{% foo %}{% endif %}15{% for item in seq %}{% item %}{% endfor %}16{% trans foo %}foo is {% foo %}{% endtrans %}17{% trans foo %}one foo{% pluralize %}{% foo %} foos{% endtrans %}'''1819PHP_SYNTAX = '''\20<!-- I'm a comment, I'm not interesting -->\21<? for item in seq -?>22 <?= item ?>23<?- endfor ?>'''2425ERB_SYNTAX = '''\26<%# I'm a comment, I'm not interesting %>\27<% for item in seq -%>28 <%= item %>29<%- endfor %>'''3031COMMENT_SYNTAX = '''\32<!--# I'm a comment, I'm not interesting -->\33<!-- for item in seq --->34 ${item}35<!--- endfor -->'''3637SMARTY_SYNTAX = '''\38{* I'm a comment, I'm not interesting *}\39{for item in seq-}40 {item}41{-endfor}'''424344def test_no_variable_block():45 env = Environment('{%', '%}', None, None)46 tmpl = env.from_string(NO_VARIABLE_BLOCK)47 assert tmpl.render(foo=42, seq=range(2)).splitlines() == [48 '42',49 '01',50 'foo is 42',51 '42 foos'52 ]535455def test_php_syntax():56 env = Environment('<?', '?>', '<?=', '?>', '<!--', '-->')57 tmpl = env.from_string(PHP_SYNTAX)58 assert tmpl.render(seq=range(5)) == '01234'596061def test_erb_syntax():62 env = Environment('<%', '%>', '<%=', '%>', '<%#', '%>')63 tmpl = env.from_string(ERB_SYNTAX)64 assert tmpl.render(seq=range(5)) == '01234'656667def test_comment_syntax():68 env = Environment('<!--', '-->', '${', '}', '<!--#', '-->')69 tmpl = env.from_string(COMMENT_SYNTAX)70 assert tmpl.render(seq=range(5)) == '01234'717273def test_smarty_syntax():74 env = Environment('{', '}', '{', '}', '{*', '*}')75 tmpl = env.from_string(SMARTY_SYNTAX)76 assert tmpl.render(seq=range(5)) == '01234'
added:tests/test_security.py+47 added
1# -*- coding: utf-8 -*-2"""3 unit test for security features4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~56 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8"""91011class PrivateStuff(object):12 bar = lambda self: 2313 foo = lambda self: 4214 foo.jinja_unsafe_call = True151617class PublicStuff(object):18 jinja_allowed_attributes = ['bar']19 bar = lambda self: 2320 foo = lambda self: 42212223test_unsafe = '''24>>> env.from_string("{{ foo.foo() }}").render(foo=MODULE.PrivateStuff())25u''26>>> env.from_string("{{ foo.bar() }}").render(foo=MODULE.PrivateStuff())27u'23'2829>>> env.from_string("{{ foo.foo() }}").render(foo=MODULE.PublicStuff())30u''31>>> env.from_string("{{ foo.bar() }}").render(foo=MODULE.PublicStuff())32u'23'3334>>> env.from_string("{{ foo.__class__ }}").render(foo=42)35u''3637>>> env.from_string("{{ foo.func_code }}").render(foo=lambda:None)38u''39'''404142test_restricted = '''43>>> env.from_string("{% for item.attribute in seq %}...{% endfor %}")44Traceback (most recent call last):45 ...46TemplateSyntaxError: can't assign to expression. (line 1)47'''
added:tests/test_streaming.py+51 added
1# -*- coding: utf-8 -*-2"""3 unit test for streaming interface4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~56 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8"""91011test_basic_streaming = r"""12>>> tmpl = env.from_string("<ul>{% for item in seq %}<li>{{ loop.index "13... "}} - {{ item }}</li>{%- endfor %}</ul>")14>>> stream = tmpl.stream(seq=range(4))15>>> stream.next()16u'<ul>'17>>> stream.next()18u'<li>1 - 0</li>'19>>> stream.next()20u'<li>2 - 1</li>'21>>> stream.next()22u'<li>3 - 2</li>'23>>> stream.next()24u'<li>4 - 3</li>'25>>> stream.next()26u'</ul>'27"""2829test_buffered_streaming = r"""30>>> tmpl = env.from_string("<ul>{% for item in seq %}<li>{{ loop.index "31... "}} - {{ item }}</li>{%- endfor %}</ul>")32>>> stream = tmpl.stream(seq=range(4))33>>> stream.enable_buffering(size=3)34>>> stream.next()35u'<ul><li>1 - 0</li><li>2 - 1</li>'36>>> stream.next()37u'<li>3 - 2</li><li>4 - 3</li></ul>'38"""3940test_streaming_behavior = r"""41>>> tmpl = env.from_string("")42>>> stream = tmpl.stream()43>>> stream.buffered44False45>>> stream.enable_buffering(20)46>>> stream.buffered47True48>>> stream.disable_buffering()49>>> stream.buffered50False51"""
modified:CHANGES+2 added-1 removed
79 unmodified lines
80 foo a, b, c %}``.8182- additional macro arguments now end up in `varargs`.8384- implemented `{% call %}` - unsure if this makes it into the final release.84- implemented the `{% call %}` block. `call` and `endcall` can still be used85 as identifiers until Jinja 1.38687- it's not possible to stream templates.8889- fixed a corner case when defining a block inside of a condition
18 unmodified lines
modified:Makefile+3 added
9 unmodified lines
1011test:12 @(cd tests; py.test $(TESTS))1314test-coverage:15 @(cd tests; py.test -C $(TESTS))1617documentation:18 @(cd docs; ./generate.py)1920webpage:
4 unmodified lines