Skip to content
Myr

Merge branch 'stable'

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 · parents d680a95, ab8218c · Browse files · 38 files+584 added−213 removed
This commit

State

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

Diff stats

38 files+584 added−213 removed

  • tests:+248 added−8 removed
  • other:+336 added−205 removed

38 files+584 added−213 removed

modified:.github/workflows/publish.yaml+2 added-6 removed
modified:.github/workflows/tests.yaml+1 added-1 removed
modified:docs/api.rst+2 added-2 removed
664 unmodified lines
665Now it can be used in templates:666667.. sourcecode:: jinja668669 {{ article.pub_date|datetimeformat }}670 {{ article.pub_date|datetimeformat("%B %Y") }}669 {{ article.pub_date|datetime_format }}670 {{ article.pub_date|datetime_format("%B %Y") }}671672Some decorators are available to tell Jinja to pass extra information to673the filter. The object is passed as the first argument, making the value674being filtered the second argument.
245 unmodified lines
modified:docs/conf.py+1 added-1 removed
22 unmodified lines
23autodoc_preserve_defaults = True24extlinks = {25 "issue": ("https://github.com/pallets/jinja/issues/%s", "#%s"),26 "pr": ("https://github.com/pallets/jinja/pull/%s", "#%s"),27 "ghsa": ("https://github.com/advisories/GHSA-%s", "GHSA-%s"),27 "ghsa": ("https://github.com/pallets/jinja/security/advisories/GHSA-%s", "GHSA-%s"),28}29intersphinx_mapping = {30 "python": ("https://docs.python.org/3/", None),31}
24 unmodified lines
modified:docs/faq.rst+3 added-1 removed
68 unmodified lines
69these document types.7071While automatic escaping means that you are less likely have an XSS72problem, it also requires significant extra processing during compiling73and rendering, which can reduce performance. Jinja uses MarkupSafe for73and rendering, which can reduce performance. Jinja uses `MarkupSafe`_ for74escaping, which provides optimized C code for speed, but it still75introduces overhead to track escaping across methods and formatting.7677.. _MarkupSafe: https://markupsafe.palletsprojects.com/
modified:docs/nativetypes.rst+11 added
53 unmodified lines
54Foo55>>> print(result.value)56155758Sandboxed Native Environment59----------------------------6061You can combine :class:`.SandboxedEnvironment` and :class:`NativeEnvironment` to62get both behaviors.6364.. code-block:: python6566 class SandboxedNativeEnvironment(SandboxedEnvironment, NativeEnvironment):67 pass6869API70---7172.. autoclass:: NativeEnvironment([options])
3 unmodified lines
modified:docs/templates.rst+49 added-36 removed
200 unmodified lines
201option can also be set to strip tabs and spaces from the beginning of a202line to the start of a block. (Nothing will be stripped if there are203other characters before the start of the block.)204205With both `trim_blocks` and `lstrip_blocks` enabled, you can put block tags206on their own lines, and the entire block line will be removed when207rendered, preserving the whitespace of the contents. For example,208without the `trim_blocks` and `lstrip_blocks` options, this template::205With both ``trim_blocks`` and ``lstrip_blocks`` disabled (the default), block206tags on their own lines will be removed, but a blank line will remain and the207spaces in the content will be preserved. For example, this template:208209.. code-block:: jinja210211 <div>212 {% if True %}213 yay214 {% endif %}215 </div>216216gets rendered with blank lines inside the div::217With both ``trim_blocks`` and ``lstrip_blocks`` disabled, the template is218rendered with blank lines inside the div:219220.. code-block:: text221222 <div>223224 yay225226 </div>227224But with both `trim_blocks` and `lstrip_blocks` enabled, the template block225lines are removed and other whitespace is preserved::228With both ``trim_blocks`` and ``lstrip_blocks`` enabled, the template block229lines are completely removed:230231.. code-block:: text232233 <div>234 yay235 </div>236
290 unmodified lines
527528Block Nesting and Scope529~~~~~~~~~~~~~~~~~~~~~~~530525Blocks can be nested for more complex layouts. However, per default blocks526may not access variables from outer scopes::531Blocks can be nested for more complex layouts. By default, a block may not532access variables from outside the block (outer scopes)::533534 {% for item in seq %}535 <li>{% block loop_item %}{{ item }}{% endblock %}</li>536 {% endfor %}
548 unmodified lines
10851086Block Assignments1087~~~~~~~~~~~~~~~~~10881083.. versionadded:: 2.81089It's possible to use `set` as a block to assign the content of the block to a1090variable. This can be used to create multi-line strings, since Jinja doesn't1091support Python's triple quotes (``"""``, ``'''``).10921085Starting with Jinja 2.8, it's possible to also use block assignments to1086capture the contents of a block into a variable name. This can be useful1087in some situations as an alternative for macros. In that case, instead of1088using an equals sign and a value, you just write the variable name and then1089everything until ``{% endset %}`` is captured.1093Instead of using an equals sign and a value, you only write the variable name,1094and everything until ``{% endset %}`` is captured.10951091Example::1096.. code-block:: jinja10971098 {% set navigation %}1099 <li><a href="/">Index</a>1100 <li><a href="/downloads">Downloads</a>1101 {% endset %}11021098The `navigation` variable then contains the navigation HTML source.1103Filters applied to the variable name will be applied to the block's content.11041100.. versionchanged:: 2.101105.. code-block:: jinja11061102Starting with Jinja 2.10, the block assignment supports filters.11031104Example::11051107 {% set reply | wordwrap %}1108 You wrote:1109 {{ message }}1110 {% endset %}11111112.. versionadded:: 2.811131114.. versionchanged:: 2.1011151116 Block assignment supports filters.11171118.. _extends:11191120Extends1121~~~~~~~
289 unmodified lines
14111412Logic1413~~~~~14141409For ``if`` statements, ``for`` filtering, and ``if`` expressions, it can be useful to1410combine multiple expressions:1415For ``if`` statements, ``for`` filtering, and ``if`` expressions, it can be1416useful to combine multiple expressions.14171418``and``1413 Return true if the left and the right operand are true.1419 For ``x and y``, if ``x`` is false, then the value is ``x``, else ``y``. In1420 a boolean context, this will be treated as ``True`` if both operands are1421 truthy.14221423``or``1416 Return true if the left or the right operand are true.1424 For ``x or y``, if ``x`` is true, then the value is ``x``, else ``y``. In a1425 boolean context, this will be treated as ``True`` if at least one operand is1426 truthy.14271428``not``1419 negate a statement (see below).1429 For ``not x``, if ``x`` is false, then the value is ``True``, else1430 ``False``.14311421``(expr)``1422 Parentheses group an expression.14231424.. admonition:: Note14251426 The ``is`` and ``in`` operators support negation using an infix notation,1427 too: ``foo is not bar`` and ``foo not in bar`` instead of ``not foo is bar``1428 and ``not foo in bar``. All other expressions require a prefix notation:1432 Prefer negating ``is`` and ``in`` using their infix notation:1433 ``foo is not bar`` instead of ``not foo is bar``; ``foo not in bar`` instead1434 of ``not foo in bar``. All other expressions require prefix notation:1435 ``not (foo and bar).``14361437``(expr)``1438 Parentheses group an expression. This is used to change evaluation order, or1439 to make a long expression easier to read or less ambiguous.144014411442Other Operators1443~~~~~~~~~~~~~~~14441445The following operators are very useful but don't fit into any of the other
231 unmodified lines
1677 Found item having something: {{ ns.found }}16781679 .. versionadded:: 2.1016801681 .. versionchanged:: 3.21682 Namespace attributes can be assigned to in multiple assignment.168316841685Extensions1686----------16871688.. py:currentmodule:: jinja2
101 unmodified lines
1790It's possible to translate strings in expressions with these functions:17911792- ``_(message)``: Alias for ``gettext``.1793- ``gettext(message)``: Translate a message.1781- ``ngettext(singluar, plural, n)``: Translate a singular or plural1794- ``ngettext(singular, plural, n)``: Translate a singular or plural1795 message based on a count variable.1796- ``pgettext(context, message)``: Like ``gettext()``, but picks the1797 translation based on the context string.1798- ``npgettext(context, singular, plural, n)``: Like ``npgettext()``,
167 unmodified lines
modified:docs/tricks.rst+1 added-1 removed
19 unmodified lines
2021Usually child templates extend from one template that adds a basic HTML22skeleton. However it's possible to put the `extends` tag into an `if` tag to23only extend from the layout template if the `standalone` variable evaluates24to false which it does per default if it's not defined. Additionally a very24to false, which it does by default if it's not defined. Additionally a very25basic skeleton is added to the file so that if it's indeed rendered with26`standalone` set to `True` a very basic HTML skeleton is added::2728 {% if not standalone %}{% extends 'default.html' %}{% endif -%}
72 unmodified lines
modified:examples/basic/test.py+2 added-2 removed
4 unmodified lines
5 loader=DictLoader(6 {7 "child.html": """\8{% extends default_layout or 'default.html' %}9{% include helpers = 'helpers.html' %}9{% import 'helpers.html' as helpers %}10{% macro get_the_answer() %}42{% endmacro %}11{% title = 'Hello World' %}11{% set title = 'Hello World' %}12{% block body %}13 {{ get_the_answer() }}14 {{ helpers.conspirate() }}15{% endblock %}
14 unmodified lines
modified:requirements/build.txt+1 added-1 removed
4 unmodified lines
5# pip-compile build.in6#7build==1.2.2.post18 # via -r build.in9packaging==24.19packaging==24.210 # via build11pyproject-hooks==1.2.012 # via build
modified:requirements/dev.txt+16 added-16 removed
4 unmodified lines
5# pip-compile dev.in6#7alabaster==1.0.08 # via sphinx9attrs==24.2.09attrs==24.3.010 # via11 # outcome12 # trio13babel==2.16.0
1 unmodified line
15build==1.2.2.post116 # via pip-tools17cachetools==5.5.018 # via tox19certifi==2024.8.3019certifi==2024.12.1420 # via requests21cfgv==3.4.022 # via pre-commit23chardet==5.2.0
13 unmodified lines
37filelock==3.16.138 # via39 # tox40 # virtualenv41identify==2.6.141identify==2.6.342 # via pre-commit43idna==3.1044 # via45 # requests
5 unmodified lines
51jinja2==3.1.452 # via sphinx53markupsafe==3.0.254 # via jinja255mypy==1.13.056 # via -r typing.in55mypy==1.14.056 # via -r /Users/david/Projects/jinja/requirements/typing.in57mypy-extensions==1.0.058 # via mypy59nodeenv==1.9.160 # via pre-commit61outcome==1.3.0.post062 # via trio63packaging==24.163packaging==24.264 # via65 # build66 # pallets-sphinx-themes67 # pyproject-api68 # pytest69 # sphinx70 # tox71pallets-sphinx-themes==2.3.072 # via -r docs.in73pip-compile-multi==2.6.472 # via -r /Users/david/Projects/jinja/requirements/docs.in73pip-compile-multi==2.7.174 # via -r dev.in75pip-tools==7.4.176 # via pip-compile-multi77platformdirs==4.3.6
13 unmodified lines
91pyproject-hooks==1.2.092 # via93 # build94 # pip-tools95pytest==8.3.396 # via -r tests.in95pytest==8.3.496 # via -r /Users/david/Projects/jinja/requirements/tests.in97pyyaml==6.0.298 # via pre-commit99requests==2.32.3100 # via sphinx
4 unmodified lines
105sortedcontainers==2.4.0106 # via trio107sphinx==8.1.3108 # via109 # -r docs.in109 # -r /Users/david/Projects/jinja/requirements/docs.in110 # pallets-sphinx-themes111 # sphinx-issues112 # sphinx-notfound-page113 # sphinxcontrib-log-cabinet114sphinx-issues==5.0.0115 # via -r docs.in115 # via -r /Users/david/Projects/jinja/requirements/docs.in116sphinx-notfound-page==1.0.4117 # via pallets-sphinx-themes118sphinxcontrib-applehelp==2.0.0119 # via sphinx
3 unmodified lines
123 # via sphinx124sphinxcontrib-jsmath==1.0.1125 # via sphinx126sphinxcontrib-log-cabinet==1.0.1127 # via -r docs.in127 # via -r /Users/david/Projects/jinja/requirements/docs.in128sphinxcontrib-qthelp==2.0.0129 # via sphinx130sphinxcontrib-serializinghtml==2.0.0131 # via sphinx
1 unmodified line
133 # via pip-compile-multi134tox==4.23.2135 # via -r dev.in136trio==0.27.0137 # via -r tests.in137 # via -r /Users/david/Projects/jinja/requirements/tests.in138typing-extensions==4.12.2139 # via mypy140urllib3==2.2.3141 # via requests142virtualenv==20.27.0142virtualenv==20.28.0143 # via144 # pre-commit145 # tox146wheel==0.44.0146wheel==0.45.1147 # via pip-tools148149# The following packages are considered to be unsafe in a requirements file:150# pip
1 unmodified line
modified:requirements/docs.txt+2 added-2 removed
6 unmodified lines
7alabaster==1.0.08 # via sphinx9babel==2.16.010 # via sphinx11certifi==2024.8.3011certifi==2024.12.1412 # via requests13charset-normalizer==3.4.014 # via requests15docutils==0.21.2
5 unmodified lines
21jinja2==3.1.422 # via sphinx23markupsafe==3.0.224 # via jinja225packaging==24.125packaging==24.226 # via27 # pallets-sphinx-themes28 # sphinx29pallets-sphinx-themes==2.3.0
34 unmodified lines
modified:requirements/tests.txt+3 added-3 removed
2 unmodified lines
3# by the following command:4#5# pip-compile tests.in6#7attrs==24.2.07attrs==24.3.08 # via9 # outcome10 # trio11idna==3.10
1 unmodified line
13iniconfig==2.0.014 # via pytest15outcome==1.3.0.post016 # via trio17packaging==24.117packaging==24.218 # via pytest19pluggy==1.5.020 # via pytest21pytest==8.3.321pytest==8.3.422 # via -r tests.in23sniffio==1.3.124 # via trio25sortedcontainers==2.4.0
3 unmodified lines
modified:requirements/typing.txt+1 added-1 removed
2 unmodified lines
3# by the following command:4#5# pip-compile typing.in6#7mypy==1.13.07mypy==1.14.08 # via -r typing.in9mypy-extensions==1.0.010 # via mypy11typing-extensions==4.12.2
1 unmodified line
modified:src/jinja2/compiler.py+37 added-15 removed
214 unmodified lines
215 # expression as it determines which errors should be raised during runtime216 # or compile time.217 self.soft_frame = False218219 def copy(self) -> "Frame":219 def copy(self) -> "te.Self":220 """Create a copy of the current one."""221 rv = object.__new__(self.__class__)222 rv.__dict__.update(self.__dict__)223 rv.symbols = self.symbols.copy()
4 unmodified lines
228 if isolated:229 return Frame(self.eval_ctx, level=self.symbols.level + 1)230 return Frame(self.eval_ctx, self)231232 def soft(self) -> "Frame":232 def soft(self) -> "te.Self":233 """Return a soft frame. A soft frame may not be modified as234 standalone thing as it shares the resources with the frame it235 was created of, but it's not a rootlevel frame any longer.236
573 unmodified lines
810 elif frame.block_frame:811 self.writeline("_block_vars.update({")812 else:813 self.writeline("context.vars.update({")814 for idx, name in enumerate(vars):814 for idx, name in enumerate(sorted(vars)):815 if idx:816 self.write(", ")817 ref = frame.symbols.ref(name)818 self.write(f"{name!r}: {ref}")
1 unmodified line
820 if not frame.block_frame and not frame.loop_frame and public_names:821 if len(public_names) == 1:822 self.writeline(f"context.exported_vars.add({public_names[0]!r})")823 else:824 names_str = ", ".join(map(repr, public_names))824 names_str = ", ".join(map(repr, sorted(public_names)))825 self.writeline(f"context.exported_vars.update(({names_str}))")826827 # -- Statement Visitors828
311 unmodified lines
1140 f" getattr(included_template, {name!r}, missing)"1141 )1142 self.writeline(f"if {frame.symbols.ref(alias)} is missing:")1143 self.indent()1144 # The position will contain the template name, and will be formatted1145 # into a string that will be compiled into an f-string. Curly braces1146 # in the name must be replaced with escapes so that they will not be1147 # executed as part of the f-string.1148 position = self.position(node).replace("{", "{{").replace("}", "}}")1149 message = (1150 "the template {included_template.__name__!r}"1146 f" (imported on {self.position(node)})"1151 f" (imported on {position})"1152 f" does not export the requested name {name!r}"1153 )1154 self.writeline(1155 f"{frame.symbols.ref(alias)} = undefined(f{message!r}, name={name!r})"
424 unmodified lines
1580 self.outdent()15811582 def visit_Assign(self, node: nodes.Assign, frame: Frame) -> None:1583 self.push_assign_tracking()15841585 # ``a.b`` is allowed for assignment, and is parsed as an NSRef. However,1586 # it is only valid if it references a Namespace object. Emit a check for1587 # that for each ref here, before assignment code is emitted. This can't1588 # be done in visit_NSRef as the ref could be in the middle of a tuple.1589 seen_refs: t.Set[str] = set()15901591 for nsref in node.find_all(nodes.NSRef):1592 if nsref.name in seen_refs:1593 # Only emit the check for each reference once, in case the same1594 # ref is used multiple times in a tuple, `ns.a, ns.b = c, d`.1595 continue15961597 seen_refs.add(nsref.name)1598 ref = frame.symbols.ref(nsref.name)1599 self.writeline(f"if not isinstance({ref}, Namespace):")1600 self.indent()1601 self.writeline(1602 "raise TemplateRuntimeError"1603 '("cannot assign attribute on non-namespace object")'1604 )1605 self.outdent()16061607 self.newline(node)1608 self.visit(node.target, frame)1609 self.write(" = ")1610 self.visit(node.node, frame)
48 unmodified lines
16591660 self.write(ref)16611662 def visit_NSRef(self, node: nodes.NSRef, frame: Frame) -> None:1635 # NSRefs can only be used to store values; since they use the normal1636 # `foo.bar` notation they will be parsed as a normal attribute access1637 # when used anywhere but in a `set` context1663 # NSRef is a dotted assignment target a.b=c, but uses a[b]=c internally.1664 # visit_Assign emits code to validate that each ref is to a Namespace1665 # object only. That can't be emitted here as the ref could be in the1666 # middle of a tuple assignment.1667 ref = frame.symbols.ref(node.name)1639 self.writeline(f"if not isinstance({ref}, Namespace):")1640 self.indent()1641 self.writeline(1642 "raise TemplateRuntimeError"1643 '("cannot assign attribute on non-namespace object")'1644 )1645 self.outdent()1668 self.writeline(f"{ref}[{node.attr!r}]")16691670 def visit_Const(self, node: nodes.Const, frame: Frame) -> None:1671 val = node.as_const(frame.eval_ctx)
327 unmodified lines
modified:src/jinja2/environment.py+7 added-4 removed
123 unmodified lines
124125 return result126127128def _environment_config_check(environment: "Environment") -> "Environment":128def _environment_config_check(environment: _env_bound) -> _env_bound:129 """Perform a sanity check on the environment."""130 assert issubclass(131 environment.undefined, Undefined132 ), "'undefined' must be a subclass of 'jinja2.Undefined'."
274 unmodified lines
407 loader: t.Optional["BaseLoader"] = missing,408 cache_size: int = missing,409 auto_reload: bool = missing,410 bytecode_cache: t.Optional["BytecodeCache"] = missing,411 enable_async: bool = False,412 ) -> "Environment":411 enable_async: bool = missing,412 ) -> "te.Self":413 """Create a new overlay environment that shares all the data with the414 current environment except for cache and the overridden attributes.415 Extensions cannot be removed for an overlayed environment. An overlayed416 environment automatically gets all the extensions of the environment it
3 unmodified lines
420 up completely. Not all attributes are truly linked, some are just421 copied over so modifications on the original environment may not shine422 through.423424 .. versionchanged:: 3.1.5425 ``enable_async`` is applied correctly.426427 .. versionchanged:: 3.1.2425 Added the ``newline_sequence``,, ``keep_trailing_newline``,428 Added the ``newline_sequence``, ``keep_trailing_newline``,429 and ``enable_async`` parameters to match ``__init__``.430 """431 args = dict(locals())432 del args["self"], args["cache_size"], args["extensions"], args["enable_async"]
1242 unmodified lines
modified:src/jinja2/ext.py+1 added-1 removed
87 unmodified lines
8889 def __init__(self, environment: Environment) -> None:90 self.environment = environment9192 def bind(self, environment: Environment) -> "Extension":92 def bind(self, environment: Environment) -> "te.Self":93 """Create a copy of this extension bound to another environment."""94 rv = object.__new__(self.__class__)95 rv.__dict__.update(self.__dict__)96 rv.environment = environment
758 unmodified lines
modified:src/jinja2/filters.py+19 added-7 removed
436 unmodified lines
437 return sorted(value, key=key_func, reverse=reverse)438439440@pass_environment441def do_unique(441def sync_do_unique(442 environment: "Environment",443 value: "t.Iterable[V]",444 case_sensitive: bool = False,445 attribute: t.Optional[t.Union[str, int]] = None,
23 unmodified lines
469 seen.add(key)470 yield item471472473@async_variant(sync_do_unique) # type: ignore474async def do_unique(475 environment: "Environment",476 value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",477 case_sensitive: bool = False,478 attribute: t.Optional[t.Union[str, int]] = None,479) -> "t.Iterator[V]":480 return sync_do_unique(481 environment, await auto_to_list(value), case_sensitive, attribute482 )483484485def _min_or_max(486 environment: "Environment",487 value: "t.Iterable[V]",488 func: "t.Callable[..., V]",
509 unmodified lines
998 except (TypeError, ValueError):999 # this quirk is necessary so that "42.23"|int gives 42.1000 try:1001 return int(float(value))990 except (TypeError, ValueError):1002 except (TypeError, ValueError, OverflowError):1003 return default100410051006def do_float(value: t.Any, default: float = 0.0) -> float:
633 unmodified lines
1640 Similar to a generator comprehension such as:16411642 .. code-block:: python16431632 (u for user in users if user.is_active)1633 (u for user in users if test_none(user.email))1644 (user for user in users if user.is_active)1645 (user for user in users if test_none(user.email))16461647 .. versionadded:: 2.71648 """1649 return select_or_reject(context, value, args, kwargs, lambda x: x, True)
28 unmodified lines
1678 Similar to a generator comprehension such as:16791680 .. code-block:: python16811670 (u for user in users if not user.is_active)1671 (u for user in users if not test_none(user.email))1682 (user for user in users if not user.is_active)1683 (user for user in users if not test_none(user.email))16841685 .. versionadded:: 2.71686 """1687 return select_or_reject(context, value, args, kwargs, lambda x: not x, True)
91 unmodified lines
1779 name = args[off]1780 args = args[1 + off :]17811782 def func(item: t.Any) -> t.Any:1771 return context.environment.call_test(name, item, args, kwargs)1783 return context.environment.call_test(name, item, args, kwargs, context)17841785 except LookupError:1786 func = bool # type: ignore1787
91 unmodified lines
modified:src/jinja2/idtracking.py+11 added-11 removed
1 unmodified line
23from . import nodes4from .visitor import NodeVisitor56if t.TYPE_CHECKING:7 import typing_extensions as te89VAR_LOAD_PARAMETER = "param"10VAR_LOAD_RESOLVE = "resolve"11VAR_LOAD_ALIAS = "alias"12VAR_LOAD_UNDEFINED = "undefined"
72 unmodified lines
85 f" unknown to the frame ({name!r})"86 )87 return rv8886 def copy(self) -> "Symbols":89 def copy(self) -> "te.Self":90 rv = object.__new__(self.__class__)91 rv.__dict__.update(self.__dict__)92 rv.refs = self.refs.copy()93 rv.loads = self.loads.copy()
26 unmodified lines
120 if self.find_ref(name) is None:121 self._define_ref(name, load=(VAR_LOAD_RESOLVE, name))122123 def branch_update(self, branch_symbols: t.Sequence["Symbols"]) -> None:121 stores: t.Dict[str, int] = {}124 stores: t.Set[str] = set()125126 for branch in branch_symbols:123 for target in branch.stores:124 if target in self.stores:125 continue126 stores[target] = stores.get(target, 0) + 1127 stores.update(branch.stores)128129 stores.difference_update(self.stores)130131 for sym in branch_symbols:132 self.refs.update(sym.refs)133 self.loads.update(sym.loads)134 self.stores.update(sym.stores)135133 for name, branch_count in stores.items():134 if branch_count == len(branch_symbols):135 continue136137 target = self.find_ref(name) # type: ignore136 for name in stores:137 target = self.find_ref(name)138 assert target is not None, "should not happen"139140 if self.parent is not None:141 outer_target = self.parent.find_ref(name)
177 unmodified lines
modified:src/jinja2/lexer.py+3 added-3 removed
260 unmodified lines
261 ) -> None:262 self.message = message263 self.error_class = cls264265 def __call__(self, lineno: int, filename: str) -> "te.NoReturn":265 def __call__(self, lineno: int, filename: t.Optional[str]) -> "te.NoReturn":266 raise self.error_class(self.message, lineno, filename)267268269class Token(t.NamedTuple):
486 unmodified lines
756 groups = [text[:l_pos], *groups[1:]]757758 for idx, token in enumerate(tokens):759 # failure group760 if token.__class__ is Failure:760 if isinstance(token, Failure):761 raise token(lineno, filename)762 # bygroup is a bit more complex, in that case we763 # yield for the current token the first named764 # group that matched
12 unmodified lines
777 else:778 data = groups[idx]779780 if data or token not in ignore_if_empty:781 yield lineno, token, data781 yield lineno, token, data # type: ignore[misc]782783 lineno += data.count("\n") + newlines_stripped784 newlines_stripped = 0785
83 unmodified lines
modified:src/jinja2/loaders.py+19 added-13 removed
202 unmodified lines
203204 if os.path.isfile(filename):205 break206 else:207 plural = "path" if len(self.searchpath) == 1 else "paths"208 paths_str = ", ".join(repr(p) for p in self.searchpath)207 raise TemplateNotFound(template)209 raise TemplateNotFound(210 template,211 f"{template!r} not found in search {plural}: {paths_str}",212 )213214 with open(filename, encoding=self.encoding) as f:215 contents = f.read()216
109 unmodified lines
326 loader = spec.loader327 assert loader is not None, "A loader was not found for the package."328 self._loader = loader329 self._archive = None325 template_root = None330331 if isinstance(loader, zipimport.zipimporter):332 self._archive = loader.archive333 pkgdir = next(iter(spec.submodule_search_locations)) # type: ignore
8 unmodified lines
342 # A single module file, use the parent directory instead.343 elif spec.origin is not None:344 roots.append(os.path.dirname(spec.origin))345346 if not roots:347 raise ValueError(348 f"The {package_name!r} package was not installed in a"349 " way that PackageLoader understands."350 )351352 for root in roots:353 root = os.path.join(root, package_path)354355 if os.path.isdir(root):356 template_root = root357 break358 else:359 raise ValueError(360 f"PackageLoader could not find a {package_path!r} directory"361 f" in the {package_name!r} package."362 )363349 if template_root is None:350 raise ValueError(351 f"The {package_name!r} package was not installed in a"352 " way that PackageLoader understands."353 )354364 self._template_root = template_root365366 def get_source(367 self, environment: "Environment", template: str
67 unmodified lines
435 template source. This loader is useful for unittesting:436437 >>> loader = DictLoader({'index.html': 'source here'})438430 Because auto reloading is rarely useful this is disabled per default.439 Because auto reloading is rarely useful this is disabled by default.440 """441442 def __init__(self, mapping: t.Mapping[str, str]) -> None:443 self.mapping = mapping
174 unmodified lines
618 """This loader loads templates from precompiled templates.619620 Example usage:621613 >>> loader = ChoiceLoader([614 ... ModuleLoader('/path/to/compiled/templates'),615 ... FileSystemLoader('/path/to/templates')616 ... ])622 >>> loader = ModuleLoader('/path/to/compiled/templates')623624 Templates can be precompiled with :meth:`Environment.compile_templates`.625 """626
64 unmodified lines
modified:src/jinja2/parser.py+24 added-16 removed
485 unmodified lines
486 `with_namespace` is enabled, a namespace assignment may be parsed.487 """488 target: nodes.Expr489490 if with_namespace and self.stream.look().type == "dot":490 if name_only:491 token = self.stream.expect("name")492 next(self.stream) # dot493 attr = self.stream.expect("name")494 target = nodes.NSRef(token.value, attr.value, lineno=token.lineno)495 elif name_only:496 token = self.stream.expect("name")492 target = nodes.Name(token.value, "store", lineno=token.lineno)493 else:494 if with_tuple:495 target = self.parse_tuple(501 simplified=True, extra_end_rules=extra_end_rules496 simplified=True,497 extra_end_rules=extra_end_rules,498 with_namespace=with_namespace,499 )500 else:504 target = self.parse_primary()501 target = self.parse_primary(with_namespace=with_namespace)502503 target.set_ctx("store")504505 if not target.can_assign():
133 unmodified lines
639 if with_filter:640 node = self.parse_filter_expr(node)641 return node642646 def parse_primary(self) -> nodes.Expr:643 def parse_primary(self, with_namespace: bool = False) -> nodes.Expr:644 """Parse a name or literal value. If ``with_namespace`` is enabled, also645 parse namespace attr refs, for use in assignments."""646 token = self.stream.current647 node: nodes.Expr648 if token.type == "name":649 next(self.stream)650 if token.value in ("true", "false", "True", "False"):651 node = nodes.Const(token.value in ("true", "True"), lineno=token.lineno)652 elif token.value in ("none", "None"):653 node = nodes.Const(None, lineno=token.lineno)654 elif with_namespace and self.stream.current.type == "dot":655 # If namespace attributes are allowed at this point, and the next656 # token is a dot, produce a namespace reference.657 next(self.stream)658 attr = self.stream.expect("name")659 node = nodes.NSRef(token.value, attr.value, lineno=token.lineno)660 else:661 node = nodes.Name(token.value, "load", lineno=token.lineno)656 next(self.stream)662 elif token.type == "string":663 next(self.stream)664 buf = [token.value]665 lineno = token.lineno
21 unmodified lines
687 simplified: bool = False,688 with_condexpr: bool = True,689 extra_end_rules: t.Optional[t.Tuple[str, ...]] = None,690 explicit_parentheses: bool = False,691 with_namespace: bool = False,692 ) -> t.Union[nodes.Tuple, nodes.Expr]:693 """Works like `parse_expression` but if multiple expressions are694 delimited by a comma a :class:`~jinja2.nodes.Tuple` node is created.695 This method could also return a regular expression instead of a tuple696 if no commas where found.697698 The default parsing mode is a full tuple. If `simplified` is `True`693 only names and literals are parsed. The `no_condexpr` parameter is694 forwarded to :meth:`parse_expression`.699 only names and literals are parsed; ``with_namespace`` allows namespace700 attr refs as well. The `no_condexpr` parameter is forwarded to701 :meth:`parse_expression`.702703 Because tuples do not require delimiters and may end in a bogus comma704 an extra hint is needed that marks the end of a tuple. For example705 for loops support tuples between `for` and `in`. In that case the
4 unmodified lines
710 tuple is a valid expression or not.711 """712 lineno = self.stream.current.lineno713 if simplified:707 parse = self.parse_primary708 elif with_condexpr:709 parse = self.parse_expression714715 def parse() -> nodes.Expr:716 return self.parse_primary(with_namespace=with_namespace)717718 else:719720 def parse() -> nodes.Expr:713 return self.parse_expression(with_condexpr=False)721 return self.parse_expression(with_condexpr=with_condexpr)722723 args: t.List[nodes.Expr] = []724 is_tuple = False725
324 unmodified lines
modified:src/jinja2/runtime.py+23 added-17 removed
365 unmodified lines
366 return BlockReference(self.name, self._context, self._stack, self._depth + 1)367368 @internalcode369 async def _async_call(self) -> str:370 rv = concat(370 rv = self._context.environment.concat( # type: ignore371 [x async for x in self._stack[self._depth](self._context)] # type: ignore372 )373374 if self._context.eval_ctx.autoescape:
5 unmodified lines
380 def __call__(self) -> str:381 if self._context.environment.is_async:382 return self._async_call() # type: ignore383384 rv = concat(self._stack[self._depth](self._context))384 rv = self._context.environment.concat( # type: ignore385 self._stack[self._depth](self._context)386 )387388 if self._context.eval_ctx.autoescape:389 return Markup(rv)390
402 unmodified lines
793 return f"<{type(self).__name__} {name}>"794795796class Undefined:795 """The default undefined type. This undefined type can be printed and796 iterated over, but every other access will raise an :exc:`UndefinedError`:797 """The default undefined type. This can be printed, iterated, and treated as798 a boolean. Any other operation will raise an :exc:`UndefinedError`.799800 >>> foo = Undefined(name='foo')801 >>> str(foo)802 ''
56 unmodified lines
859 raise self._undefined_exception(self._undefined_message)860861 @internalcode862 def __getattr__(self, name: str) -> t.Any:861 if name[:2] == "__":863 # Raise AttributeError on requests for names that appear to be unimplemented864 # dunder methods to keep Python's internal protocol probing behaviors working865 # properly in cases where another exception type could cause unexpected or866 # difficult-to-diagnose failures.867 if name[:2] == "__" and name[-2:] == "__":868 raise AttributeError(name)869870 return self._fail_with_undefined_error()871
115 unmodified lines
987988 def __html__(self) -> str:989 return str(self)990985 def __getattr__(self, _: str) -> "ChainableUndefined":991 def __getattr__(self, name: str) -> "ChainableUndefined":992 # Raise AttributeError on requests for names that appear to be unimplemented993 # dunder methods to avoid confusing Python with truthy non-method objects that994 # do not implement the protocol being probed for. e.g., copy.copy(Undefined())995 # fails spectacularly if getattr(Undefined(), '__setstate__') returns an996 # Undefined object instead of raising AttributeError to signal that it does not997 # support that style of object initialization.998 if name[:2] == "__" and name[-2:] == "__":999 raise AttributeError(name)10001001 return self1002988 __getitem__ = __getattr__ # type: ignore1003 def __getitem__(self, _name: str) -> "ChainableUndefined": # type: ignore[override]1004 return self100510061007class DebugUndefined(Undefined):1008 """An undefined that returns the debug info when printed.
50 unmodified lines
1059 __slots__ = ()1060 __iter__ = __str__ = __len__ = Undefined._fail_with_undefined_error1061 __eq__ = __ne__ = __bool__ = __hash__ = Undefined._fail_with_undefined_error1062 __contains__ = Undefined._fail_with_undefined_error104710481049# Remove slots attributes, after the metaclass is applied they are1050# unneeded and contain wrong data for subclasses.1051del (1052 Undefined.__slots__,1053 ChainableUndefined.__slots__,1054 DebugUndefined.__slots__,1055 StrictUndefined.__slots__,1056)
modified:src/jinja2/sandbox.py+46 added-39 removed
6 unmodified lines
7import typing as t8from _string import formatter_field_name_split # type: ignore9from collections import abc10from collections import deque11from functools import update_wrapper12from string import Formatter1314from markupsafe import EscapeFormatter15from markupsafe import Markup
44 unmodified lines
60 frozenset(["clear", "pop", "popitem", "setdefault", "update"]),61 ),62 (63 abc.MutableSequence,63 frozenset(["append", "reverse", "insert", "sort", "extend", "remove"]),64 frozenset(65 ["append", "clear", "pop", "reverse", "insert", "sort", "extend", "remove"]66 ),67 ),68 (69 deque,70 frozenset(
12 unmodified lines
83 ),84)858684def inspect_format_method(callable: t.Callable[..., t.Any]) -> t.Optional[str]:85 if not isinstance(86 callable, (types.MethodType, types.BuiltinMethodType)87 ) or callable.__name__ not in ("format", "format_map"):88 return None8990 obj = callable.__self__9192 if isinstance(obj, str):93 return obj9495 return None969787def safe_range(*args: int) -> range:88 """A range that can't generate ranges with a length of more than89 MAX_RANGE items.90 """
211 unmodified lines
302 value = getattr(obj, attr)303 except AttributeError:304 pass305 else:306 fmt = self.wrap_str_format(value)307 if fmt is not None:308 return fmt309 if self.is_safe_attribute(obj, argument, value):310 return value311 return self.unsafe_undefined(obj, argument)312 return self.undefined(obj=obj, name=argument)
9 unmodified lines
322 return obj[attribute]323 except (TypeError, LookupError):324 pass325 else:326 fmt = self.wrap_str_format(value)327 if fmt is not None:328 return fmt329 if self.is_safe_attribute(obj, attribute, value):330 return value331 return self.unsafe_undefined(obj, attribute)332 return self.undefined(obj=obj, name=attribute)
7 unmodified lines
340 obj=obj,341 exc=SecurityError,342 )343349 def format_string(350 self,351 s: str,352 args: t.Tuple[t.Any, ...],353 kwargs: t.Dict[str, t.Any],354 format_func: t.Optional[t.Callable[..., t.Any]] = None,355 ) -> str:356 """If a format call is detected, then this is routed through this357 method so that our safety sandbox can be used for it.344 def wrap_str_format(self, value: t.Any) -> t.Optional[t.Callable[..., str]]:345 """If the given value is a ``str.format`` or ``str.format_map`` method,346 return a new function than handles sandboxing. This is done at access347 rather than in :meth:`call`, so that calls made without ``call`` are348 also sandboxed.349 """350 if not isinstance(351 value, (types.MethodType, types.BuiltinMethodType)352 ) or value.__name__ not in ("format", "format_map"):353 return None354355 f_self: t.Any = value.__self__356357 if not isinstance(f_self, str):358 return None359360 str_type: t.Type[str] = type(f_self)361 is_format_map = value.__name__ == "format_map"362 formatter: SandboxedFormatter363360 if isinstance(s, Markup):361 formatter = SandboxedEscapeFormatter(self, escape=s.escape)364 if isinstance(f_self, Markup):365 formatter = SandboxedEscapeFormatter(self, escape=f_self.escape)366 else:367 formatter = SandboxedFormatter(self)368365 if format_func is not None and format_func.__name__ == "format_map":366 if len(args) != 1 or kwargs:367 raise TypeError(368 "format_map() takes exactly one argument"369 f" {len(args) + (kwargs is not None)} given"370 )369 vformat = formatter.vformat370372 kwargs = args[0]373 args = ()371 def wrapper(*args: t.Any, **kwargs: t.Any) -> str:372 if is_format_map:373 if kwargs:374 raise TypeError("format_map() takes no keyword arguments")375375 rv = formatter.vformat(s, args, kwargs)376 return type(s)(rv)376 if len(args) != 1:377 raise TypeError(378 f"format_map() takes exactly one argument ({len(args)} given)"379 )380381 kwargs = args[0]382 args = ()383384 return str_type(vformat(f_self, args, kwargs))385386 return update_wrapper(wrapper, value)387388 def call(389 __self, # noqa: B902390 __context: Context,391 __obj: t.Any,392 *args: t.Any,393 **kwargs: t.Any,394 ) -> t.Any:395 """Call an object from sandboxed code."""386 fmt = inspect_format_method(__obj)387 if fmt is not None:388 return __self.format_string(fmt, args, kwargs, __obj)396397 # the double prefixes are to avoid double keyword argument398 # errors when proxying the call.399 if not __self.is_safe_callable(__obj):
37 unmodified lines
modified:src/jinja2/utils.py+14 added-3 removed
16 unmodified lines
17 import typing_extensions as te1819F = t.TypeVar("F", bound=t.Callable[..., t.Any])2021# special singleton representing missing values for the runtime22missing: t.Any = type("MissingType", (), {"__repr__": lambda x: "missing"})()2122class _MissingType:23 def __repr__(self) -> str:24 return "missing"2526 def __reduce__(self) -> str:27 return "missing"282930missing: t.Any = _MissingType()31"""Special singleton representing missing values for the runtime."""3233internal_code: t.MutableSet[CodeType] = set()3435concat = "".join36
295 unmodified lines
332333 elif (334 "@" in middle335 and not middle.startswith("www.")336 # ignore values like `@a@b`337 and not middle.startswith("@")338 and ":" not in middle339 and _email_re.match(middle)340 ):341 middle = f'<a href="mailto:{middle}">{middle}</a>'
121 unmodified lines
463464 def __getnewargs__(self) -> t.Tuple[t.Any, ...]:465 return (self.capacity,)466456 def copy(self) -> "LRUCache":467 def copy(self) -> "te.Self":468 """Return a shallow copy of the instance."""469 rv = self.__class__(self.capacity)470 rv._mapping.update(self._mapping)471 rv._queue.extend(self._queue)
295 unmodified lines
modified:tests/test_api.py+8 added-8 removed
321 unmodified lines
322 und2 = Undefined(name="y")323 assert und1 == und2324 assert und1 != 42325 assert hash(und1) == hash(und2) == hash(Undefined())326 with pytest.raises(AttributeError):327 getattr(Undefined, "__slots__") # noqa: B009326327 def test_chainable_undefined(self):328 env = Environment(undefined=ChainableUndefined)329 # The following tests are copied from test_default_undefined
2 unmodified lines
332 assert env.from_string("{{ missing is not defined }}").render() == "True"333 assert env.from_string("{{ foo.missing }}").render(foo=42) == ""334 assert env.from_string("{{ not missing }}").render() == "True"335 pytest.raises(UndefinedError, env.from_string("{{ missing - 1}}").render)338 with pytest.raises(AttributeError):339 getattr(ChainableUndefined, "__slots__") # noqa: B009336337 # The following tests ensure subclass functionality works as expected338 assert env.from_string('{{ missing.bar["baz"] }}').render() == ""339 assert env.from_string('{{ foo.bar["baz"]._undefined_name }}').render() == "foo"
23 unmodified lines
363 assert (364 str(DebugUndefined(hint=undefined_hint))365 == f"{{{{ undefined value printed: {undefined_hint} }}}}"366 )371 with pytest.raises(AttributeError):372 getattr(DebugUndefined, "__slots__") # noqa: B009367368 def test_strict_undefined(self):369 env = Environment(undefined=StrictUndefined)370 pytest.raises(UndefinedError, env.from_string("{{ missing }}").render)
8 unmodified lines
379 assert (380 env.from_string('{{ missing|default("default", true) }}').render()381 == "default"382 )389 with pytest.raises(AttributeError):390 getattr(StrictUndefined, "__slots__") # noqa: B009383 assert env.from_string('{{ "foo" if false }}').render() == ""384385 def test_indexing_gives_undefined(self):386 t = Template("{{ var[42].foo }}")
37 unmodified lines
424425 env = CustomEnvironment()426 tmpl = env.from_string("{{ foo }}")427 assert tmpl.render() == "resolve-foo"428429430def test_overlay_enable_async(env):431 assert not env.is_async432 assert not env.overlay().is_async433 env_async = env.overlay(enable_async=True)434 assert env_async.is_async435 assert not env_async.overlay(enable_async=False).is_async
modified:tests/test_async_filters.py+7 added
264 unmodified lines
265 "[[0, 1, 2, 3], [4, 5, 6, 'X'], [7, 8, 9, 'X']]"266 )267268269def test_unique_with_async_gen(env_async):270 items = ["a", "b", "c", "c", "a", "d", "z"]271 tmpl = env_async.from_string("{{ items|reject('==', 'z')|unique|list }}")272 out = tmpl.render(items=items)273 assert out == "['a', 'b', 'c', 'd']"274275276def test_custom_async_filter(env_async, run_async_fn):277 async def customfilter(val):278 return str(val)279
31 unmodified lines
modified:tests/test_compile.py+80 added
1import os2import re34import pytest56from jinja2 import UndefinedError7from jinja2.environment import Environment8from jinja2.loaders import DictLoader910
17 unmodified lines
28 content = (tmp_path / name).read_text("utf8")29 expect = [f"'bar{i}': " for i in range(10)]30 found = re.findall(r"'bar\d': ", content)[:10]31 assert found == expect323334def test_top_level_set_vars_unpacking_deterministic(tmp_path):35 src = "\n".join(f"{{% set a{i}, b{i}, c{i} = tuple_var{i} %}}" for i in range(10))36 env = Environment(loader=DictLoader({"foo": src}))37 env.compile_templates(tmp_path, zip=None)38 name = os.listdir(tmp_path)[0]39 content = (tmp_path / name).read_text("utf8")40 expect = [41 f"context.vars.update({{'a{i}': l_0_a{i}, 'b{i}': l_0_b{i}, 'c{i}': l_0_c{i}}})"42 for i in range(10)43 ]44 found = re.findall(45 r"context\.vars\.update\(\{'a\d': l_0_a\d, 'b\d': l_0_b\d, 'c\d': l_0_c\d\}\)",46 content,47 )[:10]48 assert found == expect49 expect = [50 f"context.exported_vars.update(('a{i}', 'b{i}', 'c{i}'))" for i in range(10)51 ]52 found = re.findall(53 r"context\.exported_vars\.update\(\('a\d', 'b\d', 'c\d'\)\)",54 content,55 )[:10]56 assert found == expect575859def test_loop_set_vars_unpacking_deterministic(tmp_path):60 src = "\n".join(f" {{% set a{i}, b{i}, c{i} = tuple_var{i} %}}" for i in range(10))61 src = f"{{% for i in seq %}}\n{src}\n{{% endfor %}}"62 env = Environment(loader=DictLoader({"foo": src}))63 env.compile_templates(tmp_path, zip=None)64 name = os.listdir(tmp_path)[0]65 content = (tmp_path / name).read_text("utf8")66 expect = [67 f"_loop_vars.update({{'a{i}': l_1_a{i}, 'b{i}': l_1_b{i}, 'c{i}': l_1_c{i}}})"68 for i in range(10)69 ]70 found = re.findall(71 r"_loop_vars\.update\(\{'a\d': l_1_a\d, 'b\d': l_1_b\d, 'c\d': l_1_c\d\}\)",72 content,73 )[:10]74 assert found == expect757677def test_block_set_vars_unpacking_deterministic(tmp_path):78 src = "\n".join(f" {{% set a{i}, b{i}, c{i} = tuple_var{i} %}}" for i in range(10))79 src = f"{{% block test %}}\n{src}\n{{% endblock test %}}"80 env = Environment(loader=DictLoader({"foo": src}))81 env.compile_templates(tmp_path, zip=None)82 name = os.listdir(tmp_path)[0]83 content = (tmp_path / name).read_text("utf8")84 expect = [85 f"_block_vars.update({{'a{i}': l_0_a{i}, 'b{i}': l_0_b{i}, 'c{i}': l_0_c{i}}})"86 for i in range(10)87 ]88 found = re.findall(89 r"_block_vars\.update\(\{'a\d': l_0_a\d, 'b\d': l_0_b\d, 'c\d': l_0_c\d\}\)",90 content,91 )[:10]92 assert found == expect939495def test_undefined_import_curly_name():96 env = Environment(97 loader=DictLoader(98 {99 "{bad}": "{% from 'macro' import m %}{{ m() }}",100 "macro": "",101 }102 )103 )104105 # Must not raise `NameError: 'bad' is not defined`, as that would indicate106 # that `{bad}` is being interpreted as an f-string. It must be escaped.107 with pytest.raises(UndefinedError):108 env.get_template("{bad}").render()
modified:tests/test_core_tags.py+8 added
536 unmodified lines
537 "{{ ns.a }}|{{ ns.b }}"538 )539 assert tmpl.render() == "13|37"540541 def test_namespace_set_tuple(self, env_trim):542 tmpl = env_trim.from_string(543 "{% set ns = namespace(a=12, b=36) %}"544 "{% set ns.a, ns.b = ns.a + 1, ns.b + 1 %}"545 "{{ ns.a }}|{{ ns.b }}"546 )547 assert tmpl.render() == "13|37"548549 def test_block_escaping_filtered(self):550 env = Environment(autoescape=True)551 tmpl = env.from_string(552 "{% set foo | trim %}<em>{{ test }}</em> {% endset %}foo: {{ foo }}"
51 unmodified lines
modified:tests/test_filters.py+1 added
194 unmodified lines
195 ("42", "42"),196 ("abc", "0"),197 ("32.32", "32"),198 ("12345678901234567890", "12345678901234567890"),199 ("1e10000", "0"),200 ),201 )202 def test_int(self, env, value, expect):203 t = env.from_string("{{ value|int }}")
680 unmodified lines
modified:tests/test_loader.py+23 added
177 unmodified lines
178 e = Environment(loader=loader)179 t = e.get_template("foo/test.html")180 assert t.filename == str(self.searchpath / "foo" / "test.html")181182 def test_error_includes_paths(self, env, filesystem_loader):183 env.loader = filesystem_loader184185 with pytest.raises(TemplateNotFound) as info:186 env.get_template("missing")187188 e_str = str(info.value)189 assert e_str.startswith("'missing' not found in search path: ")190191 filesystem_loader.searchpath.append("other")192193 with pytest.raises(TemplateNotFound) as info:194 env.get_template("missing")195196 e_str = str(info.value)197 assert e_str.startswith("'missing' not found in search paths: ")198 assert ", 'other'" in e_str199200201class TestModuleLoader:202 archive = None203 mod_env = None204
223 unmodified lines
428 package_loader = PackageLoader("res")429 assert "test.html" in package_loader.list_templates()430 finally:431 sys.meta_path[:] = before432433434def test_package_loader_no_dir() -> None:435 with pytest.raises(ValueError, match="could not find a 'templates' directory"):436 PackageLoader("jinja2")
modified:tests/test_nativetypes.py+10 added
175 unmodified lines
176 t = env.from_string("{%- macro x() -%}{{- [1,2] -}}{%- endmacro -%}{{- x()[1] -}}")177 result = t.render()178 assert result == 2179 assert isinstance(result, int)180181182def test_block(env):183 t = env.from_string(184 "{% block b %}{% for i in range(1) %}{{ loop.index }}{% endfor %}"185 "{% endblock %}{{ self.b() }}"186 )187 result = t.render()188 assert result == 11189 assert isinstance(result, int)
modified:tests/test_regression.py+22 added
735 unmodified lines
736 "{% endset %}{{ output }}"737 )738 assert tmpl.render() == "hellohellohello"739740 def test_pass_context_with_select(self, env):741 @pass_context742 def is_foo(ctx, s):743 assert ctx is not None744 return s == "foo"745746 env.tests["foo"] = is_foo747 tmpl = env.from_string(748 "{% for x in ['one', 'foo'] | select('foo') %}{{ x }}{% endfor %}"749 )750 assert tmpl.render() == "foo"751752753def test_load_parameter_when_set_in_all_if_branches(env):754 tmpl = env.from_string(755 "{% if True %}{{ a.b }}{% set a = 1 %}"756 "{% elif False %}{% set a = 2 %}"757 "{% else %}{% set a = 3 %}{% endif %}"758 "{{ a }}"759 )760 assert tmpl.render(a={"b": 0}) == "01"761762763@pytest.mark.parametrize("unicode_char", ["\N{FORM FEED}", "\x85"])764def test_unicode_whitespace(env, unicode_char):765 content = "Lorem ipsum\n" + unicode_char + "\nMore text"766 tmpl = env.from_string(content)
1 unmodified line
modified:tests/test_runtime.py+50 added
1import copy2import itertools3import pickle45import pytest67from jinja2 import ChainableUndefined8from jinja2 import DebugUndefined9from jinja2 import StrictUndefined10from jinja2 import Template11from jinja2 import TemplateRuntimeError12from jinja2 import Undefined13from jinja2.runtime import LoopContext1415TEST_IDX_TEMPLATE_STR_1 = (16 "[{% for i in lst|reverse %}(len={{ loop.length }},"
64 unmodified lines
81 t = Template("{{ calc() }}")82 out = t.render(calc=Calc())83 # Would be "1" if context argument was passed.84 assert out == "0"858687_undefined_types = (Undefined, ChainableUndefined, DebugUndefined, StrictUndefined)888990@pytest.mark.parametrize("undefined_type", _undefined_types)91def test_undefined_copy(undefined_type):92 undef = undefined_type("a hint", ["foo"], "a name", TemplateRuntimeError)93 copied = copy.copy(undef)9495 assert copied is not undef96 assert copied._undefined_hint is undef._undefined_hint97 assert copied._undefined_obj is undef._undefined_obj98 assert copied._undefined_name is undef._undefined_name99 assert copied._undefined_exception is undef._undefined_exception100101102@pytest.mark.parametrize("undefined_type", _undefined_types)103def test_undefined_deepcopy(undefined_type):104 undef = undefined_type("a hint", ["foo"], "a name", TemplateRuntimeError)105 copied = copy.deepcopy(undef)106107 assert copied._undefined_hint is undef._undefined_hint108 assert copied._undefined_obj is not undef._undefined_obj109 assert copied._undefined_obj == undef._undefined_obj110 assert copied._undefined_name is undef._undefined_name111 assert copied._undefined_exception is undef._undefined_exception112113114@pytest.mark.parametrize("undefined_type", _undefined_types)115def test_undefined_pickle(undefined_type):116 undef = undefined_type("a hint", ["foo"], "a name", TemplateRuntimeError)117 copied = pickle.loads(pickle.dumps(undef))118119 assert copied._undefined_hint is not undef._undefined_hint120 assert copied._undefined_hint == undef._undefined_hint121 assert copied._undefined_obj is not undef._undefined_obj122 assert copied._undefined_obj == undef._undefined_obj123 assert copied._undefined_name is not undef._undefined_name124 assert copied._undefined_name == undef._undefined_name125 assert copied._undefined_exception is undef._undefined_exception
modified:tests/test_security.py+19 added
56 unmodified lines
5758 def test_immutable_environment(self, env):59 env = ImmutableSandboxedEnvironment()60 pytest.raises(SecurityError, env.from_string("{{ [].append(23) }}").render)61 pytest.raises(SecurityError, env.from_string("{{ [].clear() }}").render)62 pytest.raises(SecurityError, env.from_string("{{ [1].pop() }}").render)63 pytest.raises(SecurityError, env.from_string("{{ {1:2}.clear() }}").render)6465 def test_restricted(self, env):66 env = SandboxedEnvironment()
105 unmodified lines
172 t = env.from_string(173 '{{ ("a{x.foo}b{y}"|safe).format_map({"x":{"foo": 42}, "y":"<foo>"}) }}'174 )175 assert t.render() == "a42b&lt;foo&gt;"176177 def test_indirect_call(self):178 def run(value, arg):179 return value.run(arg)180181 env = SandboxedEnvironment()182 env.filters["run"] = run183 t = env.from_string(184 """{% set185 ns = namespace(run="{0.__call__.__builtins__[__import__]}".format)186 %}187 {{ ns | run(not_here) }}188 """189 )190191 with pytest.raises(SecurityError):192 t.render()
modified:tests/test_utils.py+20 added
1import copy2import pickle3import random4from collections import deque5from copy import copy as shallow_copy
135 unmodified lines
141 ' target="&lt;script&gt;">'142 "http://example.org</a>"143 )144145 def test_urlize_mail_mastodon(self):146 fr = "nabijaczleweli@nabijaczleweli.xyz\n@eater@cijber.social\n"147 to = (148 '<a href="mailto:nabijaczleweli@nabijaczleweli.xyz">'149 "nabijaczleweli@nabijaczleweli.xyz</a>\n@eater@cijber.social\n"150 )151 assert urlize(fr) == to152153154class TestLoremIpsum:155 def test_lorem_ipsum_markup(self):156 """Test that output of lorem_ipsum is Markup by default."""157 assert isinstance(generate_lorem_ipsum(), Markup)
33 unmodified lines
191 x = iter([1, 2, 3, 4, 5])192 consume(x)193 with pytest.raises(StopIteration):194 next(x)195196197@pytest.mark.parametrize("protocol", range(pickle.HIGHEST_PROTOCOL + 1))198def test_pickle_missing(protocol: int) -> None:199 """Test that missing can be pickled while remaining a singleton."""200 assert pickle.loads(pickle.dumps(missing, protocol)) is missing201202203def test_copy_missing() -> None:204 """Test that missing can be copied while remaining a singleton."""205 assert copy.copy(missing) is missing
modified:.pre-commit-config.yaml+1 added-1 removed
1repos:2 - repo: https://github.com/astral-sh/ruff-pre-commit3 rev: v0.7.13 rev: v0.8.44 hooks:5 - id: ruff6 - id: ruff-format7 - repo: https://github.com/pre-commit/pre-commit-hooks
7 unmodified lines
modified:CHANGES.rst+36 added-2 removed
12 unmodified lines
1314Version 3.1.515-------------1617Unreleased17Released 2024-12-211819- The sandboxed environment handles indirect calls to ``str.format``, such as20 by passing a stored reference to a filter that calls its argument.21 :ghsa:`q2x7-8rv6-6q7h`22- Escape template name before formatting it into error messages, to avoid23 issues with names that contain f-string syntax.24 :issue:`1792`, :ghsa:`gmj6-6f8f-6699`25- Sandbox does not allow ``clear`` and ``pop`` on known mutable sequence26 types. :issue:`2032`27- Calling sync ``render`` for an async template uses ``asyncio.run``.28 :pr:`1952`29- Avoid unclosed ``auto_aiter`` warnings. :pr:`1960`30- Return an ``aclose``-able ``AsyncGenerator`` from
1 unmodified line
32- Avoid leaving ``root_render_func()`` unclosed in33 ``Template.generate_async``. :pr:`1960`34- Avoid leaving async generators unclosed in blocks, includes and extends.35 :pr:`1960`36- The runtime uses the correct ``concat`` function for the current environment37 when calling block references. :issue:`1701`38- Make ``|unique`` async-aware, allowing it to be used after another39 async-aware filter. :issue:`1781`40- ``|int`` filter handles ``OverflowError`` from scientific notation.41 :issue:`1921`42- Make compiling deterministic for tuple unpacking in a ``{% set ... %}``43 call. :issue:`2021`44- Fix dunder protocol (`copy`/`pickle`/etc) interaction with ``Undefined``45 objects. :issue:`2025`46- Fix `copy`/`pickle` support for the internal ``missing`` object.47 :issue:`2027`48- ``Environment.overlay(enable_async)`` is applied correctly. :pr:`2061`49- The error message from ``FileSystemLoader`` includes the paths that were50 searched. :issue:`1661`51- ``PackageLoader`` shows a clearer error message when the package does not52 contain the templates directory. :issue:`1705`53- Improve annotations for methods returning copies. :pr:`1880`54- ``urlize`` does not add ``mailto:`` to values like `@a@b`. :pr:`1870`55- Tests decorated with `@pass_context`` can be used with the ``|select``56 filter. :issue:`1624`57- Using ``set`` for multiple assignment (``a, b = 1, 2``) does not fail when the58 target is a namespace attribute. :issue:`1413`59- Using ``set`` in all branches of ``{% if %}{% elif %}{% else %}`` blocks60 does not cause the variable to be considered initially undefined.61 :issue:`1253`626364Version 3.1.465-------------
979 unmodified lines
1045- ``else`` is optional for conditional expressions. If not given it1046 evaluates to ``false``.1047- Improved error reporting for undefined values by providing a1048 position.1015- ``filesizeformat`` filter uses decimal prefixes now per default and1049- ``filesizeformat`` filter uses decimal prefixes now by default and1050 can be set to binary mode with the second parameter.1051- Fixed bug in finalizer10521053
6 unmodified lines