Skip to content

Commit

Permalink
Fix delayed registry check to only using the short delay at running (h…
Browse files Browse the repository at this point in the history
  • Loading branch information
bdraco authored Mar 15, 2024
1 parent 052d7d1 commit 3528cc8
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 9 deletions.
6 changes: 2 additions & 4 deletions homeassistant/helpers/registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
from .storage import Store

SAVE_DELAY = 10
SAVE_DELAY_STARTING = 300
SAVE_DELAY_LONG = 180


class BaseRegistry(ABC):
Expand All @@ -25,9 +25,7 @@ def async_schedule_save(self) -> None:
"""Schedule saving the registry."""
# Schedule the save past startup to avoid writing
# the file while the system is starting.
delay = (
SAVE_DELAY_STARTING if self.hass.state is CoreState.starting else SAVE_DELAY
)
delay = SAVE_DELAY if self.hass.state is CoreState.running else SAVE_DELAY_LONG
self._store.async_delay_save(self._data_to_save, delay)

@callback
Expand Down
29 changes: 24 additions & 5 deletions tests/helpers/test_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,11 @@
from typing import Any

from freezegun.api import FrozenDateTimeFactory
import pytest

from homeassistant.core import CoreState, HomeAssistant
from homeassistant.helpers import storage
from homeassistant.helpers.registry import SAVE_DELAY, SAVE_DELAY_STARTING, BaseRegistry
from homeassistant.helpers.registry import SAVE_DELAY, SAVE_DELAY_LONG, BaseRegistry

from tests.common import async_fire_time_changed

Expand All @@ -26,20 +27,38 @@ def _data_to_save(self) -> None:
return None


@pytest.mark.parametrize(
"long_delay_state",
(
CoreState.not_running,
CoreState.starting,
CoreState.stopped,
CoreState.final_write,
),
)
async def test_async_schedule_save(
hass: HomeAssistant, freezer: FrozenDateTimeFactory, hass_storage: dict[str, Any]
hass: HomeAssistant,
freezer: FrozenDateTimeFactory,
long_delay_state: CoreState,
hass_storage: dict[str, Any],
) -> None:
"""Test saving the registry."""
"""Test saving the registry.
If CoreState is not running, it should save with long delay.
Storage will always save at final write if there is a
write pending so we should not schedule a save in that case.
"""
registry = SampleRegistry(hass)
hass.set_state(CoreState.starting)
hass.set_state(long_delay_state)

registry.async_schedule_save()
freezer.tick(SAVE_DELAY)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert registry.save_calls == 0

freezer.tick(SAVE_DELAY_STARTING)
freezer.tick(SAVE_DELAY_LONG)
async_fire_time_changed(hass)
await hass.async_block_till_done()
assert registry.save_calls == 1
Expand Down

0 comments on commit 3528cc8

Please sign in to comment.