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
Provenance
- Commit
148a191- Tree
6b71f2f- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
b0015c7
29 files changed+264 added−766 removed
deleted:src/jinja2/_compat.py-132 removed
1-# -*- coding: utf-8 -*-2-# flake8: noqa3-import marshal4-import sys5-6-PY2 = sys.version_info[0] == 27-PYPY = hasattr(sys, "pypy_translation_info")8-_identity = lambda x: x9-10-if not PY2:11- unichr = chr12- range_type = range13- text_type = str14- string_types = (str,)15- integer_types = (int,)16-17- iterkeys = lambda d: iter(d.keys())18- itervalues = lambda d: iter(d.values())19- iteritems = lambda d: iter(d.items())20-21- import pickle22- from io import BytesIO, StringIO23-24- NativeStringIO = StringIO25-26- def reraise(tp, value, tb=None):27- if value.__traceback__ is not tb:28- raise value.with_traceback(tb)29- raise value30-31- ifilter = filter32- imap = map33- izip = zip34- intern = sys.intern35-36- implements_iterator = _identity37- implements_to_string = _identity38- encode_filename = _identity39-40- marshal_dump = marshal.dump41- marshal_load = marshal.load42-43-else:44- unichr = unichr45- text_type = unicode46- range_type = xrange47- string_types = (str, unicode)48- integer_types = (int, long)49-50- iterkeys = lambda d: d.iterkeys()51- itervalues = lambda d: d.itervalues()52- iteritems = lambda d: d.iteritems()53-54- import cPickle as pickle55- from cStringIO import StringIO as BytesIO, StringIO56-57- NativeStringIO = BytesIO58-59- exec("def reraise(tp, value, tb=None):\n raise tp, value, tb")60-61- from itertools import imap, izip, ifilter62-63- intern = intern64-65- def implements_iterator(cls):66- cls.next = cls.__next__67- del cls.__next__68- return cls69-70- def implements_to_string(cls):71- cls.__unicode__ = cls.__str__72- cls.__str__ = lambda x: x.__unicode__().encode("utf-8")73- return cls74-75- def encode_filename(filename):76- if isinstance(filename, unicode):77- return filename.encode("utf-8")78- return filename79-80- def marshal_dump(code, f):81- if isinstance(f, file):82- marshal.dump(code, f)83- else:84- f.write(marshal.dumps(code))85-86- def marshal_load(f):87- if isinstance(f, file):88- return marshal.load(f)89- return marshal.loads(f.read())90-91-92-def 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)100-101- return type.__new__(metaclass, "temporary_class", (), {})102-103-104-try:105- from urllib.parse import quote_from_bytes as url_quote106-except ImportError:107- from urllib import quote as url_quote108-109-110-try:111- from collections import abc112-except ImportError:113- import collections as abc114-115-116-try:117- from os import fspath118-except ImportError:119- try:120- from pathlib import PurePath121- except ImportError:122- PurePath = None123-124- def fspath(path):125- if hasattr(path, "__fspath__"):126- return path.__fspath__()127-128- # Python 3.5 doesn't have __fspath__ yet, use str.129- if PurePath is not None and isinstance(path, PurePath):130- return str(path)131-132- return pathmodified:src/jinja2/bccache.py+9 added-13 removed
6 unmodified lines7 are initialized on the first request.8 """9 import errno10 import fnmatch11+import marshal12 import os13+import pickle14 import stat15 import sys16 import tempfile17 from hashlib import sha116-from os import listdir17-from os import path18+from io import BytesIO19 19-from ._compat import BytesIO20-from ._compat import marshal_dump21-from ._compat import marshal_load22-from ._compat import pickle23-from ._compat import text_type20 from .utils import open_if_exists21 22 bc_version = 423 # Magic bytes to identify Jinja bytecode cache files. Contains the38 unmodified lines62 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 lines73 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)78 79 def bytecode_from_string(self, string):80 """Load bytecode from a string."""81 self.load_bytecode(BytesIO(string))58 unmodified lines140 """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 lines236 237 return actual_dir238 239 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)241 242 def load_bytecode(self, bucket):243 f = open_if_exists(self._get_cache_filename(bucket), "rb")244 if f is not None:14 unmodified lines259 # write access on the file system and the function does not exist260 # normally.261 from os import remove262 267- 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 pass269 270 76 unmodified linesmodified:src/jinja2/compiler.py+32 added-78 removed
1 # -*- coding: utf-8 -*-2 """Compiles nodes from the parser into Python code."""3 from collections import namedtuple4 from functools import update_wrapper5+from io import StringIO6 from itertools import chain7 from keyword import iskeyword as is_python_keyword8 9 from markupsafe import escape10 from markupsafe import Markup11 12 from . import nodes12-from ._compat import imap13-from ._compat import iteritems14-from ._compat import izip15-from ._compat import NativeStringIO16-from ._compat import range_type17-from ._compat import string_types18-from ._compat import text_type13 from .exceptions import TemplateAssertionError14 from .idtracking import Symbols15 from .idtracking import VAR_LOAD_ALIAS16 from .idtracking import VAR_LOAD_PARAMETER14 unmodified lines31 "in": "in",32 "notin": "not in",33 }34 41-# 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 items43-if hasattr(dict, "iteritems"):44- dict_item_iter = "iteritems"45-else:46- dict_item_iter = "items"35 48-code_features = ["division"]49-50-# does this python version support generator stops? (PEP 0479)51-try:52- exec("from __future__ import generator_stop")53- code_features.append("generator_stop")54-except SyntaxError:55- pass56-57-# does this python version support yield from?58-try:59- exec("def f(): yield from x()")60-except SyntaxError:61- supports_yield_from = False62-else:63- supports_yield_from = True64-65-36 def 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 lines62 def 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:66+67+ 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 True69+70+ if type(value) in {tuple, list, set, frozenset}:71+ return all(has_safe_repr(v) for v in value)72+73+ if type(value) is dict:74+ return all(has_safe_repr(k) and has_safe_repr(v) for k, v in value.items())75+76 return False77 78 79 def find_undeclared(nodes, names):134 unmodified lines214 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 = stream174 unmodified lines397 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 lines413 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 lines442 )443 444 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 lines459 460 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 lines577 578 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 )583 584 def write_commons(self):585 """Writes a common preamble that is used by root and block functions.83 unmodified lines669 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 )675 676 # -- Statement Visitors677 2 unmodified lines680 eval_ctx = EvalContext(self.environment, self.name)681 682 from .runtime import exported683 718- self.writeline("from __future__ import %s" % ", ".join(code_features))684 self.writeline("from jinja2.runtime import " + ", ".join(exported))685 686 if self.environment.is_async:687 self.writeline(57 unmodified lines745 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 lines759 self.outdent()760 self.outdent(1 + (not self.has_known_extends))761 762 # 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 lines815 context = self.derive_context(frame)816 else:817 context = self.get_context_ref()818 854- 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 lines860 861 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 lines882 self.indent()883 884 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 lines916 "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- )922 923 if not skip_event_yield:924 self.indent()925 self.simple_write("event", frame)98 unmodified lines1024 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 )1030 1031 def visit_For(self, node, frame):1032 loop_frame = frame.inner()182 unmodified lines1215 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 lines1231 _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 = None1237 1238 def _make_finalize(self):1239 """Build the finalize function to be used on constants and at57 unmodified lines1297 const = escape(const)1298 1299 # Template data doesn't go through finalize.1300 if isinstance(node, nodes.TemplateData):1347- return text_type(const)1301+ return str(const)1302 1303 return finalize.const(const)1304 1305 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(")1315 1316 if finalize.src is not None:1317 self.write(finalize.src)1318 249 unmodified lines1568 1569 @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 linesmodified:src/jinja2/debug.py+5 added-7 removed
1+import platform2 import sys3 from types import CodeType4 5 from . import TemplateSyntaxError5-from ._compat import PYPY6 from .utils import internal_code7 from .utils import missing8 9 3 unmodified lines13 came from the template source.14 15 This must be called within an ``except`` block.16 17- :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()22 23 if isinstance(exc_value, TemplateSyntaxError) and not exc_value.translated:24 exc_value.translated = True25 exc_value.source = source41 unmodified lines67 # Assign tb_next in reverse to avoid circular references.68 for tb in reversed(stack):69 tb_next = tb_set_next(tb, tb_next)70 73- return exc_type, exc_value, tb_next71+ return exc_value.with_traceback(tb_next)72 73 74 def fake_traceback(exc_value, tb, filename, lineno):75 """Produce a new traceback object that looks like it came from the136 unmodified lines212 tb.tb_next = tb_next213 return tb214 215 218-elif PYPY:216+elif 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 linesmodified:src/jinja2/defaults.py+1 added-2 removed
1 # -*- coding: utf-8 -*-2-from ._compat import range_type2 from .filters import FILTERS as DEFAULT_FILTERS # noqa: F4013 from .tests import TESTS as DEFAULT_TESTS # noqa: F4014 from .utils import Cycler5 from .utils import generate_lorem_ipsum16 unmodified lines22 23 # default filters, tests and namespace24 25 DEFAULT_NAMESPACE = {27- "range": range_type,26+ "range": range,27 "dict": dict,28 "lipsum": generate_lorem_ipsum,29 "cycler": Cycler,30 "joiner": Joiner,13 unmodified linesmodified:src/jinja2/environment.py+13 added-24 removed
9 unmodified lines10 11 from markupsafe import Markup12 13 from . import nodes14-from ._compat import encode_filename15-from ._compat import implements_iterator16-from ._compat import implements_to_string17-from ._compat import iteritems18-from ._compat import reraise19-from ._compat import string_types20-from ._compat import text_type14 from .compiler import CodeGenerator15 from .compiler import generate16 from .defaults import BLOCK_END_STRING17 from .defaults import BLOCK_START_STRING76 unmodified lines94 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 lines368 """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)375 376 def overlay(36 unmodified lines413 rv.__dict__.update(self.__dict__)414 rv.overlayed = True415 rv.linked_to = self416 424- for key, value in iteritems(args):417+ for key, value in args.items():418 if value is not missing:419 setattr(rv, key, value)420 421 if cache_size is not missing:1 unmodified line423 else:424 rv.cache = copy_cache(self.cache)425 426 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 lines441 """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 pass76 unmodified lines526 self.handle_exception(source=source)527 528 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()531 532 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 lines538 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 lines552 """553 return reduce(554 lambda s, e: e.preprocess(s, name, filename),555 self.iter_extensions(),563- text_type(source),556+ str(source),557 )558 559 def _tokenize(self, source, name, filename=None, state=None):560 """Called by the parser to do the preprocessing and filtering52 unmodified lines613 `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 lines708 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")714 715 with open(os.path.join(target, filename), "wb") as f:716 f.write(data)68 unmodified lines785 rewritten exceptions or return a rendered traceback for the template.786 """787 from .debug import rewrite_traceback_stack788 798- reraise(*rewrite_traceback_stack(source=source))789+ raise rewrite_traceback_stack(source=source)790 791 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 lines882 :meth:`get_template`.883 884 .. 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 lines1175 name = repr(self.name)1176 return "<%s %s>" % (self.__class__.__name__, name)1177 1178 1188-@implements_to_string1179 class 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 lines1228 rv = None1229 return rv1230 1231 1242-@implements_iterator1232 class 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 unbuffered17 unmodified lines1253 1254 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 = True56 unmodified linesmodified:src/jinja2/exceptions.py+7 added-37 removed
1-# -*- coding: utf-8 -*-2-from ._compat import imap3-from ._compat import implements_to_string4-from ._compat import PY25-from ._compat import text_type6-7-1 class TemplateError(Exception):2 """Baseclass for all template errors."""3 11- if PY2:4+ def __init__(self, message=None):5+ super().__init__(message)6 13- 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]11 18- @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")12 25- def __unicode__(self):26- return self.message or u""27-28- else:29-30- def __init__(self, message=None):31- Exception.__init__(self, message)32-33- @property34- def message(self):35- if self.args:36- message = self.args[0]37- if message is not None:38- return message39-40-41-@implements_to_string13 class TemplateNotFound(IOError, LookupError, TemplateError):14 """Raised if a template does not exist.15 16 .. versionchanged:: 2.1148 unmodified lines65 else:66 parts.append(name)67 68 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)73 74 104-@implements_to_string75 class TemplateSyntaxError(TemplateError):76 """Raised to tell the user that there is a problem with the template."""77 78 def __init__(self, message, lineno, name=None, filename=None):69 unmodified linesmodified:src/jinja2/ext.py+4 added-7 removed
5 unmodified lines6 7 from markupsafe import Markup8 9 from . import nodes10-from ._compat import iteritems11-from ._compat import string_types12-from ._compat import with_metaclass10 from .defaults import BLOCK_END_STRING11 from .defaults import BLOCK_START_STRING12 from .defaults import COMMENT_END_STRING13 from .defaults import COMMENT_START_STRING29 unmodified lines43 rv.identifier = rv.__module__ + "." + rv.__name__44 return rv45 46 50-class Extension(with_metaclass(ExtensionRegistry, object)):47+class 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 (for166 unmodified lines218 for key in "gettext", "ngettext":219 self.environment.globals.pop(key, None)220 221 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)225 226 def parse(self, parser):178 unmodified lines405 # 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 continue136 unmodified lines550 continue551 552 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 linesmodified:src/jinja2/filters.py+35 added-39 removed
1 unmodified line2 """Built-in template filters used with the ``|`` operator."""3 import math4 import random5 import re6+from collections import abc7 from collections import namedtuple8 from itertools import chain9 from itertools import groupby10 11 from markupsafe import escape12 from markupsafe import Markup12-from markupsafe import soft_unicode13+from markupsafe import soft_str14 14-from ._compat import abc15-from ._compat import imap16-from ._compat import iteritems17-from ._compat import string_types18-from ._compat import text_type15 from .exceptions import FilterArgumentError16 from .runtime import Undefined17 from .utils import htmlsafe_json_dumps18 from .utils import pformat23-from .utils import unicode_urlencode19+from .utils import url_quote20 from .utils import urlize21 26-_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({\[<]+)")24 25 26 def contextfilter(f):27 """Decorator for marking context dependent filters. The current24 unmodified lines52 53 def 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 value57 58 59 def make_attrgetter(environment, attribute, postprocess=None, default=None):60 """Returns a callable that looks up the given attribute from a29 unmodified lines90 91 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 lines115 116 def _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 line125 def 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))130 131 132 def do_urlencode(value):133 """Quote data for use in a URL path or query using UTF-8.10 unmodified lines144 ``|replace("/", "%2F")`` filter.145 146 .. 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)150 151 if isinstance(value, dict):156- items = iteritems(value)152+ items = value.items()153 else:154 items = iter(value)155 156 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 )160 161 15 unmodified lines177 """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)191 192 193 def do_upper(s):194 """Convert a value to uppercase."""199- return soft_unicode(s).upper()195+ return soft_str(s).upper()196 197 198 def do_lower(s):199 """Convert a value to lowercase."""204- return soft_unicode(s).lower()200+ return soft_str(s).lower()201 202 203 @evalcontextfilter204 def do_xmlattr(_eval_ctx, d, autospace=True):20 unmodified lines225 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" " + rv5 unmodified lines239 def 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()244 245 246 def do_title(s):247 """Return a titlecased version of the value. I.e. words will start with1 unmodified line249 """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 lines466 .. 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)471 472 # 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))475 476 # 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 lines481 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)491 492 # 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))494 495 496 def 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)499 500 501 @environmentfilter502 def do_first(environment, seq):256 unmodified lines759 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 lines805 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)810 811 812 def 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)815 816 817 def 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()822 823 824 def do_slice(value, slices, fill_with=None):825 """Slice an iterator and return a list of lists containing164 unmodified lines990 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)996 997 998 def do_list(value):11 unmodified lines1010 1011 1012 def 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)1015 1016 1017 def 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 lines1350 "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 linesmodified:src/jinja2/idtracking.py+2 added-3 removed
1-from ._compat import iteritems1 from .visitor import NodeVisitor2 3 VAR_LOAD_PARAMETER = "param"4 VAR_LOAD_RESOLVE = "resolve"107 unmodified lines112 self.refs.update(sym.refs)113 self.loads.update(sym.loads)114 self.stores.update(sym.stores)115 117- 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 lines139 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 rv142 unmodified linesmodified:src/jinja2/lexer.py+5 added-11 removed
6 unmodified lines7 import re8 from ast import literal_eval9 from collections import deque10 from operator import itemgetter11+from sys import intern12 12-from ._compat import implements_iterator13-from ._compat import intern14-from ._compat import iteritems15-from ._compat import text_type13 from .exceptions import TemplateSyntaxError14 from .utils import LRUCache15 16 # cache for the lexers. Exists in order to be able to have multiple17 # environments with the same lexer18 _lexer_cache = LRUCache(50)19 20 # static regular expressions24-whitespace_re = re.compile(r"\s+", re.U)21+whitespace_re = re.compile(r"\s+")22 newline_re = re.compile(r"(\r\n|\r|\n)")23 string_re = re.compile(24 r"('([^'\\]*(?:\\.[^'\\]*)*)'" r'|"([^"\\]*(?:\\.[^"\\]*)*)")', re.S25 )106 unmodified lines132 ",": TOKEN_COMMA,133 ";": TOKEN_SEMICOLON,134 }135 139-reverse_operators = dict([(v, k) for k, v in iteritems(operators)])136+reverse_operators = dict([(v, k) for k, v in operators.items()])137 assert len(operators) == len(reverse_operators), "operators dropped"138 operator_re = re.compile(139 "(%s)" % "|".join(re.escape(x) for x in sorted(operators, key=lambda x: -len(x)))140 )151 unmodified lines292 def __repr__(self):293 return "Token(%r, %r, %r)" % (self.lineno, self.type, self.value)294 295 299-@implements_iterator296 class TokenStreamIterator(object):297 """The iterator for tokenstreams. Iterate over the stream298 until the eof token is reached.299 """12 unmodified lines312 next(self.stream)313 return token314 315 320-@implements_iterator316 class 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 lines659 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 lines737 # 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 break51 unmodified lines797 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 linesmodified:src/jinja2/loaders.py+13 added-22 removed
4 unmodified lines5 import os6 import pkgutil7 import sys8 import weakref9+from collections import abc10 from hashlib import sha111 from importlib import import_module11-from os import path12 from types import ModuleType13 14-from ._compat import abc15-from ._compat import fspath16-from ._compat import iteritems17-from ._compat import string_types14 from .exceptions import TemplateNotFound15 from .utils import internalcode16 from .utils import open_if_exists17 4 unmodified lines22 """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 lines158 The ``followlinks`` parameter was added.159 """160 161 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]164 171- # 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]174-165+ self.searchpath = list(searchpath)166 self.encoding = encoding167 self.followlinks = followlinks168 169 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()180 190- mtime = path.getmtime(filename)181+ mtime = os.path.getmtime(filename)182 183 def uptodate():184 try:194- return path.getmtime(filename) == mtime185+ return os.path.getmtime(filename) == mtime186 except OSError:187 return False188 189 return contents, filename, uptodate203 unmodified lines393 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 rv400 401 44 unmodified lines446 raise TemplateNotFound(name)447 448 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 lines519 # create a fake module that looks for the templates in the520 # path given.521 mod = _TemplateModule(package_name)522 532- 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]525 535- mod.__path__ = [fspath(p) for p in path]526+ mod.__path__ = [os.fspath(p) for p in path]527 528 sys.modules[package_name] = weakref.proxy(529 mod, lambda x: sys.modules.pop(package_name, None)530 )33 unmodified linesmodified:src/jinja2/meta.py+5 added-7 removed
1 unmodified line2 """Functions that expose information about templates that might be3 interesting for introspection.4 """5 from . import nodes6-from ._compat import iteritems7-from ._compat import string_types6 from .compiler import CodeGenerator7 8 9 class TrackingCodeGenerator(CodeGenerator):8 unmodified lines18 19 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)25 26 5 unmodified lines32 33 >>> 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 True38 39 .. admonition:: Implementation40 31 unmodified lines72 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 None1 unmodified line82 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 Nonemodified:src/jinja2/nativetypes.py+2 added-3 removed
2 unmodified lines3 from itertools import chain4 from itertools import islice5 6 from . import nodes7-from ._compat import text_type7 from .compiler import CodeGenerator8 from .compiler import has_safe_repr9 from .environment import Environment10 from .environment import Template20 unmodified lines31 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])36 37 try:38 literal = literal_eval(raw)39 except (ValueError, SyntaxError, MemoryError):10 unmodified lines50 51 52 class 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 """57 58 @staticmethod52 unmodified linesmodified:src/jinja2/nodes.py+6 added-21 removed
6 unmodified lines7 from collections import deque8 9 from markupsafe import Markup10 11-from ._compat import izip12-from ._compat import PY213-from ._compat import text_type14-from ._compat import with_metaclass15-11 _binop_to_func = {12 "*": operator.mul,13 "/": operator.truediv,14 "//": operator.floordiv,28 unmodified lines43 44 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 lines85 return EvalContext(node.environment)86 return ctx87 88 94-class Node(with_metaclass(NodeType, object)):89+class Node(metaclass=NodeType):90 """Baseclass for all Jinja nodes. There are a number of nodes available91 of different types. There are four major types:92 93 - :class:`Stmt`: statements27 unmodified lines121 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 lines504 505 fields = ("value",)506 507 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.value509 510 @classmethod511 def from_untrusted(cls, value, lineno=None, environment=None):512 """Return a const object if the value is representable as267 unmodified lines780 fields = ("nodes",)781 782 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)785 786 787 class Compare(Expr):788 """Compares an expression with some other expressions. `ops` must be a285 unmodified linesmodified:src/jinja2/parser.py+1 added-2 removed
1 # -*- coding: utf-8 -*-2 """Parse tokens from the lexer into nodes for the compiler."""3 from . import nodes4-from ._compat import imap4 from .exceptions import TemplateAssertionError5 from .exceptions import TemplateSyntaxError6 from .lexer import describe_token7 from .lexer import describe_token_expr56 unmodified lines64 65 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 linesmodified:src/jinja2/runtime.py+44 added-116 removed
1 # -*- coding: utf-8 -*-2 """The runtime functions and state used by compiled templates."""3 import sys4+from collections import abc5 from itertools import chain6 from types import MethodType7 8 from markupsafe import escape # noqa: F4019 from markupsafe import Markup9-from markupsafe import soft_unicode10+from markupsafe import soft_str11 11-from ._compat import abc12-from ._compat import imap13-from ._compat import implements_iterator14-from ._compat import implements_to_string15-from ._compat import iteritems16-from ._compat import PY217-from ._compat import string_types18-from ._compat import text_type19-from ._compat import with_metaclass12 from .exceptions import TemplateNotFound # noqa: F40113 from .exceptions import TemplateRuntimeError # noqa: F40114 from .exceptions import UndefinedError15 from .nodes import EvalContext14 unmodified lines30 "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 ]40 50-#: the name of the function that is used to convert something into51-#: a string. We can just use the text type here.52-to_string = text_type41 54-42 def identity(x):43 """Returns its argument. Useful for certain things in the44 environment.45 """2 unmodified lines48 49 def 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)58 59 73-def unicode_join(seq):60+def str_join(seq):61 """Simple args to string conversion and concatenation."""75- return concat(imap(text_type, seq))62+ return concat(map(str, seq))63 64 65+def unicode_join(seq):66+ import warnings67+68+ 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)75+76+77 def new_context(78 environment,79 template_name,80 blocks,13 unmodified lines94 # 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 lines153 return context.parent[key]154 return missing155 156 158-class Context(with_metaclass(ContextMeta)):157+@abc.Mapping.register158+class 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 not27 unmodified lines190 191 # 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()}195 196 # 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 lines303 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 context309 310 def _all(meth): # noqa: B902311 def proxy(self):5 unmodified lines317 318 keys = _all("keys")319 values = _all("values")320 items = _all("items")321-322- # not available on python 3323- if PY2:324- iterkeys = _all("iterkeys")325- itervalues = _all("itervalues")326- iteritems = _all("iteritems")321 del _all322 323 def __contains__(self, name):324 return name in self.vars or name in self.parent14 unmodified lines339 self.name,340 )341 342 349-abc.Mapping.register(Context)350-351-343 class BlockReference(object):344 """One block on a template reference."""345 346 def __init__(self, name, context, stack, depth):18 unmodified lines365 rv = Markup(rv)366 return rv367 368 378-@implements_iterator369 class LoopContext:370 """A wrapper iterable for dynamic ``for`` loops, with information371 about the loop and iteration.372 """304 unmodified lines677 self.name is None and "anonymous" or repr(self.name),678 )679 680 691-@implements_to_string681 class 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 lines716 717 if self._undefined_obj is missing:718 return "%r is undefined" % self._undefined_name719 731- 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 lines740 if name[:2] == "__":741 raise AttributeError(name)742 return self._fail_with_undefined_error()743 755- __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_error754 755 def __eq__(self, other):756 return type(self) is type(other)757 12 unmodified lines770 def __iter__(self):771 if 0:772 yield None773 820- def __nonzero__(self):774+ def __bool__(self):775 return False776 823- __bool__ = __nonzero__824-777 def __repr__(self):778 return "Undefined"779 780 28 unmodified lines809 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 lines841 rv = base.__iter__(self)842 _log_message(self)843 return rv844 893- if PY2:845+ def __bool__(self):846+ rv = base.__bool__(self)847+ _log_message(self)848+ return rv849 895- def __nonzero__(self):896- rv = base.__nonzero__(self)897- _log_message(self)898- return rv899-900- def __unicode__(self):901- rv = base.__unicode__(self)902- _log_message(self)903- return rv904-905- else:906-907- def __bool__(self):908- rv = base.__bool__(self)909- _log_message(self)910- return rv911-850 return LoggingUndefined851 852 915-# 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.853 class ChainableUndefined(Undefined):854 """An undefined that is chainable, where both ``__getattr__`` and855 ``__getitem__`` return itself rather than raising an856 :exc:`UndefinedError`.19 unmodified lines876 877 __getitem__ = __getattr__878 879 945-@implements_to_string880 class DebugUndefined(Undefined):881 """An undefined that returns the debug info when printed.882 883 >>> foo = DebugUndefined(name='foo')19 unmodified lines903 )904 return u"{{ undefined value printed: %s }}" % self._undefined_hint905 906 973-@implements_to_string907 class 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 lines924 jinja2.exceptions.UndefinedError: 'foo' is undefined925 """926 927 __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_error930 931 1004-# 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.934 del (935 Undefined.__slots__,936 ChainableUndefined.__slots__,937 DebugUndefined.__slots__,2 unmodified linesmodified:src/jinja2/sandbox.py+11 added-52 removed
2 unmodified lines3 Useful when the template itself comes from an untrusted source.4 """5 import operator6 import types7+from collections import abc8 from collections import deque9 from string import Formatter10 11 from markupsafe import EscapeFormatter12 from markupsafe import Markup13 13-from ._compat import abc14-from ._compat import PY215-from ._compat import range_type16-from ._compat import string_types14 from .environment import Environment15 from .exceptions import SecurityError16 17 #: maximum number of items a range may produce18 MAX_RANGE = 10000019 23-#: attributes of function objects that are considered unsafe.24-if PY2:25- UNSAFE_FUNCTION_ATTRIBUTES = {26- "func_closure",27- "func_code",28- "func_dict",29- "func_defaults",30- "func_globals",31- }32-else: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.21+UNSAFE_FUNCTION_ATTRIBUTES = set()22 37-#: unsafe method attributes. function attributes are unsafe for methods too38-UNSAFE_METHOD_ATTRIBUTES = {"im_class", "im_func", "im_self"}23+#: Unsafe method attributes. Function attributes are unsafe for methods too.24+UNSAFE_METHOD_ATTRIBUTES = set()25 26 #: unsafe generator attributes.27 UNSAFE_GENERATOR_ATTRIBUTES = {"gi_frame", "gi_code"}28 2 unmodified lines31 32 #: unsafe attributes on async generators33 UNSAFE_ASYNC_GENERATOR_ATTRIBUTES = {"ag_code", "ag_frame"}34 49-_mutable_set_types = (set,)50-_mutable_mapping_types = (dict,)51-_mutable_sequence_types = (list,)52-53-# on python 2.x we can register the user collection types54-try:55- from UserDict import UserDict, DictMixin56- from UserList import UserList57-58- _mutable_mapping_types += (UserDict, DictMixin)59- _mutable_set_types += (UserList,)60-except ImportError:61- pass62-63-# if sets is still available, register the mutable set from there as well64-try:65- from sets import Set66-67- _mutable_set_types += (Set,)68-except ImportError:69- pass70-71-#: register Python 2.6 abstract base classes72-_mutable_set_types += (abc.MutableSet,)73-_mutable_mapping_types += (abc.MutableMapping,)74-_mutable_sequence_types += (abc.MutableSequence,)75-35 _mutable_spec = (36 (78- _mutable_set_types,37+ abc.MutableSet,38 frozenset(39 [40 "add",41 "clear",6 unmodified lines48 ]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 lines111 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 obj117 118 119 def 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)124 125 if len(rng) > MAX_RANGE:126 raise OverflowError(127 "Range too big. The sandbox blocks ranges larger than"206 unmodified lines334 """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 pass120 unmodified linesmodified:src/jinja2/tests.py+7 added-10 removed
1 # -*- coding: utf-8 -*-2 """Built-in template tests used with the ``is`` operator."""3-import decimal3 import operator4 import re5+from collections import abc6+from numbers import Number7 7-from ._compat import abc8-from ._compat import integer_types9-from ._compat import string_types10-from ._compat import text_type8 from .runtime import Undefined9 10 number_re = re.compile(r"^-?\d+(\.\d+)?$")11 regex_type = type(number_re)71 unmodified lines83 """Return true if the object is an integer.84 85 .. 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 False88 89 90 # NOTE: The existing 'number' test matches booleans and integers91 def test_float(value):5 unmodified lines97 98 99 def test_lower(value):100 """Return true if the variable is lowercased."""104- return text_type(value).islower()101+ return str(value).islower()102 103 104 def test_upper(value):105 """Return true if the variable is uppercased."""109- return text_type(value).isupper()106+ return str(value).isupper()107 108 109 def test_string(value):110 """Return true if the object is a string."""114- return isinstance(value, string_types)111+ return isinstance(value, str)112 113 114 def test_mapping(value):115 """Return true if the object is a mapping (dict etc.).4 unmodified lines120 121 122 def 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)125 126 127 def test_sequence(value):128 """Return true if the variable is a sequence. Sequences are variables84 unmodified linesmodified:src/jinja2/utils.py+22 added-18 removed
1 # -*- coding: utf-8 -*-2 import json3 import os4 import re5+from collections import abc6 from collections import deque7 from random import choice8 from random import randrange9 from threading import Lock10+from urllib.parse import quote_from_bytes11 12 from markupsafe import escape13 from markupsafe import Markup14 13-from ._compat import abc14-from ._compat import string_types15-from ._compat import text_type16-from ._compat import url_quote17-15 _word_split_re = re.compile(r"(\s+)")16 _punctuation_re = re.compile(17 "^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$"18 % (182 unmodified lines201 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 ""208 209 for i, word in enumerate(words):210 match = _punctuation_re.match(word)84 unmodified lines295 return u"\n\n".join(result)296 return Markup(u"\n".join(u"<p>%s</p>" % escape(x) for x in result))297 298 302-def unicode_urlencode(obj, charset="utf-8", for_qs=False):299+def url_quote(obj, charset="utf-8", for_qs=False):300 """Quote a string for use in a URL using the given charset.301 302 This function is misnamed, it is a wrapper around303 :func:`urllib.parse.quote`.2 unmodified lines306 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)313 316- if isinstance(obj, text_type):314 obj = obj.encode(charset)315 316 safe = b"" if for_qs else b"/"320- rv = url_quote(obj, safe)317+ rv = quote_from_bytes(obj, safe)318 322- if not isinstance(rv, text_type):323- rv = rv.decode("utf-8")324-319 if for_qs:320 rv = rv.replace("%20", "+")321 322 return rv323 324 325+def unicode_urlencode(obj, charset="utf-8", for_qs=False):326+ import warnings327+328+ 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)335+336+337+@abc.MutableMapping.register338 class LRUCache(object):339 """A simple LRU Cache implementation."""340 341 # this is fast for small capacities (something below 1000) but doesn't148 unmodified lines490 491 __copy__ = copy492 493 487-abc.MutableMapping.register(LRUCache)488-489-494 def select_autoescape(495 enabled_extensions=("html", "htm", "xml"),496 disabled_extensions=(),497 default_for_string=True,179 unmodified linesmodified:tests/test_ext.py+3 added-5 removed
1 # -*- coding: utf-8 -*-2 import re3+from io import BytesIO4 5 import pytest6 7 from jinja2 import contextfunction8 from jinja2 import DictLoader9 from jinja2 import Environment10 from jinja2 import nodes10-from jinja2._compat import BytesIO11-from jinja2._compat import itervalues12-from jinja2._compat import text_type11 from jinja2.exceptions import TemplateAssertionError12 from jinja2.ext import Extension13 from jinja2.lexer import count_newlines14 from jinja2.lexer import Token213 unmodified lines228 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 env234 235 def test_preprocessor_extension(self):236 env = Environment(extensions=[PreprocessorExtension])379 unmodified lines616 {{ '<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"621 622 # 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 linesmodified:tests/test_features.py-29 removed
1-import sys2-1 import pytest2 5-from jinja2 import contextfilter6-from jinja2 import Environment3 from jinja2 import Template8-from jinja2._compat import text_type4 5 11-@pytest.mark.skipif(sys.version_info < (3, 5), reason="Requires 3.5 or later")6 def test_generator_stop():7 class X(object):8 def __getattr__(self, name):9 raise StopIteration()10 11 t = Template("a{{ bad.bar() }}b")12 with pytest.raises(RuntimeError):13 t.render(bad=X())20-21-22-@pytest.mark.skipif(sys.version_info[0] > 2, reason="Feature only supported on 2.x")23-def test_ascii_str():24- @contextfilter25- def assert_func(context, value):26- assert type(value) is context["expected_type"]27-28- env = Environment()29- env.filters["assert"] = assert_func30-31- env.policies["compiler.ascii_str"] = False32- t = env.from_string('{{ "foo"|assert }}')33- t.render(expected_type=text_type)34-35- env.policies["compiler.ascii_str"] = True36- t = env.from_string('{{ "foo"|assert }}')37- t.render(expected_type=str)38-39- 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 lines5 import pytest6 7 from jinja2 import Environment8 from jinja2 import Markup9-from jinja2._compat import implements_to_string10-from jinja2._compat import text_type9 10 13-@implements_to_string11 class Magic(object):12 def __init__(self, value):13 self.value = value14 15 def __str__(self):19- return text_type(self.value)16+ return str(self.value)17 18 22-@implements_to_string19 class Magic2(object):20 def __init__(self, value1, value2):21 self.value1 = value122 self.value2 = value223 24 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))26 27 28 @pytest.mark.filter29 class TestFilter(object):246 unmodified lines276 277 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)281 282 def test_title(self, env):283 tmpl = env.from_string("""{{ "foo bar"|title }}""")284 assert tmpl.render() == "Foo Bar"457 unmodified linesmodified:tests/test_lexnparse.py+22 added-36 removed
4 unmodified lines5 from jinja2 import nodes6 from jinja2 import Template7 from jinja2 import TemplateSyntaxError8 from jinja2 import UndefinedError9-from jinja2._compat import iteritems10-from jinja2._compat import PY211-from jinja2._compat import text_type9 from jinja2.lexer import Token10 from jinja2.lexer import TOKEN_BLOCK_BEGIN11 from jinja2.lexer import TOKEN_BLOCK_END12 from jinja2.lexer import TOKEN_EOF13 from jinja2.lexer import TokenStream14 15 19-# how does a string look like in jinja syntax?20-if PY2:21-22- def jinja_string_repr(string):23- return repr(string)[1:]24-25-26-else:27- jinja_string_repr = repr28-29-16 @pytest.mark.lexnparse17 @pytest.mark.tokenstream18 class TestTokenStream(object):19 test_tokens = [76 unmodified lines96 )97 98 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"103 104 def test_bytefallback(self, env):4 unmodified lines109 110 def test_operators(self, env):111 from jinja2.lexer import operators112 127- 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 lines138 result = tmpl.render()139 assert result == expect, (keep, template, result, expect)140 141 @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" }}"164 179- 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 lines513 assert tmpl.render(bar=bar) == "False"514 515 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"518 519 def test_implicit_subscribed_tuple(self, env):520 class Foo(object):521 def __getitem__(self, x):295 unmodified linesmodified:tests/test_loader.py+2 added-22 removed
1 # -*- coding: utf-8 -*-2 import os3+import platform4 import shutil5 import sys6 import tempfile7 import time3 unmodified lines11 12 from jinja2 import Environment13 from jinja2 import loaders14 from jinja2 import PackageLoader14-from jinja2._compat import PY215-from jinja2._compat import PYPY15 from jinja2.exceptions import TemplateNotFound16 from jinja2.loaders import split_template_path17 18 117 unmodified lines136 137 env = Environment(loader=filesystem_loader)138 self._test_common(env)139 141- @pytest.mark.skipif(PY2, reason="pathlib is not available in Python 2")140 def test_searchpath_as_pathlib(self):141 import pathlib142 143 searchpath = pathlib.Path(self.searchpath)146-144 filesystem_loader = loaders.FileSystemLoader(searchpath)148-145 env = Environment(loader=filesystem_loader)146 self._test_common(env)147 152- @pytest.mark.skipif(PY2, reason="pathlib is not available in Python 2")148 def test_searchpath_as_list_including_pathlib(self):149 import pathlib150 151 searchpath = pathlib.Path(self.searchpath)157-152 filesystem_loader = loaders.FileSystemLoader(["/tmp/templates", searchpath])159-153 env = Environment(loader=filesystem_loader)154 self._test_common(env)155 156 def test_caches_template_based_on_mtime(self):100 unmodified lines257 pass258 259 assert name not in sys.modules260 268- # 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")278-261 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 lines280 assert tmpl1.render() == "BAR"281 tmpl2 = self.mod_env.get_template("DICT/test.html")282 assert tmpl2.render() == "DICT_TEMPLATE"283 302- @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)286 287 mod_path = self.mod_env.loader.module.__path__[0]4 unmodified lines292 self.mod_env = Environment(loader=mod_loader)293 294 self._test_common()295 315- @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)298 299 mod_path = self.mod_env.loader.module.__path__[0]46 unmodified lines346 assert up_to_date is None347 348 349 @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 )354 def test_package_zip_list(package_zip_loader):1 unmodified linemodified:tests/test_nativetypes.py+2 added-3 removed
1 import pytest2 3-from jinja2._compat import text_type3 from jinja2.exceptions import UndefinedError4 from jinja2.nativetypes import NativeEnvironment5 from jinja2.nativetypes import NativeTemplate6 from jinja2.runtime import Undefined44 unmodified lines51 52 def 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"57 58 59 def test_loops_with_ints(env):49 unmodified lines109 110 def 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]"115 116 117 def test_string_top_level(env):21 unmodified linesmodified:tests/test_regression.py+1 added-11 removed
1 # -*- coding: utf-8 -*-2-import sys3-2 import pytest3 4 from jinja2 import DictLoader5 from jinja2 import Environment1 unmodified line7 from jinja2 import Template8 from jinja2 import TemplateAssertionError9 from jinja2 import TemplateNotFound10 from jinja2 import TemplateSyntaxError13-from jinja2._compat import text_type11 12 13 @pytest.mark.regression14 class TestCorner(object):115 unmodified lines130 131 """132 )133 137- 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)] * 5135 136 def test_weird_inline_comment(self, env):137 env = Environment(line_statement_prefix="%")138 pytest.raises(165 unmodified lines304 expected = "TEST"305 306 assert output == expected307 311- @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 = 42315-316- assert env.getitem(Foo(), "x") == 42317-308 def test_block_set_with_extends(self):309 env = Environment(310 loader=DictLoader({"main": "{% block body %}[{{ x }}]{% endblock %}"})311 )305 unmodified linesmodified:tests/test_security.py+1 added-41 removed
1 unmodified line2 import pytest3 4 from jinja2 import Environment5 from jinja2 import escape6-from jinja2 import Markup7-from jinja2._compat import text_type6 from jinja2.exceptions import SecurityError7 from jinja2.exceptions import TemplateRuntimeError8 from jinja2.exceptions import TemplateSyntaxError9 from jinja2.nodes import EvalContext64 unmodified lines74 env.from_string,75 "{% for foo, bar.baz in seq %}...{% endfor %}",76 )77 80- 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)85-86- # string interpolations are safe to use too87- assert Markup("<em>%s</em>") % "<bad user>" == "<em><bad user></em>"88- assert (89- Markup("<em>%(username)s</em>") % {"username": "<bad user>"}90- == "<em><bad user></em>"91- )92-93- # an escaped object is markup too94- assert type(Markup("foo") + "bar") is Markup95-96- # and it implements __html__ by returning itself97- x = Markup("foo")98- assert x.__html__() is x99-100- # it also knows how to treat __html__ objects101- class Foo(object):102- def __html__(self):103- return "<em>awesome</em>"104-105- def __unicode__(self):106- return "awesome"107-108- assert Markup(Foo()) == "<em>awesome</em>"109- assert (110- Markup("<strong>%s</strong>") % Foo() == "<strong><em>awesome</em></strong>"111- )112-113- # escaping and unescaping114- assert escape("\"<>&'") == ""<>&'"115- assert Markup("<em>Foo & Bar</em>").striptags() == "Foo & Bar"116- assert Markup("<test>").unescape() == "<test>"117-78 def test_template_data(self, env):79 env = Environment(autoescape=True)80 t = env.from_string(81 "{% macro say_hello(name) %}"1 unmodified line83 '{{ say_hello("<blink>foo</blink>") }}'84 )85 escaped_out = "<p>Hello <blink>foo</blink>!</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 linesmodified:tests/test_utils.py+6 added-8 removed
5 unmodified lines6 7 import pytest8 from markupsafe import Markup9 10-from jinja2._compat import range_type11-from jinja2._compat import string_types10 from jinja2.utils import consume11 from jinja2.utils import generate_lorem_ipsum12 from jinja2.utils import LRUCache13 from jinja2.utils import missing148 unmodified lines162 assert isinstance(generate_lorem_ipsum(), Markup)163 164 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)167 168 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) * 2173 174 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 - 1180 181 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 - 1187 188 189 def test_missing():10 unmodified lines