Fix exception when as_dict is called on a TemplateState (#73984)

This commit is contained in:
J. Nick Koston 2022-06-25 11:19:11 -05:00 committed by GitHub
parent 15ed329108
commit 949922ef2c
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 13 additions and 1 deletions

View File

@ -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:

View File

@ -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)