Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
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
9 changes: 7 additions & 2 deletions custom_components/hacs/utils/store.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@

_LOGGER = LOGGER

STORE_CACHE_KEY = "hacs_store_cache"


class HACSStore(Store):
"""A subclass of Store that allows multiple loads in the executor."""
Expand Down Expand Up @@ -43,8 +45,11 @@ def _get_store_for_key(hass, key, encoder):


def get_store_for_key(hass, key):
"""Create a Store object for the key."""
return _get_store_for_key(hass, key, JSONEncoder)
"""Get (or create and cache) the Store object for the key."""
cache = hass.data.setdefault(STORE_CACHE_KEY, {})
if key not in cache:
cache[key] = _get_store_for_key(hass, key, JSONEncoder)
return cache[key]
Comment thread
ludeeus marked this conversation as resolved.
Outdated


async def async_load_from_store(hass, key):
Expand Down
10 changes: 10 additions & 0 deletions tests/utils/test_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,3 +64,13 @@ async def test_store_store(hass: HomeAssistant, caplog: pytest.LogCaptureFixture

await async_save_to_store(hass, "test", {"test": "test"})
assert async_save_mock.call_count == 1


async def test_store_instance_cached_per_key(hass: HomeAssistant) -> None:
"""Repeated calls for the same key must return the same Store instance.

Store.async_delay_save() debounces via instance state, so callers that
schedule delayed writes need the same Store object each time.
"""
assert get_store_for_key(hass, "test") is get_store_for_key(hass, "test")
assert get_store_for_key(hass, "test") is not get_store_for_key(hass, "other")
Loading