Skip to content
Myr

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

15 files+228 added−189 removed

modified:jinja2/__init__.py+1 added-1 removed
59 unmodified lines
60from jinja2.loaders import BaseLoader, FileSystemLoader, PackageLoader, \61 DictLoader62from jinja2.runtime import Undefined, DebugUndefined, StrictUndefined63from jinja2.filters import environmentfilter, contextfilter64from jinja2.utils import Markup, escape64from jinja2.utils import Markup, escape, contextfunction
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 jinja2.tests import TESTS as DEFAULT_TESTS13from jinja2.utils import generate_lorem_ipsum141516DEFAULT_NAMESPACE = {16 'range': xrange17 'range': xrange,18 'lipsum': generate_lorem_ipsum19}
modified:jinja2/ext.py+3 added-2 removed
38 unmodified lines
3940 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 lines
33 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 continue4142 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)4950 if len(strings) == 1:
15 unmodified lines
66 :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 line
76 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 )8283 # 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))9192 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 lines
172 if plural:173 plural = plural.replace('%%', '%')174175 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)180181 if variables:182 variables = nodes.Dict([nodes.Pair(nodes.Const(x, lineno=lineno), y)183 for x, y in variables.items()])
63 unmodified lines
modified:jinja2/lexer.py+6 added-3 removed
36 unmodified lines
3738# set of used keywords39keywords = 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'])4344# bind operators to token types45operators = {
199 unmodified lines
245 ('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]))250251 # 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 lines
319 }320321 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 lines
333 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 lines
modified:jinja2/nodes.py+10 added-3 removed
7 unmodified lines
8 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.1112 :copyright: 2007 by Armin Ronacher.12 :copyright: 2008 by Armin Ronacher.13 :license: BSD, see LICENSE for more details.14"""15import operator16from types import FunctionType17from itertools import chain, izip18from collections import deque19from copy import copy20
21 unmodified lines
42 '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}484950class Impossible(Exception):
398 unmodified lines
449 fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')450451 def as_const(self):452 obj = self.node.as_const()453454 # don't evaluate context functions455 if type(obj) is FunctionType and \456 getattr(obj, 'contextfunction', False):457 raise Impossible()458459 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 lines
486 except:487 raise Impossible()488489 def can_assign(self):483 return True490 return False491492493class Slice(Expr):494 """1:2:3 etc."""
100 unmodified lines
modified:jinja2/optimizer.py+6 added-4 removed
30 unmodified lines
31# 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_various373839def optimize(node, environment, context_hint=None):40 """The context hint can be used to perform an static optimization
143 unmodified lines
184 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 lines
modified:jinja2/parser.py+4 added-4 removed
62 unmodified lines
63 """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 lines
93 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 = None
567 unmodified lines
modified:jinja2/runtime.py+8 added-1 removed
10 unmodified lines
11try:12 from collections import defaultdict13except ImportError:14 defaultdict = None15from types import FunctionType15from jinja2.utils import Markup16from jinja2.utils import Markup, partial17from jinja2.exceptions import UndefinedError181920__all__ = ['LoopContext', 'StaticLoopContext', 'TemplateContext',
13 unmodified lines
34 self.exported = set()35 self.name = name36 self.blocks = dict((k, [v]) for k, v in blocks.iteritems())3738 # 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))4344 # 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 lines
modified:jinja2/utils.py+74 added-2 removed
10 unmodified lines
11import re12import string13from collections import deque14from copy import deepcopy15from functools import update_wrapper15from itertools import imap161718_word_split_re = re.compile(r'(\s+)')
5 unmodified lines
24)25_simple_email_re = re.compile(r'^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$')262728def 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 f343536def 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 lines
114 words[i] = lead + middle + trail115 return u''.join(words)116117118def 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 = []124125 for _ in xrange(n):126 next_capitalized = True127 last_comma = last_fullstop = 0128 word = None129 last = None130 p = []131132 # 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)153154 # 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)161162 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))165166167class 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 lines
233 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 lines
396 """397 if not isinstance(s, unicode):398 s = unicode(s)399 return s400401402# partials403try:404 from functools import partial405except 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 lines
76 delattr(node, field)77 else:78 setattr(node, field, new_node)79 return node8081 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 rv
modified:tests/test_i18n.py+36 added-44 removed
4 unmodified lines
56 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8"""9from jinja2 import Environment, DictLoader9from jinja2 import Environment, DictLoader, contextfunction1011templates = {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 lines
29 }30}313233class SimpleTranslator(object):34 """Yes i know it's only suitable for english and german but35 that's a stupid unittest..."""33@contextfunction34def gettext(context, string):35 language = context.get('LANGUAGE', 'en')36 return languages.get(language, {}).get(string, string)3737 def __init__(self, language):38 self.strings = languages.get(language, {})3840 def gettext(self, string):41 return self.strings.get(string, string)39@contextfunction40def 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)4543 def ngettext(self, s, p, n):44 if n != 1:45 return self.strings.get(p, p)46 return self.strings.get(s, s)4647i18n_env = Environment(48 loader=DictLoader(templates),49 extensions=['jinja2.i18n.TransExtension']50)51i18n_env.globals.update({52 '_': gettext,53 'gettext': gettext,54 'ngettext': ngettext55})5649class I18NEnvironment(Environment):5751 def __init__(self):52 super(I18NEnvironment, self).__init__(loader=DictLoader(templates))5354 def get_translator(self, context):55 return SimpleTranslator(context['LANGUAGE'] or 'en')565758i18n_env = I18NEnvironment()596061def 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'676869def 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)737475def 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)798058def test_trans():59 tmpl = i18n_env.get_template('child.html')60 assert tmpl.render(LANGUAGE='de') == '<title>fehlend</title>pass auf'61
6 unmodified lines
6869def test_trans_stringformatting():70 tmpl = i18n_env.get_template('stringformat.html')71 assert tmpl.render(LANGUAGE='de', user_count=5) == 'Benutzer: 5'727374def 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 lines
56 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8"""99from jinja2 import Environment1012NO_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 %}'''1112PHP_SYNTAX = '''\13<!-- I'm a comment, I'm not interesting -->\14<? for item in seq -?>
11 unmodified lines
26<!-- for item in seq --->27 ${item}28<!--- endfor -->'''2937SMARTY_SYNTAX = '''\38{* I'm a comment, I'm not interesting *}\39{for item in seq-}40 {item}41{-endfor}'''30MAKO_SYNTAX = '''\31% for item in seq:32 ${item}33% endfor'''3435BALANCING = '''{{{'foo':'bar'}.foo}}'''3637STARTCOMMENT = '''{# foo comment
1 unmodified line
39{% macro blub() %}foo{% endmacro %}40{{ blub() }}'''414251def 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 ]606143def test_php_syntax():44 env = Environment('<?', '?>', '<?=', '?>', '<!--', '-->')45 tmpl = env.from_string(PHP_SYNTAX)46 assert tmpl.render(seq=range(5)) == '01234'
10 unmodified lines
57 tmpl = env.from_string(COMMENT_SYNTAX)58 assert tmpl.render(seq=range(5)) == '01234'596080def test_smarty_syntax():81 env = Environment('{', '}', '{', '}', '{*', '*}')82 tmpl = env.from_string(SMARTY_SYNTAX)83 assert tmpl.render(seq=range(5)) == '01234'848561def test_balancing(env):62 tmpl = env.from_string(BALANCING)63 assert tmpl.render() == 'bar'646566def test_start_comment(env):67 tmpl = env.from_string(STARTCOMMENT)68 assert tmpl.render().strip() == 'foo'697071def 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 lines
56 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8"""9from jinja2 import Environment9from jinja2.sandbox import SandboxedEnvironment, unsafe101112NONLOCALSET = '''\13{% for item in range(10) %}14 {%- set outer = item! -%}15{% endfor -%}16{{ outer }}'''12class PrivateStuff(object):1314 def bar(self):15 return 231619class PrivateStuff(object):20 bar = lambda self: 2321 foo = lambda self: 4222 foo.jinja_unsafe_call = True17 @unsafe18 def foo(self):19 return 422021 def __repr__(self):22 return 'PrivateStuff'232425class PublicStuff(object):26 jinja_allowed_attributes = ['bar']26 bar = lambda self: 2328 foo = lambda self: 4227 _foo = lambda self: 422829 def __repr__(self):30 return 'PublicStuff'313233test_unsafe = '''34>>> env = MODULE.SandboxedEnvironment()35>>> env.from_string("{{ foo.foo() }}").render(foo=MODULE.PrivateStuff())33u''36Traceback (most recent call last):37 ...38TypeError: <bound method PrivateStuff.foo of PrivateStuff> is not safely callable39>>> env.from_string("{{ foo.bar() }}").render(foo=MODULE.PrivateStuff())40u'23'4137>>> env.from_string("{{ foo.foo() }}").render(foo=MODULE.PublicStuff())38u''42>>> env.from_string("{{ foo._foo() }}").render(foo=MODULE.PublicStuff())43Traceback (most recent call last):44 ...45UndefinedError: access to attribute '_foo' of 'PublicStuff' object is unsafe.46>>> env.from_string("{{ foo.bar() }}").render(foo=MODULE.PublicStuff())47u'23'4849>>> env.from_string("{{ foo.__class__ }}").render(foo=42)50u''4451>>> env.from_string("{{ foo.func_code }}").render(foo=lambda:None)52u''53>>> env.from_string("{{ foo.__class__.__subclasses__() }}").render(foo=42)54Traceback (most recent call last):55 ...56UndefinedError: access to attribute '__class__' of 'int' object is unsafe.57'''585960test_restricted = '''61>>> env = MODULE.SandboxedEnvironment()62>>> env.from_string("{% for item.attribute in seq %}...{% endfor %}")63Traceback (most recent call last):64 ...54TemplateSyntaxError: cannot assign to expression (line 1)65TemplateSyntaxError: can't assign to 'subscript' (line 1)66>>> env.from_string("{% for foo, bar.baz in seq %}...{% endfor %}")67Traceback (most recent call last):68 ...58TemplateSyntaxError: cannot assign to expression (line 1)69TemplateSyntaxError: can't assign to 'tuple' (line 1)70'''606162def 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'] == 42
modified:tests/test_various.py+11 added-62 removed
6 unmodified lines
7 :license: BSD, see LICENSE for more details.8"""9from jinja2.exceptions import TemplateSyntaxError1011KEYWORDS = '''\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 }}'''1112UNPACKING = '''{% for a, b, c in [[1, 2, 3]] %}{{ a }}|{{ b }}|{{ c }}{% endfor %}'''13RAW = '''{% raw %}{{ FOO }} and {% BAR %}{% endraw %}'''34CONST = '''{{ true }}|{{ false }}|{{ none }}|{{ undefined }}|\35{{ none is defined }}|{{ undefined is defined }}'''36LOCALSET = '''{% set foo = 0 %}\37{% for item in [1, 2] %}{% set foo = 1 %}{% endfor %}\14CONST = '''{{ true }}|{{ false }}|{{ none }}|\15{{ none is defined }}|{{ missing is defined }}'''16LOCALSET = '''{% foo = 0 %}\17{% for item in [1, 2] %}{% foo = 1 %}{% endfor %}\18{{ foo }}'''39NONLOCALSET = '''{% set foo = 0 %}\40{% for item in [1, 2] %}{% set foo = 1! %}{% endfor %}\41{{ foo }}'''42CONSTASS1 = '''{% set true = 42 %}'''43CONSTASS2 = '''{% for undefined in seq %}{% endfor %}'''19CONSTASS1 = '''{% true = 42 %}'''20CONSTASS2 = '''{% for none in seq %}{% endfor %}'''212246def test_keywords(env):47 env.from_string(KEYWORDS)484923def test_unpacking(env):24 tmpl = env.from_string(UNPACKING)25 assert tmpl.render() == '1|2|3'26
2 unmodified lines
29 tmpl = env.from_string(RAW)30 assert tmpl.render() == '{{ FOO }} and {% BAR %}'313260def 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}'656667def test_cache_dict():68 from jinja2.utils import CacheDict69 d = CacheDict(3)33def 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 line
41 assert len(d) == 342 assert 'a' in d and 'c' in d and 'd' in d and 'b' not in d434479def test_stringfilter(env):80 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 jinja2.filters import simplefilter87 f = simplefilter(lambda f, x: f + x)88 assert f(42)(env, None, 23) == 65899045def 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'484950def test_const_assign(env):51 for tmpl in CONSTASS1, CONSTASS2:
7 unmodified lines
5960def test_localset(env):61 tmpl = env.from_string(LOCALSET)62 assert tmpl.render() == '0'109110111def test_nonlocalset(env):112 tmpl = env.from_string(NONLOCALSET)113 assert tmpl.render() == '1'