Refactor template engine: Extract raise_no_default() into helper module (#152661)

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
This commit is contained in:
Franck Nijhof
2025-09-20 18:20:05 +02:00
committed by GitHub
parent 8ca7562390
commit 12cc0ed18d
4 changed files with 33 additions and 20 deletions

View File

@@ -82,6 +82,7 @@ from .context import (
template_context_manager,
template_cv,
)
from .helpers import raise_no_default
from .render_info import RenderInfo, render_info_cv
if TYPE_CHECKING:
@@ -1818,15 +1819,6 @@ def utcnow(hass: HomeAssistant) -> datetime:
return dt_util.utcnow()
def raise_no_default(function: str, value: Any) -> NoReturn:
"""Log warning if no default is specified."""
template, action = template_cv.get() or ("", "rendering or compiling")
raise ValueError(
f"Template error: {function} got invalid input '{value}' when {action} template"
f" '{template}' but no default was specified"
)
def forgiving_round(value, precision=0, method="common", default=_SENTINEL):
"""Filter to round a value."""
try:

View File

@@ -6,12 +6,12 @@ from collections.abc import Iterable
from functools import wraps
import math
import statistics
from typing import TYPE_CHECKING, Any, NoReturn
from typing import TYPE_CHECKING, Any
import jinja2
from jinja2 import pass_environment
from homeassistant.helpers.template.context import template_cv
from homeassistant.helpers.template.helpers import raise_no_default
from .base import BaseTemplateExtension, TemplateFunction
@@ -22,15 +22,6 @@ if TYPE_CHECKING:
_SENTINEL = object()
def raise_no_default(function: str, value: Any) -> NoReturn:
"""Log warning if no default is specified."""
template, action = template_cv.get() or ("", "rendering or compiling")
raise ValueError(
f"Template error: {function} got invalid input '{value}' when {action} template"
f" '{template}' but no default was specified"
)
class MathExtension(BaseTemplateExtension):
"""Jinja2 extension for mathematical and statistical functions."""

View File

@@ -0,0 +1,16 @@
"""Template helper functions for Home Assistant."""
from __future__ import annotations
from typing import Any, NoReturn
from .context import template_cv
def raise_no_default(function: str, value: Any) -> NoReturn:
"""Raise ValueError when no default is specified for template functions."""
template, action = template_cv.get() or ("", "rendering or compiling")
raise ValueError(
f"Template error: {function} got invalid input '{value}' when {action} template"
f" '{template}' but no default was specified"
)

View File

@@ -0,0 +1,14 @@
"""Test template helper functions."""
import pytest
from homeassistant.helpers.template.helpers import raise_no_default
def test_raise_no_default() -> None:
"""Test raise_no_default raises ValueError with correct message."""
with pytest.raises(
ValueError,
match="Template error: test got invalid input 'invalid' when rendering or compiling template '' but no default was specified",
):
raise_no_default("test", "invalid")