diff --git a/homeassistant/helpers/template/extensions/string.py b/homeassistant/helpers/template/extensions/string.py index 12aa4afc6832..54ea46c61d5d 100644 --- a/homeassistant/helpers/template/extensions/string.py +++ b/homeassistant/helpers/template/extensions/string.py @@ -51,6 +51,6 @@ class StringExtension(BaseTemplateExtension): """Convert a string into a slug, such as what is used for entity ids.""" return slugify_util(str(value), separator=separator) - def urlencode(self, value: Any) -> bytes: - """Urlencode dictionary and return as UTF-8 string.""" - return urllib_urlencode(value).encode("utf-8") + def urlencode(self, value: Any) -> str: + """Urlencode dictionary and return as string.""" + return urllib_urlencode(value) diff --git a/tests/helpers/template/extensions/test_string.py b/tests/helpers/template/extensions/test_string.py index 30c46997cf65..5b33549fb439 100644 --- a/tests/helpers/template/extensions/test_string.py +++ b/tests/helpers/template/extensions/test_string.py @@ -1,5 +1,7 @@ """Test string template extension.""" +import pytest + from homeassistant.core import HomeAssistant from tests.helpers.template.helpers import render @@ -54,6 +56,25 @@ def test_urlencode(hass: HomeAssistant) -> None: assert result == "the%20quick%20brown%20fox%20%3D%20true" +@pytest.mark.parametrize( + ("template_str", "expected"), + [ + pytest.param("{{ urlencode({'a': 'b c'}) }}", "a=b+c", id="only_node"), + pytest.param("?{{ urlencode({'a': 'b c'}) }}", "?a=b+c", id="concatenated"), + pytest.param( + "{{ urlencode({'foo': 'x&y', 'bar': 42}) }}", + "foo=x%26y&bar=42", + id="special_characters", + ), + ], +) +def test_urlencode_function( + hass: HomeAssistant, template_str: str, expected: str +) -> None: + """Test the urlencode function renders a query string.""" + assert render(hass, template_str, parse_result=False) == expected + + def test_string_functions_with_non_string_input(hass: HomeAssistant) -> None: """Test string functions with non-string input (automatic conversion).""" # Test ordinal with integer