Add template function: shuffle (#140077)

This commit is contained in:
Franck Nijhof
2025-03-08 02:36:17 +01:00
committed by GitHub
parent b7094c12f7
commit d4f205c366
2 changed files with 79 additions and 1 deletions

View File

@@ -15,6 +15,7 @@ from unittest.mock import patch
from freezegun import freeze_time
import orjson
import pytest
from pytest_unordered import unordered
from syrupy import SnapshotAssertion
import voluptuous as vol
@@ -6672,3 +6673,54 @@ async def test_merge_response_not_mutate_original_object(
tpl = template.Template(_template, hass)
assert tpl.async_render()
def test_shuffle(hass: HomeAssistant) -> None:
"""Test the shuffle function and filter."""
assert list(
template.Template("{{ [1, 2, 3] | shuffle }}", hass).async_render()
) == unordered([1, 2, 3])
assert list(
template.Template("{{ shuffle([1, 2, 3]) }}", hass).async_render()
) == unordered([1, 2, 3])
assert list(
template.Template("{{ shuffle(1, 2, 3) }}", hass).async_render()
) == unordered([1, 2, 3])
assert list(template.Template("{{ shuffle([]) }}", hass).async_render()) == []
assert list(template.Template("{{ [] | shuffle }}", hass).async_render()) == []
# Testing using seed
assert list(
template.Template("{{ shuffle([1, 2, 3], 'seed') }}", hass).async_render()
) == [2, 3, 1]
assert list(
template.Template(
"{{ shuffle([1, 2, 3], seed='seed') }}",
hass,
).async_render()
) == [2, 3, 1]
assert list(
template.Template(
"{{ [1, 2, 3] | shuffle('seed') }}",
hass,
).async_render()
) == [2, 3, 1]
assert list(
template.Template(
"{{ [1, 2, 3] | shuffle(seed='seed') }}",
hass,
).async_render()
) == [2, 3, 1]
with pytest.raises(TemplateError):
template.Template("{{ 1 | shuffle }}", hass).async_render()
with pytest.raises(TemplateError):
template.Template("{{ shuffle() }}", hass).async_render()