Skip to content

Commit cac69fb

Browse files
fix(templates): ignore escaped braces when collecting fixture keys (#151)
Signed-off-by: Rudy Celekli <47457359+rudycelekli@users.noreply.github.com> Co-authored-by: n-papaioannou <n.papaioannou@ime.life>
1 parent bcf24f3 commit cac69fb

2 files changed

Lines changed: 38 additions & 3 deletions

File tree

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
import pytest
2+
3+
from ifixai.utils.template_renderer import (
4+
MissingPlaceholderError,
5+
extract_placeholders,
6+
render,
7+
)
8+
9+
10+
@pytest.mark.parametrize(
11+
"template,expected",
12+
[
13+
("Literal {{example}}; real {name}", {"name"}),
14+
("{{{{field}}}}", set()),
15+
("{{{name}}}", {"name"}),
16+
("{value!r:>12}", {"value"}),
17+
("{value:{width}.{precision}f}", {"value", "width", "precision"}),
18+
],
19+
)
20+
def test_extracted_keys_follow_actual_formatter_fields(template, expected):
21+
assert extract_placeholders(template) == expected
22+
23+
24+
def test_literal_field_does_not_require_fixture_value():
25+
assert (
26+
render("Literal {{example}}; real {name}", {"name": "Rudy"})
27+
== "Literal {example}; real Rudy"
28+
)
29+
with pytest.raises(MissingPlaceholderError):
30+
render("Literal {{example}}; real {name}", {})

‎ifixai/utils/template_renderer.py‎

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,9 @@
11
from __future__ import annotations
22

3-
import re
43
from collections.abc import Mapping
4+
from string import Formatter
55

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

88

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

3030

3131
def extract_placeholders(template: str) -> set[str]:
32-
return set(_PLACEHOLDER_RE.findall(template))
32+
fields: set[str] = set()
33+
for _, field, format_spec, _ in _FORMATTER.parse(template):
34+
if field:
35+
fields.add(field.split(".", 1)[0].split("[", 1)[0])
36+
fields.update(extract_placeholders(format_spec))
37+
return fields
3338

3439

3540
def render(template: str, context: Mapping[str, object]) -> str:

0 commit comments

Comments
 (0)