Skip to content
Closed
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
8 changes: 7 additions & 1 deletion custom_components/pyscript/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
24 changes: 22 additions & 2 deletions tests/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,17 @@
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
from custom_components.pyscript.global_ctx import GlobalContextMgr
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

Expand Down Expand Up @@ -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."""
Expand Down
Loading