Add zip to template engine (#122460)

* add zip to template engine

* fix doc strings
This commit is contained in:
Petro31 2024-08-22 13:11:08 -04:00 committed by GitHub
parent 6f66f37fc7
commit 5d64155bb6
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 46 additions and 0 deletions

View file

@ -2844,6 +2844,7 @@ class TemplateEnvironment(ImmutableSandboxedEnvironment):
self.globals["iif"] = iif
self.globals["bool"] = forgiving_boolean
self.globals["version"] = version
self.globals["zip"] = zip
self.tests["is_number"] = is_number
self.tests["list"] = _is_list
self.tests["set"] = _is_set

View file

@ -6236,3 +6236,48 @@ async def test_template_thread_safety_checks(hass: HomeAssistant) -> None:
await hass.async_add_executor_job(template_obj.async_render_to_info)
assert template_obj.async_render_to_info().result() == 23
@pytest.mark.parametrize(
("cola", "colb", "expected"),
[
([1, 2], [3, 4], [(1, 3), (2, 4)]),
([1, 2], [3, 4, 5], [(1, 3), (2, 4)]),
([1, 2, 3, 4], [3, 4], [(1, 3), (2, 4)]),
],
)
def test_zip(hass: HomeAssistant, cola, colb, expected) -> None:
"""Test zip."""
assert (
template.Template("{{ zip(cola, colb) | list }}", hass).async_render(
{"cola": cola, "colb": colb}
)
== expected
)
assert (
template.Template(
"[{% for a, b in zip(cola, colb) %}({{a}}, {{b}}), {% endfor %}]", hass
).async_render({"cola": cola, "colb": colb})
== expected
)
@pytest.mark.parametrize(
("col", "expected"),
[
([(1, 3), (2, 4)], [(1, 2), (3, 4)]),
(["ax", "by", "cz"], [("a", "b", "c"), ("x", "y", "z")]),
],
)
def test_unzip(hass: HomeAssistant, col, expected) -> None:
"""Test unzipping using zip."""
assert (
template.Template("{{ zip(*col) | list }}", hass).async_render({"col": col})
== expected
)
assert (
template.Template(
"{% set a, b = zip(*col) %}[{{a}}, {{b}}]", hass
).async_render({"col": col})
== expected
)