Skip to content
Myr

make compile_templates deterministic

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

Python3 doesn't keep insertion order for set(), so this sorts some places for deterministic output for compiled template.

authored by Takuto Ikuta · committed by David Lord · parent 02071b3 · Browse files · 4 files+32 added−2 removed
This commit

State

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

Diff stats

4 files+32 added−2 removed

  • tests:+28 added−0 removed
  • other:+4 added−2 removed

4 files+32 added−2 removed

modified:src/jinja2/compiler.py+1 added-1 removed
554 unmodified lines
555 self.tests,556 visitor.tests,557 "tests",558 ):559 for name in names:559 for name in sorted(names):560 if name not in id_map:561 id_map[name] = self.temporary_identifier()562563 # add check during runtime that dependencies used inside of executed
1396 unmodified lines
modified:src/jinja2/idtracking.py+1 added-1 removed
147 unmodified lines
148 rv: t.Dict[str, str] = {}149 node: t.Optional["Symbols"] = self150151 while node is not None:152 for name in node.stores:152 for name in sorted(node.stores):153 if name not in rv:154 rv[name] = self.find_ref(name) # type: ignore155156 node = node.parent
162 unmodified lines
added:tests/test_compile.py+28 added
1import os2import re34from jinja2.environment import Environment5from jinja2.loaders import DictLoader678def test_filters_deterministic(tmp_path):9 src = "".join(f"{{{{ {i}|filter{i} }}}}" for i in range(10))10 env = Environment(loader=DictLoader({"foo": src}))11 env.filters.update(dict.fromkeys((f"filter{i}" for i in range(10)), lambda: None))12 env.compile_templates(tmp_path, zip=None)13 name = os.listdir(tmp_path)[0]14 content = (tmp_path / name).read_text("utf8")15 expect = [f"filters['filter{i}']" for i in range(10)]16 found = re.findall(r"filters\['filter\d']", content)17 assert found == expect181920def test_import_as_with_context_deterministic(tmp_path):21 src = "\n".join(f'{{% import "bar" as bar{i} with context %}}' for i in range(10))22 env = Environment(loader=DictLoader({"foo": src}))23 env.compile_templates(tmp_path, zip=None)24 name = os.listdir(tmp_path)[0]25 content = (tmp_path / name).read_text("utf8")26 expect = [f"'bar{i}': " for i in range(10)]27 found = re.findall(r"'bar\d': ", content)[:10]28 assert found == expect
modified:CHANGES.rst+2 added
5 unmodified lines
6Unreleased78- Fix a loop scoping bug that caused assignments in nested loops9 to still be referenced outside of it. :issue:`1427`10- Make ``compile_templates`` deterministic for filter and import11 names. :issue:`1452, 1453`121314Version 3.0.115-------------
876 unmodified lines