Allow base64_encode to support bytes and strings (#145227)

This commit is contained in:
Petro31 2025-05-26 04:56:11 -07:00 committed by GitHub
parent cc504da03a
commit 13a6c13b89
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 14 additions and 7 deletions

View File

@ -2577,9 +2577,11 @@ def from_hex(value: str) -> bytes:
return bytes.fromhex(value) return bytes.fromhex(value)
def base64_encode(value: str) -> str: def base64_encode(value: str | bytes) -> str:
"""Perform base64 encode.""" """Perform base64 encode."""
return base64.b64encode(value.encode("utf-8")).decode("utf-8") if isinstance(value, str):
value = value.encode("utf-8")
return base64.b64encode(value).decode("utf-8")
def base64_decode(value: str, encoding: str | None = "utf-8") -> str | bytes: def base64_decode(value: str, encoding: str | None = "utf-8") -> str | bytes:

View File

@ -1640,12 +1640,17 @@ def test_from_hex(hass: HomeAssistant) -> None:
) )
def test_base64_encode(hass: HomeAssistant) -> None: @pytest.mark.parametrize(
"""Test the base64_encode filter.""" ("value_template", "expected"),
assert ( [
template.Template('{{ "homeassistant" | base64_encode }}', hass).async_render() ('{{ "homeassistant" | base64_encode }}', "aG9tZWFzc2lzdGFudA=="),
== "aG9tZWFzc2lzdGFudA==" ("{{ int('0F010003', base=16) | pack('>I') | base64_encode }}", "DwEAAw=="),
("{{ 'AA01000200150020' | from_hex | base64_encode }}", "qgEAAgAVACA="),
],
) )
def test_base64_encode(hass: HomeAssistant, value_template: str, expected: str) -> None:
"""Test the base64_encode filter."""
assert template.Template(value_template, hass).async_render() == expected
def test_base64_decode(hass: HomeAssistant) -> None: def test_base64_decode(hass: HomeAssistant) -> None: