mirror of
https://github.com/home-assistant/core.git
synced 2026-12-03 12:21:04 -04:00
2384 lines
78 KiB
Python
2384 lines
78 KiB
Python
"""Test the bootstrapping."""
|
|
|
|
import asyncio
|
|
from collections.abc import Generator, Iterable
|
|
import contextlib
|
|
import glob
|
|
import os
|
|
import sys
|
|
from time import monotonic
|
|
from typing import Any
|
|
from unittest.mock import AsyncMock, Mock, patch
|
|
|
|
from freezegun.api import FrozenDateTimeFactory
|
|
import pytest
|
|
from pytest_homeassistant.common import (
|
|
MockConfigEntry,
|
|
MockModule,
|
|
MockPlatform,
|
|
async_fire_time_changed,
|
|
get_test_config_dir,
|
|
mock_config_flow,
|
|
mock_integration,
|
|
mock_platform,
|
|
)
|
|
from syrupy.assertion import SnapshotAssertion
|
|
|
|
from homeassistant import (
|
|
bootstrap,
|
|
config as config_util,
|
|
config_entries,
|
|
core,
|
|
loader,
|
|
runner,
|
|
)
|
|
from homeassistant.config_entries import ConfigEntry
|
|
from homeassistant.const import (
|
|
BASE_PLATFORMS,
|
|
CONF_DEBUG,
|
|
EVENT_HOMEASSISTANT_START,
|
|
SIGNAL_BOOTSTRAP_INTEGRATIONS,
|
|
)
|
|
from homeassistant.core import CoreState, Event, HomeAssistant, async_get_hass, callback
|
|
from homeassistant.exceptions import ConfigEntryNotReady, HomeAssistantError
|
|
from homeassistant.helpers.dispatcher import async_dispatcher_connect
|
|
from homeassistant.helpers.translation import async_translations_loaded
|
|
from homeassistant.helpers.typing import ConfigType
|
|
from homeassistant.loader import Integration
|
|
from homeassistant.setup import BootstrapProgress, async_subscribe_bootstrap_progress
|
|
|
|
VERSION_PATH = os.path.join(get_test_config_dir(), config_util.VERSION_FILE)
|
|
|
|
CONFIG_LOG_FILE = get_test_config_dir("home-assistant.log")
|
|
ARG_LOG_FILE = "test.log"
|
|
|
|
|
|
def cleanup_log_files() -> None:
|
|
"""Remove all log files."""
|
|
for f in glob.glob(f"{CONFIG_LOG_FILE}*"):
|
|
os.remove(f)
|
|
for f in glob.glob(f"{ARG_LOG_FILE}*"):
|
|
os.remove(f)
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def disable_installed_check() -> Generator[None]:
|
|
"""Disable package installed check."""
|
|
with patch("homeassistant.util.package.is_installed", return_value=True):
|
|
yield
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def apply_mock_storage(hass_storage: dict[str, Any]) -> None:
|
|
"""Apply the storage mock."""
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
async def apply_stop_hass(stop_hass: None) -> None:
|
|
"""Make sure all hass are stopped."""
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def disable_block_async_io(disable_block_async_io):
|
|
"""Disable the loop protection from block_async_io after each test."""
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def disable_block_shared_serial(disable_block_shared_serial: None) -> None:
|
|
"""Restore pyserial after each test."""
|
|
|
|
|
|
@pytest.fixture(scope="module", autouse=True)
|
|
def mock_http_start_stop() -> Generator[None]:
|
|
"""Mock HTTP start and stop."""
|
|
with (
|
|
patch("homeassistant.components.http.HomeAssistantHTTP.start"),
|
|
patch("homeassistant.components.http.HomeAssistantHTTP.stop"),
|
|
):
|
|
yield
|
|
|
|
|
|
@patch("homeassistant.bootstrap.async_enable_logging", AsyncMock())
|
|
async def test_home_assistant_core_config_validation(hass: HomeAssistant) -> None:
|
|
"""Test if we pass in wrong information for HA conf."""
|
|
# Extensive HA conf validation testing is done
|
|
result = await bootstrap.async_from_config_dict(
|
|
{"homeassistant": {"latitude": "some string"}}, hass
|
|
)
|
|
assert result is None
|
|
|
|
|
|
async def test_async_enable_logging(
|
|
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
|
|
) -> None:
|
|
"""Test to ensure logging is migrated to the queue handlers."""
|
|
|
|
# Ensure we start with a clean slate
|
|
cleanup_log_files()
|
|
assert len(glob.glob(CONFIG_LOG_FILE)) == 0
|
|
assert len(glob.glob(ARG_LOG_FILE)) == 0
|
|
|
|
with (
|
|
patch("logging.getLogger"),
|
|
patch(
|
|
"homeassistant.bootstrap.async_activate_log_queue_handler"
|
|
) as mock_async_activate_log_queue_handler,
|
|
patch(
|
|
"homeassistant.bootstrap.logging.handlers.RotatingFileHandler.doRollover",
|
|
side_effect=OSError,
|
|
),
|
|
):
|
|
await bootstrap.async_enable_logging(hass)
|
|
mock_async_activate_log_queue_handler.assert_called_once()
|
|
assert len(glob.glob(CONFIG_LOG_FILE)) > 0
|
|
|
|
mock_async_activate_log_queue_handler.reset_mock()
|
|
await bootstrap.async_enable_logging(
|
|
hass,
|
|
log_rotate_days=5,
|
|
log_file="test.log",
|
|
)
|
|
mock_async_activate_log_queue_handler.assert_called_once()
|
|
assert len(glob.glob(ARG_LOG_FILE)) > 0
|
|
|
|
assert "Error rolling over log file" in caplog.text
|
|
|
|
cleanup_log_files()
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
(
|
|
"env",
|
|
"log_file_count",
|
|
"old_log_file_count",
|
|
"data_logging",
|
|
"data_logging_disabled_reason",
|
|
),
|
|
[
|
|
pytest.param(
|
|
{"SUPERVISOR": "1"},
|
|
0,
|
|
1,
|
|
None,
|
|
None,
|
|
id="supervisor",
|
|
),
|
|
pytest.param(
|
|
{"SUPERVISOR": "1", "HA_DUPLICATE_LOG_FILE": "1"},
|
|
1,
|
|
0,
|
|
CONFIG_LOG_FILE,
|
|
None,
|
|
id="supervisor-duplicate-log-file",
|
|
),
|
|
pytest.param(
|
|
{"HA_DISABLE_LOG_FILE": "1"},
|
|
0,
|
|
1,
|
|
None,
|
|
"environment",
|
|
id="disable-log-file",
|
|
),
|
|
pytest.param(
|
|
{"HA_DISABLE_LOG_FILE": "0"},
|
|
1,
|
|
0,
|
|
CONFIG_LOG_FILE,
|
|
None,
|
|
id="disable-log-file-false",
|
|
),
|
|
pytest.param(
|
|
{"HA_DISABLE_LOG_FILE": "invalid"},
|
|
1,
|
|
0,
|
|
CONFIG_LOG_FILE,
|
|
None,
|
|
id="disable-log-file-invalid",
|
|
),
|
|
],
|
|
)
|
|
async def test_async_enable_logging_log_file_disable_control(
|
|
hass: HomeAssistant,
|
|
monkeypatch: pytest.MonkeyPatch,
|
|
env: dict[str, str],
|
|
log_file_count: int,
|
|
old_log_file_count: int,
|
|
data_logging: str | None,
|
|
data_logging_disabled_reason: str | None,
|
|
) -> None:
|
|
"""Test the default log file disable controls."""
|
|
|
|
# Ensure we start with a clean slate
|
|
cleanup_log_files()
|
|
assert len(glob.glob(CONFIG_LOG_FILE)) == 0
|
|
assert len(glob.glob(ARG_LOG_FILE)) == 0
|
|
|
|
for env_var in ("SUPERVISOR", "HA_DUPLICATE_LOG_FILE", "HA_DISABLE_LOG_FILE"):
|
|
monkeypatch.delenv(env_var, raising=False)
|
|
for env_var, value in env.items():
|
|
monkeypatch.setenv(env_var, value)
|
|
|
|
with (
|
|
patch(
|
|
"homeassistant.bootstrap.async_activate_log_queue_handler"
|
|
) as mock_async_activate_log_queue_handler,
|
|
patch("logging.getLogger"),
|
|
):
|
|
await bootstrap.async_enable_logging(hass)
|
|
assert len(glob.glob(CONFIG_LOG_FILE)) == log_file_count
|
|
assert hass.data.get(bootstrap.DATA_LOGGING) == data_logging
|
|
assert (
|
|
hass.data.get(bootstrap.DATA_LOGGING_DISABLED_REASON)
|
|
== data_logging_disabled_reason
|
|
)
|
|
assert hass.config.as_dict()["logging"] == {
|
|
"log_file_disabled_reason": data_logging_disabled_reason,
|
|
}
|
|
mock_async_activate_log_queue_handler.assert_called_once()
|
|
mock_async_activate_log_queue_handler.reset_mock()
|
|
|
|
# Check that if the log file exists, it is renamed
|
|
def write_log_file() -> None:
|
|
with open(
|
|
get_test_config_dir("home-assistant.log"), "w", encoding="utf8"
|
|
) as f:
|
|
f.write("test")
|
|
|
|
await hass.async_add_executor_job(write_log_file)
|
|
assert len(glob.glob(CONFIG_LOG_FILE)) == 1
|
|
assert len(glob.glob(f"{CONFIG_LOG_FILE}.old")) == 0
|
|
|
|
await bootstrap.async_enable_logging(hass)
|
|
assert len(glob.glob(CONFIG_LOG_FILE)) == log_file_count
|
|
assert len(glob.glob(f"{CONFIG_LOG_FILE}.old")) == old_log_file_count
|
|
assert hass.data.get(bootstrap.DATA_LOGGING) == data_logging
|
|
assert (
|
|
hass.data.get(bootstrap.DATA_LOGGING_DISABLED_REASON)
|
|
== data_logging_disabled_reason
|
|
)
|
|
mock_async_activate_log_queue_handler.assert_called_once()
|
|
mock_async_activate_log_queue_handler.reset_mock()
|
|
|
|
await bootstrap.async_enable_logging(
|
|
hass,
|
|
log_rotate_days=5,
|
|
log_file="test.log",
|
|
)
|
|
mock_async_activate_log_queue_handler.assert_called_once()
|
|
# The log file should be created if it is explicitly specified.
|
|
assert len(glob.glob(ARG_LOG_FILE)) > 0
|
|
assert bootstrap.DATA_LOGGING in hass.data
|
|
|
|
cleanup_log_files()
|
|
|
|
|
|
async def test_load_hassio(hass: HomeAssistant) -> None:
|
|
"""Test that we load the hassio integration when using Supervisor."""
|
|
with patch.dict(os.environ, {}, clear=True):
|
|
assert "hassio" not in bootstrap._get_domains(hass, {})
|
|
|
|
with patch.dict(os.environ, {"SUPERVISOR": "1"}):
|
|
assert "hassio" in bootstrap._get_domains(hass, {})
|
|
|
|
|
|
@pytest.mark.parametrize("load_registries", [False])
|
|
async def test_empty_setup(hass: HomeAssistant) -> None:
|
|
"""Test an empty set up loads the core."""
|
|
await bootstrap.async_from_config_dict({}, hass)
|
|
for domain in bootstrap.CORE_INTEGRATIONS:
|
|
assert domain in hass.config.components, domain
|
|
|
|
|
|
@pytest.mark.parametrize("load_registries", [False])
|
|
async def test_config_does_not_turn_off_debug(hass: HomeAssistant) -> None:
|
|
"""Test that config does not turn off debug if its turned on by runtime config."""
|
|
# Mock that its turned on from RuntimeConfig
|
|
hass.config.debug = True
|
|
|
|
await bootstrap.async_from_config_dict({CONF_DEBUG: False}, hass)
|
|
assert hass.config.debug is True
|
|
|
|
|
|
@pytest.mark.parametrize("hass_config", [{"frontend": {}}])
|
|
@pytest.mark.usefixtures("mock_hass_config")
|
|
async def test_asyncio_debug_on_turns_hass_debug_on(
|
|
mock_enable_logging: AsyncMock,
|
|
mock_ensure_config_exists: AsyncMock,
|
|
mock_process_ha_config_upgrade: Mock,
|
|
) -> None:
|
|
"""Test that asyncio debug turns on hass debug."""
|
|
asyncio.get_running_loop().set_debug(True)
|
|
|
|
verbose = Mock()
|
|
log_rotate_days = Mock()
|
|
log_file = Mock()
|
|
log_no_color = Mock()
|
|
|
|
hass = await bootstrap.async_setup_hass(
|
|
runner.RuntimeConfig(
|
|
config_dir=get_test_config_dir(),
|
|
verbose=verbose,
|
|
log_rotate_days=log_rotate_days,
|
|
log_file=log_file,
|
|
log_no_color=log_no_color,
|
|
skip_pip=True,
|
|
recovery_mode=False,
|
|
),
|
|
)
|
|
|
|
assert hass.config.debug is True
|
|
|
|
|
|
@pytest.mark.parametrize("load_registries", [False])
|
|
async def test_preload_translations(hass: HomeAssistant) -> None:
|
|
"""Test translations are preloaded for all frontend deps and base platforms."""
|
|
await bootstrap.async_from_config_dict({}, hass)
|
|
await hass.async_block_till_done(wait_background_tasks=True)
|
|
frontend = await loader.async_get_integration(hass, "frontend")
|
|
assert async_translations_loaded(hass, set(frontend.all_dependencies))
|
|
assert async_translations_loaded(hass, BASE_PLATFORMS)
|
|
|
|
|
|
async def test_core_failure_loads_recovery_mode(
|
|
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
|
|
) -> None:
|
|
"""Test failing core setup aborts further setup."""
|
|
with patch(
|
|
"homeassistant.components.homeassistant.async_setup",
|
|
return_value=False,
|
|
):
|
|
await bootstrap.async_from_config_dict({"group": {}}, hass)
|
|
|
|
assert "core failed to initialize" in caplog.text
|
|
# We aborted early, group not set up
|
|
assert "group" not in hass.config.components
|
|
|
|
|
|
@pytest.mark.parametrize("load_registries", [False])
|
|
async def test_setting_up_empty_config(
|
|
hass: HomeAssistant,
|
|
snapshot: SnapshotAssertion,
|
|
) -> None:
|
|
"""Test default integrations are set up with empty config."""
|
|
await bootstrap._async_set_up_integrations(hass, {}, monotonic())
|
|
|
|
assert all(
|
|
domain in hass.config.components for domain in bootstrap.DEFAULT_INTEGRATIONS
|
|
)
|
|
assert set(hass.config.components) == snapshot
|
|
|
|
|
|
@pytest.mark.parametrize("load_registries", [False])
|
|
async def test_setting_up_config(
|
|
hass: HomeAssistant,
|
|
snapshot: SnapshotAssertion,
|
|
) -> None:
|
|
"""Test we set up domains in config."""
|
|
await bootstrap._async_set_up_integrations(
|
|
hass, {"group hello": {}, "homeassistant": {}}, monotonic()
|
|
)
|
|
|
|
assert "group" in hass.config.components
|
|
assert all(
|
|
domain in hass.config.components for domain in bootstrap.DEFAULT_INTEGRATIONS
|
|
)
|
|
assert set(hass.config.components) == snapshot
|
|
|
|
|
|
@pytest.mark.parametrize("load_registries", [False])
|
|
async def test_setup_after_deps_all_present(hass: HomeAssistant) -> None:
|
|
"""Test after_dependencies when all present."""
|
|
order = []
|
|
|
|
def gen_domain_setup(domain):
|
|
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
|
order.append(domain)
|
|
return True
|
|
|
|
return async_setup
|
|
|
|
mock_integration(
|
|
hass, MockModule(domain="root", async_setup=gen_domain_setup("root"))
|
|
)
|
|
mock_integration(
|
|
hass,
|
|
MockModule(
|
|
domain="first_dep",
|
|
async_setup=gen_domain_setup("first_dep"),
|
|
partial_manifest={"after_dependencies": ["root"]},
|
|
),
|
|
)
|
|
mock_integration(
|
|
hass,
|
|
MockModule(
|
|
domain="second_dep",
|
|
async_setup=gen_domain_setup("second_dep"),
|
|
partial_manifest={"after_dependencies": ["first_dep"]},
|
|
),
|
|
)
|
|
|
|
with patch(
|
|
"homeassistant.components.logger.async_setup", gen_domain_setup("logger")
|
|
):
|
|
await bootstrap._async_set_up_integrations(
|
|
hass,
|
|
{"root": {}, "first_dep": {}, "second_dep": {}, "logger": {}},
|
|
monotonic(),
|
|
)
|
|
|
|
assert "root" in hass.config.components
|
|
assert "first_dep" in hass.config.components
|
|
assert "second_dep" in hass.config.components
|
|
assert order == ["logger", "root", "first_dep", "second_dep"]
|
|
|
|
|
|
@pytest.mark.parametrize("load_registries", [False])
|
|
async def test_setup_after_deps_in_stage_1(hass: HomeAssistant) -> None:
|
|
"""Test after_dependencies are promoted in stage 1."""
|
|
# This test relies on this
|
|
assert "cloud" in bootstrap.STAGE_1_INTEGRATIONS
|
|
order = []
|
|
|
|
def gen_domain_setup(domain):
|
|
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
|
order.append(domain)
|
|
return True
|
|
|
|
return async_setup
|
|
|
|
mock_integration(
|
|
hass,
|
|
MockModule(
|
|
domain="normal_integration",
|
|
async_setup=gen_domain_setup("normal_integration"),
|
|
partial_manifest={"after_dependencies": ["an_after_dep"]},
|
|
),
|
|
)
|
|
mock_integration(
|
|
hass,
|
|
MockModule(
|
|
domain="an_after_dep",
|
|
async_setup=gen_domain_setup("an_after_dep"),
|
|
),
|
|
)
|
|
mock_integration(
|
|
hass,
|
|
MockModule(
|
|
domain="cloud",
|
|
async_setup=gen_domain_setup("cloud"),
|
|
partial_manifest={"after_dependencies": ["normal_integration"]},
|
|
),
|
|
)
|
|
|
|
await bootstrap._async_set_up_integrations(
|
|
hass, {"cloud": {}, "normal_integration": {}, "an_after_dep": {}}, monotonic()
|
|
)
|
|
|
|
assert "normal_integration" in hass.config.components
|
|
assert "cloud" in hass.config.components
|
|
assert order == ["an_after_dep", "normal_integration", "cloud"]
|
|
|
|
|
|
@pytest.mark.parametrize("load_registries", [False])
|
|
async def test_setup_after_deps_manifests_are_loaded_even_if_not_setup(
|
|
hass: HomeAssistant,
|
|
) -> None:
|
|
"""Ensure we preload manifests for after deps even if they are not setup.
|
|
|
|
It's important that we preload the after dep manifests even if they are not setup
|
|
since we will always have to check their requirements since any integration
|
|
that lists an after dep may import it and we have to ensure requirements are
|
|
up to date before the after dep can be imported.
|
|
"""
|
|
# This test relies on this
|
|
assert "cloud" in bootstrap.STAGE_1_INTEGRATIONS
|
|
order = []
|
|
|
|
def gen_domain_setup(domain):
|
|
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
|
order.append(domain)
|
|
return True
|
|
|
|
return async_setup
|
|
|
|
mock_integration(
|
|
hass,
|
|
MockModule(
|
|
domain="normal_integration",
|
|
async_setup=gen_domain_setup("normal_integration"),
|
|
partial_manifest={"after_dependencies": ["an_after_dep"]},
|
|
),
|
|
)
|
|
mock_integration(
|
|
hass,
|
|
MockModule(
|
|
domain="an_after_dep",
|
|
async_setup=gen_domain_setup("an_after_dep"),
|
|
partial_manifest={"after_dependencies": ["an_after_dep_of_after_dep"]},
|
|
),
|
|
)
|
|
mock_integration(
|
|
hass,
|
|
MockModule(
|
|
domain="an_after_dep_of_after_dep",
|
|
async_setup=gen_domain_setup("an_after_dep_of_after_dep"),
|
|
partial_manifest={
|
|
"after_dependencies": ["an_after_dep_of_after_dep_of_after_dep"]
|
|
},
|
|
),
|
|
)
|
|
mock_integration(
|
|
hass,
|
|
MockModule(
|
|
domain="an_after_dep_of_after_dep_of_after_dep",
|
|
async_setup=gen_domain_setup("an_after_dep_of_after_dep_of_after_dep"),
|
|
),
|
|
)
|
|
mock_integration(
|
|
hass,
|
|
MockModule(
|
|
domain="cloud",
|
|
async_setup=gen_domain_setup("cloud"),
|
|
partial_manifest={"after_dependencies": ["normal_integration"]},
|
|
),
|
|
)
|
|
|
|
await bootstrap._async_set_up_integrations(
|
|
hass, {"cloud": {}, "normal_integration": {}}, monotonic()
|
|
)
|
|
|
|
assert "normal_integration" in hass.config.components
|
|
assert "cloud" in hass.config.components
|
|
assert "an_after_dep" not in hass.config.components
|
|
assert "an_after_dep_of_after_dep" not in hass.config.components
|
|
assert "an_after_dep_of_after_dep_of_after_dep" not in hass.config.components
|
|
assert order == ["normal_integration", "cloud"]
|
|
assert loader.async_get_loaded_integration(hass, "an_after_dep") is not None
|
|
assert (
|
|
loader.async_get_loaded_integration(hass, "an_after_dep_of_after_dep")
|
|
is not None
|
|
)
|
|
assert (
|
|
loader.async_get_loaded_integration(
|
|
hass, "an_after_dep_of_after_dep_of_after_dep"
|
|
)
|
|
is not None
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize("load_registries", [False])
|
|
async def test_setup_frontend_before_recorder(hass: HomeAssistant) -> None:
|
|
"""Test frontend is setup before recorder."""
|
|
order = []
|
|
|
|
def gen_domain_setup(domain):
|
|
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
|
order.append(domain)
|
|
return True
|
|
|
|
return async_setup
|
|
|
|
mock_integration(
|
|
hass,
|
|
MockModule(
|
|
domain="normal_integration",
|
|
async_setup=gen_domain_setup("normal_integration"),
|
|
partial_manifest={"after_dependencies": ["an_after_dep"]},
|
|
),
|
|
)
|
|
mock_integration(
|
|
hass,
|
|
MockModule(
|
|
domain="an_after_dep",
|
|
async_setup=gen_domain_setup("an_after_dep"),
|
|
),
|
|
)
|
|
mock_integration(
|
|
hass,
|
|
MockModule(
|
|
domain="frontend",
|
|
async_setup=gen_domain_setup("frontend"),
|
|
partial_manifest={
|
|
"dependencies": ["http"],
|
|
"after_dependencies": ["an_after_dep"],
|
|
},
|
|
),
|
|
)
|
|
mock_integration(
|
|
hass,
|
|
MockModule(
|
|
domain="http",
|
|
async_setup=gen_domain_setup("http"),
|
|
),
|
|
)
|
|
mock_integration(
|
|
hass,
|
|
MockModule(
|
|
domain="recorder",
|
|
async_setup=gen_domain_setup("recorder"),
|
|
),
|
|
)
|
|
|
|
await bootstrap._async_set_up_integrations(
|
|
hass,
|
|
{
|
|
"frontend": {},
|
|
"http": {},
|
|
"recorder": {},
|
|
"normal_integration": {},
|
|
"an_after_dep": {},
|
|
},
|
|
monotonic(),
|
|
)
|
|
|
|
assert "frontend" in hass.config.components
|
|
assert "normal_integration" in hass.config.components
|
|
assert "recorder" in hass.config.components
|
|
assert "http" in hass.config.components
|
|
|
|
# http (a dependency) and an_after_dep (an after_dependency) are both set
|
|
# up in the frontend substage of stage 0; their relative order depends on
|
|
# set iteration order and is not guaranteed.
|
|
assert set(order[:2]) == {"http", "an_after_dep"}
|
|
assert order[2:] == [
|
|
"frontend",
|
|
"recorder",
|
|
"normal_integration",
|
|
]
|
|
|
|
|
|
@pytest.mark.parametrize("load_registries", [False])
|
|
async def test_setup_after_deps_via_platform(hass: HomeAssistant) -> None:
|
|
"""Test after_dependencies set up via platform."""
|
|
order = []
|
|
after_dep_event = asyncio.Event()
|
|
|
|
def gen_domain_setup(domain):
|
|
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
|
if domain == "after_dep_of_platform_int":
|
|
await after_dep_event.wait()
|
|
|
|
order.append(domain)
|
|
return True
|
|
|
|
return async_setup
|
|
|
|
mock_integration(
|
|
hass,
|
|
MockModule(
|
|
domain="after_dep_of_platform_int",
|
|
async_setup=gen_domain_setup("after_dep_of_platform_int"),
|
|
),
|
|
)
|
|
mock_integration(
|
|
hass,
|
|
MockModule(
|
|
domain="platform_int",
|
|
async_setup=gen_domain_setup("platform_int"),
|
|
partial_manifest={"after_dependencies": ["after_dep_of_platform_int"]},
|
|
),
|
|
)
|
|
mock_platform(hass, "platform_int.light", MockPlatform())
|
|
|
|
@callback
|
|
def continue_loading(_):
|
|
"""When light component loaded, continue other loading."""
|
|
after_dep_event.set()
|
|
|
|
hass.bus.async_listen_once("component_loaded", continue_loading)
|
|
|
|
await bootstrap._async_set_up_integrations(
|
|
hass,
|
|
{"light": {"platform": "platform_int"}, "after_dep_of_platform_int": {}},
|
|
monotonic(),
|
|
)
|
|
|
|
assert "light" in hass.config.components
|
|
assert "after_dep_of_platform_int" in hass.config.components
|
|
assert "platform_int" in hass.config.components
|
|
assert order == ["after_dep_of_platform_int", "platform_int"]
|
|
|
|
|
|
@pytest.mark.parametrize("load_registries", [False])
|
|
async def test_setup_after_deps_not_trigger_load(hass: HomeAssistant) -> None:
|
|
"""Test after_dependencies does not trigger loading it."""
|
|
order = []
|
|
|
|
def gen_domain_setup(domain):
|
|
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
|
order.append(domain)
|
|
return True
|
|
|
|
return async_setup
|
|
|
|
mock_integration(
|
|
hass, MockModule(domain="root", async_setup=gen_domain_setup("root"))
|
|
)
|
|
mock_integration(
|
|
hass,
|
|
MockModule(
|
|
domain="first_dep",
|
|
async_setup=gen_domain_setup("first_dep"),
|
|
partial_manifest={"after_dependencies": ["root"]},
|
|
),
|
|
)
|
|
mock_integration(
|
|
hass,
|
|
MockModule(
|
|
domain="second_dep",
|
|
async_setup=gen_domain_setup("second_dep"),
|
|
partial_manifest={"after_dependencies": ["first_dep"]},
|
|
),
|
|
)
|
|
|
|
await bootstrap._async_set_up_integrations(
|
|
hass, {"root": {}, "second_dep": {}}, monotonic()
|
|
)
|
|
|
|
assert "root" in hass.config.components
|
|
assert "first_dep" not in hass.config.components
|
|
assert "second_dep" in hass.config.components
|
|
|
|
|
|
@pytest.mark.parametrize("load_registries", [False])
|
|
async def test_setup_after_deps_not_present(hass: HomeAssistant) -> None:
|
|
"""Test after_dependencies when referenced integration doesn't exist."""
|
|
order = []
|
|
|
|
def gen_domain_setup(domain):
|
|
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
|
order.append(domain)
|
|
return True
|
|
|
|
return async_setup
|
|
|
|
mock_integration(
|
|
hass, MockModule(domain="root", async_setup=gen_domain_setup("root"))
|
|
)
|
|
mock_integration(
|
|
hass,
|
|
MockModule(
|
|
domain="second_dep",
|
|
async_setup=gen_domain_setup("second_dep"),
|
|
partial_manifest={"after_dependencies": ["first_dep", "root"]},
|
|
),
|
|
)
|
|
|
|
await bootstrap._async_set_up_integrations(
|
|
hass, {"root": {}, "first_dep": {}, "second_dep": {}}, monotonic()
|
|
)
|
|
|
|
assert "root" in hass.config.components
|
|
assert "first_dep" not in hass.config.components
|
|
assert "second_dep" in hass.config.components
|
|
assert order == ["root", "second_dep"]
|
|
|
|
|
|
@pytest.fixture
|
|
def mock_enable_logging() -> Generator[AsyncMock]:
|
|
"""Mock enable logging."""
|
|
with patch("homeassistant.bootstrap.async_enable_logging") as enable_logging:
|
|
yield enable_logging
|
|
|
|
|
|
@pytest.fixture
|
|
def mock_process_ha_config_upgrade() -> Generator[Mock]:
|
|
"""Mock enable logging."""
|
|
with patch(
|
|
"homeassistant.config.process_ha_config_upgrade", return_value=None
|
|
) as process_ha_config_upgrade:
|
|
yield process_ha_config_upgrade
|
|
|
|
|
|
@pytest.fixture
|
|
def mock_ensure_config_exists() -> Generator[AsyncMock]:
|
|
"""Mock enable logging."""
|
|
with patch(
|
|
"homeassistant.config.async_ensure_config_exists", return_value=True
|
|
) as ensure_config_exists:
|
|
yield ensure_config_exists
|
|
|
|
|
|
@pytest.mark.parametrize("hass_config", [{"browser": {}, "frontend": {}}])
|
|
@pytest.mark.usefixtures("mock_hass_config")
|
|
async def test_setup_hass(
|
|
mock_enable_logging: AsyncMock,
|
|
mock_ensure_config_exists: AsyncMock,
|
|
mock_process_ha_config_upgrade: Mock,
|
|
caplog: pytest.LogCaptureFixture,
|
|
) -> None:
|
|
"""Test it works."""
|
|
verbose = Mock()
|
|
log_rotate_days = Mock()
|
|
log_file = Mock()
|
|
log_no_color = Mock()
|
|
|
|
with patch.object(bootstrap, "LOG_SLOW_STARTUP_INTERVAL", 5000):
|
|
hass = await bootstrap.async_setup_hass(
|
|
runner.RuntimeConfig(
|
|
config_dir=get_test_config_dir(),
|
|
verbose=verbose,
|
|
log_rotate_days=log_rotate_days,
|
|
log_file=log_file,
|
|
log_no_color=log_no_color,
|
|
skip_pip=True,
|
|
recovery_mode=False,
|
|
debug=True,
|
|
),
|
|
)
|
|
|
|
assert "Waiting for integrations to complete setup" not in caplog.text
|
|
|
|
assert "browser" in hass.config.components
|
|
assert "recovery_mode" not in hass.config.components
|
|
|
|
assert len(mock_enable_logging.mock_calls) == 1
|
|
assert mock_enable_logging.mock_calls[0][1] == (
|
|
hass,
|
|
verbose,
|
|
log_rotate_days,
|
|
log_file,
|
|
log_no_color,
|
|
)
|
|
assert len(mock_ensure_config_exists.mock_calls) == 1
|
|
assert len(mock_process_ha_config_upgrade.mock_calls) == 1
|
|
assert config_util.DATA_PREVIOUS_VERSION not in hass.data
|
|
|
|
# debug in RuntimeConfig should set it it in hass.config
|
|
assert hass.config.debug is True
|
|
|
|
assert hass == async_get_hass()
|
|
|
|
|
|
@pytest.mark.parametrize("hass_config", [{"browser": {}, "frontend": {}}])
|
|
@pytest.mark.usefixtures(
|
|
"mock_hass_config", "mock_enable_logging", "mock_ensure_config_exists"
|
|
)
|
|
async def test_setup_hass_keeps_previous_version(
|
|
mock_process_ha_config_upgrade: Mock,
|
|
) -> None:
|
|
"""Test the version that ran before an update is kept for the trigger."""
|
|
mock_process_ha_config_upgrade.return_value = "2026.9.4"
|
|
|
|
hass = await bootstrap.async_setup_hass(
|
|
runner.RuntimeConfig(
|
|
config_dir=get_test_config_dir(),
|
|
skip_pip=True,
|
|
recovery_mode=False,
|
|
),
|
|
)
|
|
|
|
assert hass.data[config_util.DATA_PREVIOUS_VERSION] == "2026.9.4"
|
|
|
|
|
|
@pytest.mark.parametrize("hass_config", [{"browser": {}, "frontend": {}}])
|
|
@pytest.mark.usefixtures("mock_hass_config")
|
|
async def test_setup_hass_takes_longer_than_log_slow_startup(
|
|
mock_enable_logging: AsyncMock,
|
|
mock_ensure_config_exists: AsyncMock,
|
|
mock_process_ha_config_upgrade: Mock,
|
|
caplog: pytest.LogCaptureFixture,
|
|
) -> None:
|
|
"""Test it works."""
|
|
verbose = Mock()
|
|
log_rotate_days = Mock()
|
|
log_file = Mock()
|
|
log_no_color = Mock()
|
|
|
|
async def _async_setup_that_blocks_startup(*args, **kwargs):
|
|
await asyncio.sleep(0.2)
|
|
return True
|
|
|
|
with (
|
|
patch.object(bootstrap, "LOG_SLOW_STARTUP_INTERVAL", 0.005),
|
|
patch.object(bootstrap, "SLOW_STARTUP_CHECK_INTERVAL", 0.005),
|
|
patch(
|
|
"homeassistant.components.frontend.async_setup",
|
|
side_effect=_async_setup_that_blocks_startup,
|
|
),
|
|
):
|
|
await bootstrap.async_setup_hass(
|
|
runner.RuntimeConfig(
|
|
config_dir=get_test_config_dir(),
|
|
verbose=verbose,
|
|
log_rotate_days=log_rotate_days,
|
|
log_file=log_file,
|
|
log_no_color=log_no_color,
|
|
skip_pip=True,
|
|
recovery_mode=False,
|
|
),
|
|
)
|
|
|
|
assert "Waiting for integrations to complete setup" in caplog.text
|
|
|
|
|
|
async def test_setup_hass_invalid_yaml(
|
|
mock_enable_logging: AsyncMock,
|
|
mock_ensure_config_exists: AsyncMock,
|
|
mock_process_ha_config_upgrade: Mock,
|
|
) -> None:
|
|
"""Test it works."""
|
|
with patch(
|
|
"homeassistant.config.async_hass_config_yaml", side_effect=HomeAssistantError
|
|
):
|
|
hass = await bootstrap.async_setup_hass(
|
|
runner.RuntimeConfig(
|
|
config_dir=get_test_config_dir(),
|
|
verbose=False,
|
|
log_rotate_days=10,
|
|
log_file="",
|
|
log_no_color=False,
|
|
skip_pip=True,
|
|
recovery_mode=False,
|
|
),
|
|
)
|
|
|
|
assert "recovery_mode" in hass.config.components
|
|
|
|
|
|
async def test_setup_hass_config_dir_nonexistent(
|
|
mock_enable_logging: AsyncMock,
|
|
mock_ensure_config_exists: AsyncMock,
|
|
mock_process_ha_config_upgrade: Mock,
|
|
) -> None:
|
|
"""Test it works."""
|
|
mock_ensure_config_exists.return_value = False
|
|
|
|
assert (
|
|
await bootstrap.async_setup_hass(
|
|
runner.RuntimeConfig(
|
|
config_dir=get_test_config_dir(),
|
|
verbose=False,
|
|
log_rotate_days=10,
|
|
log_file="",
|
|
log_no_color=False,
|
|
skip_pip=True,
|
|
recovery_mode=False,
|
|
),
|
|
)
|
|
is None
|
|
)
|
|
|
|
|
|
async def test_setup_hass_recovery_mode(
|
|
mock_enable_logging: AsyncMock,
|
|
mock_ensure_config_exists: AsyncMock,
|
|
mock_process_ha_config_upgrade: Mock,
|
|
) -> None:
|
|
"""Test it works."""
|
|
with (
|
|
patch(
|
|
"homeassistant.core.HomeAssistant", wraps=core.HomeAssistant
|
|
) as mock_hass,
|
|
patch("homeassistant.components.browser.setup") as browser_setup,
|
|
patch(
|
|
"homeassistant.config_entries.ConfigEntries.async_domains",
|
|
return_value=["browser"],
|
|
),
|
|
):
|
|
hass = await bootstrap.async_setup_hass(
|
|
runner.RuntimeConfig(
|
|
config_dir=get_test_config_dir(),
|
|
verbose=False,
|
|
log_rotate_days=10,
|
|
log_file="",
|
|
log_no_color=False,
|
|
skip_pip=True,
|
|
recovery_mode=True,
|
|
),
|
|
)
|
|
|
|
mock_hass.assert_called_once()
|
|
|
|
assert "recovery_mode" in hass.config.components
|
|
|
|
# Validate we didn't try to set up config entry.
|
|
assert "browser" not in hass.config.components
|
|
assert len(browser_setup.mock_calls) == 0
|
|
|
|
# Downloading custom integrations is the last thing recovery mode needs
|
|
assert "marketplace" not in hass.config.components
|
|
|
|
|
|
@pytest.mark.parametrize("domain", ["cloud", "backup"])
|
|
async def test_setup_hass_recovery_mode_with_failing_integration(
|
|
mock_enable_logging: AsyncMock,
|
|
mock_ensure_config_exists: AsyncMock,
|
|
mock_process_ha_config_upgrade: Mock,
|
|
domain: str,
|
|
) -> None:
|
|
"""Test recovery mode still starts if cloud or backup fails to set up."""
|
|
with patch(
|
|
f"homeassistant.components.{domain}.async_setup",
|
|
side_effect=Exception(f"{domain} setup failed"),
|
|
):
|
|
hass = await bootstrap.async_setup_hass(
|
|
runner.RuntimeConfig(
|
|
config_dir=get_test_config_dir(),
|
|
verbose=False,
|
|
log_rotate_days=10,
|
|
log_file="",
|
|
log_no_color=False,
|
|
skip_pip=True,
|
|
recovery_mode=True,
|
|
),
|
|
)
|
|
|
|
assert "recovery_mode" in hass.config.components
|
|
assert domain not in hass.config.components
|
|
|
|
|
|
@pytest.mark.usefixtures("mock_hass_config")
|
|
async def test_setup_hass_safe_mode(
|
|
mock_enable_logging: AsyncMock,
|
|
mock_ensure_config_exists: AsyncMock,
|
|
mock_process_ha_config_upgrade: Mock,
|
|
caplog: pytest.LogCaptureFixture,
|
|
) -> None:
|
|
"""Test it works."""
|
|
with (
|
|
patch("homeassistant.components.browser.setup"),
|
|
patch(
|
|
"homeassistant.config_entries.ConfigEntries.async_domains",
|
|
return_value=["browser"],
|
|
),
|
|
):
|
|
hass = await bootstrap.async_setup_hass(
|
|
runner.RuntimeConfig(
|
|
config_dir=get_test_config_dir(),
|
|
verbose=False,
|
|
log_rotate_days=10,
|
|
log_file="",
|
|
log_no_color=False,
|
|
skip_pip=True,
|
|
recovery_mode=False,
|
|
safe_mode=True,
|
|
),
|
|
)
|
|
|
|
assert "recovery_mode" not in hass.config.components
|
|
assert "Starting in recovery mode" not in caplog.text
|
|
assert "Starting in safe mode" in caplog.text
|
|
|
|
|
|
@pytest.mark.usefixtures("mock_hass_config")
|
|
async def test_setup_hass_recovery_mode_and_safe_mode(
|
|
mock_enable_logging: AsyncMock,
|
|
mock_ensure_config_exists: AsyncMock,
|
|
mock_process_ha_config_upgrade: Mock,
|
|
caplog: pytest.LogCaptureFixture,
|
|
) -> None:
|
|
"""Test it works."""
|
|
with (
|
|
patch("homeassistant.components.browser.setup"),
|
|
patch(
|
|
"homeassistant.config_entries.ConfigEntries.async_domains",
|
|
return_value=["browser"],
|
|
),
|
|
):
|
|
hass = await bootstrap.async_setup_hass(
|
|
runner.RuntimeConfig(
|
|
config_dir=get_test_config_dir(),
|
|
verbose=False,
|
|
log_rotate_days=10,
|
|
log_file="",
|
|
log_no_color=False,
|
|
skip_pip=True,
|
|
recovery_mode=True,
|
|
safe_mode=True,
|
|
),
|
|
)
|
|
|
|
assert "recovery_mode" in hass.config.components
|
|
assert "Starting in recovery mode" in caplog.text
|
|
assert "Starting in safe mode" not in caplog.text
|
|
|
|
|
|
@pytest.mark.parametrize("hass_config", [{"frontend": {}}])
|
|
@pytest.mark.parametrize(
|
|
"storage_key",
|
|
[
|
|
# Loading the entity registry waits for the device registry
|
|
"core.device_registry",
|
|
# Loading restore state waits for the entity registry
|
|
"core.entity_registry",
|
|
],
|
|
)
|
|
@pytest.mark.usefixtures("mock_hass_config")
|
|
async def test_storage_version_too_new_triggers_recovery_mode(
|
|
hass_storage: dict[str, Any],
|
|
mock_enable_logging: AsyncMock,
|
|
mock_ensure_config_exists: AsyncMock,
|
|
mock_process_ha_config_upgrade: Mock,
|
|
caplog: pytest.LogCaptureFixture,
|
|
storage_key: str,
|
|
) -> None:
|
|
"""Test that a storage file with a newer major version triggers recovery mode."""
|
|
hass_storage[storage_key] = {
|
|
"version": 99,
|
|
"minor_version": 1,
|
|
"key": storage_key,
|
|
"data": {},
|
|
}
|
|
|
|
hass = await bootstrap.async_setup_hass(
|
|
runner.RuntimeConfig(
|
|
config_dir=get_test_config_dir(),
|
|
verbose=False,
|
|
log_rotate_days=10,
|
|
log_file="",
|
|
log_no_color=False,
|
|
skip_pip=True,
|
|
recovery_mode=False,
|
|
),
|
|
)
|
|
|
|
assert hass is not None
|
|
assert hass.config.recovery_mode is True
|
|
assert "recovery_mode" in hass.config.components
|
|
assert (
|
|
f"Storage file {storage_key} was created"
|
|
" by a newer version of Home Assistant" in caplog.text
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize("hass_config", [{"homeassistant": {"non-existing": 1}}])
|
|
@pytest.mark.usefixtures("mock_hass_config")
|
|
async def test_setup_hass_invalid_core_config(
|
|
mock_enable_logging: AsyncMock,
|
|
mock_ensure_config_exists: AsyncMock,
|
|
mock_process_ha_config_upgrade: Mock,
|
|
) -> None:
|
|
"""Test it works."""
|
|
with patch("homeassistant.bootstrap.async_notify_setup_error") as mock_notify:
|
|
hass = await bootstrap.async_setup_hass(
|
|
runner.RuntimeConfig(
|
|
config_dir=get_test_config_dir(),
|
|
verbose=False,
|
|
log_rotate_days=10,
|
|
log_file="",
|
|
log_no_color=False,
|
|
skip_pip=True,
|
|
recovery_mode=False,
|
|
),
|
|
)
|
|
assert len(mock_notify.mock_calls) == 1
|
|
|
|
assert "recovery_mode" in hass.config.components
|
|
|
|
|
|
@pytest.mark.parametrize(
|
|
"hass_config",
|
|
[
|
|
{
|
|
"homeassistant": {
|
|
"internal_url": "http://192.168.1.100:8123",
|
|
"external_url": "https://abcdef.ui.nabu.casa",
|
|
},
|
|
"map": {},
|
|
"frontend": {"invalid": True},
|
|
}
|
|
],
|
|
)
|
|
@pytest.mark.usefixtures("mock_hass_config")
|
|
async def test_setup_recovery_mode_if_no_frontend(
|
|
mock_enable_logging: AsyncMock,
|
|
mock_ensure_config_exists: AsyncMock,
|
|
mock_process_ha_config_upgrade: Mock,
|
|
) -> None:
|
|
"""Test we setup recovery mode if frontend didn't load."""
|
|
verbose = Mock()
|
|
log_rotate_days = Mock()
|
|
log_file = Mock()
|
|
log_no_color = Mock()
|
|
|
|
hass = await bootstrap.async_setup_hass(
|
|
runner.RuntimeConfig(
|
|
config_dir=get_test_config_dir(),
|
|
verbose=verbose,
|
|
log_rotate_days=log_rotate_days,
|
|
log_file=log_file,
|
|
log_no_color=log_no_color,
|
|
skip_pip=True,
|
|
recovery_mode=False,
|
|
),
|
|
)
|
|
|
|
assert "recovery_mode" in hass.config.components
|
|
assert hass.config.config_dir == get_test_config_dir()
|
|
assert hass.config.skip_pip
|
|
assert hass.config.internal_url == "http://192.168.1.100:8123"
|
|
assert hass.config.external_url == "https://abcdef.ui.nabu.casa"
|
|
|
|
|
|
@pytest.mark.parametrize("load_registries", [False])
|
|
@patch("homeassistant.bootstrap.DEFAULT_INTEGRATIONS", set())
|
|
async def test_empty_integrations_list_is_only_sent_at_the_end_of_bootstrap(
|
|
hass: HomeAssistant,
|
|
) -> None:
|
|
"""Test empty integrations list is only sent at the end of bootstrap."""
|
|
# setup times only tracked when not running
|
|
hass.set_state(CoreState.not_running)
|
|
|
|
order = []
|
|
|
|
def gen_domain_setup(domain):
|
|
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
|
order.append(domain)
|
|
await asyncio.sleep(0.05)
|
|
|
|
async def _background_task():
|
|
await asyncio.sleep(0.1)
|
|
|
|
await hass.async_create_task(_background_task())
|
|
return True
|
|
|
|
return async_setup
|
|
|
|
mock_integration(
|
|
hass,
|
|
MockModule(
|
|
domain="normal_integration",
|
|
async_setup=gen_domain_setup("normal_integration"),
|
|
partial_manifest={"after_dependencies": ["an_after_dep"]},
|
|
),
|
|
)
|
|
mock_integration(
|
|
hass,
|
|
MockModule(
|
|
domain="an_after_dep",
|
|
async_setup=gen_domain_setup("an_after_dep"),
|
|
),
|
|
)
|
|
|
|
integrations = []
|
|
|
|
@callback
|
|
def _bootstrap_integrations(data):
|
|
integrations.append(data)
|
|
|
|
async_dispatcher_connect(
|
|
hass, SIGNAL_BOOTSTRAP_INTEGRATIONS, _bootstrap_integrations
|
|
)
|
|
with patch.object(bootstrap, "SLOW_STARTUP_CHECK_INTERVAL", 0.025):
|
|
await bootstrap._async_set_up_integrations(
|
|
hass, {"normal_integration": {}, "an_after_dep": {}}, monotonic()
|
|
)
|
|
await hass.async_block_till_done()
|
|
|
|
assert integrations[0] != {}
|
|
assert "an_after_dep" in integrations[0]
|
|
assert integrations[-2] != {}
|
|
assert integrations[-1] == {}
|
|
|
|
assert "normal_integration" in hass.config.components
|
|
assert order == ["an_after_dep", "normal_integration"]
|
|
|
|
|
|
@pytest.mark.parametrize("load_registries", [False])
|
|
async def test_warning_logged_on_wrap_up_timeout(
|
|
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
|
|
) -> None:
|
|
"""Test we log a warning on bootstrap timeout."""
|
|
task: asyncio.Task | None = None
|
|
|
|
def gen_domain_setup(domain):
|
|
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
|
nonlocal task
|
|
|
|
async def _not_marked_background_task():
|
|
await asyncio.sleep(2)
|
|
|
|
task = hass.async_create_task(_not_marked_background_task())
|
|
return True
|
|
|
|
return async_setup
|
|
|
|
mock_integration(
|
|
hass,
|
|
MockModule(
|
|
domain="normal_integration",
|
|
async_setup=gen_domain_setup("normal_integration"),
|
|
partial_manifest={},
|
|
),
|
|
)
|
|
|
|
with patch.object(bootstrap, "WRAP_UP_TIMEOUT", 0):
|
|
await bootstrap._async_set_up_integrations(
|
|
hass, {"normal_integration": {}}, monotonic()
|
|
)
|
|
|
|
task.cancel()
|
|
with contextlib.suppress(asyncio.CancelledError):
|
|
await task
|
|
assert "Setup timed out for bootstrap" in caplog.text
|
|
assert "waiting on" in caplog.text
|
|
assert "_not_marked_background_task" in caplog.text
|
|
|
|
|
|
@pytest.mark.parametrize("load_registries", [False])
|
|
async def test_tasks_logged_that_block_stage_1(
|
|
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
|
|
) -> None:
|
|
"""Test we log tasks that delay stage 1 startup."""
|
|
task: asyncio.Task | None = None
|
|
|
|
def gen_domain_setup(domain):
|
|
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
|
nonlocal task
|
|
|
|
async def _not_marked_background_task():
|
|
await hass.loop.create_future()
|
|
|
|
task = hass.async_create_task(_not_marked_background_task())
|
|
await asyncio.sleep(0.1)
|
|
return True
|
|
|
|
return async_setup
|
|
|
|
mock_integration(
|
|
hass,
|
|
MockModule(
|
|
domain="normal_integration",
|
|
async_setup=gen_domain_setup("normal_integration"),
|
|
partial_manifest={},
|
|
),
|
|
)
|
|
|
|
original_stage_1 = bootstrap.STAGE_1_INTEGRATIONS
|
|
with (
|
|
patch.object(bootstrap, "STAGE_1_TIMEOUT", 0),
|
|
patch.object(bootstrap, "COOLDOWN_TIME", 0),
|
|
patch.object(bootstrap, "WRAP_UP_TIMEOUT", 0),
|
|
patch.object(
|
|
bootstrap, "STAGE_1_INTEGRATIONS", {*original_stage_1, "normal_integration"}
|
|
),
|
|
):
|
|
await bootstrap._async_set_up_integrations(
|
|
hass, {"normal_integration": {}}, monotonic()
|
|
)
|
|
|
|
task.cancel()
|
|
with contextlib.suppress(asyncio.CancelledError):
|
|
await task
|
|
|
|
assert "Setup timed out for stage 1 waiting on" in caplog.text
|
|
assert "waiting on" in caplog.text
|
|
assert "_not_marked_background_task" in caplog.text
|
|
|
|
|
|
@pytest.mark.parametrize("load_registries", [False])
|
|
async def test_tasks_logged_that_block_stage_2(
|
|
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
|
|
) -> None:
|
|
"""Test we log tasks that delay stage 2 startup."""
|
|
task: asyncio.Task | None = None
|
|
|
|
def gen_domain_setup(domain):
|
|
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
|
nonlocal task
|
|
|
|
async def _not_marked_background_task():
|
|
await hass.loop.create_future()
|
|
|
|
task = hass.async_create_task(_not_marked_background_task())
|
|
await asyncio.sleep(0.1)
|
|
return True
|
|
|
|
return async_setup
|
|
|
|
mock_integration(
|
|
hass,
|
|
MockModule(
|
|
domain="normal_integration",
|
|
async_setup=gen_domain_setup("normal_integration"),
|
|
partial_manifest={},
|
|
),
|
|
)
|
|
|
|
with (
|
|
patch.object(bootstrap, "STAGE_2_TIMEOUT", 0),
|
|
patch.object(bootstrap, "COOLDOWN_TIME", 0),
|
|
patch.object(bootstrap, "WRAP_UP_TIMEOUT", 0),
|
|
):
|
|
await bootstrap._async_set_up_integrations(
|
|
hass, {"normal_integration": {}}, monotonic()
|
|
)
|
|
|
|
task.cancel()
|
|
with contextlib.suppress(asyncio.CancelledError):
|
|
await task
|
|
|
|
assert "Setup timed out for stage 2 waiting on" in caplog.text
|
|
assert "waiting on" in caplog.text
|
|
assert "_not_marked_background_task" in caplog.text
|
|
|
|
|
|
@pytest.mark.parametrize("load_registries", [False])
|
|
async def test_bootstrap_is_cancellation_safe(
|
|
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
|
|
) -> None:
|
|
"""Test cancellation during async_setup_component does not cancel bootstrap."""
|
|
mock_integration(hass, MockModule(domain="cancel_integration"))
|
|
with patch.object(
|
|
bootstrap, "async_setup_component", side_effect=asyncio.CancelledError
|
|
):
|
|
await bootstrap._async_set_up_integrations(
|
|
hass, {"cancel_integration": {}}, monotonic()
|
|
)
|
|
await hass.async_block_till_done()
|
|
|
|
assert "Error setting up integration cancel_integration" in caplog.text
|
|
|
|
|
|
@pytest.mark.parametrize("load_registries", [False])
|
|
async def test_bootstrap_empty_integrations(hass: HomeAssistant) -> None:
|
|
"""Test setting up an empty integrations does not raise."""
|
|
await bootstrap._async_setup_multi_components(hass, set(), {})
|
|
await hass.async_block_till_done()
|
|
|
|
|
|
@pytest.mark.parametrize("load_registries", [False])
|
|
async def test_bootstrap_log_already_setup_stage(
|
|
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
|
|
) -> None:
|
|
"""Test logging when all integrations in a stage were already setup."""
|
|
with patch.object(bootstrap, "STAGE_1_INTEGRATIONS", {"frontend"}):
|
|
await bootstrap._async_set_up_integrations(hass, {}, monotonic())
|
|
await hass.async_block_till_done()
|
|
|
|
assert "Already set up stage 1: {'frontend'}" in caplog.text
|
|
|
|
|
|
@pytest.fixture(name="mock_mqtt_config_flow")
|
|
def mock_mqtt_config_flow_fixture() -> Generator[None]:
|
|
"""Mock MQTT config flow."""
|
|
|
|
class MockConfigFlow:
|
|
"""Mock the MQTT config flow."""
|
|
|
|
VERSION = 1
|
|
MINOR_VERSION = 1
|
|
|
|
with mock_config_flow("mqtt", MockConfigFlow):
|
|
yield
|
|
|
|
|
|
@pytest.mark.parametrize("integration", ["mqtt_eventstream", "mqtt_statestream"])
|
|
@pytest.mark.parametrize("load_registries", [False])
|
|
async def test_bootstrap_dependencies(
|
|
hass: HomeAssistant,
|
|
caplog: pytest.LogCaptureFixture,
|
|
integration: str,
|
|
mock_mqtt_config_flow: None,
|
|
) -> None:
|
|
"""Test dependencies are set up correctly,."""
|
|
entry = MockConfigEntry(domain="mqtt", data={"broker": "test-broker"})
|
|
entry.add_to_hass(hass)
|
|
|
|
calls: list[str] = []
|
|
assertions: list[bool] = []
|
|
|
|
async def async_mqtt_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
|
|
"""Assert the mqtt config entry was set up."""
|
|
calls.append("mqtt")
|
|
# assert the integration is not yet set up
|
|
assertions.append(hass.data["setup_done"][integration].done() is False)
|
|
assertions.append(
|
|
all(
|
|
dependency in hass.config.components
|
|
for dependency in integrations[integration]["dependencies"]
|
|
)
|
|
)
|
|
assertions.append(integration not in hass.config.components)
|
|
|
|
async def async_integration_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
|
"""Assert the mqtt config entry was set up."""
|
|
calls.append(integration)
|
|
# assert mqtt was already set up
|
|
assertions.append(
|
|
"mqtt" not in hass.data["setup_done"]
|
|
or hass.data["setup_done"]["mqtt"].done()
|
|
)
|
|
assertions.append("mqtt" in hass.config.components)
|
|
return True
|
|
|
|
mqtt_integration = mock_integration(
|
|
hass,
|
|
MockModule(
|
|
"mqtt",
|
|
async_setup_entry=async_mqtt_setup_entry,
|
|
dependencies=["file_upload", "http"],
|
|
),
|
|
)
|
|
|
|
# We patch the _import platform method to avoid loading the platform module
|
|
# to avoid depending on non core components in the tests.
|
|
mqtt_integration._import_platform = Mock()
|
|
mqtt_integration.platforms_exists = Mock(return_value=True)
|
|
|
|
integrations = {
|
|
"mqtt": {
|
|
"dependencies": {"file_upload", "http"},
|
|
"integration": mqtt_integration,
|
|
},
|
|
"mqtt_eventstream": {
|
|
"dependencies": {"mqtt"},
|
|
"integration": mock_integration(
|
|
hass,
|
|
MockModule(
|
|
"mqtt_eventstream",
|
|
async_setup=async_integration_setup,
|
|
dependencies=["mqtt"],
|
|
),
|
|
),
|
|
},
|
|
"mqtt_statestream": {
|
|
"dependencies": {"mqtt"},
|
|
"integration": mock_integration(
|
|
hass,
|
|
MockModule(
|
|
"mqtt_statestream",
|
|
async_setup=async_integration_setup,
|
|
dependencies=["mqtt"],
|
|
),
|
|
),
|
|
},
|
|
"file_upload": {
|
|
"dependencies": {"http"},
|
|
"integration": mock_integration(
|
|
hass,
|
|
MockModule(
|
|
"file_upload",
|
|
dependencies=["http"],
|
|
),
|
|
),
|
|
},
|
|
"http": {
|
|
"dependencies": set(),
|
|
"integration": mock_integration(
|
|
hass,
|
|
MockModule("http", dependencies=[]),
|
|
),
|
|
},
|
|
}
|
|
|
|
async def mock_async_get_integrations(
|
|
hass: HomeAssistant, domains: Iterable[str]
|
|
) -> dict[str, Integration | Exception]:
|
|
"""Mock integrations."""
|
|
return {domain: integrations[domain]["integration"] for domain in domains}
|
|
|
|
with (
|
|
patch(
|
|
"homeassistant.setup.loader.async_get_integrations",
|
|
side_effect=mock_async_get_integrations,
|
|
),
|
|
patch(
|
|
"homeassistant.config.async_process_component_config",
|
|
return_value=config_util.IntegrationConfigInfo({}, []),
|
|
),
|
|
):
|
|
bootstrap.async_set_domains_to_be_loaded(hass, {integration})
|
|
await bootstrap._async_setup_multi_components(hass, {integration}, {})
|
|
await hass.async_block_till_done()
|
|
|
|
for assertion in assertions:
|
|
assert assertion
|
|
|
|
assert calls == ["mqtt", integration]
|
|
|
|
assert (
|
|
f"Dependency {integration} will wait for dependencies dict_keys(['mqtt'])"
|
|
in caplog.text
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize("load_registries", [False])
|
|
async def test_bootstrap_dependency_not_found(
|
|
hass: HomeAssistant,
|
|
caplog: pytest.LogCaptureFixture,
|
|
) -> None:
|
|
"""Test setup when an integration has missing dependencies."""
|
|
mock_integration(
|
|
hass,
|
|
MockModule("good_integration", dependencies=[]),
|
|
)
|
|
# Simulate an integration with missing dependencies. While a core integration
|
|
# can't have missing dependencies thanks to checks by hassfest, there's no such
|
|
# guarantee for custom integrations.
|
|
mock_integration(
|
|
hass,
|
|
MockModule("bad_integration", dependencies=["hahaha_crash_and_burn"]),
|
|
)
|
|
|
|
assert await bootstrap.async_from_config_dict(
|
|
{"good_integration": {}, "bad_integration": {}}, hass
|
|
)
|
|
|
|
assert "good_integration" in hass.config.components
|
|
assert "bad_integration" not in hass.config.components
|
|
|
|
assert "Unable to resolve dependencies for bad_integration" in caplog.text
|
|
|
|
|
|
async def test_pre_import_no_requirements(hass: HomeAssistant) -> None:
|
|
"""Test pre-imported and do not have any requirements."""
|
|
pre_imports = [
|
|
name.removesuffix("_pre_import")
|
|
for name in dir(bootstrap)
|
|
if name.endswith("_pre_import")
|
|
]
|
|
|
|
# Make sure future refactoring does not
|
|
# accidentally remove the pre-imports
|
|
# or change the naming convention without
|
|
# updating this test.
|
|
assert len(pre_imports) > 3
|
|
|
|
for pre_import in pre_imports:
|
|
integration = await loader.async_get_integration(hass, pre_import)
|
|
assert not integration.requirements
|
|
|
|
|
|
@pytest.mark.timeout(20)
|
|
async def test_bootstrap_does_not_preimport_stage_1_integrations() -> None:
|
|
"""Test that the bootstrap does not preimport stage 1 integrations.
|
|
|
|
If this test fails it means that stage1 integrations are being
|
|
imported too soon and will not get their requirements updated
|
|
before they are loaded at runtime.
|
|
"""
|
|
|
|
process = await asyncio.create_subprocess_exec(
|
|
sys.executable,
|
|
"-c",
|
|
"import homeassistant.bootstrap; import sys; print(sys.modules)",
|
|
stdout=asyncio.subprocess.PIPE,
|
|
)
|
|
stdout, _ = await process.communicate()
|
|
assert process.returncode == 0
|
|
decoded_stdout = stdout.decode()
|
|
|
|
# Ensure no stage1 integrations have been imported
|
|
# as a side effect of importing the pre-imports
|
|
for integration in bootstrap.STAGE_1_INTEGRATIONS:
|
|
assert f"homeassistant.components.{integration}" not in decoded_stdout
|
|
|
|
|
|
@pytest.mark.parametrize("load_registries", [False])
|
|
@pytest.mark.usefixtures("enable_custom_integrations")
|
|
async def test_cancellation_does_not_leak_upward_from_async_setup(
|
|
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
|
|
) -> None:
|
|
"""Test setting up an integration that raises asyncio.CancelledError."""
|
|
await bootstrap._async_setup_multi_components(
|
|
hass, {"test_package_raises_cancelled_error"}, {}
|
|
)
|
|
await hass.async_block_till_done()
|
|
|
|
assert (
|
|
"Error during setup of component test_package_raises_cancelled_error"
|
|
in caplog.text
|
|
)
|
|
|
|
|
|
@pytest.mark.parametrize("load_registries", [False])
|
|
@pytest.mark.usefixtures("enable_custom_integrations")
|
|
async def test_cancellation_does_not_leak_upward_from_async_setup_entry(
|
|
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
|
|
) -> None:
|
|
"""Test setting up an integration that raises asyncio.CancelledError."""
|
|
entry = MockConfigEntry(
|
|
domain="test_package_raises_cancelled_error_config_entry", data={}
|
|
)
|
|
entry.add_to_hass(hass)
|
|
await bootstrap._async_setup_multi_components(
|
|
hass, {"test_package_raises_cancelled_error_config_entry"}, {}
|
|
)
|
|
await hass.async_block_till_done()
|
|
|
|
await bootstrap._async_setup_multi_components(hass, {"test_package"}, {})
|
|
await hass.async_block_till_done()
|
|
assert (
|
|
"Error setting up entry Mock Title"
|
|
" for test_package_raises_cancelled_error_config_entry" in caplog.text
|
|
)
|
|
|
|
assert "test_package" in hass.config.components
|
|
assert "test_package_raises_cancelled_error_config_entry" in hass.config.components
|
|
|
|
|
|
@pytest.mark.parametrize("load_registries", [False])
|
|
async def test_setup_does_base_platforms_first(hass: HomeAssistant) -> None:
|
|
"""Test setup does base platforms first.
|
|
|
|
Its important that base platforms are setup before other integrations
|
|
in stage1/2 since they are the foundation for other integrations and
|
|
almost every integration has to wait for them to be setup.
|
|
"""
|
|
order = []
|
|
|
|
def gen_domain_setup(domain):
|
|
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
|
order.append(domain)
|
|
return True
|
|
|
|
return async_setup
|
|
|
|
mock_integration(
|
|
hass, MockModule(domain="sensor", async_setup=gen_domain_setup("sensor"))
|
|
)
|
|
mock_integration(
|
|
hass,
|
|
MockModule(
|
|
domain="binary_sensor", async_setup=gen_domain_setup("binary_sensor")
|
|
),
|
|
)
|
|
mock_integration(
|
|
hass, MockModule(domain="root", async_setup=gen_domain_setup("root"))
|
|
)
|
|
mock_integration(
|
|
hass,
|
|
MockModule(
|
|
domain="first_dep",
|
|
async_setup=gen_domain_setup("first_dep"),
|
|
partial_manifest={"after_dependencies": ["root"]},
|
|
),
|
|
)
|
|
mock_integration(
|
|
hass,
|
|
MockModule(
|
|
domain="second_dep",
|
|
async_setup=gen_domain_setup("second_dep"),
|
|
partial_manifest={"after_dependencies": ["first_dep"]},
|
|
),
|
|
)
|
|
|
|
with patch(
|
|
"homeassistant.components.logger.async_setup", gen_domain_setup("logger")
|
|
):
|
|
await bootstrap._async_set_up_integrations(
|
|
hass,
|
|
{
|
|
"root": {},
|
|
"first_dep": {},
|
|
"second_dep": {},
|
|
"sensor": {},
|
|
"logger": {},
|
|
"binary_sensor": {},
|
|
},
|
|
monotonic(),
|
|
)
|
|
|
|
assert "binary_sensor" in hass.config.components
|
|
assert "sensor" in hass.config.components
|
|
assert "root" in hass.config.components
|
|
assert "first_dep" in hass.config.components
|
|
assert "second_dep" in hass.config.components
|
|
|
|
assert order[0] == "logger"
|
|
# base platforms (sensor/binary_sensor) should be setup before other integrations
|
|
# but after logger integrations. The order of base platforms is not guaranteed,
|
|
# only that they are setup before other integrations.
|
|
assert set(order[1:3]) == {"sensor", "binary_sensor"}
|
|
assert order[3:] == ["root", "first_dep", "second_dep"]
|
|
|
|
|
|
def test_should_rollover_is_always_false() -> None:
|
|
"""Test that shouldRollover always returns False."""
|
|
assert (
|
|
bootstrap._RotatingFileHandlerWithoutShouldRollOver(
|
|
"any.log", delay=True
|
|
).shouldRollover(Mock())
|
|
is False
|
|
)
|
|
|
|
|
|
async def test_no_base_platforms_loaded_before_recorder(hass: HomeAssistant) -> None:
|
|
"""Verify stage 0 not load base platforms before recorder.
|
|
|
|
If a stage 0 integration implements base platforms or has a base
|
|
platform in its dependencies and it loads before the recorder,
|
|
because of platform-based YAML schema, it may inadvertently
|
|
load integrations that expect the recorder to already be loaded.
|
|
We need to ensure that doesn't happen.
|
|
"""
|
|
IGNORE_BASE_PLATFORM_FILES = {
|
|
# config/scene.py is not a platform
|
|
"config": {"scene.py"},
|
|
# websocket_api/sensor.py is using the platform YAML schema
|
|
# we must not migrate it to an integration key until
|
|
# we remove the platform YAML schema support for sensors
|
|
"websocket_api": {"sensor.py"},
|
|
}
|
|
# person is a special case because it is a base platform
|
|
# in the sense that it creates entities in its namespace
|
|
# but its not used by other integrations to create entities
|
|
# so we want to make sure it is not loaded before the recorder
|
|
base_platforms = BASE_PLATFORMS | {"person"}
|
|
|
|
integrations_before_recorder: set[str] = set()
|
|
for _, integrations, _ in bootstrap.STAGE_0_INTEGRATIONS:
|
|
integrations_before_recorder |= integrations
|
|
if "recorder" in integrations:
|
|
break
|
|
else:
|
|
pytest.fail("recorder not in stage 0")
|
|
|
|
integrations_or_excs = await loader.async_get_integrations(
|
|
hass, integrations_before_recorder
|
|
)
|
|
integrations: dict[str, Integration] = {}
|
|
for domain, integration in integrations_or_excs.items():
|
|
assert not isinstance(integrations_or_excs, Exception)
|
|
integrations[domain] = integration
|
|
|
|
integrations_all_dependencies = (
|
|
await loader.resolve_integrations_after_dependencies(
|
|
hass, integrations.values(), ignore_exceptions=True
|
|
)
|
|
)
|
|
all_integrations = integrations.copy()
|
|
all_integrations.update(
|
|
(domain, loader.async_get_loaded_integration(hass, domain))
|
|
for domains in integrations_all_dependencies.values()
|
|
for domain in domains
|
|
)
|
|
|
|
problems: dict[str, set[str]] = {}
|
|
for domain in integrations:
|
|
domain_with_base_platforms_deps = (
|
|
integrations_all_dependencies[domain] & base_platforms
|
|
)
|
|
if domain_with_base_platforms_deps:
|
|
problems[domain] = domain_with_base_platforms_deps
|
|
assert not problems, (
|
|
"Integrations that are setup before recorder have"
|
|
f" base platforms in their dependencies: {problems}"
|
|
)
|
|
|
|
base_platform_py_files = {f"{base_platform}.py" for base_platform in base_platforms}
|
|
|
|
for domain, integration in all_integrations.items():
|
|
integration_base_platforms_files = (
|
|
integration._top_level_files & base_platform_py_files
|
|
)
|
|
if ignore := IGNORE_BASE_PLATFORM_FILES.get(domain):
|
|
integration_base_platforms_files -= ignore
|
|
if integration_base_platforms_files:
|
|
problems[domain] = integration_base_platforms_files
|
|
assert not problems, (
|
|
"Integrations that are setup before recorder"
|
|
f" implement base platforms: {problems}"
|
|
)
|
|
|
|
|
|
async def test_recorder_not_promoted(hass: HomeAssistant) -> None:
|
|
"""Verify that recorder is not promoted to earlier than its own stage."""
|
|
integrations_before_recorder: set[str] = set()
|
|
for _, integrations, _ in bootstrap.STAGE_0_INTEGRATIONS:
|
|
if "recorder" in integrations:
|
|
break
|
|
integrations_before_recorder |= integrations
|
|
else:
|
|
pytest.fail("recorder not in stage 0")
|
|
|
|
integrations_or_excs = await loader.async_get_integrations(
|
|
hass, integrations_before_recorder
|
|
)
|
|
integrations: dict[str, Integration] = {}
|
|
for domain, integration in integrations_or_excs.items():
|
|
assert not isinstance(integrations_or_excs, Exception)
|
|
integrations[domain] = integration
|
|
|
|
integrations_all_dependencies = (
|
|
await loader.resolve_integrations_after_dependencies(
|
|
hass, integrations.values(), ignore_exceptions=True
|
|
)
|
|
)
|
|
all_integrations = integrations.copy()
|
|
all_integrations.update(
|
|
(domain, loader.async_get_loaded_integration(hass, domain))
|
|
for domains in integrations_all_dependencies.values()
|
|
for domain in domains
|
|
)
|
|
|
|
assert "recorder" not in all_integrations
|
|
|
|
|
|
def _track_bootstrap_progress(
|
|
hass: HomeAssistant,
|
|
) -> list[tuple[CoreState, BootstrapProgress]]:
|
|
"""Record each bootstrap progress message with the core state it was sent in."""
|
|
progress: list[tuple[CoreState, BootstrapProgress]] = []
|
|
|
|
@callback
|
|
def _progress(data: BootstrapProgress) -> None:
|
|
progress.append((hass.state, data))
|
|
|
|
async_subscribe_bootstrap_progress(hass, _progress)
|
|
return progress
|
|
|
|
|
|
@pytest.mark.parametrize("load_registries", [False])
|
|
@patch("homeassistant.bootstrap.DEFAULT_INTEGRATIONS", set())
|
|
async def test_bootstrap_progress_concurrent_setup(
|
|
hass: HomeAssistant, freezer: FrozenDateTimeFactory
|
|
) -> None:
|
|
"""Test progress lists concurrent setups as active and counts finished ones."""
|
|
hass.set_state(CoreState.not_running)
|
|
release = asyncio.Event()
|
|
all_started = asyncio.Event()
|
|
started: set[str] = set()
|
|
|
|
def gen_domain_setup(domain: str):
|
|
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
|
started.add(domain)
|
|
if len(started) == 2:
|
|
all_started.set()
|
|
await release.wait()
|
|
return True
|
|
|
|
return async_setup
|
|
|
|
for domain in ("integration_a", "integration_b"):
|
|
mock_integration(
|
|
hass, MockModule(domain=domain, async_setup=gen_domain_setup(domain))
|
|
)
|
|
progress = _track_bootstrap_progress(hass)
|
|
|
|
setup_task = hass.async_create_task(
|
|
bootstrap._async_set_up_integrations(
|
|
hass, {"integration_a": {}, "integration_b": {}}, monotonic()
|
|
)
|
|
)
|
|
await all_started.wait()
|
|
freezer.tick(bootstrap.SLOW_STARTUP_CHECK_INTERVAL)
|
|
async_fire_time_changed(hass)
|
|
_, blocked = progress[-1]
|
|
release.set()
|
|
await setup_task
|
|
|
|
_, first = progress[0]
|
|
assert first["phase"] == bootstrap.BootstrapPhase.PREPARING
|
|
assert first["integrations"]["total"] is None
|
|
|
|
assert blocked["phase"] == bootstrap.BootstrapPhase.SETUP
|
|
assert set(blocked["active"]) == {"integration_a", "integration_b"}
|
|
assert blocked["integrations"]["done"] == blocked["integrations"]["total"] - 2
|
|
|
|
_, final = progress[-1]
|
|
assert final["phase"] == bootstrap.BootstrapPhase.WRAP_UP
|
|
assert final["active"] == {}
|
|
assert final["integrations"]["done"] == final["integrations"]["total"]
|
|
assert final["integrations"]["failed"] == []
|
|
|
|
|
|
@pytest.mark.parametrize("load_registries", [False])
|
|
@patch("homeassistant.bootstrap.DEFAULT_INTEGRATIONS", set())
|
|
async def test_bootstrap_progress_failures_and_running_summary(
|
|
hass: HomeAssistant,
|
|
) -> None:
|
|
"""Test failed integrations are reported and the running summary is final."""
|
|
hass.set_state(CoreState.not_running)
|
|
retry_attempt = asyncio.Event()
|
|
|
|
async def async_setup_entry_retry(hass: HomeAssistant, entry: ConfigEntry) -> None:
|
|
if not retry_attempt.is_set():
|
|
retry_attempt.set()
|
|
raise ConfigEntryNotReady
|
|
await asyncio.Event().wait()
|
|
|
|
async def async_setup_failed(hass: HomeAssistant, config: ConfigType) -> bool:
|
|
return False
|
|
|
|
mock_integration(
|
|
hass, MockModule(domain="integration_fail", async_setup=async_setup_failed)
|
|
)
|
|
mock_integration(
|
|
hass,
|
|
MockModule(
|
|
domain="integration_retry", async_setup_entry=async_setup_entry_retry
|
|
),
|
|
)
|
|
mock_platform(hass, "integration_retry.config_flow", None)
|
|
MockConfigEntry(domain="integration_retry").add_to_hass(hass)
|
|
progress = _track_bootstrap_progress(hass)
|
|
|
|
with mock_config_flow("integration_retry", config_entries.ConfigFlow):
|
|
await bootstrap._async_set_up_integrations(
|
|
hass, {"integration_fail": {}, "integration_retry": {}}, monotonic()
|
|
)
|
|
_, final = progress[-1]
|
|
# The entry sets up again once Home Assistant has started.
|
|
await hass.async_start()
|
|
|
|
assert final["phase"] == bootstrap.BootstrapPhase.WRAP_UP
|
|
assert final["integrations"]["done"] == final["integrations"]["total"]
|
|
assert final["integrations"]["failed"] == ["integration_fail"]
|
|
|
|
_, running = progress[-1]
|
|
assert running["phase"] == bootstrap.BootstrapPhase.RUNNING
|
|
assert running["integrations"] == final["integrations"]
|
|
# A late subscriber gets the summary from when Core started running.
|
|
assert _track_bootstrap_progress(hass) == [(CoreState.running, running)]
|
|
|
|
|
|
@pytest.mark.parametrize("load_registries", [False])
|
|
@patch("homeassistant.bootstrap.DEFAULT_INTEGRATIONS", set())
|
|
async def test_bootstrap_progress_cancelled_entry_setup(hass: HomeAssistant) -> None:
|
|
"""Test a setup cancelled during its config entry setup counts as failed."""
|
|
hass.set_state(CoreState.not_running)
|
|
|
|
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> bool:
|
|
# Cancel like a stage timeout, after the domain was added to components.
|
|
task = asyncio.current_task()
|
|
assert task is not None
|
|
task.cancel()
|
|
await asyncio.Event().wait()
|
|
return True
|
|
|
|
mock_integration(
|
|
hass,
|
|
MockModule(domain="integration_cancel", async_setup_entry=async_setup_entry),
|
|
)
|
|
mock_platform(hass, "integration_cancel.config_flow", None)
|
|
MockConfigEntry(domain="integration_cancel").add_to_hass(hass)
|
|
progress = _track_bootstrap_progress(hass)
|
|
|
|
with mock_config_flow("integration_cancel", config_entries.ConfigFlow):
|
|
await bootstrap._async_set_up_integrations(
|
|
hass, {"integration_cancel": {}}, monotonic()
|
|
)
|
|
|
|
_, final = progress[-1]
|
|
assert "integration_cancel" in hass.config.components
|
|
assert final["integrations"] == {
|
|
"total": 1,
|
|
"done": 1,
|
|
"failed": ["integration_cancel"],
|
|
}
|
|
|
|
|
|
@pytest.mark.parametrize("load_registries", [False])
|
|
@patch("homeassistant.bootstrap.DEFAULT_INTEGRATIONS", set())
|
|
async def test_bootstrap_progress_unscheduled_dependency(hass: HomeAssistant) -> None:
|
|
"""Test a dependency no stage sets up does not keep progress below the total."""
|
|
hass.set_state(CoreState.not_running)
|
|
mock_integration(hass, MockModule(domain="dependency_only"))
|
|
# The after dependency cycle drops both from the domains to set up.
|
|
mock_integration(
|
|
hass,
|
|
MockModule(
|
|
domain="cycle_a",
|
|
dependencies=["dependency_only"],
|
|
partial_manifest={"after_dependencies": ["cycle_b"]},
|
|
),
|
|
)
|
|
mock_integration(
|
|
hass,
|
|
MockModule(
|
|
domain="cycle_b", partial_manifest={"after_dependencies": ["cycle_a"]}
|
|
),
|
|
)
|
|
progress = _track_bootstrap_progress(hass)
|
|
|
|
await bootstrap._async_set_up_integrations(
|
|
hass, {"cycle_a": {}, "cycle_b": {}}, monotonic()
|
|
)
|
|
|
|
_, final = progress[-1]
|
|
assert "dependency_only" not in hass.config.components
|
|
assert final["integrations"] == {
|
|
"total": 2,
|
|
"done": 2,
|
|
"failed": ["cycle_a", "cycle_b"],
|
|
}
|
|
|
|
|
|
@pytest.mark.parametrize("load_registries", [False])
|
|
@patch("homeassistant.bootstrap.DEFAULT_INTEGRATIONS", set())
|
|
@pytest.mark.parametrize(
|
|
("modules", "total", "failed"),
|
|
[
|
|
pytest.param(
|
|
[
|
|
MockModule(domain="good_integration"),
|
|
MockModule(
|
|
domain="bad_integration", dependencies=["missing_integration"]
|
|
),
|
|
],
|
|
3,
|
|
["bad_integration", "not_found"],
|
|
id="missing_dependency",
|
|
),
|
|
pytest.param(
|
|
[
|
|
MockModule(domain="good_integration"),
|
|
MockModule(domain="bad_integration", dependencies=["bad_integration"]),
|
|
],
|
|
3,
|
|
["bad_integration", "not_found"],
|
|
id="circular_dependency",
|
|
),
|
|
pytest.param(
|
|
[
|
|
MockModule(domain="good_integration", dependencies=["intermediate"]),
|
|
MockModule(
|
|
domain="intermediate",
|
|
partial_manifest={"after_dependencies": ["bad_integration"]},
|
|
),
|
|
MockModule(
|
|
domain="bad_integration",
|
|
partial_manifest={"after_dependencies": ["intermediate"]},
|
|
),
|
|
],
|
|
4,
|
|
["bad_integration", "good_integration", "intermediate", "not_found"],
|
|
id="dependency_in_after_dependency_cycle",
|
|
),
|
|
],
|
|
)
|
|
async def test_bootstrap_progress_unresolved_dependencies(
|
|
hass: HomeAssistant, modules: list[MockModule], total: int, failed: list[str]
|
|
) -> None:
|
|
"""Test integrations dropped while resolving dependencies count as failed."""
|
|
hass.set_state(CoreState.not_running)
|
|
for module in modules:
|
|
mock_integration(hass, module)
|
|
progress = _track_bootstrap_progress(hass)
|
|
|
|
await bootstrap._async_set_up_integrations(
|
|
hass,
|
|
{"good_integration": {}, "bad_integration": {}, "not_found": {}},
|
|
monotonic(),
|
|
)
|
|
|
|
_, final = progress[-1]
|
|
assert final["integrations"] == {
|
|
"total": total,
|
|
"done": total,
|
|
"failed": failed,
|
|
}
|
|
|
|
|
|
@pytest.mark.parametrize("load_registries", [False])
|
|
@patch("homeassistant.bootstrap.DEFAULT_INTEGRATIONS", set())
|
|
async def test_bootstrap_progress_running_transition(hass: HomeAssistant) -> None:
|
|
"""Test progress reports starting and running only on the core state change."""
|
|
hass.set_state(CoreState.not_running)
|
|
mock_integration(hass, MockModule(domain="normal_integration"))
|
|
progress = _track_bootstrap_progress(hass)
|
|
|
|
await bootstrap._async_set_up_integrations(
|
|
hass, {"normal_integration": {}}, monotonic() - 100
|
|
)
|
|
# Elapsed counts from the given start of Home Assistant.
|
|
assert progress[0][1]["elapsed"] >= 100
|
|
state, data = progress[-1]
|
|
assert state is CoreState.not_running
|
|
assert data["phase"] == bootstrap.BootstrapPhase.WRAP_UP
|
|
|
|
await hass.async_start()
|
|
|
|
assert [(state, data["phase"]) for state, data in progress[-2:]] == [
|
|
(CoreState.starting, bootstrap.BootstrapPhase.STARTING),
|
|
(CoreState.running, bootstrap.BootstrapPhase.RUNNING),
|
|
]
|
|
assert _track_bootstrap_progress(hass) == [progress[-1]]
|
|
|
|
|
|
@pytest.mark.parametrize("load_registries", [False])
|
|
@patch("homeassistant.bootstrap.DEFAULT_INTEGRATIONS", set())
|
|
async def test_bootstrap_progress_while_starting(
|
|
hass: HomeAssistant, freezer: FrozenDateTimeFactory
|
|
) -> None:
|
|
"""Test progress keeps updating while starting."""
|
|
hass.set_state(CoreState.not_running)
|
|
entry_setup_started = asyncio.Event()
|
|
release_entry = asyncio.Event()
|
|
start_listener_running = asyncio.Event()
|
|
release_start = asyncio.Event()
|
|
|
|
async def async_setup_entry(hass: HomeAssistant, entry: ConfigEntry) -> None:
|
|
entry_setup_started.set()
|
|
await release_entry.wait()
|
|
|
|
async def slow_start_listener(event: Event) -> None:
|
|
start_listener_running.set()
|
|
await release_start.wait()
|
|
|
|
mock_integration(
|
|
hass, MockModule(domain="integration_new", async_setup_entry=async_setup_entry)
|
|
)
|
|
mock_platform(hass, "integration_new.config_flow", None)
|
|
progress = _track_bootstrap_progress(hass)
|
|
|
|
with mock_config_flow("integration_new", config_entries.ConfigFlow):
|
|
await bootstrap._async_set_up_integrations(
|
|
hass, {"integration_new": {}}, monotonic()
|
|
)
|
|
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, slow_start_listener)
|
|
start_task = hass.async_create_task(hass.async_start())
|
|
await start_listener_running.wait()
|
|
|
|
entry = MockConfigEntry(domain="integration_new")
|
|
entry.add_to_hass(hass)
|
|
add_task = hass.async_create_background_task(
|
|
hass.config_entries.async_setup(entry.entry_id), "set up new entry"
|
|
)
|
|
await entry_setup_started.wait()
|
|
|
|
message_count = len(progress)
|
|
freezer.tick(bootstrap.SLOW_STARTUP_CHECK_INTERVAL)
|
|
async_fire_time_changed(hass)
|
|
assert len(progress) == message_count + 1
|
|
state, data = progress[-1]
|
|
assert state is CoreState.starting
|
|
assert data["phase"] == bootstrap.BootstrapPhase.STARTING
|
|
assert "integration_new" in data["active"]
|
|
|
|
release_start.set()
|
|
await start_task
|
|
_, running = progress[-1]
|
|
assert running["phase"] == bootstrap.BootstrapPhase.RUNNING
|
|
# The kept running summary does not list the entry still setting up.
|
|
assert running["active"] == {}
|
|
|
|
message_count = len(progress)
|
|
freezer.tick(bootstrap.SLOW_STARTUP_CHECK_INTERVAL)
|
|
async_fire_time_changed(hass)
|
|
assert len(progress) == message_count
|
|
|
|
release_entry.set()
|
|
await add_task
|
|
|
|
|
|
@pytest.mark.parametrize("load_registries", [False])
|
|
@pytest.mark.usefixtures("enable_custom_integrations")
|
|
@patch("homeassistant.bootstrap.DEFAULT_INTEGRATIONS", set())
|
|
@pytest.mark.parametrize(
|
|
("safe_mode", "total"),
|
|
[
|
|
pytest.param(False, 2, id="normal_mode"),
|
|
pytest.param(True, 0, id="safe_mode"),
|
|
],
|
|
)
|
|
async def test_bootstrap_progress_custom_integrations(
|
|
hass: HomeAssistant, safe_mode: bool, total: int
|
|
) -> None:
|
|
"""Test custom integrations skipped in safe mode do not count as failed."""
|
|
hass.set_state(CoreState.not_running)
|
|
hass.config.safe_mode = safe_mode
|
|
MockConfigEntry(domain="test_package_loaded_executor").add_to_hass(hass)
|
|
progress = _track_bootstrap_progress(hass)
|
|
|
|
await bootstrap._async_set_up_integrations(hass, {"test_package": {}}, monotonic())
|
|
|
|
_, final = progress[-1]
|
|
assert final["integrations"] == {"total": total, "done": total, "failed": []}
|
|
|
|
|
|
@pytest.mark.parametrize("load_registries", [False])
|
|
@patch("homeassistant.bootstrap.DEFAULT_INTEGRATIONS", set())
|
|
async def test_bootstrap_progress_late_subscriber(
|
|
hass: HomeAssistant, freezer: FrozenDateTimeFactory
|
|
) -> None:
|
|
"""Test progress is only built for subscribers, a late one gets it right away."""
|
|
hass.set_state(CoreState.not_running)
|
|
setup_started = asyncio.Event()
|
|
release = asyncio.Event()
|
|
|
|
async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
|
|
setup_started.set()
|
|
await release.wait()
|
|
return True
|
|
|
|
mock_integration(
|
|
hass, MockModule(domain="slow_integration", async_setup=async_setup)
|
|
)
|
|
|
|
with patch.object(
|
|
bootstrap._WatchPendingSetups,
|
|
"_async_progress",
|
|
autospec=True,
|
|
side_effect=bootstrap._WatchPendingSetups._async_progress,
|
|
) as build_progress:
|
|
setup_task = hass.async_create_task(
|
|
bootstrap._async_set_up_integrations(
|
|
hass, {"slow_integration": {}}, monotonic()
|
|
)
|
|
)
|
|
await setup_started.wait()
|
|
freezer.tick(bootstrap.SLOW_STARTUP_CHECK_INTERVAL)
|
|
async_fire_time_changed(hass)
|
|
build_progress.assert_not_called()
|
|
|
|
progress = _track_bootstrap_progress(hass)
|
|
build_progress.assert_called_once()
|
|
freezer.tick(bootstrap.SLOW_STARTUP_CHECK_INTERVAL)
|
|
async_fire_time_changed(hass)
|
|
release.set()
|
|
await setup_task
|
|
|
|
(_, current), (_, tick), *_ = progress
|
|
assert current["phase"] == bootstrap.BootstrapPhase.SETUP
|
|
assert set(current["active"]) == {"slow_integration"}
|
|
assert current["integrations"] == {"total": 1, "done": 0, "failed": []}
|
|
assert tick["active"]["slow_integration"] > current["active"]["slow_integration"]
|
|
_, final = progress[-1]
|
|
assert final["integrations"] == {"total": 1, "done": 1, "failed": []}
|
|
|
|
|
|
@pytest.mark.parametrize("load_registries", [False])
|
|
@patch("homeassistant.bootstrap.DEFAULT_INTEGRATIONS", set())
|
|
async def test_bootstrap_progress_listener_raises(hass: HomeAssistant) -> None:
|
|
"""Test a progress listener that raises does not stop bootstrap."""
|
|
hass.set_state(CoreState.not_running)
|
|
mock_integration(hass, MockModule(domain="normal_integration"))
|
|
async_subscribe_bootstrap_progress(hass, Mock(side_effect=ValueError))
|
|
progress = _track_bootstrap_progress(hass)
|
|
|
|
await bootstrap._async_set_up_integrations(
|
|
hass, {"normal_integration": {}}, monotonic()
|
|
)
|
|
await hass.async_start()
|
|
|
|
assert "normal_integration" in hass.config.components
|
|
_, running = progress[-1]
|
|
assert running["phase"] == bootstrap.BootstrapPhase.RUNNING
|
|
|
|
|
|
@pytest.mark.parametrize("load_registries", [False])
|
|
@patch("homeassistant.bootstrap.DEFAULT_INTEGRATIONS", set())
|
|
async def test_bootstrap_progress_stopped_while_starting(
|
|
hass: HomeAssistant, freezer: FrozenDateTimeFactory
|
|
) -> None:
|
|
"""Test progress stops updating when Core stops while starting."""
|
|
hass.set_state(CoreState.not_running)
|
|
start_listener_running = asyncio.Event()
|
|
|
|
async def slow_start_listener(event: Event) -> None:
|
|
start_listener_running.set()
|
|
await asyncio.Event().wait()
|
|
|
|
mock_integration(hass, MockModule(domain="normal_integration"))
|
|
progress = _track_bootstrap_progress(hass)
|
|
|
|
await bootstrap._async_set_up_integrations(
|
|
hass, {"normal_integration": {}}, monotonic()
|
|
)
|
|
hass.bus.async_listen_once(EVENT_HOMEASSISTANT_START, slow_start_listener)
|
|
start_task = hass.async_create_task(hass.async_start())
|
|
await start_listener_running.wait()
|
|
|
|
await hass.async_stop()
|
|
assert start_task.cancelled()
|
|
assert hass.state is CoreState.stopped
|
|
|
|
message_count = len(progress)
|
|
freezer.tick(bootstrap.SLOW_STARTUP_CHECK_INTERVAL)
|
|
async_fire_time_changed(hass)
|
|
assert len(progress) == message_count
|