From 949922ef2cb7a7c6e4a83cb91856c70728acd806 Mon Sep 17 00:00:00 2001 From: "J. Nick Koston" Date: Sat, 25 Jun 2022 11:19:11 -0500 Subject: [PATCH] Fix exception when as_dict is called on a TemplateState (#73984) --- homeassistant/helpers/template.py | 4 +++- tests/helpers/test_template.py | 10 ++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/homeassistant/helpers/template.py b/homeassistant/helpers/template.py index eca76a8c7bc..53e2eb122f6 100644 --- a/homeassistant/helpers/template.py +++ b/homeassistant/helpers/template.py @@ -5,7 +5,7 @@ from ast import literal_eval import asyncio import base64 import collections.abc -from collections.abc import Callable, Generator, Iterable +from collections.abc import Callable, Collection, Generator, Iterable from contextlib import contextmanager, suppress from contextvars import ContextVar from datetime import datetime, timedelta @@ -54,6 +54,7 @@ from homeassistant.util import ( slugify as slugify_util, ) from homeassistant.util.async_ import run_callback_threadsafe +from homeassistant.util.read_only_dict import ReadOnlyDict from homeassistant.util.thread import ThreadWithException from . import area_registry, device_registry, entity_registry, location as loc_helper @@ -764,6 +765,7 @@ class TemplateStateBase(State): self._hass = hass self._collect = collect self._entity_id = entity_id + self._as_dict: ReadOnlyDict[str, Collection[Any]] | None = None def _collect_state(self) -> None: if self._collect and _RENDER_INFO in self._hass.data: diff --git a/tests/helpers/test_template.py b/tests/helpers/test_template.py index 69a3af22759..59b653bc23e 100644 --- a/tests/helpers/test_template.py +++ b/tests/helpers/test_template.py @@ -26,6 +26,7 @@ from homeassistant.core import HomeAssistant from homeassistant.exceptions import TemplateError from homeassistant.helpers import device_registry as dr, entity, template from homeassistant.helpers.entity_platform import EntityPlatform +from homeassistant.helpers.json import json_dumps from homeassistant.setup import async_setup_component import homeassistant.util.dt as dt_util from homeassistant.util.unit_system import UnitSystem @@ -3841,3 +3842,12 @@ async def test_template_states_blocks_setitem(hass): template_state = template.TemplateState(hass, state, True) with pytest.raises(RuntimeError): template_state["any"] = "any" + + +async def test_template_states_can_serialize(hass): + """Test TemplateState is serializable.""" + hass.states.async_set("light.new", STATE_ON) + state = hass.states.get("light.new") + template_state = template.TemplateState(hass, state, True) + assert template_state.as_dict() is template_state.as_dict() + assert json_dumps(template_state) == json_dumps(template_state)