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
Provenance
- Commit
6aeab5d- Tree
d0892ff- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent 1
d680a95- Parent 2
ab8218c
38 files changed+584 added−213 removed
modified:.github/workflows/publish.yaml+2 added-6 removed
21 unmodified lines2223242526262728293032 unmodified lines63646566676768696971727321 unmodified lines # Generate hashes used for provenance. - name: generate hash id: hash run: cd dist && echo "hash=$(sha256sum * | base64 -w0)" >> $GITHUB_OUTPUT - uses: actions/upload-artifact@b4b15b8c7c6ac21ea08fcf65892d2ee8f75cf882 # v4.4.3 - uses: actions/upload-artifact@6f51ac03b9356f520e9adb1b1b7802705f340c2b # v4.5.0 with: path: ./dist provenance: needs: [build]32 unmodified lines permissions: id-token: write steps: - uses: actions/download-artifact@fa0a91b85d4f404e444e00e005971372dc801d16 # v4.1.8 - uses: pypa/gh-action-pypi-publish@f7600683efdcb7656dec5b29656edb7bc586e597 # v1.10.3 - uses: pypa/gh-action-pypi-publish@67339c736fd9354cd4f8cb0b744f2b82a74b5c70 # v1.12.3 with: repository-url: https://test.pypi.org/legacy/ packages-dir: artifact/ - uses: pypa/gh-action-pypi-publish@f7600683efdcb7656dec5b29656edb7bc586e597 # v1.10.3 with: packages-dir: artifact/modified:.github/workflows/tests.yaml+1 added-1 removed
40 unmodified lines414243444545464748495040 unmodified lines python-version: '3.x' cache: pip cache-dependency-path: requirements*/*.txt - name: cache mypy uses: actions/cache@6849a6489940f00c2f30c0fb92c6274307ccb58a # v4.1.2 uses: actions/cache@1bd1e32a3bdc45362d1e726936510720a7c30a57 # v4.2.0 with: path: ./.mypy_cache key: mypy|${{ hashFiles('pyproject.toml') }} - run: pip install tox - run: tox run -e typingmodified:docs/api.rst+2 added-2 removed
664 unmodified lines665 Now it can be used in templates:666 667 .. sourcecode:: jinja668 669- {{ 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") }}671 672 Some decorators are available to tell Jinja to pass extra information to673 the filter. The object is passed as the first argument, making the value674 being filtered the second argument.245 unmodified linesmodified:docs/conf.py+1 added-1 removed
22 unmodified lines23 autodoc_preserve_defaults = True24 extlinks = {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 }29 intersphinx_mapping = {30 "python": ("https://docs.python.org/3/", None),31 }24 unmodified linesmodified:docs/faq.rst+3 added-1 removed
68 unmodified lines69 these document types.70 71 While automatic escaping means that you are less likely have an XSS72 problem, it also requires significant extra processing during compiling73-and rendering, which can reduce performance. Jinja uses MarkupSafe for73+and rendering, which can reduce performance. Jinja uses `MarkupSafe`_ for74 escaping, which provides optimized C code for speed, but it still75 introduces overhead to track escaping across methods and formatting.76+77+.. _MarkupSafe: https://markupsafe.palletsprojects.com/modified:docs/nativetypes.rst+11 added
53 unmodified lines54 Foo55 >>> print(result.value)56 1557 58+Sandboxed Native Environment59+----------------------------60+61+You can combine :class:`.SandboxedEnvironment` and :class:`NativeEnvironment` to62+get both behaviors.63+64+.. code-block:: python65+66+ class SandboxedNativeEnvironment(SandboxedEnvironment, NativeEnvironment):67+ pass68+69 API70 ---71 72 .. autoclass:: NativeEnvironment([options])3 unmodified linesmodified:docs/templates.rst+49 added-36 removed
200 unmodified lines201 option can also be set to strip tabs and spaces from the beginning of a202 line to the start of a block. (Nothing will be stripped if there are203 other characters before the start of the block.)204 205-With both `trim_blocks` and `lstrip_blocks` enabled, you can put block tags206-on their own lines, and the entire block line will be removed when207-rendered, preserving the whitespace of the contents. For example,208-without the `trim_blocks` and `lstrip_blocks` options, this template::205+With both ``trim_blocks`` and ``lstrip_blocks`` disabled (the default), block206+tags on their own lines will be removed, but a blank line will remain and the207+spaces in the content will be preserved. For example, this template:208 209+.. code-block:: jinja210+211 <div>212 {% if True %}213 yay214 {% endif %}215 </div>216 216-gets rendered with blank lines inside the div::217+With both ``trim_blocks`` and ``lstrip_blocks`` disabled, the template is218+rendered with blank lines inside the div:219 220+.. code-block:: text221+222 <div>223 224 yay225 226 </div>227 224-But with both `trim_blocks` and `lstrip_blocks` enabled, the template block225-lines are removed and other whitespace is preserved::228+With both ``trim_blocks`` and ``lstrip_blocks`` enabled, the template block229+lines are completely removed:230 231+.. code-block:: text232+233 <div>234 yay235 </div>236 290 unmodified lines527 528 Block Nesting and Scope529 ~~~~~~~~~~~~~~~~~~~~~~~530 525-Blocks can be nested for more complex layouts. However, per default blocks526-may not access variables from outer scopes::531+Blocks can be nested for more complex layouts. By default, a block may not532+access variables from outside the block (outer scopes)::533 534 {% for item in seq %}535 <li>{% block loop_item %}{{ item }}{% endblock %}</li>536 {% endfor %}548 unmodified lines1085 1086 Block Assignments1087 ~~~~~~~~~~~~~~~~~1088 1083-.. versionadded:: 2.81089+It's possible to use `set` as a block to assign the content of the block to a1090+variable. This can be used to create multi-line strings, since Jinja doesn't1091+support Python's triple quotes (``"""``, ``'''``).1092 1085-Starting with Jinja 2.8, it's possible to also use block assignments to1086-capture the contents of a block into a variable name. This can be useful1087-in some situations as an alternative for macros. In that case, instead of1088-using an equals sign and a value, you just write the variable name and then1089-everything until ``{% endset %}`` is captured.1093+Instead of using an equals sign and a value, you only write the variable name,1094+and everything until ``{% endset %}`` is captured.1095 1091-Example::1096+.. code-block:: jinja1097 1098 {% set navigation %}1099 <li><a href="/">Index</a>1100 <li><a href="/downloads">Downloads</a>1101 {% endset %}1102 1098-The `navigation` variable then contains the navigation HTML source.1103+Filters applied to the variable name will be applied to the block's content.1104 1100-.. versionchanged:: 2.101105+.. code-block:: jinja1106 1102-Starting with Jinja 2.10, the block assignment supports filters.1103-1104-Example::1105-1107 {% set reply | wordwrap %}1108 You wrote:1109 {{ message }}1110 {% endset %}1111 1112+.. versionadded:: 2.81113 1114+.. versionchanged:: 2.101115+1116+ Block assignment supports filters.1117+1118 .. _extends:1119 1120 Extends1121 ~~~~~~~289 unmodified lines1411 1412 Logic1413 ~~~~~1414 1409-For ``if`` statements, ``for`` filtering, and ``if`` expressions, it can be useful to1410-combine multiple expressions:1415+For ``if`` statements, ``for`` filtering, and ``if`` expressions, it can be1416+useful to combine multiple expressions.1417 1418 ``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.1422 1423 ``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.1427 1428 ``not``1419- negate a statement (see below).1429+ For ``not x``, if ``x`` is false, then the value is ``True``, else1430+ ``False``.1431 1421-``(expr)``1422- Parentheses group an expression.1423-1424-.. admonition:: Note1425-1426- 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).``1436 1437+``(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.1440 1441+1442 Other Operators1443 ~~~~~~~~~~~~~~~1444 1445 The following operators are very useful but don't fit into any of the other231 unmodified lines1677 Found item having something: {{ ns.found }}1678 1679 .. versionadded:: 2.101680 1681+ .. versionchanged:: 3.21682+ Namespace attributes can be assigned to in multiple assignment.1683 1684+1685 Extensions1686 ----------1687 1688 .. py:currentmodule:: jinja2101 unmodified lines1790 It's possible to translate strings in expressions with these functions:1791 1792 - ``_(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 linesmodified:docs/tricks.rst+1 added-1 removed
19 unmodified lines20 21 Usually child templates extend from one template that adds a basic HTML22 skeleton. However it's possible to put the `extends` tag into an `if` tag to23 only extend from the layout template if the `standalone` variable evaluates24-to false which it does per default if it's not defined. Additionally a very24+to false, which it does by default if it's not defined. Additionally a very25 basic 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::27 28 {% if not standalone %}{% extends 'default.html' %}{% endif -%}72 unmodified linesmodified:examples/basic/test.py+2 added-2 removed
4 unmodified lines5 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 linesmodified:requirements/build.txt+1 added-1 removed
4 unmodified lines5 # pip-compile build.in6 #7 build==1.2.2.post18 # via -r build.in9-packaging==24.19+packaging==24.210 # via build11 pyproject-hooks==1.2.012 # via buildmodified:requirements/dev.txt+16 added-16 removed
4 unmodified lines5 # pip-compile dev.in6 #7 alabaster==1.0.08 # via sphinx9-attrs==24.2.09+attrs==24.3.010 # via11 # outcome12 # trio13 babel==2.16.01 unmodified line15 build==1.2.2.post116 # via pip-tools17 cachetools==5.5.018 # via tox19-certifi==2024.8.3019+certifi==2024.12.1420 # via requests21 cfgv==3.4.022 # via pre-commit23 chardet==5.2.013 unmodified lines37 filelock==3.16.138 # via39 # tox40 # virtualenv41-identify==2.6.141+identify==2.6.342 # via pre-commit43 idna==3.1044 # via45 # requests5 unmodified lines51 jinja2==3.1.452 # via sphinx53 markupsafe==3.0.254 # via jinja255-mypy==1.13.056- # via -r typing.in55+mypy==1.14.056+ # via -r /Users/david/Projects/jinja/requirements/typing.in57 mypy-extensions==1.0.058 # via mypy59 nodeenv==1.9.160 # via pre-commit61 outcome==1.3.0.post062 # via trio63-packaging==24.163+packaging==24.264 # via65 # build66 # pallets-sphinx-themes67 # pyproject-api68 # pytest69 # sphinx70 # tox71 pallets-sphinx-themes==2.3.072- # via -r docs.in73-pip-compile-multi==2.6.472+ # via -r /Users/david/Projects/jinja/requirements/docs.in73+pip-compile-multi==2.7.174 # via -r dev.in75 pip-tools==7.4.176 # via pip-compile-multi77 platformdirs==4.3.613 unmodified lines91 pyproject-hooks==1.2.092 # via93 # build94 # pip-tools95-pytest==8.3.396- # via -r tests.in95+pytest==8.3.496+ # via -r /Users/david/Projects/jinja/requirements/tests.in97 pyyaml==6.0.298 # via pre-commit99 requests==2.32.3100 # via sphinx4 unmodified lines105 sortedcontainers==2.4.0106 # via trio107 sphinx==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-cabinet114 sphinx-issues==5.0.0115- # via -r docs.in115+ # via -r /Users/david/Projects/jinja/requirements/docs.in116 sphinx-notfound-page==1.0.4117 # via pallets-sphinx-themes118 sphinxcontrib-applehelp==2.0.0119 # via sphinx3 unmodified lines123 # via sphinx124 sphinxcontrib-jsmath==1.0.1125 # via sphinx126 sphinxcontrib-log-cabinet==1.0.1127- # via -r docs.in127+ # via -r /Users/david/Projects/jinja/requirements/docs.in128 sphinxcontrib-qthelp==2.0.0129 # via sphinx130 sphinxcontrib-serializinghtml==2.0.0131 # via sphinx1 unmodified line133 # via pip-compile-multi134 tox==4.23.2135 # via -r dev.in136 trio==0.27.0137- # via -r tests.in137+ # via -r /Users/david/Projects/jinja/requirements/tests.in138 typing-extensions==4.12.2139 # via mypy140 urllib3==2.2.3141 # via requests142-virtualenv==20.27.0142+virtualenv==20.28.0143 # via144 # pre-commit145 # tox146-wheel==0.44.0146+wheel==0.45.1147 # via pip-tools148 149 # The following packages are considered to be unsafe in a requirements file:150 # pip1 unmodified linemodified:requirements/docs.txt+2 added-2 removed
6 unmodified lines7 alabaster==1.0.08 # via sphinx9 babel==2.16.010 # via sphinx11-certifi==2024.8.3011+certifi==2024.12.1412 # via requests13 charset-normalizer==3.4.014 # via requests15 docutils==0.21.25 unmodified lines21 jinja2==3.1.422 # via sphinx23 markupsafe==3.0.224 # via jinja225-packaging==24.125+packaging==24.226 # via27 # pallets-sphinx-themes28 # sphinx29 pallets-sphinx-themes==2.3.034 unmodified linesmodified:requirements/tests.txt+3 added-3 removed
2 unmodified lines3 # by the following command:4 #5 # pip-compile tests.in6 #7-attrs==24.2.07+attrs==24.3.08 # via9 # outcome10 # trio11 idna==3.101 unmodified line13 iniconfig==2.0.014 # via pytest15 outcome==1.3.0.post016 # via trio17-packaging==24.117+packaging==24.218 # via pytest19 pluggy==1.5.020 # via pytest21-pytest==8.3.321+pytest==8.3.422 # via -r tests.in23 sniffio==1.3.124 # via trio25 sortedcontainers==2.4.03 unmodified linesmodified:requirements/typing.txt+1 added-1 removed
2 unmodified lines3 # by the following command:4 #5 # pip-compile typing.in6 #7-mypy==1.13.07+mypy==1.14.08 # via -r typing.in9 mypy-extensions==1.0.010 # via mypy11 typing-extensions==4.12.21 unmodified linemodified:src/jinja2/compiler.py+37 added-15 removed
214 unmodified lines215 # expression as it determines which errors should be raised during runtime216 # or compile time.217 self.soft_frame = False218 219- 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 lines228 if isolated:229 return Frame(self.eval_ctx, level=self.symbols.level + 1)230 return Frame(self.eval_ctx, self)231 232- 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 lines810 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 line820 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}))")826 827 # -- Statement Visitors828 311 unmodified lines1140 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 lines1580 self.outdent()1581 1582 def visit_Assign(self, node: nodes.Assign, frame: Frame) -> None:1583 self.push_assign_tracking()1584+1585+ # ``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()1590+1591+ 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+ continue1596+1597+ 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()1606+1607 self.newline(node)1608 self.visit(node.target, frame)1609 self.write(" = ")1610 self.visit(node.node, frame)48 unmodified lines1659 1660 self.write(ref)1661 1662 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}]")1669 1670 def visit_Const(self, node: nodes.Const, frame: Frame) -> None:1671 val = node.as_const(frame.eval_ctx)327 unmodified linesmodified:src/jinja2/environment.py+7 added-4 removed
123 unmodified lines124 125 return result126 127 128-def _environment_config_check(environment: "Environment") -> "Environment":128+def _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 lines407 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 it3 unmodified lines420 up completely. Not all attributes are truly linked, some are just421 copied over so modifications on the original environment may not shine422 through.423 424+ .. versionchanged:: 3.1.5425+ ``enable_async`` is applied correctly.426+427 .. 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 linesmodified:src/jinja2/ext.py+1 added-1 removed
87 unmodified lines88 89 def __init__(self, environment: Environment) -> None:90 self.environment = environment91 92- 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 = environment758 unmodified linesmodified:src/jinja2/filters.py+19 added-7 removed
436 unmodified lines437 return sorted(value, key=key_func, reverse=reverse)438 439 440 @pass_environment441-def do_unique(441+def 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 lines469 seen.add(key)470 yield item471 472 473+@async_variant(sync_do_unique) # type: ignore474+async 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+ )483+484+485 def _min_or_max(486 environment: "Environment",487 value: "t.Iterable[V]",488 func: "t.Callable[..., V]",509 unmodified lines998 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 default1004 1005 1006 def do_float(value: t.Any, default: float = 0.0) -> float:633 unmodified lines1640 Similar to a generator comprehension such as:1641 1642 .. code-block:: python1643 1632- (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))1646 1647 .. versionadded:: 2.71648 """1649 return select_or_reject(context, value, args, kwargs, lambda x: x, True)28 unmodified lines1678 Similar to a generator comprehension such as:1679 1680 .. code-block:: python1681 1670- (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))1684 1685 .. versionadded:: 2.71686 """1687 return select_or_reject(context, value, args, kwargs, lambda x: not x, True)91 unmodified lines1779 name = args[off]1780 args = args[1 + off :]1781 1782 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)1784 1785 except LookupError:1786 func = bool # type: ignore1787 91 unmodified linesmodified:src/jinja2/idtracking.py+11 added-11 removed
1 unmodified line2 3 from . import nodes4 from .visitor import NodeVisitor5 6+if t.TYPE_CHECKING:7+ import typing_extensions as te8+9 VAR_LOAD_PARAMETER = "param"10 VAR_LOAD_RESOLVE = "resolve"11 VAR_LOAD_ALIAS = "alias"12 VAR_LOAD_UNDEFINED = "undefined"72 unmodified lines85 f" unknown to the frame ({name!r})"86 )87 return rv88 86- 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 lines120 if self.find_ref(name) is None:121 self._define_ref(name, load=(VAR_LOAD_RESOLVE, name))122 123 def branch_update(self, branch_symbols: t.Sequence["Symbols"]) -> None:121- stores: t.Dict[str, int] = {}124+ stores: t.Set[str] = set()125+126 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)128 129+ stores.difference_update(self.stores)130+131 for sym in branch_symbols:132 self.refs.update(sym.refs)133 self.loads.update(sym.loads)134 self.stores.update(sym.stores)135 133- for name, branch_count in stores.items():134- if branch_count == len(branch_symbols):135- continue136-137- 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"139 140 if self.parent is not None:141 outer_target = self.parent.find_ref(name)177 unmodified linesmodified:src/jinja2/lexer.py+3 added-3 removed
260 unmodified lines261 ) -> None:262 self.message = message263 self.error_class = cls264 265- 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)267 268 269 class Token(t.NamedTuple):486 unmodified lines756 groups = [text[:l_pos], *groups[1:]]757 758 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 matched12 unmodified lines777 else:778 data = groups[idx]779 780 if data or token not in ignore_if_empty:781- yield lineno, token, data781+ yield lineno, token, data # type: ignore[misc]782 783 lineno += data.count("\n") + newlines_stripped784 newlines_stripped = 0785 83 unmodified linesmodified:src/jinja2/loaders.py+19 added-13 removed
202 unmodified lines203 204 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+ )213 214 with open(filename, encoding=self.encoding) as f:215 contents = f.read()216 109 unmodified lines326 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 = None330 331 if isinstance(loader, zipimport.zipimporter):332 self._archive = loader.archive333 pkgdir = next(iter(spec.submodule_search_locations)) # type: ignore8 unmodified lines342 # A single module file, use the parent directory instead.343 elif spec.origin is not None:344 roots.append(os.path.dirname(spec.origin))345 346+ if not roots:347+ raise ValueError(348+ f"The {package_name!r} package was not installed in a"349+ " way that PackageLoader understands."350+ )351+352 for root in roots:353 root = os.path.join(root, package_path)354 355 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+ )363 349- 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- )354-364 self._template_root = template_root365 366 def get_source(367 self, environment: "Environment", template: str67 unmodified lines435 template source. This loader is useful for unittesting:436 437 >>> loader = DictLoader({'index.html': 'source here'})438 430- Because auto reloading is rarely useful this is disabled per default.439+ Because auto reloading is rarely useful this is disabled by default.440 """441 442 def __init__(self, mapping: t.Mapping[str, str]) -> None:443 self.mapping = mapping174 unmodified lines618 """This loader loads templates from precompiled templates.619 620 Example usage:621 613- >>> loader = ChoiceLoader([614- ... ModuleLoader('/path/to/compiled/templates'),615- ... FileSystemLoader('/path/to/templates')616- ... ])622+ >>> loader = ModuleLoader('/path/to/compiled/templates')623 624 Templates can be precompiled with :meth:`Environment.compile_templates`.625 """626 64 unmodified linesmodified:src/jinja2/parser.py+24 added-16 removed
485 unmodified lines486 `with_namespace` is enabled, a namespace assignment may be parsed.487 """488 target: nodes.Expr489 490- 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)502 503 target.set_ctx("store")504 505 if not target.can_assign():133 unmodified lines639 if with_filter:640 node = self.parse_filter_expr(node)641 return node642 646- 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.lineno21 unmodified lines687 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.697 698 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`.702 703 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 the4 unmodified lines710 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_expression714+715+ def parse() -> nodes.Expr:716+ return self.parse_primary(with_namespace=with_namespace)717+718 else:719 720 def parse() -> nodes.Expr:713- return self.parse_expression(with_condexpr=False)721+ return self.parse_expression(with_condexpr=with_condexpr)722 723 args: t.List[nodes.Expr] = []724 is_tuple = False725 324 unmodified linesmodified:src/jinja2/runtime.py+23 added-17 removed
365 unmodified lines366 return BlockReference(self.name, self._context, self._stack, self._depth + 1)367 368 @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 )373 374 if self._context.eval_ctx.autoescape:5 unmodified lines380 def __call__(self) -> str:381 if self._context.environment.is_async:382 return self._async_call() # type: ignore383 384- rv = concat(self._stack[self._depth](self._context))384+ rv = self._context.environment.concat( # type: ignore385+ self._stack[self._depth](self._context)386+ )387 388 if self._context.eval_ctx.autoescape:389 return Markup(rv)390 402 unmodified lines793 return f"<{type(self).__name__} {name}>"794 795 796 class 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`.799 800 >>> foo = Undefined(name='foo')801 >>> str(foo)802 ''56 unmodified lines859 raise self._undefined_exception(self._undefined_message)860 861 @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)869 870 return self._fail_with_undefined_error()871 115 unmodified lines987 988 def __html__(self) -> str:989 return str(self)990 985- 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)1000+1001 return self1002 988- __getitem__ = __getattr__ # type: ignore1003+ def __getitem__(self, _name: str) -> "ChainableUndefined": # type: ignore[override]1004+ return self1005 1006 1007 class DebugUndefined(Undefined):1008 """An undefined that returns the debug info when printed.50 unmodified lines1059 __slots__ = ()1060 __iter__ = __str__ = __len__ = Undefined._fail_with_undefined_error1061 __eq__ = __ne__ = __bool__ = __hash__ = Undefined._fail_with_undefined_error1062 __contains__ = Undefined._fail_with_undefined_error1047-1048-1049-# Remove slots attributes, after the metaclass is applied they are1050-# unneeded and contain wrong data for subclasses.1051-del (1052- Undefined.__slots__,1053- ChainableUndefined.__slots__,1054- DebugUndefined.__slots__,1055- StrictUndefined.__slots__,1056-)modified:src/jinja2/sandbox.py+46 added-39 removed
6 unmodified lines7 import typing as t8 from _string import formatter_field_name_split # type: ignore9 from collections import abc10 from collections import deque11+from functools import update_wrapper12 from string import Formatter13 14 from markupsafe import EscapeFormatter15 from markupsafe import Markup44 unmodified lines60 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 lines83 ),84 )85 86 84-def 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 None89-90- obj = callable.__self__91-92- if isinstance(obj, str):93- return obj94-95- return None96-97-87 def 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 lines302 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 lines322 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 lines340 obj=obj,341 exc=SecurityError,342 )343 349- 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 None354+355+ f_self: t.Any = value.__self__356+357+ if not isinstance(f_self, str):358+ return None359+360+ str_type: t.Type[str] = type(f_self)361+ is_format_map = value.__name__ == "format_map"362 formatter: SandboxedFormatter363+360- 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)368 365- 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.vformat370 372- 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")375 375- 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+ )380 381+ kwargs = args[0]382+ args = ()383+384+ return str_type(vformat(f_self, args, kwargs))385+386+ return update_wrapper(wrapper, value)387+388 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)396 397 # the double prefixes are to avoid double keyword argument398 # errors when proxying the call.399 if not __self.is_safe_callable(__obj):37 unmodified linesmodified:src/jinja2/utils.py+14 added-3 removed
16 unmodified lines17 import typing_extensions as te18 19 F = t.TypeVar("F", bound=t.Callable[..., t.Any])20 21-# special singleton representing missing values for the runtime22-missing: t.Any = type("MissingType", (), {"__repr__": lambda x: "missing"})()21 22+class _MissingType:23+ def __repr__(self) -> str:24+ return "missing"25+26+ def __reduce__(self) -> str:27+ return "missing"28+29+30+missing: t.Any = _MissingType()31+"""Special singleton representing missing values for the runtime."""32+33 internal_code: t.MutableSet[CodeType] = set()34 35 concat = "".join36 295 unmodified lines332 333 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 lines463 464 def __getnewargs__(self) -> t.Tuple[t.Any, ...]:465 return (self.capacity,)466 456- 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 linesmodified:tests/test_api.py+8 added-8 removed
321 unmodified lines322 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: B009326 327 def test_chainable_undefined(self):328 env = Environment(undefined=ChainableUndefined)329 # The following tests are copied from test_default_undefined2 unmodified lines332 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: B009336 337 # 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 lines363 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: B009367 368 def test_strict_undefined(self):369 env = Environment(undefined=StrictUndefined)370 pytest.raises(UndefinedError, env.from_string("{{ missing }}").render)8 unmodified lines379 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() == ""384 385 def test_indexing_gives_undefined(self):386 t = Template("{{ var[42].foo }}")37 unmodified lines424 425 env = CustomEnvironment()426 tmpl = env.from_string("{{ foo }}")427 assert tmpl.render() == "resolve-foo"428+429+430+def 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_asyncmodified:tests/test_async_filters.py+7 added
264 unmodified lines265 "[[0, 1, 2, 3], [4, 5, 6, 'X'], [7, 8, 9, 'X']]"266 )267 268 269+def 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']"274+275+276 def test_custom_async_filter(env_async, run_async_fn):277 async def customfilter(val):278 return str(val)279 31 unmodified linesmodified:tests/test_compile.py+80 added
1 import os2 import re3 4+import pytest5+6+from jinja2 import UndefinedError7 from jinja2.environment import Environment8 from jinja2.loaders import DictLoader9 10 17 unmodified lines28 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 == expect32+33+34+def 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 == expect57+58+59+def 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 == expect75+76+77+def 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 == expect93+94+95+def test_undefined_import_curly_name():96+ env = Environment(97+ loader=DictLoader(98+ {99+ "{bad}": "{% from 'macro' import m %}{{ m() }}",100+ "macro": "",101+ }102+ )103+ )104+105+ # 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 lines537 "{{ ns.a }}|{{ ns.b }}"538 )539 assert tmpl.render() == "13|37"540 541+ 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"548+549 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 linesmodified:tests/test_filters.py+1 added
194 unmodified lines195 ("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 linesmodified:tests/test_loader.py+23 added
177 unmodified lines178 e = Environment(loader=loader)179 t = e.get_template("foo/test.html")180 assert t.filename == str(self.searchpath / "foo" / "test.html")181 182+ def test_error_includes_paths(self, env, filesystem_loader):183+ env.loader = filesystem_loader184 185+ with pytest.raises(TemplateNotFound) as info:186+ env.get_template("missing")187+188+ e_str = str(info.value)189+ assert e_str.startswith("'missing' not found in search path: ")190+191+ filesystem_loader.searchpath.append("other")192+193+ with pytest.raises(TemplateNotFound) as info:194+ env.get_template("missing")195+196+ e_str = str(info.value)197+ assert e_str.startswith("'missing' not found in search paths: ")198+ assert ", 'other'" in e_str199+200+201 class TestModuleLoader:202 archive = None203 mod_env = None204 223 unmodified lines428 package_loader = PackageLoader("res")429 assert "test.html" in package_loader.list_templates()430 finally:431 sys.meta_path[:] = before432+433+434+def 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 lines176 t = env.from_string("{%- macro x() -%}{{- [1,2] -}}{%- endmacro -%}{{- x()[1] -}}")177 result = t.render()178 assert result == 2179 assert isinstance(result, int)180+181+182+def 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 lines736 "{% endset %}{{ output }}"737 )738 assert tmpl.render() == "hellohellohello"739 740+ 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"745 746+ 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"751+752+753+def 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"761+762+763 @pytest.mark.parametrize("unicode_char", ["\N{FORM FEED}", "\x85"])764 def test_unicode_whitespace(env, unicode_char):765 content = "Lorem ipsum\n" + unicode_char + "\nMore text"766 tmpl = env.from_string(content)1 unmodified linemodified:tests/test_runtime.py+50 added
1+import copy2 import itertools3+import pickle4 5+import pytest6+7+from jinja2 import ChainableUndefined8+from jinja2 import DebugUndefined9+from jinja2 import StrictUndefined10 from jinja2 import Template11+from jinja2 import TemplateRuntimeError12+from jinja2 import Undefined13 from jinja2.runtime import LoopContext14 15 TEST_IDX_TEMPLATE_STR_1 = (16 "[{% for i in lst|reverse %}(len={{ loop.length }},"64 unmodified lines81 t = Template("{{ calc() }}")82 out = t.render(calc=Calc())83 # Would be "1" if context argument was passed.84 assert out == "0"85+86+87+_undefined_types = (Undefined, ChainableUndefined, DebugUndefined, StrictUndefined)88+89+90+@pytest.mark.parametrize("undefined_type", _undefined_types)91+def test_undefined_copy(undefined_type):92+ undef = undefined_type("a hint", ["foo"], "a name", TemplateRuntimeError)93+ copied = copy.copy(undef)94+95+ 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_exception100+101+102+@pytest.mark.parametrize("undefined_type", _undefined_types)103+def test_undefined_deepcopy(undefined_type):104+ undef = undefined_type("a hint", ["foo"], "a name", TemplateRuntimeError)105+ copied = copy.deepcopy(undef)106+107+ 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_exception112+113+114+@pytest.mark.parametrize("undefined_type", _undefined_types)115+def test_undefined_pickle(undefined_type):116+ undef = undefined_type("a hint", ["foo"], "a name", TemplateRuntimeError)117+ copied = pickle.loads(pickle.dumps(undef))118+119+ 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_exceptionmodified:tests/test_security.py+19 added
56 unmodified lines57 58 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)64 65 def test_restricted(self, env):66 env = SandboxedEnvironment()105 unmodified lines172 t = env.from_string(173 '{{ ("a{x.foo}b{y}"|safe).format_map({"x":{"foo": 42}, "y":"<foo>"}) }}'174 )175 assert t.render() == "a42b<foo>"176+177+ def test_indirect_call(self):178+ def run(value, arg):179+ return value.run(arg)180+181+ 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+ )190+191+ with pytest.raises(SecurityError):192+ t.render()modified:tests/test_utils.py+20 added
1+import copy2 import pickle3 import random4 from collections import deque5 from copy import copy as shallow_copy135 unmodified lines141 ' target="<script>">'142 "http://example.org</a>"143 )144 145+ 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) == to152 153+154 class 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 lines191 x = iter([1, 2, 3, 4, 5])192 consume(x)193 with pytest.raises(StopIteration):194 next(x)195+196+197+@pytest.mark.parametrize("protocol", range(pickle.HIGHEST_PROTOCOL + 1))198+def 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 missing201+202+203+def test_copy_missing() -> None:204+ """Test that missing can be copied while remaining a singleton."""205+ assert copy.copy(missing) is missingmodified:.pre-commit-config.yaml+1 added-1 removed
1 repos: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-hooks7 unmodified linesmodified:CHANGES.rst+36 added-2 removed
12 unmodified lines13 14 Version 3.1.515 -------------16 17-Unreleased17+Released 2024-12-2118 19+- 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`` from1 unmodified line32 - 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`62 63 64 Version 3.1.465 -------------979 unmodified lines1045 - ``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 finalizer1052 1053 6 unmodified lines