Log deprecation warning when template.Template is created without hass (#125142)

* Log deprecation warning when template.Template is created without hass

* Improve docstring
This commit is contained in:
Erik Montnemery 2024-09-03 14:28:33 +02:00 committed by GitHub
parent e3896d1f60
commit 851600630c
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 34 additions and 1 deletions

View file

@ -507,10 +507,26 @@ class Template:
)
def __init__(self, template: str, hass: HomeAssistant | None = None) -> None:
"""Instantiate a template."""
"""Instantiate a template.
Note: A valid hass instance should always be passed in. The hass parameter
will be non optional in Home Assistant Core 2025.10.
"""
# pylint: disable-next=import-outside-toplevel
from .frame import report
if not isinstance(template, str):
raise TypeError("Expected template to be a string")
if not hass:
report(
(
"creates a template object without passing hass, "
"which will stop working in HA Core 2025.10"
),
error_if_core=False,
)
self.template: str = template.strip()
self._compiled_code: CodeType | None = None
self._compiled: jinja2.Template | None = None

View file

@ -6547,3 +6547,20 @@ async def test_merge_response_with_incorrect_response(hass: HomeAssistant) -> No
tpl = template.Template(_template, hass)
with pytest.raises(TemplateError, match="TypeError: Response is not a dictionary"):
tpl.async_render()
def test_warn_no_hass(hass: HomeAssistant, caplog: pytest.LogCaptureFixture) -> None:
"""Test deprecation warning when instantiating Template without hass."""
message = "Detected code that creates a template object without passing hass"
template.Template("blah")
assert message in caplog.text
caplog.clear()
template.Template("blah", None)
assert message in caplog.text
caplog.clear()
template.Template("blah", hass)
assert message not in caplog.text
caplog.clear()