Skip to content
Myr

remove _compat module

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

authored by David Lord · committed by David Lord · parent b0015c7 · Browse files · 29 files+264 added−766 removed
This commit

State

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

Diff stats

29 files+264 added−766 removed

  • tests:+40 added−162 removed
  • other:+224 added−604 removed

29 files+264 added−766 removed

deleted:src/jinja2/_compat.py-132 removed
1# -*- coding: utf-8 -*-2# flake8: noqa3import marshal4import sys56PY2 = sys.version_info[0] == 27PYPY = hasattr(sys, "pypy_translation_info")8_identity = lambda x: x910if not PY2:11 unichr = chr12 range_type = range13 text_type = str14 string_types = (str,)15 integer_types = (int,)1617 iterkeys = lambda d: iter(d.keys())18 itervalues = lambda d: iter(d.values())19 iteritems = lambda d: iter(d.items())2021 import pickle22 from io import BytesIO, StringIO2324 NativeStringIO = StringIO2526 def reraise(tp, value, tb=None):27 if value.__traceback__ is not tb:28 raise value.with_traceback(tb)29 raise value3031 ifilter = filter32 imap = map33 izip = zip34 intern = sys.intern3536 implements_iterator = _identity37 implements_to_string = _identity38 encode_filename = _identity3940 marshal_dump = marshal.dump41 marshal_load = marshal.load4243else:44 unichr = unichr45 text_type = unicode46 range_type = xrange47 string_types = (str, unicode)48 integer_types = (int, long)4950 iterkeys = lambda d: d.iterkeys()51 itervalues = lambda d: d.itervalues()52 iteritems = lambda d: d.iteritems()5354 import cPickle as pickle55 from cStringIO import StringIO as BytesIO, StringIO5657 NativeStringIO = BytesIO5859 exec("def reraise(tp, value, tb=None):\n raise tp, value, tb")6061 from itertools import imap, izip, ifilter6263 intern = intern6465 def implements_iterator(cls):66 cls.next = cls.__next__67 del cls.__next__68 return cls6970 def implements_to_string(cls):71 cls.__unicode__ = cls.__str__72 cls.__str__ = lambda x: x.__unicode__().encode("utf-8")73 return cls7475 def encode_filename(filename):76 if isinstance(filename, unicode):77 return filename.encode("utf-8")78 return filename7980 def marshal_dump(code, f):81 if isinstance(f, file):82 marshal.dump(code, f)83 else:84 f.write(marshal.dumps(code))8586 def marshal_load(f):87 if isinstance(f, file):88 return marshal.load(f)89 return marshal.loads(f.read())909192def with_metaclass(meta, *bases):93 """Create a base class with a metaclass."""94 # This requires a bit of explanation: the basic idea is to make a95 # dummy metaclass for one level of class instantiation that replaces96 # itself with the actual metaclass.97 class metaclass(type):98 def __new__(cls, name, this_bases, d):99 return meta(name, bases, d)100101 return type.__new__(metaclass, "temporary_class", (), {})102103104try:105 from urllib.parse import quote_from_bytes as url_quote106except ImportError:107 from urllib import quote as url_quote108109110try:111 from collections import abc112except ImportError:113 import collections as abc114115116try:117 from os import fspath118except ImportError:119 try:120 from pathlib import PurePath121 except ImportError:122 PurePath = None123124 def fspath(path):125 if hasattr(path, "__fspath__"):126 return path.__fspath__()127128 # Python 3.5 doesn't have __fspath__ yet, use str.129 if PurePath is not None and isinstance(path, PurePath):130 return str(path)131132 return path
modified:src/jinja2/bccache.py+9 added-13 removed
6 unmodified lines
7are initialized on the first request.8"""9import errno10import fnmatch11import marshal12import os13import pickle14import stat15import sys16import tempfile17from hashlib import sha116from os import listdir17from os import path18from io import BytesIO1919from ._compat import BytesIO20from ._compat import marshal_dump21from ._compat import marshal_load22from ._compat import pickle23from ._compat import text_type20from .utils import open_if_exists2122bc_version = 423# Magic bytes to identify Jinja bytecode cache files. Contains the
38 unmodified lines
62 self.reset()63 return64 # if marshal_load fails then we need to reload65 try:70 self.code = marshal_load(f)66 self.code = marshal.load(f)67 except (EOFError, ValueError, TypeError):68 self.reset()69 return70
2 unmodified lines
73 if self.code is None:74 raise TypeError("can't write empty bucket")75 f.write(bc_magic)76 pickle.dump(self.checksum, f, 2)81 marshal_dump(self.code, f)77 marshal.dump(self.code, f)7879 def bytecode_from_string(self, string):80 """Load bytecode from a string."""81 self.load_bytecode(BytesIO(string))
58 unmodified lines
140 """Returns the unique hash key for this template name."""141 hash = sha1(name.encode("utf-8"))142 if filename is not None:143 filename = "|" + filename148 if isinstance(filename, text_type):144 if isinstance(filename, str):145 filename = filename.encode("utf-8")146 hash.update(filename)147 return hash.hexdigest()148
87 unmodified lines
236237 return actual_dir238239 def _get_cache_filename(self, bucket):244 return path.join(self.directory, self.pattern % bucket.key)240 return os.path.join(self.directory, self.pattern % bucket.key)241242 def load_bytecode(self, bucket):243 f = open_if_exists(self._get_cache_filename(bucket), "rb")244 if f is not None:
14 unmodified lines
259 # write access on the file system and the function does not exist260 # normally.261 from os import remove262267 files = fnmatch.filter(listdir(self.directory), self.pattern % "*")263 files = fnmatch.filter(os.listdir(self.directory), self.pattern % "*")264 for filename in files:265 try:270 remove(path.join(self.directory, filename))266 remove(os.path.join(self.directory, filename))267 except OSError:268 pass269270
76 unmodified lines
modified:src/jinja2/compiler.py+32 added-78 removed
1# -*- coding: utf-8 -*-2"""Compiles nodes from the parser into Python code."""3from collections import namedtuple4from functools import update_wrapper5from io import StringIO6from itertools import chain7from keyword import iskeyword as is_python_keyword89from markupsafe import escape10from markupsafe import Markup1112from . import nodes12from ._compat import imap13from ._compat import iteritems14from ._compat import izip15from ._compat import NativeStringIO16from ._compat import range_type17from ._compat import string_types18from ._compat import text_type13from .exceptions import TemplateAssertionError14from .idtracking import Symbols15from .idtracking import VAR_LOAD_ALIAS16from .idtracking import VAR_LOAD_PARAMETER
14 unmodified lines
31 "in": "in",32 "notin": "not in",33}3441# what method to iterate over items do we want to use for dict iteration42# in generated code? on 2.x let's go with iteritems, on 3.x with items43if hasattr(dict, "iteritems"):44 dict_item_iter = "iteritems"45else:46 dict_item_iter = "items"3548code_features = ["division"]4950# does this python version support generator stops? (PEP 0479)51try:52 exec("from __future__ import generator_stop")53 code_features.append("generator_stop")54except SyntaxError:55 pass5657# does this python version support yield from?58try:59 exec("def f(): yield from x()")60except SyntaxError:61 supports_yield_from = False62else:63 supports_yield_from = True646536def optimizeconst(f):37 def new_func(self, node, frame, **kwargs):38 # Only optimize if the frame is not volatile39 if self.optimized and not frame.eval_ctx.volatile:
22 unmodified lines
62def has_safe_repr(value):63 """Does the node have a safe representation?"""64 if value is None or value is NotImplemented or value is Ellipsis:65 return True96 if type(value) in (bool, int, float, complex, range_type, Markup) + string_types:6667 if type(value) in {bool, int, float, complex, range, str, Markup}:68 return True98 if type(value) in (tuple, list, set, frozenset):99 for item in value:100 if not has_safe_repr(item):101 return False102 return True103 elif type(value) is dict:104 for key, value in iteritems(value):105 if not has_safe_repr(key):106 return False107 if not has_safe_repr(value):108 return False109 return True6970 if type(value) in {tuple, list, set, frozenset}:71 return all(has_safe_repr(v) for v in value)7273 if type(value) is dict:74 return all(has_safe_repr(k) and has_safe_repr(v) for k, v in value.items())7576 return False777879def find_undeclared(nodes, names):
134 unmodified lines
214 def __init__(215 self, environment, name, filename, stream=None, defer_init=False, optimized=True216 ):217 if stream is None:252 stream = NativeStringIO()218 stream = StringIO()219 self.environment = environment220 self.name = name221 self.filename = filename222 self.stream = stream
174 unmodified lines
397 for kwarg in node.kwargs:398 self.write(", ")399 self.visit(kwarg, frame)400 if extra_kwargs is not None:435 for key, value in iteritems(extra_kwargs):401 for key, value in extra_kwargs.items():402 self.write(", %s=%s" % (key, value))403 if node.dyn_args:404 self.write(", *")405 self.visit(node.dyn_args, frame)
7 unmodified lines
413 self.write("%r: " % kwarg.key)414 self.visit(kwarg.value, frame)415 self.write(", ")416 if extra_kwargs is not None:451 for key, value in iteritems(extra_kwargs):417 for key, value in extra_kwargs.items():418 self.write("%r: %s, " % (key, value))419 if node.dyn_kwargs is not None:420 self.write("}, **")421 self.visit(node.dyn_kwargs, frame)
20 unmodified lines
442 )443444 def enter_frame(self, frame):445 undefs = []480 for target, (action, param) in iteritems(frame.symbols.loads):446 for target, (action, param) in frame.symbols.loads.items():447 if action == VAR_LOAD_PARAMETER:448 pass449 elif action == VAR_LOAD_RESOLVE:450 self.writeline("%s = %s(%r)" % (target, self.get_resolve_func(), param))
8 unmodified lines
459460 def leave_frame(self, frame, with_python_scope=False):461 if not with_python_scope:462 undefs = []497 for target, _ in iteritems(frame.symbols.loads):463 for target in frame.symbols.loads:464 undefs.append(target)465 if undefs:466 self.writeline("%s = missing" % " = ".join(undefs))467
109 unmodified lines
577578 def dump_local_context(self, frame):579 return "{%s}" % ", ".join(580 "%r: %s" % (name, target)615 for name, target in iteritems(frame.symbols.dump_stores())581 for name, target in frame.symbols.dump_stores().items()582 )583584 def write_commons(self):585 """Writes a common preamble that is used by root and block functions.
83 unmodified lines
669 self.writeline("context.exported_vars.add(%r)" % public_names[0])670 else:671 self.writeline(672 "context.exported_vars.update((%s))"707 % ", ".join(imap(repr, public_names))673 % ", ".join(map(repr, public_names))674 )675676 # -- Statement Visitors677
2 unmodified lines
680 eval_ctx = EvalContext(self.environment, self.name)681682 from .runtime import exported683718 self.writeline("from __future__ import %s" % ", ".join(code_features))684 self.writeline("from jinja2.runtime import " + ", ".join(exported))685686 if self.environment.is_async:687 self.writeline(
57 unmodified lines
745 if not self.has_known_extends:746 self.indent()747 self.writeline("if parent_template is not None:")748 self.indent()784 if supports_yield_from and not self.environment.is_async:749 if not self.environment.is_async:750 self.writeline("yield from parent_template.root_render_func(context)")751 else:752 self.writeline(753 "%sfor event in parent_template."
5 unmodified lines
759 self.outdent()760 self.outdent(1 + (not self.has_known_extends))761762 # at this point we now have the blocks collected and can visit them too.798 for name, block in iteritems(self.blocks):763 for name, block in self.blocks.items():764 self.writeline(765 "%s(context, missing=missing%s):"766 % (self.func("block_" + name), envenv),767 block,
47 unmodified lines
815 context = self.derive_context(frame)816 else:817 context = self.get_context_ref()818854 if (855 supports_yield_from856 and not self.environment.is_async857 and frame.buffer is None858 ):819 if not self.environment.is_async and frame.buffer is None:820 self.writeline(821 "yield from context.blocks[%r][0](%s)" % (node.name, context), node822 )823 else:
36 unmodified lines
860861 self.writeline("parent_template = environment.get_template(", node)862 self.visit(node.template, frame)863 self.write(", %r)" % self.name)903 self.writeline(904 "for name, parent_block in parent_template.blocks.%s():" % dict_item_iter905 )864 self.writeline("for name, parent_block in parent_template.blocks.items():")865 self.indent()866 self.writeline("context.blocks.setdefault(name, []).append(parent_block)")867 self.outdent()868
13 unmodified lines
882 self.indent()883884 func_name = "get_or_select_template"885 if isinstance(node.template, nodes.Const):927 if isinstance(node.template.value, string_types):886 if isinstance(node.template.value, str):887 func_name = "get_template"888 elif isinstance(node.template.value, (tuple, list)):889 func_name = "select_template"890 elif isinstance(node.template, (nodes.Tuple, nodes.List)):
25 unmodified lines
916 "template._get_default_module_async())"917 "._body_stream:"918 )919 else:961 if supports_yield_from:962 self.writeline("yield from template._get_default_module()._body_stream")963 skip_event_yield = True920 self.writeline("yield from template._get_default_module()._body_stream")921 skip_event_yield = True964 else:965 self.writeline(966 "for event in template._get_default_module()._body_stream:"967 )922923 if not skip_event_yield:924 self.indent()925 self.simple_write("event", frame)
98 unmodified lines
1024 self.writeline("context.exported_vars.discard(%r)" % discarded_names[0])1025 else:1026 self.writeline(1027 "context.exported_vars.difference_"1074 "update((%s))" % ", ".join(imap(repr, discarded_names))1028 "update((%s))" % ", ".join(map(repr, discarded_names))1029 )10301031 def visit_For(self, node, frame):1032 loop_frame = frame.inner()
182 unmodified lines
1215 def visit_With(self, node, frame):1216 with_frame = frame.inner()1217 with_frame.symbols.analyze_node(node)1218 self.enter_frame(with_frame)1265 for target, expr in izip(node.targets, node.values):1219 for target, expr in zip(node.targets, node.values):1220 self.newline()1221 self.visit(target, with_frame)1222 self.write(" = ")1223 self.visit(expr, frame)
7 unmodified lines
1231 _FinalizeInfo = namedtuple("_FinalizeInfo", ("const", "src"))1232 #: The default finalize function if the environment isn't configured1233 #: with one. Or if the environment has one, this is called on that1234 #: function's output for constants.1281 _default_finalize = text_type1235 _default_finalize = str1236 _finalize = None12371238 def _make_finalize(self):1239 """Build the finalize function to be used on constants and at
57 unmodified lines
1297 const = escape(const)12981299 # Template data doesn't go through finalize.1300 if isinstance(node, nodes.TemplateData):1347 return text_type(const)1301 return str(const)13021303 return finalize.const(const)13041305 def _output_child_pre(self, node, frame, finalize):1306 """Output extra source code before visiting a child of an1307 ``Output`` node.1308 """1309 if frame.eval_ctx.volatile:1356 self.write("(escape if context.eval_ctx.autoescape else to_string)(")1310 self.write("(escape if context.eval_ctx.autoescape else str)(")1311 elif frame.eval_ctx.autoescape:1312 self.write("escape(")1313 else:1360 self.write("to_string(")1314 self.write("str(")13151316 if finalize.src is not None:1317 self.write(finalize.src)1318
249 unmodified lines
15681569 @optimizeconst1570 def visit_Concat(self, node, frame):1571 if frame.eval_ctx.volatile:1618 func_name = "(context.eval_ctx.volatile and markup_join or unicode_join)"1572 func_name = "(context.eval_ctx.volatile and markup_join or str_join)"1573 elif frame.eval_ctx.autoescape:1574 func_name = "markup_join"1575 else:1622 func_name = "unicode_join"1576 func_name = "str_join"1577 self.write("%s((" % func_name)1578 for arg in node.nodes:1579 self.visit(arg, frame)1580 self.write(", ")
217 unmodified lines
modified:src/jinja2/debug.py+5 added-7 removed
1import platform2import sys3from types import CodeType45from . import TemplateSyntaxError5from ._compat import PYPY6from .utils import internal_code7from .utils import missing89
3 unmodified lines
13 came from the template source.1415 This must be called within an ``except`` block.1617 :param exc_info: A :meth:`sys.exc_info` tuple. If not provided,18 the current ``exc_info`` is used.17 :param source: For ``TemplateSyntaxError``, the original source if18 known.21 :return: A :meth:`sys.exc_info` tuple that can be re-raised.19 :return: The original exception with the rewritten traceback.20 """23 exc_type, exc_value, tb = sys.exc_info()21 _, exc_value, tb = sys.exc_info()2223 if isinstance(exc_value, TemplateSyntaxError) and not exc_value.translated:24 exc_value.translated = True25 exc_value.source = source
41 unmodified lines
67 # Assign tb_next in reverse to avoid circular references.68 for tb in reversed(stack):69 tb_next = tb_set_next(tb, tb_next)7073 return exc_type, exc_value, tb_next71 return exc_value.with_traceback(tb_next)727374def fake_traceback(exc_value, tb, filename, lineno):75 """Produce a new traceback object that looks like it came from the
136 unmodified lines
212 tb.tb_next = tb_next213 return tb214215218elif PYPY:216elif platform.python_implementation() == "PyPy":217 # PyPy might have special support, and won't work with ctypes.218 try:219 import tputil220 except ImportError:
49 unmodified lines
modified:src/jinja2/defaults.py+1 added-2 removed
1# -*- coding: utf-8 -*-2from ._compat import range_type2from .filters import FILTERS as DEFAULT_FILTERS # noqa: F4013from .tests import TESTS as DEFAULT_TESTS # noqa: F4014from .utils import Cycler5from .utils import generate_lorem_ipsum
16 unmodified lines
2223# default filters, tests and namespace2425DEFAULT_NAMESPACE = {27 "range": range_type,26 "range": range,27 "dict": dict,28 "lipsum": generate_lorem_ipsum,29 "cycler": Cycler,30 "joiner": Joiner,
13 unmodified lines
modified:src/jinja2/environment.py+13 added-24 removed
9 unmodified lines
1011from markupsafe import Markup1213from . import nodes14from ._compat import encode_filename15from ._compat import implements_iterator16from ._compat import implements_to_string17from ._compat import iteritems18from ._compat import reraise19from ._compat import string_types20from ._compat import text_type14from .compiler import CodeGenerator15from .compiler import generate16from .defaults import BLOCK_END_STRING17from .defaults import BLOCK_START_STRING
76 unmodified lines
94 Returns a dict of instantiated environments.95 """96 result = {}97 for extension in extensions:105 if isinstance(extension, string_types):98 if isinstance(extension, str):99 extension = import_string(extension)100 result[extension.identifier] = extension(environment)101 return result102
265 unmodified lines
368 """Add the items to the instance of the environment if they do not exist369 yet. This is used by :ref:`extensions <writing-extensions>` to register370 callbacks and configuration values without breaking inheritance.371 """379 for key, value in iteritems(attributes):372 for key, value in attributes.items():373 if not hasattr(self, key):374 setattr(self, key, value)375376 def overlay(
36 unmodified lines
413 rv.__dict__.update(self.__dict__)414 rv.overlayed = True415 rv.linked_to = self416424 for key, value in iteritems(args):417 for key, value in args.items():418 if value is not missing:419 setattr(rv, key, value)420421 if cache_size is not missing:
1 unmodified line
423 else:424 rv.cache = copy_cache(self.cache)425426 rv.extensions = {}434 for key, value in iteritems(self.extensions):427 for key, value in self.extensions.items():428 rv.extensions[key] = value.bind(rv)429 if extensions is not missing:430 rv.extensions.update(load_extensions(rv, extensions))431
9 unmodified lines
441 """Get an item or attribute of an object but prefer the item."""442 try:443 return obj[argument]444 except (AttributeError, TypeError, LookupError):452 if isinstance(argument, string_types):445 if isinstance(argument, str):446 try:447 attr = str(argument)448 except Exception:449 pass
76 unmodified lines
526 self.handle_exception(source=source)527528 def _parse(self, source, name, filename):529 """Internal parsing function used by `parse` and `compile`."""537 return Parser(self, source, name, encode_filename(filename)).parse()530 return Parser(self, source, name, filename).parse()531532 def lex(self, source, name=None, filename=None):533 """Lex the given sourcecode and return a generator that yields534 tokens as tuples in the form ``(lineno, token_type, value)``.
3 unmodified lines
538 This does not perform preprocessing. If you want the preprocessing539 of the extensions to be applied you have to filter source through540 the :meth:`preprocess` method.541 """549 source = text_type(source)542 source = str(source)543 try:544 return self.lexer.tokeniter(source, name, filename)545 except TemplateSyntaxError:546 self.handle_exception(source=source)
5 unmodified lines
552 """553 return reduce(554 lambda s, e: e.preprocess(s, name, filename),555 self.iter_extensions(),563 text_type(source),556 str(source),557 )558559 def _tokenize(self, source, name, filename=None, state=None):560 """Called by the parser to do the preprocessing and filtering
52 unmodified lines
613 `defer_init` parameter added.614 """615 source_hint = None616 try:624 if isinstance(source, string_types):617 if isinstance(source, str):618 source_hint = source619 source = self._parse(source, name, filename)620 source = self._generate(source, name, filename, defer_init=defer_init)621 if raw:622 return source623 if filename is None:624 filename = "<template>"632 else:633 filename = encode_filename(filename)625 return self._compile(source, filename)626 except TemplateSyntaxError:627 self.handle_exception(source=source_hint)628
79 unmodified lines
708 info = ZipInfo(filename)709 info.external_attr = 0o755 << 16710 zip_file.writestr(info, data)711 else:721 if isinstance(data, text_type):712 if isinstance(data, str):713 data = data.encode("utf8")714715 with open(os.path.join(target, filename), "wb") as f:716 f.write(data)
68 unmodified lines
785 rewritten exceptions or return a rendered traceback for the template.786 """787 from .debug import rewrite_traceback_stack788798 reraise(*rewrite_traceback_stack(source=source))789 raise rewrite_traceback_stack(source=source)790791 def join_path(self, template, parent):792 """Join a template with the parent. By default all the lookups are793 relative to the loader root so this method returns the `template`
88 unmodified lines
882 :meth:`get_template`.883884 .. versionadded:: 2.3885 """895 if isinstance(template_name_or_list, (string_types, Undefined)):886 if isinstance(template_name_or_list, (str, Undefined)):887 return self.get_template(template_name_or_list, parent, globals)888 elif isinstance(template_name_or_list, Template):889 return template_name_or_list890 return self.select_template(template_name_or_list, parent, globals)
284 unmodified lines
1175 name = repr(self.name)1176 return "<%s %s>" % (self.__class__.__name__, name)117711781188@implements_to_string1179class TemplateModule(object):1180 """Represents an imported template. All the exported names of the1181 template are available as attributes on this object. Additionally1182 converting it into a string renders the contents.
45 unmodified lines
1228 rv = None1229 return rv123012311242@implements_iterator1232class TemplateStream(object):1233 """A template stream works pretty much like an ordinary python generator1234 but it can buffer multiple items to reduce the number of total iterations.1235 Per default the output is unbuffered which means that for every unbuffered
17 unmodified lines
12531254 Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')1255 """1256 close = False1268 if isinstance(fp, string_types):1257 if isinstance(fp, str):1258 if encoding is None:1259 encoding = "utf-8"1260 fp = open(fp, "wb")1261 close = True
56 unmodified lines
modified:src/jinja2/exceptions.py+7 added-37 removed
1# -*- coding: utf-8 -*-2from ._compat import imap3from ._compat import implements_to_string4from ._compat import PY25from ._compat import text_type671class TemplateError(Exception):2 """Baseclass for all template errors."""311 if PY2:4 def __init__(self, message=None):5 super().__init__(message)613 def __init__(self, message=None):14 if message is not None:15 message = text_type(message).encode("utf-8")16 Exception.__init__(self, message)7 @property8 def message(self):9 if self.args:10 return self.args[0]1118 @property19 def message(self):20 if self.args:21 message = self.args[0]22 if message is not None:23 return message.decode("utf-8", "replace")1225 def __unicode__(self):26 return self.message or u""2728 else:2930 def __init__(self, message=None):31 Exception.__init__(self, message)3233 @property34 def message(self):35 if self.args:36 message = self.args[0]37 if message is not None:38 return message394041@implements_to_string13class TemplateNotFound(IOError, LookupError, TemplateError):14 """Raised if a template does not exist.1516 .. versionchanged:: 2.11
48 unmodified lines
65 else:66 parts.append(name)6768 message = u"none of the templates given were found: " + u", ".join(98 imap(text_type, parts)69 map(str, parts)70 )71 TemplateNotFound.__init__(self, names and names[-1] or None, message)72 self.templates = list(names)7374104@implements_to_string75class TemplateSyntaxError(TemplateError):76 """Raised to tell the user that there is a problem with the template."""7778 def __init__(self, message, lineno, name=None, filename=None):
69 unmodified lines
modified:src/jinja2/ext.py+4 added-7 removed
5 unmodified lines
67from markupsafe import Markup89from . import nodes10from ._compat import iteritems11from ._compat import string_types12from ._compat import with_metaclass10from .defaults import BLOCK_END_STRING11from .defaults import BLOCK_START_STRING12from .defaults import COMMENT_END_STRING13from .defaults import COMMENT_START_STRING
29 unmodified lines
43 rv.identifier = rv.__module__ + "." + rv.__name__44 return rv454650class Extension(with_metaclass(ExtensionRegistry, object)):47class Extension(metaclass=ExtensionRegistry):48 """Extensions can be used to add extra functionality to the Jinja template49 system at the parser level. Custom extensions are bound to an environment50 but may not store environment specific data on `self`. The reason for51 this is that an extension can be bound to another environment (for
166 unmodified lines
218 for key in "gettext", "ngettext":219 self.environment.globals.pop(key, None)220221 def _extract(self, source, gettext_functions=GETTEXT_FUNCTIONS):225 if isinstance(source, string_types):222 if isinstance(source, str):223 source = self.environment.parse(source)224 return extract_from_ast(source, gettext_functions)225226 def parse(self, parser):
178 unmodified lines
405 # in case newstyle gettext is used, the method is powerful406 # enough to handle the variable expansion and autoescape407 # handling itself408 if self.environment.newstyle_gettext:412 for key, value in iteritems(variables):409 for key, value in variables.items():410 # the function adds that later anyways in case num was411 # called num, so just skip it.412 if num_called_num and key == "num":413 continue
136 unmodified lines
550 continue551552 strings = []553 for arg in node.args:557 if isinstance(arg, nodes.Const) and isinstance(arg.value, string_types):554 if isinstance(arg, nodes.Const) and isinstance(arg.value, str):555 strings.append(arg.value)556 else:557 strings.append(None)558
143 unmodified lines
modified:src/jinja2/filters.py+35 added-39 removed
1 unmodified line
2"""Built-in template filters used with the ``|`` operator."""3import math4import random5import re6from collections import abc7from collections import namedtuple8from itertools import chain9from itertools import groupby1011from markupsafe import escape12from markupsafe import Markup12from markupsafe import soft_unicode13from markupsafe import soft_str1414from ._compat import abc15from ._compat import imap16from ._compat import iteritems17from ._compat import string_types18from ._compat import text_type15from .exceptions import FilterArgumentError16from .runtime import Undefined17from .utils import htmlsafe_json_dumps18from .utils import pformat23from .utils import unicode_urlencode19from .utils import url_quote20from .utils import urlize2126_word_re = re.compile(r"\w+", re.UNICODE)27_word_beginning_split_re = re.compile(r"([-\s\(\{\[\<]+)", re.UNICODE)22_word_re = re.compile(r"\w+")23_word_beginning_split_re = re.compile(r"([-\s({\[<]+)")242526def contextfilter(f):27 """Decorator for marking context dependent filters. The current
24 unmodified lines
5253def ignore_case(value):54 """For use as a postprocessor for :func:`make_attrgetter`. Converts strings55 to lowercase and returns other types as-is."""60 return value.lower() if isinstance(value, string_types) else value56 return value.lower() if isinstance(value, str) else value575859def make_attrgetter(environment, attribute, postprocess=None, default=None):60 """Returns a callable that looks up the given attribute from a
29 unmodified lines
9091 Examples of attribute: "attr1,attr2", "attr1.inner1.0,attr2.inner2.0", etc.92 """93 attribute_parts = (98 attribute.split(",") if isinstance(attribute, string_types) else [attribute]94 attribute.split(",") if isinstance(attribute, str) else [attribute]95 )96 attribute = [97 _prepare_attribute_parts(attribute_part) for attribute_part in attribute_parts98 ]
16 unmodified lines
115116def _prepare_attribute_parts(attr):117 if attr is None:118 return []123 elif isinstance(attr, string_types):119 elif isinstance(attr, str):120 return [int(x) if x.isdigit() else x for x in attr.split(".")]121 else:122 return [attr]123
1 unmodified line
125def do_forceescape(value):126 """Enforce HTML escaping. This will probably double escape variables."""127 if hasattr(value, "__html__"):128 value = value.__html__()133 return escape(text_type(value))129 return escape(str(value))130131132def do_urlencode(value):133 """Quote data for use in a URL path or query using UTF-8.
10 unmodified lines
144 ``|replace("/", "%2F")`` filter.145146 .. versionadded:: 2.7147 """152 if isinstance(value, string_types) or not isinstance(value, abc.Iterable):153 return unicode_urlencode(value)148 if isinstance(value, str) or not isinstance(value, abc.Iterable):149 return url_quote(value)150151 if isinstance(value, dict):156 items = iteritems(value)152 items = value.items()153 else:154 items = iter(value)155156 return u"&".join(161 "%s=%s" % (unicode_urlencode(k, for_qs=True), unicode_urlencode(v, for_qs=True))157 "%s=%s" % (url_quote(k, for_qs=True), url_quote(v, for_qs=True))158 for k, v in items159 )160161
15 unmodified lines
177 """178 if count is None:179 count = -1180 if not eval_ctx.autoescape:185 return text_type(s).replace(text_type(old), text_type(new), count)181 return str(s).replace(str(old), str(new), count)182 if (183 hasattr(old, "__html__")184 or hasattr(new, "__html__")185 and not hasattr(s, "__html__")186 ):187 s = escape(s)188 else:193 s = soft_unicode(s)194 return s.replace(soft_unicode(old), soft_unicode(new), count)189 s = soft_str(s)190 return s.replace(soft_str(old), soft_str(new), count)191192193def do_upper(s):194 """Convert a value to uppercase."""199 return soft_unicode(s).upper()195 return soft_str(s).upper()196197198def do_lower(s):199 """Convert a value to lowercase."""204 return soft_unicode(s).lower()200 return soft_str(s).lower()201202203@evalcontextfilter204def do_xmlattr(_eval_ctx, d, autospace=True):
20 unmodified lines
225 if the filter returned something unless the second parameter is false.226 """227 rv = u" ".join(228 u'%s="%s"' % (escape(key), escape(value))233 for key, value in iteritems(d)229 for key, value in d.items()230 if value is not None and not isinstance(value, Undefined)231 )232 if autospace and rv:233 rv = u" " + rv
5 unmodified lines
239def do_capitalize(s):240 """Capitalize a value. The first character will be uppercase, all others241 lowercase.242 """247 return soft_unicode(s).capitalize()243 return soft_str(s).capitalize()244245246def do_title(s):247 """Return a titlecased version of the value. I.e. words will start with
1 unmodified line
249 """250 return "".join(251 [252 item[0].upper() + item[1:].lower()257 for item in _word_beginning_split_re.split(soft_unicode(s))253 for item in _word_beginning_split_re.split(soft_str(s))254 if item255 ]256 )257
208 unmodified lines
466 .. versionadded:: 2.6467 The `attribute` parameter was added.468 """469 if attribute is not None:474 value = imap(make_attrgetter(eval_ctx.environment, attribute), value)470 value = map(make_attrgetter(eval_ctx.environment, attribute), value)471472 # no automatic escaping? joining is a lot easier then473 if not eval_ctx.autoescape:478 return text_type(d).join(imap(text_type, value))474 return str(d).join(map(str, value))475476 # if the delimiter doesn't have an html representation we check477 # if any of the items has. If yes we do a coercion to Markup478 if not hasattr(d, "__html__"):
2 unmodified lines
481 for idx, item in enumerate(value):482 if hasattr(item, "__html__"):483 do_escape = True484 else:489 value[idx] = text_type(item)485 value[idx] = str(item)486 if do_escape:487 d = escape(d)488 else:493 d = text_type(d)489 d = str(d)490 return d.join(value)491492 # no html involved, to normal joining497 return soft_unicode(d).join(imap(soft_unicode, value))493 return soft_str(d).join(map(soft_str, value))494495496def do_center(value, width=80):497 """Centers the value in a field of a given width."""502 return text_type(value).center(width)498 return str(value).center(width)499500501@environmentfilter502def do_first(environment, seq):
256 unmodified lines
759 0b, 0o and 0x for bases 2, 8 and 16 respectively.760 The base is ignored for decimal numbers and non-string values.761 """762 try:767 if isinstance(value, string_types):763 if isinstance(value, str):764 return int(value, base)765 return int(value)766 except (TypeError, ValueError):767 # this quirk is necessary so that "42.23"|int gives 42.
37 unmodified lines
805 if args and kwargs:806 raise FilterArgumentError(807 "can't handle positional and keyword arguments at the same time"808 )813 return soft_unicode(value) % (kwargs or args)809 return soft_str(value) % (kwargs or args)810811812def do_trim(value, chars=None):813 """Strip leading and trailing characters, by default whitespace."""818 return soft_unicode(value).strip(chars)814 return soft_str(value).strip(chars)815816817def do_striptags(value):818 """Strip SGML/XML tags and replace adjacent whitespace by one space."""819 if hasattr(value, "__html__"):820 value = value.__html__()825 return Markup(text_type(value)).striptags()821 return Markup(str(value)).striptags()822823824def do_slice(value, slices, fill_with=None):825 """Slice an iterator and return a list of lists containing
164 unmodified lines
990 The `attribute` parameter was added to allow suming up over991 attributes. Also the `start` parameter was moved on to the right.992 """993 if attribute is not None:998 iterable = imap(make_attrgetter(environment, attribute), iterable)994 iterable = map(make_attrgetter(environment, attribute), iterable)995 return sum(iterable, start)996997998def do_list(value):
11 unmodified lines
101010111012def do_mark_unsafe(value):1013 """Mark a value as unsafe. This is the reverse operation for :func:`safe`."""1018 return text_type(value)1014 return str(value)101510161017def do_reverse(value):1018 """Reverse the object or return an iterator that iterates over it the other1019 way round.1020 """1025 if isinstance(value, string_types):1021 if isinstance(value, str):1022 return value[::-1]1023 try:1024 return reversed(value)1025 except TypeError:
324 unmodified lines
1350 "select": do_select,1351 "selectattr": do_selectattr,1352 "slice": do_slice,1353 "sort": do_sort,1358 "string": soft_unicode,1354 "string": soft_str,1355 "striptags": do_striptags,1356 "sum": do_sum,1357 "title": do_title,1358 "trim": do_trim,
10 unmodified lines
modified:src/jinja2/idtracking.py+2 added-3 removed
1from ._compat import iteritems1from .visitor import NodeVisitor23VAR_LOAD_PARAMETER = "param"4VAR_LOAD_RESOLVE = "resolve"
107 unmodified lines
112 self.refs.update(sym.refs)113 self.loads.update(sym.loads)114 self.stores.update(sym.stores)115117 for name, branch_count in iteritems(stores):116 for name, branch_count in stores.items():117 if branch_count == len(branch_symbols):118 continue119 target = self.find_ref(name)120 assert target is not None, "should not happen"
18 unmodified lines
139 def dump_param_targets(self):140 rv = set()141 node = self142 while node is not None:144 for target, (instr, _) in iteritems(self.loads):143 for target, (instr, _) in self.loads.items():144 if instr == VAR_LOAD_PARAMETER:145 rv.add(target)146 node = node.parent147 return rv
142 unmodified lines
modified:src/jinja2/lexer.py+5 added-11 removed
6 unmodified lines
7import re8from ast import literal_eval9from collections import deque10from operator import itemgetter11from sys import intern1212from ._compat import implements_iterator13from ._compat import intern14from ._compat import iteritems15from ._compat import text_type13from .exceptions import TemplateSyntaxError14from .utils import LRUCache1516# cache for the lexers. Exists in order to be able to have multiple17# environments with the same lexer18_lexer_cache = LRUCache(50)1920# static regular expressions24whitespace_re = re.compile(r"\s+", re.U)21whitespace_re = re.compile(r"\s+")22newline_re = re.compile(r"(\r\n|\r|\n)")23string_re = re.compile(24 r"('([^'\\]*(?:\\.[^'\\]*)*)'" r'|"([^"\\]*(?:\\.[^"\\]*)*)")', re.S25)
106 unmodified lines
132 ",": TOKEN_COMMA,133 ";": TOKEN_SEMICOLON,134}135139reverse_operators = dict([(v, k) for k, v in iteritems(operators)])136reverse_operators = dict([(v, k) for k, v in operators.items()])137assert len(operators) == len(reverse_operators), "operators dropped"138operator_re = re.compile(139 "(%s)" % "|".join(re.escape(x) for x in sorted(operators, key=lambda x: -len(x)))140)
151 unmodified lines
292 def __repr__(self):293 return "Token(%r, %r, %r)" % (self.lineno, self.type, self.value)294295299@implements_iterator296class TokenStreamIterator(object):297 """The iterator for tokenstreams. Iterate over the stream298 until the eof token is reached.299 """
12 unmodified lines
312 next(self.stream)313 return token314315320@implements_iterator316class TokenStream(object):317 """A token stream is an iterable that yields :class:`Token`\\s. The318 parser however does not iterate over it but calls :meth:`next` to go319 one token ahead. The current active token is stored as :attr:`current`.
339 unmodified lines
659 def tokeniter(self, source, name, filename=None, state=None):660 """This method tokenizes the text and returns the tokens in a661 generator. Use this method if you just want to tokenize a template.662 """668 source = text_type(source)663 lines = source.splitlines()664 if self.keep_trailing_newline and source:665 for newline in ("\r\n", "\r", "\n"):666 if source.endswith(newline):
70 unmodified lines
737 # bygroup is a bit more complex, in that case we738 # yield for the current token the first named739 # group that matched740 elif token == "#bygroup":747 for key, value in iteritems(m.groupdict()):741 for key, value in m.groupdict().items():742 if value is not None:743 yield lineno, key, value744 lineno += value.count("\n")745 break
51 unmodified lines
797 if new_state == "#pop":798 stack.pop()799 # resolve the new state by group checking800 elif new_state == "#bygroup":807 for key, value in iteritems(m.groupdict()):801 for key, value in m.groupdict().items():802 if value is not None:803 stack.append(key)804 break805 else:
32 unmodified lines
modified:src/jinja2/loaders.py+13 added-22 removed
4 unmodified lines
5import os6import pkgutil7import sys8import weakref9from collections import abc10from hashlib import sha111from importlib import import_module11from os import path12from types import ModuleType1314from ._compat import abc15from ._compat import fspath16from ._compat import iteritems17from ._compat import string_types14from .exceptions import TemplateNotFound15from .utils import internalcode16from .utils import open_if_exists17
4 unmodified lines
22 """23 pieces = []24 for piece in template.split("/"):25 if (30 path.sep in piece31 or (path.altsep and path.altsep in piece)32 or piece == path.pardir26 os.path.sep in piece27 or (os.path.altsep and os.path.altsep in piece)28 or piece == os.path.pardir29 ):30 raise TemplateNotFound(template)31 elif piece and piece != ".":32 pieces.append(piece)
125 unmodified lines
158 The ``followlinks`` parameter was added.159 """160161 def __init__(self, searchpath, encoding="utf-8", followlinks=False):166 if not isinstance(searchpath, abc.Iterable) or isinstance(167 searchpath, string_types168 ):162 if not isinstance(searchpath, abc.Iterable) or isinstance(searchpath, str):163 searchpath = [searchpath]164171 # In Python 3.5, os.path.join doesn't support Path. This can be172 # simplified to list(searchpath) when Python 3.5 is dropped.173 self.searchpath = [fspath(p) for p in searchpath]174165 self.searchpath = list(searchpath)166 self.encoding = encoding167 self.followlinks = followlinks168169 def get_source(self, environment, template):170 pieces = split_template_path(template)171 for searchpath in self.searchpath:181 filename = path.join(searchpath, *pieces)172 filename = os.path.join(searchpath, *pieces)173 f = open_if_exists(filename)174 if f is None:175 continue176 try:177 contents = f.read().decode(self.encoding)178 finally:179 f.close()180190 mtime = path.getmtime(filename)181 mtime = os.path.getmtime(filename)182183 def uptodate():184 try:194 return path.getmtime(filename) == mtime185 return os.path.getmtime(filename) == mtime186 except OSError:187 return False188189 return contents, filename, uptodate
203 unmodified lines
393 def get_source(self, environment, template):394 rv = self.load_func(template)395 if rv is None:396 raise TemplateNotFound(template)406 elif isinstance(rv, string_types):397 elif isinstance(rv, str):398 return rv, None, None399 return rv400401
44 unmodified lines
446 raise TemplateNotFound(name)447448 def list_templates(self):449 result = []459 for prefix, loader in iteritems(self.mapping):450 for prefix, loader in self.mapping.items():451 for template in loader.list_templates():452 result.append(prefix + self.delimiter + template)453 return result454
64 unmodified lines
519 # create a fake module that looks for the templates in the520 # path given.521 mod = _TemplateModule(package_name)522532 if not isinstance(path, abc.Iterable) or isinstance(path, string_types):523 if not isinstance(path, abc.Iterable) or isinstance(path, str):524 path = [path]525535 mod.__path__ = [fspath(p) for p in path]526 mod.__path__ = [os.fspath(p) for p in path]527528 sys.modules[package_name] = weakref.proxy(529 mod, lambda x: sys.modules.pop(package_name, None)530 )
33 unmodified lines
modified:src/jinja2/meta.py+5 added-7 removed
1 unmodified line
2"""Functions that expose information about templates that might be3interesting for introspection.4"""5from . import nodes6from ._compat import iteritems7from ._compat import string_types6from .compiler import CodeGenerator789class TrackingCodeGenerator(CodeGenerator):
8 unmodified lines
1819 def enter_frame(self, frame):20 """Remember all undeclared identifiers."""21 CodeGenerator.enter_frame(self, frame)24 for _, (action, param) in iteritems(frame.symbols.loads):22 for _, (action, param) in frame.symbols.loads.items():23 if action == "resolve" and param not in self.environment.globals:24 self.undeclared_identifiers.add(param)2526
5 unmodified lines
3233 >>> from jinja2 import Environment, meta34 >>> env = Environment()35 >>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}')38 >>> meta.find_undeclared_variables(ast) == set(['bar'])36 >>> meta.find_undeclared_variables(ast) == {'bar'}37 True3839 .. admonition:: Implementation40
31 unmodified lines
72 for template_name in node.template.items:73 # something const, only yield the strings and ignore74 # non-string consts that really just make no sense75 if isinstance(template_name, nodes.Const):78 if isinstance(template_name.value, string_types):76 if isinstance(template_name.value, str):77 yield template_name.value78 # something dynamic in there79 else:80 yield None
1 unmodified line
82 else:83 yield None84 continue85 # constant is a basestring, direct template name88 if isinstance(node.template.value, string_types):86 if isinstance(node.template.value, str):87 yield node.template.value88 # a tuple or list (latter *should* not happen) made of consts,89 # yield the consts that are strings. We could warn here for90 # non string values91 elif isinstance(node, nodes.Include) and isinstance(92 node.template.value, (tuple, list)93 ):94 for template_name in node.template.value:97 if isinstance(template_name, string_types):95 if isinstance(template_name, str):96 yield template_name97 # something else we don't care about, we could warn here98 else:99 yield None
modified:src/jinja2/nativetypes.py+2 added-3 removed
2 unmodified lines
3from itertools import chain4from itertools import islice56from . import nodes7from ._compat import text_type7from .compiler import CodeGenerator8from .compiler import has_safe_repr9from .environment import Environment10from .environment import Template
20 unmodified lines
31 raw = head[0]32 else:33 if isinstance(nodes, types.GeneratorType):34 nodes = chain(head, nodes)36 raw = u"".join([text_type(v) for v in nodes])35 raw = u"".join([str(v) for v in nodes])3637 try:38 literal = literal_eval(raw)39 except (ValueError, SyntaxError, MemoryError):
10 unmodified lines
505152class NativeCodeGenerator(CodeGenerator):53 """A code generator which renders Python types by not adding55 ``to_string()`` around output nodes, and using :func:`native_concat`54 ``str()`` around output nodes, and using :func:`native_concat`55 to convert complex strings back to Python types if possible.56 """5758 @staticmethod
52 unmodified lines
modified:src/jinja2/nodes.py+6 added-21 removed
6 unmodified lines
7from collections import deque89from markupsafe import Markup1011from ._compat import izip12from ._compat import PY213from ._compat import text_type14from ._compat import with_metaclass1511_binop_to_func = {12 "*": operator.mul,13 "/": operator.truediv,14 "//": operator.floordiv,
28 unmodified lines
4344 def __new__(mcs, name, bases, d):45 for attr in "fields", "attributes":46 storage = []52 storage.extend(getattr(bases[0], attr, ()))47 storage.extend(getattr(bases[0] if bases else object, attr, ()))48 storage.extend(d.get(attr, ()))54 assert len(bases) == 1, "multiple inheritance not allowed"49 assert len(bases) <= 1, "multiple inheritance not allowed"50 assert len(storage) == len(set(storage)), "layout conflict"51 d[attr] = tuple(storage)52 d.setdefault("abstract", False)53 return type.__new__(mcs, name, bases, d)
31 unmodified lines
85 return EvalContext(node.environment)86 return ctx878894class Node(with_metaclass(NodeType, object)):89class Node(metaclass=NodeType):90 """Baseclass for all Jinja nodes. There are a number of nodes available91 of different types. There are four major types:9293 - :class:`Stmt`: statements
27 unmodified lines
121 len(self.fields),122 len(self.fields) != 1 and "s" or "",123 )124 )130 for name, arg in izip(self.fields, fields):125 for name, arg in zip(self.fields, fields):126 setattr(self, name, arg)127 for attr in self.attributes:128 setattr(self, attr, attributes.pop(attr, None))129 if attributes:
374 unmodified lines
504505 fields = ("value",)506507 def as_const(self, eval_ctx=None):513 rv = self.value514 if (515 PY2516 and type(rv) is text_type517 and self.environment.policies["compiler.ascii_str"]518 ):519 try:520 rv = rv.encode("ascii")521 except UnicodeError:522 pass523 return rv508 return self.value509510 @classmethod511 def from_untrusted(cls, value, lineno=None, environment=None):512 """Return a const object if the value is representable as
267 unmodified lines
780 fields = ("nodes",)781782 def as_const(self, eval_ctx=None):783 eval_ctx = get_eval_context(self, eval_ctx)799 return "".join(text_type(x.as_const(eval_ctx)) for x in self.nodes)784 return "".join(str(x.as_const(eval_ctx)) for x in self.nodes)785786787class Compare(Expr):788 """Compares an expression with some other expressions. `ops` must be a
285 unmodified lines
modified:src/jinja2/parser.py+1 added-2 removed
1# -*- coding: utf-8 -*-2"""Parse tokens from the lexer into nodes for the compiler."""3from . import nodes4from ._compat import imap4from .exceptions import TemplateAssertionError5from .exceptions import TemplateSyntaxError6from .lexer import describe_token7from .lexer import describe_token_expr
56 unmodified lines
6465 def _fail_ut_eof(self, name, end_token_stack, lineno):66 expected = []67 for exprs in end_token_stack:69 expected.extend(imap(describe_token_expr, exprs))68 expected.extend(map(describe_token_expr, exprs))69 if end_token_stack:70 currently_looking = " or ".join(71 "'%s'" % describe_token_expr(expr) for expr in end_token_stack[-1]72 )
866 unmodified lines
modified:src/jinja2/runtime.py+44 added-116 removed
1# -*- coding: utf-8 -*-2"""The runtime functions and state used by compiled templates."""3import sys4from collections import abc5from itertools import chain6from types import MethodType78from markupsafe import escape # noqa: F4019from markupsafe import Markup9from markupsafe import soft_unicode10from markupsafe import soft_str1111from ._compat import abc12from ._compat import imap13from ._compat import implements_iterator14from ._compat import implements_to_string15from ._compat import iteritems16from ._compat import PY217from ._compat import string_types18from ._compat import text_type19from ._compat import with_metaclass12from .exceptions import TemplateNotFound # noqa: F40113from .exceptions import TemplateRuntimeError # noqa: F40114from .exceptions import UndefinedError15from .nodes import EvalContext
14 unmodified lines
30 "missing",31 "concat",32 "escape",33 "markup_join",42 "unicode_join",43 "to_string",34 "str_join",35 "identity",36 "TemplateNotFound",37 "Namespace",38 "Undefined",39]4050#: the name of the function that is used to convert something into51#: a string. We can just use the text type here.52to_string = text_type415442def identity(x):43 """Returns its argument. Useful for certain things in the44 environment.45 """
2 unmodified lines
4849def markup_join(seq):50 """Concatenation that escapes if necessary and converts to string."""51 buf = []65 iterator = imap(soft_unicode, seq)52 iterator = map(soft_str, seq)53 for arg in iterator:54 buf.append(arg)55 if hasattr(arg, "__html__"):56 return Markup(u"").join(chain(buf, iterator))57 return concat(buf)585973def unicode_join(seq):60def str_join(seq):61 """Simple args to string conversion and concatenation."""75 return concat(imap(text_type, seq))62 return concat(map(str, seq))636465def unicode_join(seq):66 import warnings6768 warnings.warn(69 "This template must be recompiled with at least Jinja 3.0, or"70 " it will fail in 3.1.",71 DeprecationWarning,72 stacklevel=2,73 )74 return str_join(seq)757677def new_context(78 environment,79 template_name,80 blocks,
13 unmodified lines
94 # if the parent is shared a copy should be created because95 # we don't want to modify the dict passed96 if shared:97 parent = dict(parent)99 for key, value in iteritems(locals):98 for key, value in locals.items():99 if value is not missing:100 parent[key] = value101 return environment.context_class(environment, parent, template_name, blocks)102
50 unmodified lines
153 return context.parent[key]154 return missing155156158class Context(with_metaclass(ContextMeta)):157@abc.Mapping.register158class Context(metaclass=ContextMeta):159 """The template context holds the variables of a template. It stores the160 values passed to the template and also the names the template exports.161 Creating instances is neither supported nor useful as it's created162 automatically at various stages of the template evaluation and should not
27 unmodified lines
190191 # create the initial mapping of blocks. Whenever template inheritance192 # takes place the runtime will update this mapping with the new blocks193 # from the template.194 self.blocks = dict((k, [v]) for k, v in iteritems(blocks))194 self.blocks = {k: [v] for k, v in blocks.items()}195196 # In case we detect the fast resolve mode we can set up an alias197 # here that bypasses the legacy code logic.198 if self._fast_resolve_mode:
104 unmodified lines
303 context = new_context(304 self.environment, self.name, {}, self.get_all(), True, None, locals305 )306 context.eval_ctx = self.eval_ctx307 context.blocks.update((k, list(v)) for k, v in iteritems(self.blocks))307 context.blocks.update((k, list(v)) for k, v in self.blocks.items())308 return context309310 def _all(meth): # noqa: B902311 def proxy(self):
5 unmodified lines
317318 keys = _all("keys")319 values = _all("values")320 items = _all("items")321322 # not available on python 3323 if PY2:324 iterkeys = _all("iterkeys")325 itervalues = _all("itervalues")326 iteritems = _all("iteritems")321 del _all322323 def __contains__(self, name):324 return name in self.vars or name in self.parent
14 unmodified lines
339 self.name,340 )341342349abc.Mapping.register(Context)350351343class BlockReference(object):344 """One block on a template reference."""345346 def __init__(self, name, context, stack, depth):
18 unmodified lines
365 rv = Markup(rv)366 return rv367368378@implements_iterator369class LoopContext:370 """A wrapper iterable for dynamic ``for`` loops, with information371 about the loop and iteration.372 """
304 unmodified lines
677 self.name is None and "anonymous" or repr(self.name),678 )679680691@implements_to_string681class Undefined(object):682 """The default undefined type. This undefined type can be printed and683 iterated over, but every other access will raise an :exc:`UndefinedError`:684
31 unmodified lines
716717 if self._undefined_obj is missing:718 return "%r is undefined" % self._undefined_name719731 if not isinstance(self._undefined_name, string_types):720 if not isinstance(self._undefined_name, str):721 return "%s has no element %r" % (722 object_type_repr(self._undefined_obj),723 self._undefined_name,724 )
15 unmodified lines
740 if name[:2] == "__":741 raise AttributeError(name)742 return self._fail_with_undefined_error()743755 __add__ = (756 __radd__757 ) = (758 __mul__759 ) = (760 __rmul__761 ) = (762 __div__763 ) = (764 __rdiv__765 ) = (766 __truediv__767 ) = (768 __rtruediv__769 ) = (770 __floordiv__771 ) = (772 __rfloordiv__773 ) = (774 __mod__775 ) = (776 __rmod__777 ) = (778 __pos__779 ) = (780 __neg__781 ) = (782 __call__783 ) = (784 __getitem__785 ) = (786 __lt__787 ) = (788 __le__789 ) = (790 __gt__791 ) = (792 __ge__793 ) = (794 __int__795 ) = (796 __float__797 ) = (798 __complex__799 ) = __pow__ = __rpow__ = __sub__ = __rsub__ = _fail_with_undefined_error744 __add__ = __radd__ = __sub__ = __rsub__ = _fail_with_undefined_error745 __mul__ = __rmul__ = __div__ = __rdiv__ = _fail_with_undefined_error746 __truediv__ = __rtruediv__ = _fail_with_undefined_error747 __floordiv__ = __rfloordiv__ = _fail_with_undefined_error748 __mod__ = __rmod__ = _fail_with_undefined_error749 __pos__ = __neg__ = _fail_with_undefined_error750 __call__ = __getitem__ = _fail_with_undefined_error751 __lt__ = __le__ = __gt__ = __ge__ = _fail_with_undefined_error752 __int__ = __float__ = __complex__ = _fail_with_undefined_error753 __pow__ = __rpow__ = _fail_with_undefined_error754755 def __eq__(self, other):756 return type(self) is type(other)757
12 unmodified lines
770 def __iter__(self):771 if 0:772 yield None773820 def __nonzero__(self):774 def __bool__(self):775 return False776823 __bool__ = __nonzero__824777 def __repr__(self):778 return "Undefined"779780
28 unmodified lines
809 def _log_message(undef):810 if undef._undefined_hint is None:811 if undef._undefined_obj is missing:812 hint = "%s is undefined" % undef._undefined_name861 elif not isinstance(undef._undefined_name, string_types):813 elif not isinstance(undef._undefined_name, str):814 hint = "%s has no element %s" % (815 object_type_repr(undef._undefined_obj),816 undef._undefined_name,817 )
23 unmodified lines
841 rv = base.__iter__(self)842 _log_message(self)843 return rv844893 if PY2:845 def __bool__(self):846 rv = base.__bool__(self)847 _log_message(self)848 return rv849895 def __nonzero__(self):896 rv = base.__nonzero__(self)897 _log_message(self)898 return rv899900 def __unicode__(self):901 rv = base.__unicode__(self)902 _log_message(self)903 return rv904905 else:906907 def __bool__(self):908 rv = base.__bool__(self)909 _log_message(self)910 return rv911850 return LoggingUndefined851852915# No @implements_to_string decorator here because __str__916# is not overwritten from Undefined in this class.917# This would cause a recursion error in Python 2.853class ChainableUndefined(Undefined):854 """An undefined that is chainable, where both ``__getattr__`` and855 ``__getitem__`` return itself rather than raising an856 :exc:`UndefinedError`.
19 unmodified lines
876877 __getitem__ = __getattr__878879945@implements_to_string880class DebugUndefined(Undefined):881 """An undefined that returns the debug info when printed.882883 >>> foo = DebugUndefined(name='foo')
19 unmodified lines
903 )904 return u"{{ undefined value printed: %s }}" % self._undefined_hint905906973@implements_to_string907class StrictUndefined(Undefined):908 """An undefined that barks on print and iteration as well as boolean909 tests and all kinds of comparisons. In other words: you can do nothing910 with it except checking if it's defined using the `defined` test.
13 unmodified lines
924 jinja2.exceptions.UndefinedError: 'foo' is undefined925 """926927 __slots__ = ()995 __iter__ = (996 __str__997 ) = (998 __len__999 ) = (1000 __nonzero__1001 ) = __eq__ = __ne__ = __bool__ = __hash__ = Undefined._fail_with_undefined_error928 __iter__ = __str__ = __len__ = Undefined._fail_with_undefined_error929 __eq__ = __ne__ = __bool__ = __hash__ = Undefined._fail_with_undefined_error9309311004# remove remaining slots attributes, after the metaclass did the magic they1005# are unneeded and irritating as they contain wrong data for the subclasses.932# Remove slots attributes, after the metaclass is applied they are933# unneeded and contain wrong data for subclasses.934del (935 Undefined.__slots__,936 ChainableUndefined.__slots__,937 DebugUndefined.__slots__,
2 unmodified lines
modified:src/jinja2/sandbox.py+11 added-52 removed
2 unmodified lines
3Useful when the template itself comes from an untrusted source.4"""5import operator6import types7from collections import abc8from collections import deque9from string import Formatter1011from markupsafe import EscapeFormatter12from markupsafe import Markup1313from ._compat import abc14from ._compat import PY215from ._compat import range_type16from ._compat import string_types14from .environment import Environment15from .exceptions import SecurityError1617#: maximum number of items a range may produce18MAX_RANGE = 1000001923#: attributes of function objects that are considered unsafe.24if PY2:25 UNSAFE_FUNCTION_ATTRIBUTES = {26 "func_closure",27 "func_code",28 "func_dict",29 "func_defaults",30 "func_globals",31 }32else:33 # On versions > python 2 the special attributes on functions are gone,34 # but they remain on methods and generators for whatever reason.35 UNSAFE_FUNCTION_ATTRIBUTES = set()20#: Unsafe function attributes.21UNSAFE_FUNCTION_ATTRIBUTES = set()2237#: unsafe method attributes. function attributes are unsafe for methods too38UNSAFE_METHOD_ATTRIBUTES = {"im_class", "im_func", "im_self"}23#: Unsafe method attributes. Function attributes are unsafe for methods too.24UNSAFE_METHOD_ATTRIBUTES = set()2526#: unsafe generator attributes.27UNSAFE_GENERATOR_ATTRIBUTES = {"gi_frame", "gi_code"}28
2 unmodified lines
3132#: unsafe attributes on async generators33UNSAFE_ASYNC_GENERATOR_ATTRIBUTES = {"ag_code", "ag_frame"}3449_mutable_set_types = (set,)50_mutable_mapping_types = (dict,)51_mutable_sequence_types = (list,)5253# on python 2.x we can register the user collection types54try:55 from UserDict import UserDict, DictMixin56 from UserList import UserList5758 _mutable_mapping_types += (UserDict, DictMixin)59 _mutable_set_types += (UserList,)60except ImportError:61 pass6263# if sets is still available, register the mutable set from there as well64try:65 from sets import Set6667 _mutable_set_types += (Set,)68except ImportError:69 pass7071#: register Python 2.6 abstract base classes72_mutable_set_types += (abc.MutableSet,)73_mutable_mapping_types += (abc.MutableMapping,)74_mutable_sequence_types += (abc.MutableSequence,)7535_mutable_spec = (36 (78 _mutable_set_types,37 abc.MutableSet,38 frozenset(39 [40 "add",41 "clear",
6 unmodified lines
48 ]49 ),50 ),51 (93 _mutable_mapping_types,52 abc.MutableMapping,53 frozenset(["clear", "pop", "popitem", "setdefault", "update"]),54 ),55 (97 _mutable_sequence_types,56 abc.MutableSequence,57 frozenset(["append", "reverse", "insert", "sort", "extend", "remove"]),58 ),59 (60 deque,
50 unmodified lines
111 callable, (types.MethodType, types.BuiltinMethodType)112 ) or callable.__name__ not in ("format", "format_map"):113 return None114 obj = callable.__self__156 if isinstance(obj, string_types):115 if isinstance(obj, str):116 return obj117118119def safe_range(*args):120 """A range that can't generate ranges with a length of more than121 MAX_RANGE items.122 """164 rng = range_type(*args)123 rng = range(*args)124125 if len(rng) > MAX_RANGE:126 raise OverflowError(127 "Range too big. The sandbox blocks ranges larger than"
206 unmodified lines
334 """Subscribe an object from sandboxed code."""335 try:336 return obj[argument]337 except (TypeError, LookupError):379 if isinstance(argument, string_types):338 if isinstance(argument, str):339 try:340 attr = str(argument)341 except Exception:342 pass
120 unmodified lines
modified:src/jinja2/tests.py+7 added-10 removed
1# -*- coding: utf-8 -*-2"""Built-in template tests used with the ``is`` operator."""3import decimal3import operator4import re5from collections import abc6from numbers import Number77from ._compat import abc8from ._compat import integer_types9from ._compat import string_types10from ._compat import text_type8from .runtime import Undefined910number_re = re.compile(r"^-?\d+(\.\d+)?$")11regex_type = type(number_re)
71 unmodified lines
83 """Return true if the object is an integer.8485 .. versionadded:: 2.1186 """90 return isinstance(value, integer_types) and value is not True and value is not False87 return isinstance(value, int) and value is not True and value is not False888990# NOTE: The existing 'number' test matches booleans and integers91def test_float(value):
5 unmodified lines
979899def test_lower(value):100 """Return true if the variable is lowercased."""104 return text_type(value).islower()101 return str(value).islower()102103104def test_upper(value):105 """Return true if the variable is uppercased."""109 return text_type(value).isupper()106 return str(value).isupper()107108109def test_string(value):110 """Return true if the object is a string."""114 return isinstance(value, string_types)111 return isinstance(value, str)112113114def test_mapping(value):115 """Return true if the object is a mapping (dict etc.).
4 unmodified lines
120121122def test_number(value):123 """Return true if the variable is a number."""127 return isinstance(value, integer_types + (float, complex, decimal.Decimal))124 return isinstance(value, Number)125126127def test_sequence(value):128 """Return true if the variable is a sequence. Sequences are variables
84 unmodified lines
modified:src/jinja2/utils.py+22 added-18 removed
1# -*- coding: utf-8 -*-2import json3import os4import re5from collections import abc6from collections import deque7from random import choice8from random import randrange9from threading import Lock10from urllib.parse import quote_from_bytes1112from markupsafe import escape13from markupsafe import Markup1413from ._compat import abc14from ._compat import string_types15from ._compat import text_type16from ._compat import url_quote1715_word_split_re = re.compile(r"(\s+)")16_punctuation_re = re.compile(17 "^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$"18 % (
182 unmodified lines
201 lambda x, limit=trim_url_limit: limit is not None202 and (x[:limit] + (len(x) >= limit and "..." or ""))203 or x204 )208 words = _word_split_re.split(text_type(escape(text)))209 rel_attr = rel and ' rel="%s"' % text_type(escape(rel)) or ""205 words = _word_split_re.split(str(escape(text)))206 rel_attr = rel and ' rel="%s"' % str(escape(rel)) or ""207 target_attr = target and ' target="%s"' % escape(target) or ""208209 for i, word in enumerate(words):210 match = _punctuation_re.match(word)
84 unmodified lines
295 return u"\n\n".join(result)296 return Markup(u"\n".join(u"<p>%s</p>" % escape(x) for x in result))297298302def unicode_urlencode(obj, charset="utf-8", for_qs=False):299def url_quote(obj, charset="utf-8", for_qs=False):300 """Quote a string for use in a URL using the given charset.301302 This function is misnamed, it is a wrapper around303 :func:`urllib.parse.quote`.
2 unmodified lines
306 string then encoded to bytes using the given charset.307 :param charset: Encode text to bytes using this charset.308 :param for_qs: Quote "/" and use "+" for spaces.309 """313 if not isinstance(obj, string_types):314 obj = text_type(obj)310 if not isinstance(obj, bytes):311 if not isinstance(obj, str):312 obj = str(obj)313316 if isinstance(obj, text_type):314 obj = obj.encode(charset)315316 safe = b"" if for_qs else b"/"320 rv = url_quote(obj, safe)317 rv = quote_from_bytes(obj, safe)318322 if not isinstance(rv, text_type):323 rv = rv.decode("utf-8")324319 if for_qs:320 rv = rv.replace("%20", "+")321322 return rv323324325def unicode_urlencode(obj, charset="utf-8", for_qs=False):326 import warnings327328 warnings.warn(329 "'unicode_urlencode' has been renamed to 'url_quote'. The old"330 " name will be removed in version 3.1.",331 DeprecationWarning,332 stacklevel=2,333 )334 return url_quote(obj, charset=charset, for_qs=for_qs)335336337@abc.MutableMapping.register338class LRUCache(object):339 """A simple LRU Cache implementation."""340341 # this is fast for small capacities (something below 1000) but doesn't
148 unmodified lines
490491 __copy__ = copy492493487abc.MutableMapping.register(LRUCache)488489494def select_autoescape(495 enabled_extensions=("html", "htm", "xml"),496 disabled_extensions=(),497 default_for_string=True,
179 unmodified lines
modified:tests/test_ext.py+3 added-5 removed
1# -*- coding: utf-8 -*-2import re3from io import BytesIO45import pytest67from jinja2 import contextfunction8from jinja2 import DictLoader9from jinja2 import Environment10from jinja2 import nodes10from jinja2._compat import BytesIO11from jinja2._compat import itervalues12from jinja2._compat import text_type11from jinja2.exceptions import TemplateAssertionError12from jinja2.ext import Extension13from jinja2.lexer import count_newlines14from jinja2.lexer import Token
213 unmodified lines
228 def test_rebinding(self):229 original = Environment(extensions=[ExampleExtension])230 overlay = original.overlay()231 for env in original, overlay:234 for ext in itervalues(env.extensions):232 for ext in env.extensions.values():233 assert ext.environment is env234235 def test_preprocessor_extension(self):236 env = Environment(extensions=[PreprocessorExtension])
379 unmodified lines
616 {{ '<testing>' }}617 """618 tmpl = env.from_string(tmplsource)619 assert tmpl.render(val=True).split()[0] == "Markup"622 assert tmpl.render(val=False).split()[0] == text_type.__name__620 assert tmpl.render(val=False).split()[0] == "str"621622 # looking at the source we should see <testing> there in raw623 # (and then escaped as well)624 env = Environment(extensions=["jinja2.ext.autoescape"])
34 unmodified lines
modified:tests/test_features.py-29 removed
1import sys21import pytest25from jinja2 import contextfilter6from jinja2 import Environment3from jinja2 import Template8from jinja2._compat import text_type4511@pytest.mark.skipif(sys.version_info < (3, 5), reason="Requires 3.5 or later")6def test_generator_stop():7 class X(object):8 def __getattr__(self, name):9 raise StopIteration()1011 t = Template("a{{ bad.bar() }}b")12 with pytest.raises(RuntimeError):13 t.render(bad=X())202122@pytest.mark.skipif(sys.version_info[0] > 2, reason="Feature only supported on 2.x")23def test_ascii_str():24 @contextfilter25 def assert_func(context, value):26 assert type(value) is context["expected_type"]2728 env = Environment()29 env.filters["assert"] = assert_func3031 env.policies["compiler.ascii_str"] = False32 t = env.from_string('{{ "foo"|assert }}')33 t.render(expected_type=text_type)3435 env.policies["compiler.ascii_str"] = True36 t = env.from_string('{{ "foo"|assert }}')37 t.render(expected_type=str)3839 for val in True, False:40 env.policies["compiler.ascii_str"] = val41 t = env.from_string(u'{{ "\N{SNOWMAN}"|assert }}')42 t.render(expected_type=text_type)
modified:tests/test_filters.py+3 added-7 removed
4 unmodified lines
5import pytest67from jinja2 import Environment8from jinja2 import Markup9from jinja2._compat import implements_to_string10from jinja2._compat import text_type91013@implements_to_string11class Magic(object):12 def __init__(self, value):13 self.value = value1415 def __str__(self):19 return text_type(self.value)16 return str(self.value)171822@implements_to_string19class Magic2(object):20 def __init__(self, value1, value2):21 self.value1 = value122 self.value2 = value22324 def __str__(self):29 return u"(%s,%s)" % (text_type(self.value1), text_type(self.value2))25 return u"(%s,%s)" % (str(self.value1), str(self.value2))262728@pytest.mark.filter29class TestFilter(object):
246 unmodified lines
276277 def test_string(self, env):278 x = [1, 2, 3, 4, 5]279 tmpl = env.from_string("""{{ obj|string }}""")284 assert tmpl.render(obj=x) == text_type(x)280 assert tmpl.render(obj=x) == str(x)281282 def test_title(self, env):283 tmpl = env.from_string("""{{ "foo bar"|title }}""")284 assert tmpl.render() == "Foo Bar"
457 unmodified lines
modified:tests/test_lexnparse.py+22 added-36 removed
4 unmodified lines
5from jinja2 import nodes6from jinja2 import Template7from jinja2 import TemplateSyntaxError8from jinja2 import UndefinedError9from jinja2._compat import iteritems10from jinja2._compat import PY211from jinja2._compat import text_type9from jinja2.lexer import Token10from jinja2.lexer import TOKEN_BLOCK_BEGIN11from jinja2.lexer import TOKEN_BLOCK_END12from jinja2.lexer import TOKEN_EOF13from jinja2.lexer import TokenStream141519# how does a string look like in jinja syntax?20if PY2:2122 def jinja_string_repr(string):23 return repr(string)[1:]242526else:27 jinja_string_repr = repr282916@pytest.mark.lexnparse17@pytest.mark.tokenstream18class TestTokenStream(object):19 test_tokens = [
76 unmodified lines
96 )9798 def test_string_escapes(self, env):99 for char in u"\0", u"\u2668", u"\xe4", u"\t", u"\r", u"\n":114 tmpl = env.from_string("{{ %s }}" % jinja_string_repr(char))100 tmpl = env.from_string("{{ %s }}" % repr(char))101 assert tmpl.render() == char102 assert env.from_string('{{ "\N{HOT SPRINGS}" }}').render() == u"\u2668"103104 def test_bytefallback(self, env):
4 unmodified lines
109110 def test_operators(self, env):111 from jinja2.lexer import operators112127 for test, expect in iteritems(operators):113 for test, expect in operators.items():114 if test in "([{}])":115 continue116 stream = env.lexer.tokenize("{{ %s }}" % test)117 next(stream)
20 unmodified lines
138 result = tmpl.render()139 assert result == expect, (keep, template, result, expect)140141 @pytest.mark.parametrize(156 "name,valid2,valid3",157 (158 (u"foo", True, True),159 (u"föö", False, True),160 (u"き", False, True),161 (u"_", True, True),162 (u"1a", False, False), # invalid ascii start163 (u"a-", False, False), # invalid ascii continue164 (u"🐍", False, False), # invalid unicode start165 (u"a🐍", False, False), # invalid unicode continue142 ("name", "valid"),143 [144 (u"foo", True),145 (u"föö", True),146 (u"き", True),147 (u"_", True),148 (u"1a", False), # invalid ascii start149 (u"a-", False), # invalid ascii continue150 (u"🐍", False), # invalid unicode start151 (u"a🐍", False), # invalid unicode continue152 # start characters not matched by \w167 (u"\u1885", False, True),168 (u"\u1886", False, True),169 (u"\u2118", False, True),170 (u"\u212e", False, True),153 (u"\u1885", True),154 (u"\u1886", True),155 (u"\u2118", True),156 (u"\u212e", True),157 # continue character not matched by \w172 (u"\xb7", False, False),173 (u"a\xb7", False, True),174 ),158 (u"\xb7", False),159 (u"a\xb7", True),160 ],161 )176 def test_name(self, env, name, valid2, valid3):162 def test_name(self, env, name, valid):163 t = u"{{ " + name + u" }}"164179 if (valid2 and PY2) or (valid3 and not PY2):165 if valid:166 # valid for version being tested, shouldn't raise167 env.from_string(t)168 else:169 pytest.raises(TemplateSyntaxError, env.from_string, t)
343 unmodified lines
513 assert tmpl.render(bar=bar) == "False"514515 def test_operator_precedence(self, env):516 tmpl = env.from_string("""{{ 2 * 3 + 4 % 2 + 1 - 2 }}""")531 assert tmpl.render() == text_type(2 * 3 + 4 % 2 + 1 - 2)517 assert tmpl.render() == "5"518519 def test_implicit_subscribed_tuple(self, env):520 class Foo(object):521 def __getitem__(self, x):
295 unmodified lines
modified:tests/test_loader.py+2 added-22 removed
1# -*- coding: utf-8 -*-2import os3import platform4import shutil5import sys6import tempfile7import time
3 unmodified lines
1112from jinja2 import Environment13from jinja2 import loaders14from jinja2 import PackageLoader14from jinja2._compat import PY215from jinja2._compat import PYPY15from jinja2.exceptions import TemplateNotFound16from jinja2.loaders import split_template_path1718
117 unmodified lines
136137 env = Environment(loader=filesystem_loader)138 self._test_common(env)139141 @pytest.mark.skipif(PY2, reason="pathlib is not available in Python 2")140 def test_searchpath_as_pathlib(self):141 import pathlib142143 searchpath = pathlib.Path(self.searchpath)146144 filesystem_loader = loaders.FileSystemLoader(searchpath)148145 env = Environment(loader=filesystem_loader)146 self._test_common(env)147152 @pytest.mark.skipif(PY2, reason="pathlib is not available in Python 2")148 def test_searchpath_as_list_including_pathlib(self):149 import pathlib150151 searchpath = pathlib.Path(self.searchpath)157152 filesystem_loader = loaders.FileSystemLoader(["/tmp/templates", searchpath])159153 env = Environment(loader=filesystem_loader)154 self._test_common(env)155156 def test_caches_template_based_on_mtime(self):
100 unmodified lines
257 pass258259 assert name not in sys.modules260268 # This test only makes sense on non-pypy python 2269 @pytest.mark.skipif(270 not (PY2 and not PYPY), reason="This test only makes sense on non-pypy python 2"271 )272 def test_byte_compilation(self, prefix_loader):273 log = self.compile_down(prefix_loader, py_compile=True)274 assert 'Byte-compiled "a/test.html"' in log275 self.mod_env.get_template("a/test.html")276 mod = self.mod_env.loader.module.tmpl_3c4ddf650c1a73df961a6d3d2ce2752f1b8fd490277 assert mod.__file__.endswith(".pyc")278261 def test_choice_loader(self, prefix_loader):262 self.compile_down(prefix_loader)263 self.mod_env.loader = loaders.ChoiceLoader(264 [self.mod_env.loader, loaders.DictLoader({"DICT_SOURCE": "DICT_TEMPLATE"})]
15 unmodified lines
280 assert tmpl1.render() == "BAR"281 tmpl2 = self.mod_env.get_template("DICT/test.html")282 assert tmpl2.render() == "DICT_TEMPLATE"283302 @pytest.mark.skipif(PY2, reason="pathlib is not available in Python 2")284 def test_path_as_pathlib(self, prefix_loader):285 self.compile_down(prefix_loader)286287 mod_path = self.mod_env.loader.module.__path__[0]
4 unmodified lines
292 self.mod_env = Environment(loader=mod_loader)293294 self._test_common()295315 @pytest.mark.skipif(PY2, reason="pathlib is not available in Python 2")296 def test_supports_pathlib_in_list_of_paths(self, prefix_loader):297 self.compile_down(prefix_loader)298299 mod_path = self.mod_env.loader.module.__path__[0]
46 unmodified lines
346 assert up_to_date is None347348349@pytest.mark.xfail(370 PYPY,350 platform.python_implementation() == "PyPy",351 reason="PyPy's zipimporter doesn't have a _files attribute.",352 raises=TypeError,353)354def test_package_zip_list(package_zip_loader):
1 unmodified line
modified:tests/test_nativetypes.py+2 added-3 removed
1import pytest23from jinja2._compat import text_type3from jinja2.exceptions import UndefinedError4from jinja2.nativetypes import NativeEnvironment5from jinja2.nativetypes import NativeTemplate6from jinja2.runtime import Undefined
44 unmodified lines
5152def test_loops(env):53 t = env.from_string("{% for x in value %}{{ x }}{% endfor %}")54 result = t.render(value=["a", "b", "c", "d"])56 assert isinstance(result, text_type)55 assert isinstance(result, str)56 assert result == "abcd"575859def test_loops_with_ints(env):
49 unmodified lines
109110def test_string_literal_var(env):111 t = env.from_string("[{{ 'all' }}]")112 result = t.render()114 assert isinstance(result, text_type)113 assert isinstance(result, str)114 assert result == "[all]"115116117def test_string_top_level(env):
21 unmodified lines
modified:tests/test_regression.py+1 added-11 removed
1# -*- coding: utf-8 -*-2import sys32import pytest34from jinja2 import DictLoader5from jinja2 import Environment
1 unmodified line
7from jinja2 import Template8from jinja2 import TemplateAssertionError9from jinja2 import TemplateNotFound10from jinja2 import TemplateSyntaxError13from jinja2._compat import text_type111213@pytest.mark.regression14class TestCorner(object):
115 unmodified lines
130131 """132 )133137 assert tmpl.render().split() == [text_type(x) for x in range(1, 11)] * 5134 assert tmpl.render().split() == [str(x) for x in range(1, 11)] * 5135136 def test_weird_inline_comment(self, env):137 env = Environment(line_statement_prefix="%")138 pytest.raises(
165 unmodified lines
304 expected = "TEST"305306 assert output == expected307311 @pytest.mark.skipif(sys.version_info[0] > 2, reason="This only works on 2.x")312 def test_old_style_attribute(self, env):313 class Foo:314 x = 42315316 assert env.getitem(Foo(), "x") == 42317308 def test_block_set_with_extends(self):309 env = Environment(310 loader=DictLoader({"main": "{% block body %}[{{ x }}]{% endblock %}"})311 )
305 unmodified lines
modified:tests/test_security.py+1 added-41 removed
1 unmodified line
2import pytest34from jinja2 import Environment5from jinja2 import escape6from jinja2 import Markup7from jinja2._compat import text_type6from jinja2.exceptions import SecurityError7from jinja2.exceptions import TemplateRuntimeError8from jinja2.exceptions import TemplateSyntaxError9from jinja2.nodes import EvalContext
64 unmodified lines
74 env.from_string,75 "{% for foo, bar.baz in seq %}...{% endfor %}",76 )7780 def test_markup_operations(self, env):81 # adding two strings should escape the unsafe one82 unsafe = '<script type="application/x-some-script">alert("foo");</script>'83 safe = Markup("<em>username</em>")84 assert unsafe + safe == text_type(escape(unsafe)) + text_type(safe)8586 # string interpolations are safe to use too87 assert Markup("<em>%s</em>") % "<bad user>" == "<em>&lt;bad user&gt;</em>"88 assert (89 Markup("<em>%(username)s</em>") % {"username": "<bad user>"}90 == "<em>&lt;bad user&gt;</em>"91 )9293 # an escaped object is markup too94 assert type(Markup("foo") + "bar") is Markup9596 # and it implements __html__ by returning itself97 x = Markup("foo")98 assert x.__html__() is x99100 # it also knows how to treat __html__ objects101 class Foo(object):102 def __html__(self):103 return "<em>awesome</em>"104105 def __unicode__(self):106 return "awesome"107108 assert Markup(Foo()) == "<em>awesome</em>"109 assert (110 Markup("<strong>%s</strong>") % Foo() == "<strong><em>awesome</em></strong>"111 )112113 # escaping and unescaping114 assert escape("\"<>&'") == "&#34;&lt;&gt;&amp;&#39;"115 assert Markup("<em>Foo &amp; Bar</em>").striptags() == "Foo & Bar"116 assert Markup("&lt;test&gt;").unescape() == "<test>"11778 def test_template_data(self, env):79 env = Environment(autoescape=True)80 t = env.from_string(81 "{% macro say_hello(name) %}"
1 unmodified line
83 '{{ say_hello("<blink>foo</blink>") }}'84 )85 escaped_out = "<p>Hello &lt;blink&gt;foo&lt;/blink&gt;!</p>"86 assert t.render() == escaped_out127 assert text_type(t.module) == escaped_out87 assert str(t.module) == escaped_out88 assert escape(t.module) == escaped_out89 assert t.module.say_hello("<blink>foo</blink>") == escaped_out90 assert (91 escape(t.module.say_hello(EvalContext(env), "<blink>foo</blink>"))
82 unmodified lines
modified:tests/test_utils.py+6 added-8 removed
5 unmodified lines
67import pytest8from markupsafe import Markup910from jinja2._compat import range_type11from jinja2._compat import string_types10from jinja2.utils import consume11from jinja2.utils import generate_lorem_ipsum12from jinja2.utils import LRUCache13from jinja2.utils import missing
148 unmodified lines
162 assert isinstance(generate_lorem_ipsum(), Markup)163164 def test_lorem_ipsum_html(self):165 """Test that output of lorem_ipsum is a string_type when not html."""168 assert isinstance(generate_lorem_ipsum(html=False), string_types)166 assert isinstance(generate_lorem_ipsum(html=False), str)167168 def test_lorem_ipsum_n(self):169 """Test that the n (number of lines) works as expected."""170 assert generate_lorem_ipsum(n=0, html=False) == u""173 for n in range_type(1, 50):171 for n in range(1, 50):172 assert generate_lorem_ipsum(n=n, html=False).count("\n") == (n - 1) * 2173174 def test_lorem_ipsum_min(self):175 """Test that at least min words are in the output of each line"""178 for _ in range_type(5):176 for _ in range(5):177 m = random.randrange(20, 99)180 for _ in range_type(10):178 for _ in range(10):179 assert generate_lorem_ipsum(n=1, min=m, html=False).count(" ") >= m - 1180181 def test_lorem_ipsum_max(self):182 """Test that at least max words are in the output of each line"""185 for _ in range_type(5):183 for _ in range(5):184 m = random.randrange(21, 100)187 for _ in range_type(10):185 for _ in range(10):186 assert generate_lorem_ipsum(n=1, max=m, html=False).count(" ") < m - 1187188189def test_missing():
10 unmodified lines