Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add zip to template engine #122460

Merged
merged 2 commits into from
Aug 22, 2024
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
1 change: 1 addition & 0 deletions homeassistant/helpers/template.py
Original file line number Diff line number Diff line change
Expand Up @@ -2844,6 +2844,7 @@ def __init__(
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
Expand Down
45 changes: 45 additions & 0 deletions tests/helpers/test_template.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
)