diff --git a/custom_components/pyscript/__init__.py b/custom_components/pyscript/__init__.py index 590e3d0..7b954d4 100644 --- a/custom_components/pyscript/__init__.py +++ b/custom_components/pyscript/__init__.py @@ -91,7 +91,13 @@ async def restore_state(hass: HomeAssistant) -> None: """Restores the persisted pyscript state.""" # this is a hack accessing hass internals; should re-implement using RestoreEntity restore_data = hass.data[DATA_RESTORE_STATE] - for entity_id, value in restore_data.last_states.items(): + try: + # HA >= 2026.11; pyscript vars have no entity registry entry, so they're indexed by entity_id + last_states = restore_data.last_states_by_entity_id + except AttributeError: + # HA < 2026.11 + last_states = restore_data.last_states + for entity_id, value in last_states.items(): if entity_id.startswith("pyscript."): last_state = value.state hass.states.async_set(entity_id, last_state.state, last_state.attributes) diff --git a/tests/test_init.py b/tests/test_init.py index 47995dd..5b43ea3 100644 --- a/tests/test_init.py +++ b/tests/test_init.py @@ -7,8 +7,9 @@ from unittest.mock import mock_open, patch import pytest +from pytest_homeassistant_custom_component.common import mock_restore_cache -from custom_components.pyscript import trigger +from custom_components.pyscript import restore_state, trigger from custom_components.pyscript.const import DOMAIN from custom_components.pyscript.event import Event from custom_components.pyscript.function import Function @@ -16,7 +17,7 @@ from custom_components.pyscript.state import State from homeassistant import loader from homeassistant.const import EVENT_STATE_CHANGED -from homeassistant.core import Context +from homeassistant.core import Context, State as HassState from homeassistant.helpers.service import async_get_all_descriptions from homeassistant.setup import async_setup_component @@ -85,6 +86,25 @@ async def test_setup_makedirs_on_no_dir(hass, caplog): assert makedirs_call.called +@pytest.mark.asyncio +async def test_restore_state(hass): + """Test persisted pyscript state variables are restored, and others are ignored.""" + mock_restore_cache( + hass, + [ + HassState("pyscript.restored", "123", {"attr1": "abc"}), + HassState("sensor.not_pyscript", "456"), + ], + ) + + await restore_state(hass) + + restored = hass.states.get("pyscript.restored") + assert restored.state == "123" + assert restored.attributes == {"attr1": "abc"} + assert hass.states.get("sensor.not_pyscript") is None + + @pytest.mark.asyncio async def test_service_exists(hass, caplog): """Test discover, compile script and install a service."""