Generate HomeAssistantError message from English translations (#113305)

* Fetch exception message from translation cache

* Improve tests

* Return translation key without path, cleanup

* Fetch translations when string variant is requested

* Move import

* revert changes ConfigValidationError

* mypy

* Remove _str__ method instead

* Type _message for mqtt template exception classes

* Revert changes made to test_config.py

* Undo changes TemplateError

* Follow up comments and test coverage
This commit is contained in:
Jan Bouwhuis 2024-03-16 22:56:48 +01:00 committed by GitHub
parent 2bc4a5067d
commit 554aefed42
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
6 changed files with 136 additions and 13 deletions

View file

@ -2,12 +2,17 @@
from __future__ import annotations
from typing import Any
from unittest.mock import patch
import pytest
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import (
ConditionErrorContainer,
ConditionErrorIndex,
ConditionErrorMessage,
HomeAssistantError,
TemplateError,
)
@ -62,3 +67,55 @@ def test_template_message(arg: str | Exception, expected: str) -> None:
"""Ensure we can create TemplateError."""
template_error = TemplateError(arg)
assert str(template_error) == expected
@pytest.mark.parametrize(
("exception_args", "exception_kwargs", "args_base_class", "message"),
[
((), {}, (), ""),
(("bla",), {}, ("bla",), "bla"),
((None,), {}, (None,), "None"),
((type_error_bla := TypeError("bla"),), {}, (type_error_bla,), "bla"),
(
(),
{"translation_domain": "test", "translation_key": "test"},
("test",),
"test",
),
(
(),
{"translation_domain": "test", "translation_key": "bla"},
("bla",),
"{bla} from cache",
),
(
(),
{
"translation_domain": "test",
"translation_key": "bla",
"translation_placeholders": {"bla": "Bla"},
},
("bla",),
"Bla from cache",
),
],
)
async def test_home_assistant_error(
hass: HomeAssistant,
exception_args: tuple[Any,],
exception_kwargs: dict[str, Any],
args_base_class: tuple[Any],
message: str,
) -> None:
"""Test edge cases with HomeAssistantError."""
with patch(
"homeassistant.helpers.translation.async_get_cached_translations",
return_value={"component.test.exceptions.bla.message": "{bla} from cache"},
):
with pytest.raises(HomeAssistantError) as exc:
raise HomeAssistantError(*exception_args, **exception_kwargs)
assert exc.value.args == args_base_class
assert str(exc.value) == message
# Get string of exception again from the cache
assert str(exc.value) == message