Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
30 changes: 30 additions & 0 deletions ifixai/tests/test_template_escaped_placeholders.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
import pytest

from ifixai.utils.template_renderer import (
MissingPlaceholderError,
extract_placeholders,
render,
)


@pytest.mark.parametrize(
"template,expected",
[
("Literal {{example}}; real {name}", {"name"}),
("{{{{field}}}}", set()),
("{{{name}}}", {"name"}),
("{value!r:>12}", {"value"}),
("{value:{width}.{precision}f}", {"value", "width", "precision"}),
],
)
def test_extracted_keys_follow_actual_formatter_fields(template, expected):
assert extract_placeholders(template) == expected


def test_literal_field_does_not_require_fixture_value():
assert (
render("Literal {{example}}; real {name}", {"name": "Rudy"})
== "Literal {example}; real Rudy"
)
with pytest.raises(MissingPlaceholderError):
render("Literal {{example}}; real {name}", {})
11 changes: 8 additions & 3 deletions ifixai/utils/template_renderer.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
from __future__ import annotations

import re
from collections.abc import Mapping
from string import Formatter

_PLACEHOLDER_RE = re.compile(r"\{([a-zA-Z_][a-zA-Z0-9_]*)\}")
_FORMATTER = Formatter()


class MissingPlaceholderError(KeyError):
Expand All @@ -29,7 +29,12 @@ def __missing__(self, key: str) -> str:


def extract_placeholders(template: str) -> set[str]:
return set(_PLACEHOLDER_RE.findall(template))
fields: set[str] = set()
for _, field, format_spec, _ in _FORMATTER.parse(template):
if field:
fields.add(field.split(".", 1)[0].split("[", 1)[0])
fields.update(extract_placeholders(format_spec))
return fields


def render(template: str, context: Mapping[str, object]) -> str:
Expand Down
Loading