[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
Provenance
- Commit
ccf284b- Tree
817d7bf- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
25d3322
19 files changed+414 added−71 removed
modified:docs/src/altsyntax.txt+5 added-2 removed
44 unmodified lines45 <%# example eruby like configuration for jinja %>46 <ul>47 <% for item in seq %>48 <li><%= item %></li>49- <% endfor %>49+ <% endfor %>50 </ul>51 52 53 SGML Comment Syntax27 unmodified lines81 Jinja 1.1 or higher.82 83 84 Block / Variable Tag Unification85---------------------------------85+================================86 87 If variable end and start tags are `None` or look the same as block tags and88 you'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 block12 unmodified lines102 Something is the answer to all questions and stuff like that.103 {else}104 Something is {something}.105 {endif}106+107+This feature however can cause strange looking templates because there is no108+visible difference between blocks and variables.modified:docs/src/designerdoc.txt+5 added-6 removed
417 unmodified lines418 419 `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`*,423 424+keywords marked with `*` can be used until Jinja 1.3 as identifiers because425+they were introduced after the Jinja 1.0 release and can cause backwards426+compatiblity problems otherwise. You should not use them any more.427+428 If you want to use such a name you have to prefix or suffix it or use429 alternative names:430 431 .. sourcecode:: jinja1 unmodified line433 {% for macro_ in macros %}434 {{ macro_('foo') }}435 {% endfor %}436 433-If future Jinja releases add new keywords those will be "light" keywords which434-means that they won't raise an error for several releases but yield warnings435-on the application side. But it's very unlikely that new keywords will be436-added.437 438-438 Bleeding Edge439 =============440 441 Here are some features documented that are new in the SVN version and might58 unmodified linesmodified:docs/src/devrecipies.txt+6 added-5 removed
21 unmodified lines22 from jinja import Environment23 24 class AutoEnvironment(Environment):25 26- 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)29 30 You can use it now like this:31 32 .. sourcecode:: python33 33- foo_tmpl = env.get_template('foo.html')34-34 def foo():35 seq = range(10)36 foo = "blub"38- return foo_tmpl.autorender()37+ return env.autorender('foo.html')38+39+In the template you can now access the local variables `seq` and `foo`.modified:docs/src/objects.txt+24 added
47 unmodified lines48 from the template it should return the content of the context as simple html49 template. Of course you can modify the context too. For more informations about50 the context object have a look at the `context object`_ documentation.51 52+The new ``{% call %}`` tag that exists with Jinja 1.1 onwards can not only53+be used with Jinja macros but also with Python functions. If a template54+designers uses the ``{% call %}`` tag to call a function provided by the55+application Jinja will call this function with a keyword argument called56+`caller` which points to a `function`. If you call this function (optionally57+with keyword arguments that appear in the context) you get a string back58+that was the content of that block. This should explain this:59+60+.. sourcecode:: python61+62+ 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)67+68+This can be used like this in the template now:69+70+.. sourcecode:: html+jinja71+72+ {% call make_dialog('Dialog Title') %}73+ This is the body of the dialog entitled "{{ title }}".74+ {% endcall %}75+76 Deferred Values77 ===============78 79 You can pass functions to the template that are called to provide values at74 unmodified linesmodified:docs/generate.py+1 added-1 removed
258 unmodified lines259 260 def 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 linesmodified:jinja/translators/python.py+13 added-27 removed
421 unmodified lines422 node = parent423 424 # 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 lines447 # 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 lines484 '%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 lines561 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)567 568 def handle_dynamic_text(self, node):569 """570 Like `handle_template_text` but for nodes of the type34 unmodified lines605 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()')610 611 # recursive loops612 if node.recursive:613 write('def loop(seq):')39 unmodified lines653 self.indention += 1654 write('yield item')655 self.indention -= 1656 671- write('ctx_pop()')657+ write('context.pop()')658 return '\n'.join(buf)659 660 def handle_if_condition(self, node):661 """124 unmodified lines786 arg_items.append('\'caller\': kw.pop(\'caller\', undefined_singleton)')787 if varargs_init:788 arg_items.append(varargs_init)789 804- 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 lines803 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 lines821 write = lambda x: buf.append(self.indent(x))822 823 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 lines855 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 lines883 buf = []884 write = lambda x: buf.append(self.indent(x))885 886 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)895 896 def handle_include(self, node):897 """331 unmodified linesmodified:jinja/_native.py+28 added-11 removed
12 unmodified lines13 :copyright: 2007 by Armin Ronacher.14 :license: BSD, see LICENSE for more details.15 """16 from jinja.datastructure import Deferred, Undefined17+try:18+ from collections import deque19+except ImportError:20+ class deque(list):21+ """22+ Minimal subclass of list that provides the deque23+ interface used by the native `BaseContext`.24+ """25 26+ def appendleft(self, item):27+ list.insert(self, 0, item)28 29+ def popleft(self):30+ return list.pop(self, 0)31+32+33 class BaseContext(object):34 35 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 = initial41 42+ self._push = self._stack.appendleft43+ self._pop = self._stack.popleft44+45+ def stack(self):46+ return list(self._stack)[::-1]47+ stack = property(stack)48+49 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 rv56 57 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 data66 67 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 lines99 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 Falsemodified:jinja/datastructure.py+1 added-1 removed
545 unmodified lines546 """547 548 def __init__(self, gen):549 self._gen = gen550- self._next = gen._next550+ self._next = gen.next551 self.buffered = False552 553 def disable_buffering(self):554 """40 unmodified linesmodified:jinja/lexer.py+1 added-1 removed
62 unmodified lines63 keywords = 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'])68 69 70 class Failure(object):71 """301 unmodified linesmodified:jinja/loaders.py+12 added-5 removed
60 unmodified lines61 self.available = False62 else:63 self.available = True64 65+ def __getattr__(self, name):66+ """67+ Not found attributes are redirected to the loader68+ """69+ return getattr(self.loader, name)70+71 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 lines341 template loader in the same folder. Defaults342 to ``package_name + '/' + package_path``.343 *New in Jinja 1.1*344 =================== =================================================345+346+ 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 """352 353 def __init__(self, package_name, package_path, use_memcache=False,354 memcache_size=40, cache_folder=None, auto_reload=True,3 unmodified lines358 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)364 365 def get_source(self, environment, name, parent):153 unmodified linesmodified:jinja/parser.py+4 added-2 removed
39 unmodified lines40 switch_if = StateTest.expect_name('else', 'elif', 'endif')41 end_of_if = StateTest.expect_name('endif')42 end_of_filter = StateTest.expect_name('endfilter')43 end_of_macro = StateTest.expect_name('endmacro')44-end_of_call = StateTest.expect_name('endcall')44+end_of_call = StateTest.expect_name('endcall_')45 end_of_block_tag = StateTest.expect_name('endblock')46 end_of_trans = StateTest.expect_name('endtrans')47 48 4 unmodified lines53 Transforms sourcecode into an abstract syntax tree.54 """55 56 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 lines79 '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_directive742 unmodified linesmodified:tests/runtime/bigtable.py+19 added-5 removed
11 unmodified lines12 import timeit13 import jdebug14 from StringIO import StringIO15 16+try:16-from genshi.builder import tag17-from genshi.template import MarkupTemplate17+ from genshi.builder import tag18+ from genshi.template import MarkupTemplate19+ have_genshi = True20+except ImportError:21+ have_genshi = False22 23 from jinja import Environment24 25 try:10 unmodified lines36 have_kid = True37 except ImportError:38 have_kid = False39 40+try:36-from Cheetah.Template import Template as CheetahTemplate41+ from Cheetah.Template import Template as CheetahTemplate42+ have_cheetah = True43+except ImportError:44+ have_cheetah = False45 46 try:47 from mako.template import Template as MakoTemplate48 have_mako = True2 unmodified lines51 52 table = [dict(zip('abcdefghij', map(unicode,range(1, 11))))53 for x in range(1000)]54 55+if have_genshi:47-genshi_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 lines86 {% endfor %}87 </table>88 ''')89 90+if have_cheetah:81-cheetah_tmpl = CheetahTemplate('''91+ cheetah_tmpl = CheetahTemplate('''92 <table>93 #for $row in $table94 <tr>95 #for $col in $row.values()29 unmodified lines125 jinja_tmpl.render(table=table)126 127 def 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)133 134 def test_kid():4 unmodified lines139 kid_tmpl.serialize(output="html")140 141 def test_cheetah():142 """Cheetah Templates"""143+ if not have_cheetah:144+ return145 cheetah_tmpl.respond()146 147 def test_mako():148 """Mako Templates"""38 unmodified linesmodified:tests/conftest.py+56 added-4 removed
15 unmodified lines16 import py17 from jinja import Environment18 from jinja.parser import Parser19 20+try: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".25 26+ import coverage, atexit27+28+ IGNORED_MODULES = ['jinja._speedups', 'jinja.defaults',29+ 'jinja.translators']30+31+ 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)41+42+ def callback(option, opt_str, value, parser):43+ atexit.register(report_coverage)44+ coverage.erase()45+ coverage.start()46+47+ 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!)'))50+51+except ImportError:52+ coverage = None53+54+55 class GlobalLoader(object):56 57 def __init__(self, scope):58 self.scope = scope19 unmodified lines78 def __init__(self, *args, **kwargs):79 self.env = simple_env80 super(Module, self).__init__(*args, **kwargs)81 48- 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)88 89 90 class JinjaTestFunction(py.test.collect.Function):91 3 unmodified lines95 if 'env' in co.co_varnames[:co.co_argcount]:96 target(self.parent.env, *args)97 else:98 target(*args)99+100+101+class JinjaDocTest(py.test.collect.Item):102+103+ def run(self):104+ mod = py.std.types.ModuleType(self.name)105+ mod.__doc__ = self.obj106+ self.execute(mod)107+108+ 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 lines6 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8 """9 10+import time11+import tempfile12 from jinja import Environment, loaders13 from jinja.exceptions import TemplateNotFound14 15 9 unmodified lines25 26 choice_loader = loaders.ChoiceLoader([dict_loader, package_loader])27 28 29+class FakeLoader(loaders.BaseLoader):30+ local_attr = 4231+32+33 def test_dict_loader():34 env = Environment(loader=dict_loader)35 tmpl = env.get_template('justdict.html')36 assert tmpl.render().strip() == 'FOO'52 unmodified lines89 except TemplateNotFound:90 pass91 else:92 raise AssertionError('expected template exception')93+94+95+def test_loader_redirect():96+ env = Environment(loader=FakeLoader())97+ assert env.loader.local_attr == 4298+ assert env.loader.get_source99+ assert env.loader.load100+101+102+class MemcacheTestingLoader(loaders.CachedLoaderMixin, loaders.BaseLoader):103+104+ def __init__(self, enable):105+ loaders.CachedLoaderMixin.__init__(self, enable, 40, None, True, 'foo')106+ self.times = {}107+ self.idx = 0108+109+ def touch(self, name):110+ self.times[name] = time.time()111+112+ def get_source(self, environment, name, parent):113+ self.touch(name)114+ self.idx += 1115+ return 'Template %s (%d)' % (name, self.idx)116+117+ def check_source_changed(self, environment, name):118+ if name in self.times:119+ return self.times[name]120+ return -1121+122+123+memcache_env = Environment(loader=MemcacheTestingLoader(True))124+no_memcache_env = Environment(loader=MemcacheTestingLoader(False))125+126+127+test_memcaching = r'''128+>>> not_caching = MODULE.no_memcache_env.loader129+>>> caching = MODULE.memcache_env.loader130+>>> touch = caching.touch131+132+>>> tmpl1 = not_caching.load('test.html')133+>>> tmpl2 = not_caching.load('test.html')134+>>> tmpl1 == tmpl2135+False136+137+>>> tmpl1 = caching.load('test.html')138+>>> tmpl2 = caching.load('test.html')139+>>> tmpl1 == tmpl2140+True141+142+>>> touch('test.html')143+>>> tmpl2 = caching.load('test.html')144+>>> tmpl1 == tmpl2145+False146+'''added:tests/test_parser.py+76 added
1+# -*- coding: utf-8 -*-2+"""3+ unit test for the parser4+ ~~~~~~~~~~~~~~~~~~~~~~~~5+6+ :copyright: 2007 by Armin Ronacher.7+ :license: BSD, see LICENSE for more details.8+"""9+10+from jinja import Environment11+12+NO_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 %}'''18+19+PHP_SYNTAX = '''\20+<!-- I'm a comment, I'm not interesting -->\21+<? for item in seq -?>22+ <?= item ?>23+<?- endfor ?>'''24+25+ERB_SYNTAX = '''\26+<%# I'm a comment, I'm not interesting %>\27+<% for item in seq -%>28+ <%= item %>29+<%- endfor %>'''30+31+COMMENT_SYNTAX = '''\32+<!--# I'm a comment, I'm not interesting -->\33+<!-- for item in seq --->34+ ${item}35+<!--- endfor -->'''36+37+SMARTY_SYNTAX = '''\38+{* I'm a comment, I'm not interesting *}\39+{for item in seq-}40+ {item}41+{-endfor}'''42+43+44+def 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+ ]53+54+55+def test_php_syntax():56+ env = Environment('<?', '?>', '<?=', '?>', '<!--', '-->')57+ tmpl = env.from_string(PHP_SYNTAX)58+ assert tmpl.render(seq=range(5)) == '01234'59+60+61+def test_erb_syntax():62+ env = Environment('<%', '%>', '<%=', '%>', '<%#', '%>')63+ tmpl = env.from_string(ERB_SYNTAX)64+ assert tmpl.render(seq=range(5)) == '01234'65+66+67+def test_comment_syntax():68+ env = Environment('<!--', '-->', '${', '}', '<!--#', '-->')69+ tmpl = env.from_string(COMMENT_SYNTAX)70+ assert tmpl.render(seq=range(5)) == '01234'71+72+73+def 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+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~5+6+ :copyright: 2007 by Armin Ronacher.7+ :license: BSD, see LICENSE for more details.8+"""9+10+11+class PrivateStuff(object):12+ bar = lambda self: 2313+ foo = lambda self: 4214+ foo.jinja_unsafe_call = True15+16+17+class PublicStuff(object):18+ jinja_allowed_attributes = ['bar']19+ bar = lambda self: 2320+ foo = lambda self: 4221+22+23+test_unsafe = '''24+>>> env.from_string("{{ foo.foo() }}").render(foo=MODULE.PrivateStuff())25+u''26+>>> env.from_string("{{ foo.bar() }}").render(foo=MODULE.PrivateStuff())27+u'23'28+29+>>> env.from_string("{{ foo.foo() }}").render(foo=MODULE.PublicStuff())30+u''31+>>> env.from_string("{{ foo.bar() }}").render(foo=MODULE.PublicStuff())32+u'23'33+34+>>> env.from_string("{{ foo.__class__ }}").render(foo=42)35+u''36+37+>>> env.from_string("{{ foo.func_code }}").render(foo=lambda:None)38+u''39+'''40+41+42+test_restricted = '''43+>>> env.from_string("{% for item.attribute in seq %}...{% endfor %}")44+Traceback (most recent call last):45+ ...46+TemplateSyntaxError: 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+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~5+6+ :copyright: 2007 by Armin Ronacher.7+ :license: BSD, see LICENSE for more details.8+"""9+10+11+test_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()16+u'<ul>'17+>>> stream.next()18+u'<li>1 - 0</li>'19+>>> stream.next()20+u'<li>2 - 1</li>'21+>>> stream.next()22+u'<li>3 - 2</li>'23+>>> stream.next()24+u'<li>4 - 3</li>'25+>>> stream.next()26+u'</ul>'27+"""28+29+test_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()35+u'<ul><li>1 - 0</li><li>2 - 1</li>'36+>>> stream.next()37+u'<li>3 - 2</li><li>4 - 3</li></ul>'38+"""39+40+test_streaming_behavior = r"""41+>>> tmpl = env.from_string("")42+>>> stream = tmpl.stream()43+>>> stream.buffered44+False45+>>> stream.enable_buffering(20)46+>>> stream.buffered47+True48+>>> stream.disable_buffering()49+>>> stream.buffered50+False51+"""modified:CHANGES+2 added-1 removed
79 unmodified lines80 foo a, b, c %}``.81 82 - additional macro arguments now end up in `varargs`.83 84-- 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.386 87 - it's not possible to stream templates.88 89 - fixed a corner case when defining a block inside of a condition18 unmodified linesmodified:Makefile+3 added
9 unmodified lines10 11 test:12 @(cd tests; py.test $(TESTS))13 14+test-coverage:15+ @(cd tests; py.test -C $(TESTS))16+17 documentation:18 @(cd docs; ./generate.py)19 20 webpage:4 unmodified lines