Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Merged
merged 2 commits into from
Sep 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion homeassistant/helpers/template.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
17 changes: 17 additions & 0 deletions tests/helpers/test_template.py
Original file line number Diff line number Diff line change
Expand Up @@ -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()
Loading