diff --git a/homeassistant/helpers/registry.py b/homeassistant/helpers/registry.py index 83079af6228..d5b1035531a 100644 --- a/homeassistant/helpers/registry.py +++ b/homeassistant/helpers/registry.py @@ -11,7 +11,7 @@ if TYPE_CHECKING: from .storage import Store SAVE_DELAY = 10 -SAVE_DELAY_STARTING = 300 +SAVE_DELAY_LONG = 180 class BaseRegistry(ABC): @@ -25,9 +25,7 @@ class BaseRegistry(ABC): """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 diff --git a/tests/helpers/test_registry.py b/tests/helpers/test_registry.py index 40e3d0cbb28..2cfa3be26c7 100644 --- a/tests/helpers/test_registry.py +++ b/tests/helpers/test_registry.py @@ -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 @@ -26,12 +27,30 @@ class SampleRegistry(BaseRegistry): 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) @@ -39,7 +58,7 @@ async def test_async_schedule_save( 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