fixed more 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 2b60fe5 · Browse files · 15 files·+228 added−189 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
15 files+228 added−189 removed
- tests:+87 added−161 removed
- other:+141 added−28 removed
Provenance
- Commit
4f7d2d5- Tree
538e40c- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
2b60fe5
15 files changed+228 added−189 removed
modified:jinja2/__init__.py+1 added-1 removed
59 unmodified lines60 from jinja2.loaders import BaseLoader, FileSystemLoader, PackageLoader, \61 DictLoader62 from jinja2.runtime import Undefined, DebugUndefined, StrictUndefined63 from jinja2.filters import environmentfilter, contextfilter64-from jinja2.utils import Markup, escape64+from jinja2.utils import Markup, escape, contextfunctionmodified:jinja2/defaults.py+3 added-1 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 from jinja2.filters import FILTERS as DEFAULT_FILTERS12 from jinja2.tests import TESTS as DEFAULT_TESTS13+from jinja2.utils import generate_lorem_ipsum14 15 16 DEFAULT_NAMESPACE = {16- 'range': xrange17+ 'range': xrange,18+ 'lipsum': generate_lorem_ipsum19 }modified:jinja2/ext.py+3 added-2 removed
38 unmodified lines39 40 def parse(self, parser):41 lineno = parser.stream.next().lineno42 args = [parser.parse_expression()]43- if self.stream.current.type is 'comma':43+ if parser.stream.current.type is 'comma':44+ parser.stream.next()45 args.append(parser.parse_expression())46 body = parser.parse_statements(('name:endcache',), drop_needle=True)47 return nodes.CallBlock(47- nodes.Call(nodes.Name('cache_support'), args, [], None, None),48+ nodes.Call(nodes.Name('cache_support', 'load'), args, [], None, None),49 [], [], body50 )modified:jinja2/i18n.py+17 added-7 removed
32 unmodified lines33 string was extracted from embedded Python code), and34 * ``message`` is the string itself (a ``unicode`` object, or a tuple35 of ``unicode`` objects for functions with multiple string arguments).36 """37- for call in node.find_all(nodes.Call):37+ for node in node.find_all(nodes.Call):38 if not isinstance(node.node, nodes.Name) or \39 node.node.name not in gettext_functions:40 continue41 42 strings = []43 for arg in node.args:44 if isinstance(arg, nodes.Const) and \45 isinstance(arg.value, basestring):46- strings.append(arg)46+ strings.append(arg.value)47 else:48 strings.append(None)49 50 if len(strings) == 1:15 unmodified lines66 :return: an iterator over ``(lineno, funcname, message, comments)`` tuples.67 (comments will be empty currently)68 """69 encoding = options.get('encoding', 'utf-8')70+ extensions = [x.strip() for x in options.get('extensions', '').split(',')]71 environment = Environment(72 options.get('block_start_string', '{%'),73 options.get('block_end_string', '%}'),74 options.get('variable_start_string', '{{'),1 unmodified line76 options.get('comment_start_string', '{#'),77 options.get('comment_end_string', '#}'),78 options.get('line_statement_prefix') or None,79 options.get('trim_blocks', '').lower() in ('1', 'on', 'yes', 'true'),79- extensions=[x.strip() for x in options.get('extensions', '')80- .split(',')] + [TransExtension]80+ extensions=[x for x in extensions if x]81 )82+83+ # add the i18n extension only if it's not yet in the list. Some people84+ # might use a script to sync the babel ini with the Jinja configuration85+ # so we want to avoid having the trans extension twice in the list.86+ for extension in environment.extensions:87+ if isinstance(extension, TransExtension):88+ break89+ else:90+ environment.extensions.append(TransExtension(environment))91+92 node = environment.parse(fileobj.read().decode(encoding))93 for lineno, func, message in extract_from_ast(node, keywords):94 yield lineno, func, message, []95 76 unmodified lines172 if plural:173 plural = plural.replace('%%', '%')174 175 if not have_plural:166- if plural_expr is None:167- raise TemplateAssertionError('pluralize without variables',168- lineno, parser.filename)176 plural_expr = None177+ elif plural_expr is None:178+ raise TemplateAssertionError('pluralize without variables',179+ lineno, parser.filename)180 181 if variables:182 variables = nodes.Dict([nodes.Pair(nodes.Const(x, lineno=lineno), y)183 for x, y in variables.items()])63 unmodified linesmodified:jinja2/lexer.py+6 added-3 removed
36 unmodified lines37 38 # set of used keywords39 keywords = set(['and', 'block', 'elif', 'else', 'endblock', 'print',40 'endfilter', 'endfor', 'endif', 'endmacro', 'endraw',41- 'extends', 'filter', 'for', 'if', 'in', 'include'41+ 'extends', 'filter', 'for', 'if', 'in', 'include',42 'is', 'macro', 'not', 'or', 'raw', 'call', 'endcall'])43 44 # bind operators to token types45 operators = {199 unmodified lines245 ('comment', environment.comment_start_string),246 ('block', environment.block_start_string),247 ('variable', environment.variable_start_string)248 ]249- root_tag_rules.sort(key=lambda x: len(x[1]))249+ root_tag_rules.sort(key=lambda x: -len(x[1]))250 251 # now escape the rules. This is done here so that the escape252 # signs don't count for the lengths of the tags.253 root_tag_rules = [(a, e(b)) for a, b in root_tag_rules]65 unmodified lines319 }320 321 def tokenize(self, source, filename=None):322 """Works like `tokeniter` but returns a tokenstream of tokens and not323- a generator or token tuples. Additionally all token values are already323+ a generator or token tuples. Additionally all token values are already324 converted into types and postprocessed. For example keywords are325 already keyword tokens, not named tokens, comments are removed,326 integers and floats converted, strings unescaped etc.327 """5 unmodified lines333 elif token == 'linestatement_begin':334 token = 'block_begin'335 elif token == 'linestatement_end':336 token = 'block_end'337+ # we are not interested in those tokens in the parser338+ elif token in ('raw_begin', 'raw_end'):339+ continue340 elif token == 'data':341 try:342 value = str(value)343 except UnicodeError:158 unmodified linesmodified:jinja2/nodes.py+10 added-3 removed
7 unmodified lines8 It also provides some node tree helper functions like `in_lineno` and9 `get_nodes` used by the parser and translator in order to normalize10 python and jinja nodes.11 12- :copyright: 2007 by Armin Ronacher.12+ :copyright: 2008 by Armin Ronacher.13 :license: BSD, see LICENSE for more details.14 """15 import operator16+from types import FunctionType17 from itertools import chain, izip18 from collections import deque19 from copy import copy20 21 unmodified lines42 'gteq': operator.ge,43 'lt': operator.lt,44 'lteq': operator.le,45 'in': operator.contains,45- 'notin': lambda a, b: not operator.contains(a, b)46+ 'notin': lambda a, b: b not in a47 }48 49 50 class Impossible(Exception):398 unmodified lines449 fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')450 451 def as_const(self):452 obj = self.node.as_const()453+454+ # don't evaluate context functions455+ if type(obj) is FunctionType and \456+ getattr(obj, 'contextfunction', False):457+ raise Impossible()458+459 args = [x.as_const() for x in self.args]460 kwargs = dict(x.as_const() for x in self.kwargs)461 if self.dyn_args is not None:462 try:23 unmodified lines486 except:487 raise Impossible()488 489 def can_assign(self):483- return True490+ return False491 492 493 class Slice(Expr):494 """1:2:3 etc."""100 unmodified linesmodified:jinja2/optimizer.py+6 added-4 removed
30 unmodified lines31 # for l_item in xrange(10: even though it would be possible32 # - multiple Output() nodes should be concatenated into one node.33 # for example the i18n system could output such nodes:34 # "foo{% trans %}bar{% endtrans %}blah"35+# - when unrolling loops local sets become global sets :-/36+# see also failing test case `test_localset` in test_various37 38 39 def optimize(node, environment, context_hint=None):40 """The context hint can be used to perform an static optimization143 unmodified lines184 try:185 for item, loop in LoopContext(iterable, True):186 context['loop'] = loop.make_static()187 assign(node.target, item)186- result.extend(self.visit(n.copy(), context)187- for n in node.body)188+ for n in node.body:189+ result.extend(self.visit_list(n.copy(), context))190 iterated = True191 if not iterated and node.else_:190- result.extend(self.visit(n.copy(), context)191- for n in node.else_)192+ for n in node.else_:193+ result.extend(self.visit_list(n.copy(), context))194 except nodes.Impossible:195 return node196 finally:197 context.pop()71 unmodified linesmodified:jinja2/parser.py+4 added-4 removed
62 unmodified lines63 """Parse an assign statement."""64 lineno = self.stream.expect('assign').lineno65 if not target.can_assign():66 raise TemplateSyntaxError("can't assign to '%s'" %67- target, target.lineno,68- self.filename)67+ target.__class__.__name__.lower(),68+ target.lineno, self.filename)69 expr = self.parse_tuple()70 target.set_ctx('store')71 return nodes.Assign(target, expr, lineno=lineno)72 20 unmodified lines93 lineno = self.stream.expect('for').lineno94 target = self.parse_tuple(simplified=True)95 if not target.can_assign():96 raise TemplateSyntaxError("can't assign to '%s'" %97- target, target.lineno,98- self.filename)97+ target.__class__.__name__.lower(),98+ target.lineno, self.filename)99 target.set_ctx('store')100 self.stream.expect('in')101 iter = self.parse_tuple(no_condexpr=True)102 test = None567 unmodified linesmodified:jinja2/runtime.py+8 added-1 removed
10 unmodified lines11 try:12 from collections import defaultdict13 except ImportError:14 defaultdict = None15+from types import FunctionType15-from jinja2.utils import Markup16+from jinja2.utils import Markup, partial17 from jinja2.exceptions import UndefinedError18 19 20 __all__ = ['LoopContext', 'StaticLoopContext', 'TemplateContext',13 unmodified lines34 self.exported = set()35 self.name = name36 self.blocks = dict((k, [v]) for k, v in blocks.iteritems())37 38+ # give all context functions the context as first argument39+ for key, value in self.iteritems():40+ if type(value) is FunctionType and \41+ getattr(value, 'contextfunction', False):42+ dict.__setitem__(self, key, partial(value, self))43+44 # if the template is in standalone mode we don't copy the blocks over.45 # this is used for includes for example but otherwise, if the globals46 # are a template context, this template is participating in a template47 # inheritance chain and we have to copy the blocks over.286 unmodified linesmodified:jinja2/utils.py+74 added-2 removed
10 unmodified lines11 import re12 import string13 from collections import deque14 from copy import deepcopy15-from functools import update_wrapper15 from itertools import imap16 17 18 _word_split_re = re.compile(r'(\s+)')5 unmodified lines24 )25 _simple_email_re = re.compile(r'^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$')26 27 28+def contextfunction(f):29+ """Mark a callable as context callable. A context callable is passed30+ the active context as first argument.31+ """32+ f.contextfunction = True33+ return f34+35+36 def import_string(import_name, silent=False):37 """Imports an object based on a string. This use useful if you want to38 use import paths as endpoints or something similar. An import path can39 be specified either in dotted notation (``xml.sax.saxutils.escape``)74 unmodified lines114 words[i] = lead + middle + trail115 return u''.join(words)116 117 118+def generate_lorem_ipsum(n=5, html=True, min=20, max=100):119+ """Generate some lorem impsum for the template."""120+ from jinja2.constants import LOREM_IPSUM_WORDS121+ from random import choice, random, randrange122+ words = LOREM_IPSUM_WORDS.split()123+ result = []124+125+ for _ in xrange(n):126+ next_capitalized = True127+ last_comma = last_fullstop = 0128+ word = None129+ last = None130+ p = []131+132+ # each paragraph contains out of 20 to 100 words.133+ for idx, _ in enumerate(xrange(randrange(min, max))):134+ while True:135+ word = choice(words)136+ if word != last:137+ last = word138+ break139+ if next_capitalized:140+ word = word.capitalize()141+ next_capitalized = False142+ # add commas143+ if idx - randrange(3, 8) > last_comma:144+ last_comma = idx145+ last_fullstop += 2146+ word += ','147+ # add end of sentences148+ if idx - randrange(10, 20) > last_fullstop:149+ last_comma = last_fullstop = idx150+ word += '.'151+ next_capitalized = True152+ p.append(word)153+154+ # ensure that the paragraph ends with a dot.155+ p = u' '.join(p)156+ if p.endswith(','):157+ p = p[:-1] + '.'158+ elif not p.endswith('.'):159+ p += '.'160+ result.append(p)161+162+ if not html:163+ return u'\n\n'.join(result)164+ return Markup(u'\n'.join(u'<p>%s</p>' % escape(x) for x in result))165+166+167 class Markup(unicode):168 """Marks a string as being safe for inclusion in HTML/XML output without169 needing to be escaped. This implements the `__html__` interface a couple170 of frameworks and web applications use.62 unmodified lines233 for name, arg in kwargs.iteritems():234 if hasattr(arg, '__html__') or isinstance(arg, basestring):235 kwargs[name] = escape(arg)236 return self.__class__(orig(self, *args, **kwargs))181- return update_wrapper(func, orig, ('__name__', '__doc__'))237+ func.__name__ = orig.__name__238+ func.__doc__ = orig.__doc__239+ return func240 for method in '__getitem__', '__getslice__', 'capitalize', \241 'title', 'lower', 'upper', 'replace', 'ljust', \242 'rjust', 'lstrip', 'rstrip', 'partition', 'center', \243 'strip', 'translate', 'expandtabs', 'rpartition', \152 unmodified lines396 """397 if not isinstance(s, unicode):398 s = unicode(s)399 return s400+401+402+# partials403+try:404+ from functools import partial405+except ImportError:406+ class partial(object):407+ def __init__(self, _func, *args, **kwargs):408+ self._func = func409+ self._args = args410+ self._kwargs = kwargs411+ def __call__(self, *args, **kwargs):412+ kwargs.update(self._kwargs)413+ return self._func(*(self._args + args), **kwargs)modified:jinja2/visitor.py+9 added
75 unmodified lines76 delattr(node, field)77 else:78 setattr(node, field, new_node)79 return node80+81+ def visit_list(self, node, *args, **kwargs):82+ """As transformers may return lists in some places this method83+ can be used to enforce a list as return value.84+ """85+ rv = self.visit(node, *args, **kwargs)86+ if not isinstance(rv, list):87+ rv = [rv]88+ return rvmodified:tests/test_i18n.py+36 added-44 removed
4 unmodified lines5 6 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8 """9-from jinja2 import Environment, DictLoader9+from jinja2 import Environment, DictLoader, contextfunction10 11 templates = {12 'master.html': '<title>{{ page_title|default(_("missing")) }}</title>'13 '{% block body %}{% endblock %}',14 'child.html': '{% extends "master.html" %}{% block body %}'15- '{% trans "watch out" %}{% endblock %}',15+ '{% trans %}watch out{% endtrans %}{% endblock %}',16 'plural.html': '{% trans user_count %}One user online{% pluralize %}'17 '{{ user_count }} users online{% endtrans %}',18 'stringformat.html': '{{ _("User: %d")|format(user_count) }}'19 }9 unmodified lines29 }30 }31 32 33-class SimpleTranslator(object):34- """Yes i know it's only suitable for english and german but35- that's a stupid unittest..."""33+@contextfunction34+def gettext(context, string):35+ language = context.get('LANGUAGE', 'en')36+ return languages.get(language, {}).get(string, string)37 37- def __init__(self, language):38- self.strings = languages.get(language, {})38 40- def gettext(self, string):41- return self.strings.get(string, string)39+@contextfunction40+def ngettext(context, s, p, n):41+ language = context.get('LANGUAGE', 'en')42+ if n != 1:43+ return languages.get(language, {}).get(p, p)44+ return languages.get(language, {}).get(s, s)45 43- def ngettext(self, s, p, n):44- if n != 1:45- return self.strings.get(p, p)46- return self.strings.get(s, s)46 47+i18n_env = Environment(48+ loader=DictLoader(templates),49+ extensions=['jinja2.i18n.TransExtension']50+)51+i18n_env.globals.update({52+ '_': gettext,53+ 'gettext': gettext,54+ 'ngettext': ngettext55+})56 49-class I18NEnvironment(Environment):57 51- def __init__(self):52- super(I18NEnvironment, self).__init__(loader=DictLoader(templates))53-54- def get_translator(self, context):55- return SimpleTranslator(context['LANGUAGE'] or 'en')56-57-58-i18n_env = I18NEnvironment()59-60-61-def test_factory():62- def factory(context):63- return SimpleTranslator(context['LANGUAGE'] or 'en')64- env = Environment(translator_factory=factory)65- tmpl = env.from_string('{% trans "watch out" %}')66- assert tmpl.render(LANGUAGE='de') == 'pass auf'67-68-69-def test_get_translations():70- trans = list(i18n_env.get_translations('child.html'))71- assert len(trans) == 172- assert trans[0] == (1, u'watch out', None)73-74-75-def test_get_translations_for_string():76- trans = list(i18n_env.get_translations('master.html'))77- assert len(trans) == 178- assert trans[0] == (1, u'missing', None)79-80-58 def test_trans():59 tmpl = i18n_env.get_template('child.html')60 assert tmpl.render(LANGUAGE='de') == '<title>fehlend</title>pass auf'61 6 unmodified lines68 69 def test_trans_stringformatting():70 tmpl = i18n_env.get_template('stringformat.html')71 assert tmpl.render(LANGUAGE='de', user_count=5) == 'Benutzer: 5'72+73+74+def test_extract():75+ from jinja2.i18n import babel_extract76+ from StringIO import StringIO77+ source = StringIO('''78+ {{ gettext('Hello World') }}79+ {% trans %}Hello World{% endtrans %}80+ {% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %}81+ ''')82+ assert list(babel_extract(source, ('gettext', 'ngettext', '_'), [], {})) == [83+ (2, 'gettext', 'Hello World', []),84+ (3, 'gettext', u'Hello World', []),85+ (4, 'ngettext', (u'%(users)s user', u'%(users)s users', None), [])86+ ]modified:tests/test_parser.py+11 added-29 removed
4 unmodified lines5 6 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8 """9-9 from jinja2 import Environment10 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 %}'''11 12 PHP_SYNTAX = '''\13 <!-- I'm a comment, I'm not interesting -->\14 <? for item in seq -?>11 unmodified lines26 <!-- for item in seq --->27 ${item}28 <!--- endfor -->'''29 37-SMARTY_SYNTAX = '''\38-{* I'm a comment, I'm not interesting *}\39-{for item in seq-}40- {item}41-{-endfor}'''30+MAKO_SYNTAX = '''\31+% for item in seq:32+ ${item}33+% endfor'''34 35 BALANCING = '''{{{'foo':'bar'}.foo}}'''36 37 STARTCOMMENT = '''{# foo comment1 unmodified line39 {% macro blub() %}foo{% endmacro %}40 {{ blub() }}'''41 42 51-def test_no_variable_block():52- env = Environment('{%', '%}', None, None)53- tmpl = env.from_string(NO_VARIABLE_BLOCK)54- assert tmpl.render(foo=42, seq=range(2)).splitlines() == [55- '42',56- '01',57- 'foo is 42',58- '42 foos'59- ]60-61-43 def test_php_syntax():44 env = Environment('<?', '?>', '<?=', '?>', '<!--', '-->')45 tmpl = env.from_string(PHP_SYNTAX)46 assert tmpl.render(seq=range(5)) == '01234'10 unmodified lines57 tmpl = env.from_string(COMMENT_SYNTAX)58 assert tmpl.render(seq=range(5)) == '01234'59 60 80-def test_smarty_syntax():81- env = Environment('{', '}', '{', '}', '{*', '*}')82- tmpl = env.from_string(SMARTY_SYNTAX)83- assert tmpl.render(seq=range(5)) == '01234'84-85-61 def test_balancing(env):62 tmpl = env.from_string(BALANCING)63 assert tmpl.render() == 'bar'64 65 66 def test_start_comment(env):67 tmpl = env.from_string(STARTCOMMENT)68 assert tmpl.render().strip() == 'foo'69+70+71+def test_line_syntax():72+ env = Environment('<%', '%>', '${', '}', '<%#', '%>', '%')73+ tmpl = env.from_string(MAKO_SYNTAX)74+ assert [int(x.strip()) for x in tmpl.render(seq=range(5)).split()] == \75+ range(5)modified:tests/test_security.py+29 added-26 removed
4 unmodified lines5 6 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8 """9-from jinja2 import Environment9+from jinja2.sandbox import SandboxedEnvironment, unsafe10 11 12-NONLOCALSET = '''\13-{% for item in range(10) %}14- {%- set outer = item! -%}15-{% endfor -%}16-{{ outer }}'''12+class PrivateStuff(object):13 14+ def bar(self):15+ return 2316 19-class PrivateStuff(object):20- bar = lambda self: 2321- foo = lambda self: 4222- foo.jinja_unsafe_call = True17+ @unsafe18+ def foo(self):19+ return 4220 21+ def __repr__(self):22+ return 'PrivateStuff'23 24+25 class PublicStuff(object):26- jinja_allowed_attributes = ['bar']26 bar = lambda self: 2328- foo = lambda self: 4227+ _foo = lambda self: 4228 29+ def __repr__(self):30+ return 'PublicStuff'31 32+33 test_unsafe = '''34+>>> env = MODULE.SandboxedEnvironment()35 >>> env.from_string("{{ foo.foo() }}").render(foo=MODULE.PrivateStuff())33-u''36+Traceback (most recent call last):37+ ...38+TypeError: <bound method PrivateStuff.foo of PrivateStuff> is not safely callable39 >>> env.from_string("{{ foo.bar() }}").render(foo=MODULE.PrivateStuff())40 u'23'41 37->>> env.from_string("{{ foo.foo() }}").render(foo=MODULE.PublicStuff())38-u''42+>>> env.from_string("{{ foo._foo() }}").render(foo=MODULE.PublicStuff())43+Traceback (most recent call last):44+ ...45+UndefinedError: access to attribute '_foo' of 'PublicStuff' object is unsafe.46 >>> env.from_string("{{ foo.bar() }}").render(foo=MODULE.PublicStuff())47 u'23'48 49 >>> env.from_string("{{ foo.__class__ }}").render(foo=42)50 u''44-51 >>> env.from_string("{{ foo.func_code }}").render(foo=lambda:None)52 u''53+>>> env.from_string("{{ foo.__class__.__subclasses__() }}").render(foo=42)54+Traceback (most recent call last):55+ ...56+UndefinedError: access to attribute '__class__' of 'int' object is unsafe.57 '''58 59 60 test_restricted = '''61+>>> env = MODULE.SandboxedEnvironment()62 >>> env.from_string("{% for item.attribute in seq %}...{% endfor %}")63 Traceback (most recent call last):64 ...54-TemplateSyntaxError: cannot assign to expression (line 1)65+TemplateSyntaxError: can't assign to 'subscript' (line 1)66 >>> env.from_string("{% for foo, bar.baz in seq %}...{% endfor %}")67 Traceback (most recent call last):68 ...58-TemplateSyntaxError: cannot assign to expression (line 1)69+TemplateSyntaxError: can't assign to 'tuple' (line 1)70 '''60-61-62-def test_nonlocal_set():63- env = Environment()64- env.globals['outer'] = 4265- tmpl = env.from_string(NONLOCALSET)66- assert tmpl.render() == '9'67- assert env.globals['outer'] == 42modified:tests/test_various.py+11 added-62 removed
6 unmodified lines7 :license: BSD, see LICENSE for more details.8 """9 from jinja2.exceptions import TemplateSyntaxError10 11-KEYWORDS = '''\12-{{ with }}13-{{ as }}14-{{ import }}15-{{ from }}16-{{ class }}17-{{ def }}18-{{ try }}19-{{ except }}20-{{ exec }}21-{{ global }}22-{{ assert }}23-{{ break }}24-{{ continue }}25-{{ lambda }}26-{{ return }}27-{{ raise }}28-{{ yield }}29-{{ while }}30-{{ pass }}31-{{ finally }}'''11+12 UNPACKING = '''{% for a, b, c in [[1, 2, 3]] %}{{ a }}|{{ b }}|{{ c }}{% endfor %}'''13 RAW = '''{% raw %}{{ FOO }} and {% BAR %}{% endraw %}'''34-CONST = '''{{ true }}|{{ false }}|{{ none }}|{{ undefined }}|\35-{{ none is defined }}|{{ undefined is defined }}'''36-LOCALSET = '''{% set foo = 0 %}\37-{% for item in [1, 2] %}{% set foo = 1 %}{% endfor %}\14+CONST = '''{{ true }}|{{ false }}|{{ none }}|\15+{{ none is defined }}|{{ missing is defined }}'''16+LOCALSET = '''{% foo = 0 %}\17+{% for item in [1, 2] %}{% foo = 1 %}{% endfor %}\18 {{ foo }}'''39-NONLOCALSET = '''{% set foo = 0 %}\40-{% for item in [1, 2] %}{% set foo = 1! %}{% endfor %}\41-{{ foo }}'''42-CONSTASS1 = '''{% set true = 42 %}'''43-CONSTASS2 = '''{% for undefined in seq %}{% endfor %}'''19+CONSTASS1 = '''{% true = 42 %}'''20+CONSTASS2 = '''{% for none in seq %}{% endfor %}'''21 22 46-def test_keywords(env):47- env.from_string(KEYWORDS)48-49-23 def test_unpacking(env):24 tmpl = env.from_string(UNPACKING)25 assert tmpl.render() == '1|2|3'26 2 unmodified lines29 tmpl = env.from_string(RAW)30 assert tmpl.render() == '{{ FOO }} and {% BAR %}'31 32 60-def test_crazy_raw():61- from jinja2 import Environment62- env = Environment('{', '}', '{', '}')63- tmpl = env.from_string('{raw}{broken foo}{endraw}')64- assert tmpl.render() == '{broken foo}'65-66-67-def test_cache_dict():68- from jinja2.utils import CacheDict69- d = CacheDict(3)33+def test_lru_cache():34+ from jinja2.utils import LRUCache35+ d = LRUCache(3)36 d["a"] = 137 d["b"] = 238 d["c"] = 339 d["a"]1 unmodified line41 assert len(d) == 342 assert 'a' in d and 'c' in d and 'd' in d and 'b' not in d43 44 79-def test_stringfilter(env):80- from jinja2.filters import stringfilter81- f = stringfilter(lambda f, x: f + x)82- assert f('42')(env, None, 23) == '2342'83-84-85-def test_simplefilter(env):86- from jinja2.filters import simplefilter87- f = simplefilter(lambda f, x: f + x)88- assert f(42)(env, None, 23) == 6589-90-45 def test_const(env):46 tmpl = env.from_string(CONST)93- assert tmpl.render() == 'True|False|||True|False'47+ assert tmpl.render() == 'True|False|None|True|False'48 49 50 def test_const_assign(env):51 for tmpl in CONSTASS1, CONSTASS2:7 unmodified lines59 60 def test_localset(env):61 tmpl = env.from_string(LOCALSET)62 assert tmpl.render() == '0'109-110-111-def test_nonlocalset(env):112- tmpl = env.from_string(NONLOCALSET)113- assert tmpl.render() == '1'