Skip to content

Build AI methods with your coding agent, then run them anywhere: as an MCP for chatbots, as a webapp for people, or via API for your software.

fix/Filter-block-prints-through-finalize · L-261010-d3190c (#1417)

Louis Choquel843169090be7
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 0e784c5f1..78649e550 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,5 +1,11 @@
# Changelog
+## [Unreleased]
+
+### Fixed
+
+- **A `{% filter %}` block prints its result as a `{{ }}` tag does**: a filter block whose filter returns something other than text, such as `{% filter markdown %}…{% endfilter %}` in a document template or `{% filter length %}`, now prints its result as a `{{ }}` tag prints a value, through the environment's `finalize` and then as text, where it used to fail the render with a type error naming a Python type. A block whose filter returns text prints as before, and the printed result is charged to the render's budget like any printed value.
+
## [v0.83.0] - 2026-10-11
### Added
diff --git a/docs/under-the-hood/document-engine-plugins.md b/docs/under-the-hood/document-engine-plugins.md
index 169c7d255..b995dfaf4 100644
--- a/docs/under-the-hood/document-engine-plugins.md
+++ b/docs/under-the-hood/document-engine-plugins.md
@@ -160,7 +160,7 @@ A document should read the same whichever engine printed it, and a template shou
`pipelex.cogt.doc_gen.template_environment` holds **`make_plain_data_template_environment()`**, the Jinja environment an engine fills a template file's tags in when it fills them itself, as a Word template's tags are filled through docxtpl. It is synchronous; sandboxed as every Pipelex template is, each render spending from a budget of its own (see [Template Sandbox](template-sandbox.md)); strict, so a missing value fails the render instead of printing as empty text; and it registers Jinja's built-in filters and one of Pipelex's, `markdown`, since the plain data it reads holds no stuff for Pipelex's other filters to work on.
-`{{ invoice.notes | markdown }}` reads a text as Markdown into a `FormattedMarkdown`, as the HTML templates' `markdown` filter reads it into HTML: None gives an empty one, any other value is read as its string form, and an undefined value fails the render, as it would anywhere in a strict template. An empty one is false, so a template leaves out a section whose notes are None, empty or blank by converting them once into a variable and testing it, `{% set notes = invoice.notes | markdown %}{% if notes %}…{{ notes }}…{% endif %}`: every conversion is charged to the render's budget, so testing `invoice.notes | markdown` and then printing `invoice.notes | markdown` converts the text twice and halves the length a render affords. How a `FormattedMarkdown` prints is the engine's business, so `make_plain_data_template_environment(finalize=…)` takes a function applied to every value a tag prints, before the environment converts it to text: an engine turns a `FormattedMarkdown` into its own form there and hands every other value back as it is. The environment wraps it to charge what is printed, which is why it is passed at construction rather than assigned afterwards. Without one, a `FormattedMarkdown` prints its plain text, so a place that cannot format, such as a document's properties, prints clean text rather than asterisks.
+`{{ invoice.notes | markdown }}` reads a text as Markdown into a `FormattedMarkdown`, as the HTML templates' `markdown` filter reads it into HTML: None gives an empty one, any other value is read as its string form, and an undefined value fails the render, as it would anywhere in a strict template. An empty one is false, so a template leaves out a section whose notes are None, empty or blank by converting them once into a variable and testing it, `{% set notes = invoice.notes | markdown %}{% if notes %}…{{ notes }}…{% endif %}`: every conversion is charged to the render's budget, so testing `invoice.notes | markdown` and then printing `invoice.notes | markdown` converts the text twice and halves the length a render affords. How a `FormattedMarkdown` prints is the engine's business, so `make_plain_data_template_environment(finalize=…)` takes a function applied to every value a tag prints, before the environment converts it to text: an engine turns a `FormattedMarkdown` into its own form there and hands every other value back as it is. The environment wraps it to charge what is printed, which is why it is passed at construction rather than assigned afterwards. A filter block prints through it too, so `{% filter markdown %}…{% endfilter %}` formats the text of its body as `{{ … | markdown }}` formats a text. The block reads its body as printed text, though, so a None value printed in it reaches the filter as the text `None`: an optional value is converted with the tag form, which turns None into an empty one. Without one, a `FormattedMarkdown` prints its plain text, so a place that cannot format, such as a document's properties, prints clean text rather than asterisks.
---
diff --git a/docs/under-the-hood/template-sandbox.md b/docs/under-the-hood/template-sandbox.md
index 5b89ef48f..56f631521 100644
--- a/docs/under-the-hood/template-sandbox.md
+++ b/docs/under-the-hood/template-sandbox.md
@@ -78,7 +78,8 @@ The environment charges through the sandbox's hooks and one rewrite, all in `Pip
- **Calls and operators** go through the sandbox's `call` and `call_binop` hooks, and every arithmetic operator is intercepted.
- **Filters and tests** are wrapped before a template compiles. A filter or a test registered on the environment must have a cost in `FILTER_COSTS` or `TEST_COSTS` (`pipelex/tools/jinja2/jinja2_render_costs.py`), or the first compile fails with a `TypeError` naming it.
- **Printed values** go through the environment's `finalize`, which charges the text it produces. A caller's own `finalize` is passed to the constructor and runs first.
-- **What no hook reaches**, which is loop iteration, `~`, comparisons, slices, list, tuple and dict literals and the template's static text, is routed through internal charging filters by a rewrite of the parsed template (`pipelex/tools/jinja2/jinja2_render_rewrite.py`). The rewrite changes what is charged, never what a template renders. A tuple used as a key, in a dict literal or an item read, is also charged for hashing, since a tuple hashes every element again each time.
+- **What no hook reaches**, which is loop iteration, `~`, comparisons, slices, list, tuple and dict literals, the template's static text and a `{% filter %}` block's result, is routed through internal filters by a rewrite of the parsed template (`pipelex/tools/jinja2/jinja2_render_rewrite.py`). The rewrite changes what is charged, never what a template that renders without it renders. A tuple used as a key, in a dict literal or an item read, is also charged for hashing, since a tuple hashes every element again each time.
+- **A filter block's result** is printed as a `{{ }}` tag prints a value. Jinja writes it out as it is, with neither `finalize` nor a conversion to text, so a filter returning something other than text, such as `{% filter length %}`, would otherwise fail the render. The rewrite hands the result to an internal filter that returns text as it is, unescaped under autoescape as Jinja leaves it, and passes any other result through `finalize`, the caller's own included, then converts it as a printed value is. Either way the result is charged as a print.
- **Converting Markdown to HTML** is charged where it happens, in `pipelex/tools/markdown/markdown_parser.py`, since markupsafe converts a Markdown value through its `__html__` wherever an HTML template prints, escapes, joins or formats one, and no hook sees that call. The template makes its budget the active one while it renders, and the conversion charges it 2,048 units for every character of its source and every cell of its tables before it parses, then checks that its output, bounded from the parsed tokens, fits what is left before it renders, since a reference link is printed at every use. A conversion costs microseconds a character, so a render converts at most about 65,000 characters of Markdown, a document printed twice counting twice. Formatting Markdown for a document engine, which the `markdown` filter of plain-data templates does, is charged the same way, in `pipelex/tools/markdown/markdown_formatting.py`: both conversions parse through `charged_parse`, which holds the order of the charges.
The budget is the same for every template category and is not a setting in `pipelex.toml`: it is a safety bound, not a tuning knob. `PipelexTemplateEnvironment` takes it as the `render_budget_units` constructor argument, which the tests use to exercise small budgets.
diff --git a/pipelex/cogt/doc_gen/template_environment.py b/pipelex/cogt/doc_gen/template_environment.py
index dbe4574c3..c0fcc8310 100644
--- a/pipelex/cogt/doc_gen/template_environment.py
+++ b/pipelex/cogt/doc_gen/template_environment.py
@@ -36,8 +36,11 @@ def make_plain_data_template_environment(*, finalize: Callable[..., Any] | None
`finalize`, when given, is applied to every value a tag prints before the environment converts it to text, so an
engine turns a printed `FormattedMarkdown` into its own form there and hands every other value back as it is.
- Without one, a `FormattedMarkdown` prints its plain text. It is handed to the environment at construction, which a
- Pipelex environment requires, since the environment wraps it to charge what is printed.
+ A filter block's result that is not text is printed the same way, so `{% filter markdown %}…{% endfilter %}`
+ formats the text of its body as `{{ … | markdown }}` formats a text; the block reads its body as printed text,
+ so a None value printed in it reaches the filter as the text "None". Without one, a `FormattedMarkdown` prints
+ its plain text. It is handed to the environment at construction, which a Pipelex environment requires, since the
+ environment wraps it to charge what is printed.
It loads no template by name, so a template is built from its source with `from_string`.
"""
diff --git a/pipelex/tools/jinja2/jinja2_filters.py b/pipelex/tools/jinja2/jinja2_filters.py
index 02227a669..04ff7c05a 100644
--- a/pipelex/tools/jinja2/jinja2_filters.py
+++ b/pipelex/tools/jinja2/jinja2_filters.py
@@ -231,9 +231,9 @@ def markdown_to_formatted(value: Any) -> FormattedMarkdown:
The result is a `FormattedMarkdown` (`markdown_formatting.py`, which the document engine contract names in
`pipelex/cogt/doc_gen/formatted_markdown.py`), which the engine's `finalize` turns into its own form when it
- prints, which prints as its plain text where nothing does, and which is false when it holds nothing, as for None
- or a blank text. The conversion is charged to the render's budget, or, called outside any render, to a budget of
- its own, as large as one render's.
+ prints, in a `{{ … | markdown }}` tag or a `{% filter markdown %}` block alike, which prints as its plain text
+ where nothing does, and which is false when it holds nothing, as for None or a blank text. The conversion is
+ charged to the render's budget, or, called outside any render, to a budget of its own, as large as one render's.
"""
if value is None:
return FormattedMarkdown(blocks=[])
diff --git a/pipelex/tools/jinja2/jinja2_render_charging.py b/pipelex/tools/jinja2/jinja2_render_charging.py
index f4c4c2e08..f14284953 100644
--- a/pipelex/tools/jinja2/jinja2_render_charging.py
+++ b/pipelex/tools/jinja2/jinja2_render_charging.py
@@ -9,10 +9,11 @@ the render runs, for the work a template sets off where no hook reaches (`active
- **Filters and tests.** Every filter and test registered on the environment is wrapped by
`charged_filter` and `charged_test` before a template compiles (`charge_registered_functions`),
which refuses a function the cost tables do not classify.
-- **Printing.** `{{ value }}` goes through the environment's `finalize`, built by `make_charged_finalize`.
-- **What no hook reaches.** Loops, `~`, comparisons, slices and static text compile to plain Python,
- so the environment rewrites the parsed template (`jinja2_render_rewrite.py`) to route each through
- one of the internal filters defined here.
+- **Printing.** `{{ value }}` goes through the environment's `finalize`, built by `make_charged_finalize`,
+ and a `{% filter %}` block's result through `printed_block`, which prints it the same way.
+- **What no hook reaches.** Loops, `~`, comparisons, slices, static text and a filter block's result
+ compile to plain Python, so the environment rewrites the parsed template (`jinja2_render_rewrite.py`)
+ to route each through one of the internal filters defined here.
The rule each hook applies is in `jinja2_render_budget.py`, and the estimates in `jinja2_render_costs.py`.
"""
@@ -504,7 +505,8 @@ def make_charged_finalize(*, inner: Callable[..., Any] | None) -> Callable[...,
"""The environment's `finalize`: convert a printed value to text, charged, after the caller's own `finalize`.
Jinja converts what `finalize` returns once more (`str()`, or `escape()` under autoescape), which
- leaves text this has already converted unchanged.
+ leaves text this has already converted unchanged. A `{% filter %}` block's result that is not text
+ reaches it too, through `printed_block`.
"""
inner_pass_arg = _pass_arg_of(function=inner) if inner is not None else None
@@ -537,6 +539,7 @@ COMPARE_FILTER: Final = "_pipelex_charged_comparison"
COMPARED_FILTER: Final = "_pipelex_charged_operand"
SLICED_FILTER: Final = "_pipelex_charged_slice"
LITERAL_FILTER: Final = "_pipelex_charged_literal"
+PRINTED_BLOCK_FILTER: Final = "_pipelex_printed_block"
_COMPARISONS: Final[dict[str, Callable[[Any, Any], Any]]] = {
"eq": operator.eq,
@@ -617,6 +620,26 @@ def tuple_keys_weight(*, literal: object, limit: int) -> int:
return sum(compare_weight(key, limit=limit) for key in cast("dict[object, object]", literal) if isinstance(key, tuple))
+@pass_context
+def printed_block(context: Context, value: Any) -> Any:
+ """What a `{% filter %}` block prints: its filters' result, printed as a `{{ }}` tag prints a value.
+
+ Jinja writes a filter block's result out as it is, with neither the environment's `finalize` nor a conversion
+ to text, so a filter returning anything but text, such as `length` or the document templates' `markdown`, would
+ fail the render. A text result is returned as it is, left unescaped under autoescape as Jinja leaves it, since
+ Jinja's filters keep the markup of a block's body. Any other result goes through the environment's `finalize`,
+ which charges it, then is converted as a printed value is. A text result is charged here as `finalize` charges
+ a printed one, so that everything a template prints is charged as printing.
+ """
+ if isinstance(value, str):
+ render_budget_of(context).charge(units=STEP_UNITS + size_of(value), operation=_PRINTING)
+ return value
+ finalize = context.environment.finalize
+ if finalize is not None:
+ value = finalize(*_first_argument(pass_arg=_pass_arg_of(function=finalize), context=context), value)
+ return escape(value) if context.eval_ctx.autoescape else str(value)
+
+
INTERNAL_FILTERS: Final[dict[str, Callable[..., Any]]] = {
ITERATE_FILTER: charged_iteration,
CONCAT_FILTER: charged_concat,
@@ -624,4 +647,5 @@ INTERNAL_FILTERS: Final[dict[str, Callable[..., Any]]] = {
COMPARED_FILTER: charged_operand,
SLICED_FILTER: charged_slice,
LITERAL_FILTER: charged_literal,
+ PRINTED_BLOCK_FILTER: printed_block,
}
diff --git a/pipelex/tools/jinja2/jinja2_render_rewrite.py b/pipelex/tools/jinja2/jinja2_render_rewrite.py
index 0b202b408..6f600b0eb 100644
--- a/pipelex/tools/jinja2/jinja2_render_rewrite.py
+++ b/pipelex/tools/jinja2/jinja2_render_rewrite.py
@@ -1,19 +1,23 @@
"""Rewrite a parsed template so that what no sandbox hook reaches is charged to the render's budget.
-Six constructs compile to plain Python, with no hook the sandbox could use to charge them:
+These constructs compile to plain Python, with no hook the sandbox could use to charge them:
- iterating a `{% for %}` loop, which an empty loop body makes free;
- joining with `~`;
- comparing (`==`, `<`, `in` and the rest);
- slicing (`value[a:b]`), which bypasses the sandbox's `getitem`;
- writing out a list, a tuple or a dict (`[a, b]`, `(a, b)`, `{k: v}`), which a loop rebuilds;
-- emitting the template's own static text, which a loop repeats.
+- emitting the template's own static text, which a loop repeats;
+- printing a `{% filter %}` block's result, which Jinja writes out without the environment's `finalize`.
`PipelexTemplateEnvironment._generate`, the hook Jinja documents for this, runs the parsed template
-through `rewrite_for_render_budget` before compiling it, so that each goes through one of the charging
+through `rewrite_for_render_budget` before compiling it, so that each goes through one of the internal
filters of `jinja2_render_charging.py`. Static text becomes a constant marked safe, which the
-environment's `finalize` charges without escaping it. The rewrite changes what is charged, never what
-a template renders.
+environment's `finalize` charges without escaping it. A filter block's result goes through
+`printed_block`, which prints it as a `{{ }}` tag prints a value, so a filter returning anything but
+text, which Jinja would fail to join into the output, prints through `finalize` too. The rewrite
+changes what is charged, and makes such a filter block print, but never changes what a template that
+renders without it renders.
"""
from __future__ import annotations
@@ -30,6 +34,7 @@ from pipelex.tools.jinja2.jinja2_render_charging import (
CONCAT_FILTER,
ITERATE_FILTER,
LITERAL_FILTER,
+ PRINTED_BLOCK_FILTER,
SLICED_FILTER,
)
@@ -46,7 +51,7 @@ def _is_charging_filter(*, node: nodes.Node, name: str) -> bool:
class _RenderBudgetRewriter(NodeTransformer):
- """Route loops, `~`, comparisons, slices, literals and static text through the budget's charging filters."""
+ """Route loops, `~`, comparisons, slices, literals, static text and filter blocks through the budget's internal filters."""
@override
def get_visitor(self, node: nodes.Node) -> Callable[..., Any] | None:
@@ -63,6 +68,8 @@ class _RenderBudgetRewriter(NodeTransformer):
return self._rewrite_filter
case nodes.Output():
return self._rewrite_output
+ case nodes.FilterBlock():
+ return self._rewrite_filter_block
case nodes.List() | nodes.Dict():
return self._rewrite_literal
case nodes.Tuple():
@@ -116,6 +123,13 @@ class _RenderBudgetRewriter(NodeTransformer):
self.generic_visit(node)
return node
+ def _rewrite_filter_block(self, node: nodes.FilterBlock) -> nodes.Node:
+ self.generic_visit(node)
+ if not _is_charging_filter(node=node.filter, name=PRINTED_BLOCK_FILTER):
+ # The block's filters apply to its body; the outermost one's result is what the block prints.
+ node.filter = _charging_filter(node=node.filter, name=PRINTED_BLOCK_FILTER)
+ return node
+
def _rewrite_output(self, node: nodes.Output) -> nodes.Node:
self.generic_visit(node)
children: list[Any] = []
diff --git a/subject_grants.toml b/subject_grants.toml
index 4e25b479f..562a8c25d 100644
--- a/subject_grants.toml
+++ b/subject_grants.toml
@@ -5752,6 +5752,10 @@ rationale = "Jinja NodeVisitor dispatch: visit() calls the visitor get_visitor r
param = "node"
rationale = "Jinja NodeVisitor dispatch: visit() calls the visitor get_visitor returns with the node positionally."
+["pipelex/tools/jinja2/jinja2_render_rewrite.py::_RenderBudgetRewriter._rewrite_filter_block"]
+param = "node"
+rationale = "Jinja NodeVisitor dispatch: visit() calls the visitor get_visitor returns with the node positionally."
+
["pipelex/tools/jinja2/jinja2_render_rewrite.py::_RenderBudgetRewriter._rewrite_item"]
param = "node"
rationale = "Jinja NodeVisitor dispatch: visit() calls the visitor get_visitor returns with the node positionally."
diff --git a/tests/unit/pipelex/cogt/doc_gen/test_template_environment.py b/tests/unit/pipelex/cogt/doc_gen/test_template_environment.py
index 0305f6b70..84dcffbdf 100644
--- a/tests/unit/pipelex/cogt/doc_gen/test_template_environment.py
+++ b/tests/unit/pipelex/cogt/doc_gen/test_template_environment.py
@@ -69,6 +69,69 @@ class TestPlainDataTemplateEnvironment:
)
assert rendered == "<paragraph,list_item,list_item>|3|Invoice"
+ def test_a_markdown_filter_block_prints_through_the_engine_s_finalize(self) -> None:
+ environment = make_plain_data_template_environment(finalize=_kinds_of_formatted)
+ over_a_value = environment.from_string("{% filter markdown %}{{ notes }}{% endfilter %}|{{ count }}").render(
+ notes=MarkdownFormattingTestData.NOTES, count=3
+ )
+ assert over_a_value == "<paragraph,list_item,list_item>|3"
+ assert environment.from_string("{% filter markdown %}Due in **30** days.{% endfilter %}").render() == "<paragraph>"
+
+ def test_a_markdown_filter_block_prints_its_plain_text_without_a_finalize(self) -> None:
+ template = make_plain_data_template_environment().from_string("{% filter markdown %}{{ notes }}{% endfilter %}")
+ assert template.render(notes=MarkdownFormattingTestData.NOTES) == MarkdownFormattingTestData.NOTES_PLAIN_TEXT
+
+ @pytest.mark.parametrize(
+ ("block_source", "printed_source"),
+ [
+ pytest.param(
+ "{% set out %}{% filter markdown %}{{ notes }}{% endfilter %}{% endset %}[{{ out }}]",
+ "{% set out %}{{ notes | markdown }}{% endset %}[{{ out }}]",
+ id="in_a_set_block",
+ ),
+ pytest.param(
+ "{% macro m(n) %}[{% filter markdown %}{{ n }}{% endfilter %}]{% endmacro %}{{ m(notes) }}",
+ "{% macro m(n) %}[{{ n | markdown }}]{% endmacro %}{{ m(notes) }}",
+ id="in_a_macro",
+ ),
+ pytest.param(
+ "{% for n in [notes, notes] %}{% filter markdown %}{{ n }}{% endfilter %};{% endfor %}",
+ "{% for n in [notes, notes] %}{{ n | markdown }};{% endfor %}",
+ id="in_a_loop",
+ ),
+ pytest.param(
+ "{% filter upper %}{% filter markdown %}{{ notes }}{% endfilter %}{% endfilter %}",
+ "{% filter upper %}{{ notes | markdown }}{% endfilter %}",
+ id="in_another_filter_block",
+ ),
+ ],
+ )
+ @pytest.mark.parametrize("with_finalize", [True, False])
+ def test_a_markdown_filter_block_prints_as_the_printed_form_does(self, block_source: str, printed_source: str, with_finalize: bool) -> None:
+ environment = make_plain_data_template_environment(finalize=_kinds_of_formatted if with_finalize else None)
+ notes = MarkdownFormattingTestData.NOTES
+ assert environment.from_string(block_source).render(notes=notes) == environment.from_string(printed_source).render(notes=notes)
+
+ def test_a_markdown_filter_block_reads_none_printed_in_its_body_as_text(self) -> None:
+ # The block's body is printed before the filter reads it, so None arrives as the text "None"; the tag form
+ # is the one that turns None into nothing, as the docs say.
+ environment = make_plain_data_template_environment()
+ assert environment.from_string("[{% filter markdown %}{{ notes }}{% endfilter %}]").render(notes=None) == "[None]"
+ assert environment.from_string("[{{ notes | markdown }}]").render(notes=None) == "[]"
+
+ def test_a_filter_after_markdown_in_a_block_prints_what_it_returns(self) -> None:
+ environment = make_plain_data_template_environment(finalize=_kinds_of_formatted)
+ template = environment.from_string("{% filter markdown | upper %}{{ notes }}{% endfilter %}")
+ assert template.render(notes=MarkdownFormattingTestData.NOTES) == MarkdownFormattingTestData.NOTES_PLAIN_TEXT.upper()
+
+ def test_a_markdown_filter_block_under_autoescape_prints_as_the_printed_form_does(self) -> None:
+ environment = make_plain_data_template_environment(finalize=_marker_for_formatted)
+ environment.autoescape = True
+ assert environment.from_string("{% filter markdown %}a < b{% endfilter %}").render() == "<?marker?>"
+ plain_environment = make_plain_data_template_environment()
+ plain_environment.autoescape = True
+ assert plain_environment.from_string("{% filter markdown %}a < **b** & c{% endfilter %}").render() == "a &lt; b &amp; c"
+
def test_markdown_prints_its_plain_text_without_a_finalize(self) -> None:
rendered = (
make_plain_data_template_environment()
diff --git a/tests/unit/pipelex/tools/test_jinja2_render_budget.py b/tests/unit/pipelex/tools/test_jinja2_render_budget.py
index 8a6fdb809..7a83c923f 100644
--- a/tests/unit/pipelex/tools/test_jinja2_render_budget.py
+++ b/tests/unit/pipelex/tools/test_jinja2_render_budget.py
@@ -30,8 +30,8 @@ from pipelex.tools.jinja2.exceptions import Jinja2TemplateBudgetError
from pipelex.tools.jinja2.jinja2_environment import make_jinja2_env_without_loader
from pipelex.tools.jinja2.jinja2_filters import markdown_to_html
from pipelex.tools.jinja2.jinja2_models import Jinja2ContextKey
-from pipelex.tools.jinja2.jinja2_render_budget import DEFAULT_RENDER_BUDGET_UNITS, RenderBudgetExceededError, active_render_budget
-from pipelex.tools.jinja2.jinja2_render_charging import CHARGED_MARK, INTERNAL_FILTERS
+from pipelex.tools.jinja2.jinja2_render_budget import DEFAULT_RENDER_BUDGET_UNITS, RenderBudget, RenderBudgetExceededError, active_render_budget
+from pipelex.tools.jinja2.jinja2_render_charging import CHARGED_MARK, INTERNAL_FILTERS, RENDER_BUDGET_KEY
from pipelex.tools.jinja2.jinja2_render_costs import FILTER_COSTS, PLAIN_VALUE_METHOD_COSTS, REFUSED_PLAIN_VALUE_METHODS, TEST_COSTS
from pipelex.tools.jinja2.jinja2_rendering import render_jinja2_async, render_jinja2_sync
from pipelex.tools.jinja2.jinja2_sandbox import PipelexTemplateEnvironment
@@ -63,6 +63,15 @@ def _render_stock(template_source: str, *, autoescape: bool = False, is_async: b
return template.render(**context)
+def _spent(template_source: str, *, is_async: bool = False, **context: Any) -> int:
+ """The units a render of `template_source` spends from its budget."""
+ budget = RenderBudget(total=DEFAULT_RENDER_BUDGET_UNITS)
+ # A render takes a budget handed in among its variables (`_with_render_budget`).
+ variables: dict[str, Any] = {**context, RENDER_BUDGET_KEY: budget}
+ _render(template_source, is_async=is_async, **variables)
+ return budget.total - budget.remaining
+
+
def _refused_render_peak_bytes(render: Callable[[], object]) -> int:
"""Run a render the budget must refuse, and return the most memory it held on the way."""
was_tracing = tracemalloc.is_tracing()
@@ -258,6 +267,8 @@ _UNCHANGED = [
),
pytest.param("{% macro wrap(x) %}[{{ x }}{{ caller() }}]{% endmacro %}{% call wrap(1) %}C{% endcall %}", id="macro_with_caller"),
pytest.param("{% set x %}a{{ 1 }}{% endset %}{{ x }}{% filter upper %}b{{ 'c' }}{% endfilter %}", id="set_and_filter_blocks"),
+ # A filter block whose filter returns text prints it as it is, never escaped again under autoescape.
+ pytest.param("{% filter wordwrap(3) %}aaa <b> {{ x }}{% endfilter %}|{% filter replace('a', x) %}a<i>{% endfilter %}", id="text_filter_blocks"),
pytest.param("{{ 2 ** 10 }}|{{ 7 // 2 }}|{{ 7 % 3 }}|{{ 1.5 * 2 }}|{{ 'ab' * 3 }}|{{ [1] * 3 }}|{{ -3 + 1 }}|{{ 1 / 4 }}", id="arithmetic"),
pytest.param("{{ '%05.1f|%s' % (3.14159, 'x') }}|{{ '%(a)s-%(a)s' % {'a': 1} }}", id="percent_format"),
pytest.param("{{ '{:>5}|{}|{x:.2f}'.format('a', 2, x=1.5) }}|{{ '%d items' | format(3) }}", id="str_format"),
@@ -627,6 +638,37 @@ class TestRenderBudget:
big = "a" * 20_000_000
assert len(_render("{{ big }}{{ big | escape }}", autoescape=True, big=big)) == 40_000_000
+ @pytest.mark.parametrize("is_async", [False, True])
+ def test_a_filter_block_prints_a_result_that_is_no_text_as_a_tag_prints_it(self, is_async: bool) -> None:
+ # Jinja writes a filter block's result out as it is, which fails the render's join for anything but text.
+ rendered = _render("{% filter length %}abc{% endfilter %}|{% filter list %}ab{% endfilter %}", is_async=is_async)
+ assert rendered == _render("{{ 'abc' | length }}|{{ 'ab' | list }}", is_async=is_async) == "3|['a', 'b']"
+
+ def test_a_filter_block_s_result_that_is_no_text_is_escaped_as_a_printed_value(self) -> None:
+ rendered = _render("{% filter list %}<{% endfilter %}", autoescape=True)
+ assert rendered == _render("{{ '<' | list }}", autoescape=True) == "[&#39;&lt;&#39;]"
+
+ def test_a_filter_block_s_result_goes_through_the_caller_s_finalize(self) -> None:
+ def blank_none(value: object) -> object:
+ return "" if value is None else value
+
+ env = PipelexTemplateEnvironment(finalize=blank_none)
+ # An empty body is false, so `default(none, true)` returns None, which the caller's finalize blanks.
+ assert env.from_string("[{% filter default(none, true) %}{% endfilter %}]").render() == "[]"
+
+ @pytest.mark.parametrize(
+ ("block_source", "printed_source"),
+ [
+ pytest.param("{% filter upper %}{{ big }}{% endfilter %}", "{{ big }}{{ big | upper }}", id="text"),
+ pytest.param("{% filter list %}{{ big }}{% endfilter %}", "{{ big }}{{ big | list }}", id="no_text"),
+ ],
+ )
+ @pytest.mark.parametrize("is_async", [False, True])
+ def test_a_filter_block_s_result_is_charged_as_a_print(self, block_source: str, printed_source: str, is_async: bool) -> None:
+ # The block prints its body's value, then the filter's result; the printed form prints the same two values.
+ big = "x" * 10_000
+ assert _spent(block_source, is_async=is_async, big=big) == _spent(printed_source, is_async=is_async, big=big)
+
def test_caller_finalize_still_applies(self) -> None:
def blank_none(value: object) -> object:
return "" if value is None else value