init home-assistant

This commit is contained in:
2026-11-19 15:15:32 -05:00
parent 2e81d9d300
commit feec6ef9fb
19230 changed files with 3335526 additions and 0 deletions

View File

@@ -0,0 +1,98 @@
"""Tests for the cloud component."""
from typing import Any
from unittest.mock import AsyncMock, patch
from homeassistant.components.cloud.const import (
DATA_CLOUD,
DOMAIN,
PREF_ALEXA_SETTINGS_VERSION,
PREF_ENABLE_ALEXA,
PREF_ENABLE_GOOGLE,
PREF_GOOGLE_SECURE_DEVICES_PIN,
PREF_GOOGLE_SETTINGS_VERSION,
)
from homeassistant.components.cloud.prefs import (
ALEXA_SETTINGS_VERSION,
GOOGLE_SETTINGS_VERSION,
CloudPreferences,
)
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
PIPELINE_DATA = {
"items": [
{
"conversation_engine": "conversation_engine_1",
"conversation_language": "language_1",
"id": "01GX8ZWBAQYWNB1XV3EXEZ75DY",
"language": "language_1",
"name": "Home Assistant Cloud",
"stt_engine": "cloud",
"stt_language": "language_1",
"tts_engine": "cloud",
"tts_language": "language_1",
"tts_voice": "Arnold Schwarzenegger",
"wake_word_entity": None,
"wake_word_id": None,
"prefer_local_intents": False,
},
{
"conversation_engine": "conversation_engine_2",
"conversation_language": "language_2",
"id": "01GX8ZWBAQTKFQNK4W7Q4CTRCX",
"language": "language_2",
"name": "name_2",
"stt_engine": "stt_engine_2",
"stt_language": "language_2",
"tts_engine": "tts_engine_2",
"tts_language": "language_2",
"tts_voice": "The Voice",
"wake_word_entity": None,
"wake_word_id": None,
"prefer_local_intents": False,
},
{
"conversation_engine": "conversation_engine_3",
"conversation_language": "language_3",
"id": "01GX8ZWBAQSV1HP3WGJPFWEJ8J",
"language": "language_3",
"name": "name_3",
"stt_engine": None,
"stt_language": None,
"tts_engine": None,
"tts_language": None,
"tts_voice": None,
"wake_word_entity": None,
"wake_word_id": None,
"prefer_local_intents": False,
},
],
"preferred_item": "01GX8ZWBAQYWNB1XV3EXEZ75DY",
}
async def mock_cloud(hass: HomeAssistant, config: dict[str, Any] | None = None) -> None:
"""Mock cloud."""
# The homeassistant integration is needed by cloud. It's not in it's requirements
# because it's always setup by bootstrap. Set it up manually in tests.
assert await async_setup_component(hass, "homeassistant", {})
assert await async_setup_component(hass, DOMAIN, {"cloud": config or {}})
cloud_inst = hass.data[DATA_CLOUD]
with patch("hass_nabucasa.Cloud.run_executor", AsyncMock(return_value=None)):
await cloud_inst.initialize()
def mock_cloud_prefs(hass: HomeAssistant, prefs: dict[str, Any]) -> CloudPreferences:
"""Fixture for cloud component."""
prefs_to_set = {
PREF_ALEXA_SETTINGS_VERSION: ALEXA_SETTINGS_VERSION,
PREF_ENABLE_ALEXA: True,
PREF_ENABLE_GOOGLE: True,
PREF_GOOGLE_SECURE_DEVICES_PIN: None,
PREF_GOOGLE_SETTINGS_VERSION: GOOGLE_SETTINGS_VERSION,
}
prefs_to_set.update(prefs)
hass.data[DATA_CLOUD].client._prefs._prefs = prefs_to_set
return hass.data[DATA_CLOUD].client._prefs

View File

@@ -0,0 +1,269 @@
"""Fixtures for cloud tests."""
from collections.abc import AsyncGenerator, Callable, Coroutine, Generator
from pathlib import Path
from typing import Any
from unittest.mock import DEFAULT, AsyncMock, MagicMock, PropertyMock, patch
from hass_nabucasa import Cloud
from hass_nabucasa.auth import CognitoAuth
from hass_nabucasa.cloudhooks import Cloudhooks
from hass_nabucasa.const import DEFAULT_SERVERS, DEFAULT_VALUES, STATE_CONNECTED
from hass_nabucasa.google_report_state import GoogleReportState
from hass_nabucasa.ice_servers import IceServers
from hass_nabucasa.iot import CloudIoT
from hass_nabucasa.remote import RemoteUI
from hass_nabucasa.voice import Voice
import jwt
import pytest
from homeassistant.components.cloud.client import CloudClient
from homeassistant.components.cloud.const import DATA_CLOUD
from homeassistant.components.cloud.prefs import (
PREF_ALEXA_DEFAULT_EXPOSE,
PREF_GOOGLE_DEFAULT_EXPOSE,
CloudPreferences,
)
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from homeassistant.util.dt import utcnow
from . import mock_cloud, mock_cloud_prefs
@pytest.fixture(autouse=True)
async def load_homeassistant(hass: HomeAssistant) -> None:
"""Load the homeassistant integration.
This is needed for the cloud integration to work.
"""
assert await async_setup_component(hass, "homeassistant", {})
@pytest.fixture(name="cloud")
async def cloud_fixture() -> AsyncGenerator[MagicMock]:
"""Mock the cloud object.
See the real hass_nabucasa.Cloud class for how to configure the mock.
"""
with patch(
"homeassistant.components.cloud.Cloud", autospec=True
) as mock_cloud_class:
mock_cloud = mock_cloud_class.return_value
# Attributes set in the constructor without parameters.
# We spec the mocks with the real classes
# and set constructor attributes or mock properties as needed.
mock_cloud.google_report_state = MagicMock(spec=GoogleReportState)
mock_cloud.cloudhooks = MagicMock(spec=Cloudhooks)
mock_cloud.remote = MagicMock(
spec=RemoteUI,
certificate=None,
certificate_status=None,
instance_domain=None,
is_connected=False,
)
mock_cloud.auth = MagicMock(spec=CognitoAuth)
mock_cloud.iot = MagicMock(
spec=CloudIoT, last_disconnect_reason=None, state=STATE_CONNECTED
)
mock_cloud.voice = MagicMock(spec=Voice)
mock_cloud.started = None
mock_cloud.ice_servers = MagicMock(
spec=IceServers,
async_register_ice_servers_listener=AsyncMock(
return_value=lambda: "mock-unregister"
),
)
def set_up_mock_cloud(
cloud_client: CloudClient, mode: str, **kwargs: Any
) -> DEFAULT:
"""Set up mock cloud with a mock constructor."""
# Attributes set in the constructor with parameters.
cloud_client.cloud = mock_cloud
mock_cloud.client = cloud_client
default_values = DEFAULT_VALUES[mode]
servers = {
f"{name}_server": server
for name, server in DEFAULT_SERVERS[mode].items()
}
mock_cloud.configure_mock(**default_values, **servers)
mock_cloud.configure_mock(**kwargs)
mock_cloud.mode = mode
# Properties that we mock as attributes from the constructor.
mock_cloud.websession = cloud_client.websession
return DEFAULT
mock_cloud_class.side_effect = set_up_mock_cloud
# Attributes that we mock with default values.
mock_cloud.id_token = None
mock_cloud.access_token = None
mock_cloud.refresh_token = None
# Properties that we keep as properties.
def mock_is_logged_in() -> bool:
"""Mock is logged in."""
return mock_cloud.id_token is not None
is_logged_in = PropertyMock(side_effect=mock_is_logged_in)
type(mock_cloud).is_logged_in = is_logged_in
def mock_claims() -> dict[str, Any]:
"""Mock claims."""
return Cloud._decode_claims(mock_cloud.id_token)
claims = PropertyMock(side_effect=mock_claims)
type(mock_cloud).claims = claims
def mock_is_connected() -> bool:
"""Return True if we are connected."""
return mock_cloud.iot.state == STATE_CONNECTED
is_connected = PropertyMock(side_effect=mock_is_connected)
type(mock_cloud).is_connected = is_connected
type(mock_cloud.iot).connected = is_connected
def mock_username() -> bool:
"""Return the subscription username."""
return "abcdefghjkl"
username = PropertyMock(side_effect=mock_username)
type(mock_cloud).username = username
# Properties that we mock as attributes.
mock_cloud.expiration_date = utcnow()
mock_cloud.subscription_expired = False
# Methods that we mock with a custom side effect.
async def mock_login(email: str, password: str) -> None:
"""Mock login.
When called, it should call the on_start callback.
"""
mock_cloud.id_token = jwt.encode(
{
"email": "hello@home-assistant.io",
"custom:sub-exp": "2018-01-03",
"cognito:username": "abcdefghjkl",
},
"test",
)
mock_cloud.access_token = "test_access_token"
mock_cloud.refresh_token = "test_refresh_token"
on_start_callback = mock_cloud.register_on_start.call_args[0][0]
await on_start_callback()
mock_cloud.login.side_effect = mock_login
async def mock_logout() -> None:
"""Mock logout."""
mock_cloud.id_token = None
mock_cloud.access_token = None
mock_cloud.refresh_token = None
await mock_cloud.stop()
await mock_cloud.client.logout_cleanups()
mock_cloud.logout.side_effect = mock_logout
yield mock_cloud
@pytest.fixture(name="set_cloud_prefs")
def set_cloud_prefs_fixture(
cloud: MagicMock,
) -> Callable[[dict[str, Any]], Coroutine[Any, Any, None]]:
"""Fixture for cloud component."""
async def set_cloud_prefs(prefs_settings: dict[str, Any]) -> None:
"""Set cloud prefs."""
prefs_to_set = cloud.client.prefs.as_dict()
prefs_to_set.pop(PREF_ALEXA_DEFAULT_EXPOSE)
prefs_to_set.pop(PREF_GOOGLE_DEFAULT_EXPOSE)
prefs_to_set.update(prefs_settings)
await cloud.client.prefs.async_update(**prefs_to_set)
return set_cloud_prefs
@pytest.fixture(autouse=True)
def mock_tts_cache_dir_autouse(mock_tts_cache_dir: Path) -> None:
"""Mock the TTS cache dir with empty dir."""
@pytest.fixture(autouse=True)
def tts_mutagen_mock_fixture_autouse(tts_mutagen_mock: MagicMock) -> None:
"""Mock writing tags."""
@pytest.fixture(autouse=True)
def mock_user_data() -> Generator[MagicMock]:
"""Mock os module."""
with patch("hass_nabucasa.Cloud._write_user_info") as writer:
yield writer
@pytest.fixture
def mock_cloud_fixture(hass: HomeAssistant) -> CloudPreferences:
"""Fixture for cloud component."""
hass.loop.run_until_complete(mock_cloud(hass))
return mock_cloud_prefs(hass, {})
@pytest.fixture
async def cloud_prefs(hass: HomeAssistant) -> CloudPreferences:
"""Fixture for cloud preferences."""
cloud_prefs = CloudPreferences(hass)
await cloud_prefs.async_initialize()
return cloud_prefs
@pytest.fixture
async def mock_cloud_setup(hass: HomeAssistant) -> None:
"""Set up the cloud."""
await mock_cloud(hass)
@pytest.fixture
def mock_cloud_login(hass: HomeAssistant, mock_cloud_setup: None) -> Generator[None]:
"""Mock cloud is logged in."""
hass.data[DATA_CLOUD].id_token = jwt.encode(
{
"email": "hello@home-assistant.io",
"custom:sub-exp": "2300-01-03",
"cognito:username": "abcdefghjkl",
},
"test",
)
with patch.object(hass.data[DATA_CLOUD].auth, "async_check_token"):
yield
@pytest.fixture(name="mock_auth")
def mock_auth_fixture() -> Generator[None]:
"""Mock check token."""
with (
patch("hass_nabucasa.auth.CognitoAuth.async_check_token"),
patch("hass_nabucasa.auth.CognitoAuth.async_renew_access_token"),
):
yield
@pytest.fixture
def mock_expired_cloud_login(hass: HomeAssistant, mock_cloud_setup: None) -> None:
"""Mock cloud is logged in."""
hass.data[DATA_CLOUD].id_token = jwt.encode(
{
"email": "hello@home-assistant.io",
"custom:sub-exp": "2018-01-01",
"cognito:username": "abcdefghjkl",
},
"test",
)

View File

@@ -0,0 +1,248 @@
"""Test account link services."""
import asyncio
from collections.abc import Generator
import logging
from time import time
from unittest.mock import AsyncMock, Mock, patch
import pytest
from homeassistant import config_entries
from homeassistant.components.cloud import account_link
from homeassistant.components.cloud.const import DATA_CLOUD
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.helpers import config_entry_oauth2_flow
from homeassistant.util.dt import utcnow
from tests.common import MockConfigEntry, async_fire_time_changed, mock_platform
TEST_DOMAIN = "oauth2_test"
@pytest.fixture
def flow_handler(
hass: HomeAssistant,
) -> Generator[type[config_entry_oauth2_flow.AbstractOAuth2FlowHandler]]:
"""Return a registered config flow."""
mock_platform(hass, f"{TEST_DOMAIN}.config_flow")
class TestFlowHandler(config_entry_oauth2_flow.AbstractOAuth2FlowHandler):
"""Test flow handler."""
DOMAIN = TEST_DOMAIN
@property
def logger(self) -> logging.Logger:
"""Return logger."""
return logging.getLogger(__name__)
with patch.dict(config_entries.HANDLERS, {TEST_DOMAIN: TestFlowHandler}):
yield TestFlowHandler
async def test_setup_provide_implementation(hass: HomeAssistant) -> None:
"""Test that we provide implementations."""
legacy_entry = MockConfigEntry(
domain="legacy",
version=1,
data={"auth_implementation": "cloud"},
)
none_cloud_entry = MockConfigEntry(
domain="no_cloud",
version=1,
data={"auth_implementation": "somethingelse"},
)
none_cloud_entry.add_to_hass(hass)
legacy_entry.add_to_hass(hass)
account_link.async_setup(hass)
with (
patch(
"homeassistant.components.cloud.account_link._get_services",
return_value=[
{"service": "test", "min_version": "0.1.0"},
{"service": "too_new", "min_version": "1000000.0.0"},
{"service": "dev", "min_version": "2022.9.0"},
{
"service": "deprecated",
"min_version": "0.1.0",
"accepts_new_authorizations": False,
},
{
"service": "legacy",
"min_version": "0.1.0",
"accepts_new_authorizations": False,
},
{
"service": "no_cloud",
"min_version": "0.1.0",
"accepts_new_authorizations": False,
},
],
),
patch(
"homeassistant.components.cloud.account_link.HA_VERSION",
"2022.9.0.dev20220817",
),
):
assert (
await config_entry_oauth2_flow.async_get_implementations(
hass, "non_existing"
)
== {}
)
assert (
await config_entry_oauth2_flow.async_get_implementations(hass, "too_new")
== {}
)
assert (
await config_entry_oauth2_flow.async_get_implementations(hass, "deprecated")
== {}
)
assert (
await config_entry_oauth2_flow.async_get_implementations(hass, "no_cloud")
== {}
)
implementations = await config_entry_oauth2_flow.async_get_implementations(
hass, "test"
)
legacy_implementations = (
await config_entry_oauth2_flow.async_get_implementations(hass, "legacy")
)
dev_implementations = await config_entry_oauth2_flow.async_get_implementations(
hass, "dev"
)
assert "cloud" in implementations
assert implementations["cloud"].domain == "cloud"
assert implementations["cloud"].service == "test"
assert implementations["cloud"].hass is hass
assert "cloud" in legacy_implementations
assert legacy_implementations["cloud"].domain == "cloud"
assert legacy_implementations["cloud"].service == "legacy"
assert legacy_implementations["cloud"].hass is hass
assert "cloud" in dev_implementations
assert dev_implementations["cloud"].domain == "cloud"
assert dev_implementations["cloud"].service == "dev"
assert dev_implementations["cloud"].hass is hass
async def test_get_services_cached(hass: HomeAssistant) -> None:
"""Test that we cache services."""
hass.data[DATA_CLOUD] = None
services = 1
with (
patch.object(account_link, "CACHE_TIMEOUT", 0),
patch(
"hass_nabucasa.account_link.async_fetch_available_services",
side_effect=lambda _: services,
) as mock_fetch,
):
assert await account_link._get_services(hass) == 1
services = 2
assert len(mock_fetch.mock_calls) == 1
assert await account_link._get_services(hass) == 1
services = 3
hass.data.pop(account_link.DATA_SERVICES)
assert await account_link._get_services(hass) == 3
services = 4
async_fire_time_changed(hass, utcnow())
await hass.async_block_till_done()
# Check cache purged
assert await account_link._get_services(hass) == 4
async def test_get_services_error(hass: HomeAssistant) -> None:
"""Test that we cache services."""
hass.data[DATA_CLOUD] = None
with (
patch.object(account_link, "CACHE_TIMEOUT", 0),
patch(
"hass_nabucasa.account_link.async_fetch_available_services",
side_effect=TimeoutError,
),
):
assert await account_link._get_services(hass) == []
assert account_link.DATA_SERVICES not in hass.data
@pytest.mark.usefixtures("current_request_with_host")
async def test_implementation(
hass: HomeAssistant,
flow_handler: type[config_entry_oauth2_flow.AbstractOAuth2FlowHandler],
) -> None:
"""Test Cloud OAuth2 implementation."""
hass.data[DATA_CLOUD] = None
impl = account_link.CloudOAuth2Implementation(hass, "test")
assert impl.name == "Home Assistant Cloud"
assert impl.domain == "cloud"
flow_handler.async_register_implementation(hass, impl)
flow_finished = asyncio.Future()
helper = Mock(
async_get_authorize_url=AsyncMock(return_value="http://example.com/auth"),
async_get_tokens=Mock(return_value=flow_finished),
)
with patch(
"hass_nabucasa.account_link.AuthorizeAccountHelper", return_value=helper
):
result = await hass.config_entries.flow.async_init(
TEST_DOMAIN, context={"source": config_entries.SOURCE_USER}
)
assert result["type"] is FlowResultType.EXTERNAL_STEP
assert result["url"] == "http://example.com/auth"
flow_finished.set_result(
{
"refresh_token": "mock-refresh",
"access_token": "mock-access",
"expires_in": 10,
"token_type": "bearer",
}
)
await hass.async_block_till_done()
# Flow finished!
result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["data"]["auth_implementation"] == "cloud"
expires_at = result["data"]["token"].pop("expires_at")
assert round(expires_at - time()) == 10
assert result["data"]["token"] == {
"refresh_token": "mock-refresh",
"access_token": "mock-access",
"token_type": "bearer",
"expires_in": 10,
}
entry = hass.config_entries.async_entries(TEST_DOMAIN)[0]
assert (
await config_entry_oauth2_flow.async_get_config_entry_implementation(
hass, entry
)
is impl
)

View File

@@ -0,0 +1,897 @@
"""Test Alexa config."""
import contextlib
from unittest.mock import AsyncMock, Mock, patch
import pytest
from homeassistant.components.alexa import errors
from homeassistant.components.cloud import ALEXA_SCHEMA, alexa_config
from homeassistant.components.cloud.const import (
DATA_CLOUD,
PREF_ALEXA_DEFAULT_EXPOSE,
PREF_ALEXA_ENTITY_CONFIGS,
PREF_SHOULD_EXPOSE,
)
from homeassistant.components.cloud.prefs import CloudPreferences
from homeassistant.components.homeassistant.exposed_entities import (
DATA_EXPOSED_ENTITIES,
async_expose_entity,
async_get_entity_settings,
)
from homeassistant.const import (
EVENT_HOMEASSISTANT_START,
EVENT_HOMEASSISTANT_STARTED,
EntityCategory,
)
from homeassistant.core import CoreState, HomeAssistant
from homeassistant.helpers import entity_registry as er
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from homeassistant.setup import async_setup_component
from tests.common import async_fire_time_changed
from tests.test_util.aiohttp import AiohttpClientMocker
@pytest.fixture
def cloud_stub() -> Mock:
"""Stub the cloud."""
return Mock(is_logged_in=True, subscription_expired=False)
def expose_new(hass: HomeAssistant, expose_new: bool) -> None:
"""Enable exposing new entities to Alexa."""
exposed_entities = hass.data[DATA_EXPOSED_ENTITIES]
exposed_entities.async_set_expose_new_entities("cloud.alexa", expose_new)
def expose_entity(hass: HomeAssistant, entity_id: str, should_expose: bool) -> None:
"""Expose an entity to Alexa."""
async_expose_entity(hass, "cloud.alexa", entity_id, should_expose)
async def test_alexa_config_expose_entity_prefs(
hass: HomeAssistant,
cloud_prefs: CloudPreferences,
cloud_stub: Mock,
entity_registry: er.EntityRegistry,
) -> None:
"""Test Alexa config should expose using prefs."""
assert await async_setup_component(hass, "homeassistant", {})
entity_entry1 = entity_registry.async_get_or_create(
"light",
"test",
"light_config_id",
suggested_object_id="config_light",
entity_category=EntityCategory.CONFIG,
)
entity_entry2 = entity_registry.async_get_or_create(
"light",
"test",
"light_diagnostic_id",
suggested_object_id="diagnostic_light",
entity_category=EntityCategory.DIAGNOSTIC,
)
entity_entry3 = entity_registry.async_get_or_create(
"light",
"test",
"light_hidden_integration_id",
suggested_object_id="hidden_integration_light",
hidden_by=er.RegistryEntryHider.INTEGRATION,
)
entity_entry4 = entity_registry.async_get_or_create(
"light",
"test",
"light_hidden_user_id",
suggested_object_id="hidden_user_light",
hidden_by=er.RegistryEntryHider.USER,
)
entity_entry5 = entity_registry.async_get_or_create(
"light",
"test",
"light_basement_id",
suggested_object_id="basement",
)
entity_entry6 = entity_registry.async_get_or_create(
"light",
"test",
"light_entrance_id",
suggested_object_id="entrance",
)
await cloud_prefs.async_update(
alexa_enabled=True,
alexa_report_state=False,
)
expose_new(hass, True)
expose_entity(hass, entity_entry5.entity_id, False)
conf = alexa_config.CloudAlexaConfig(
hass, ALEXA_SCHEMA({}), "mock-user-id", cloud_prefs, cloud_stub
)
await conf.async_initialize()
# an entity which is not in the entity registry can be exposed
expose_entity(hass, "light.kitchen", True)
assert conf.should_expose("light.kitchen")
# categorized and hidden entities should not be exposed
assert not conf.should_expose(entity_entry1.entity_id)
assert not conf.should_expose(entity_entry2.entity_id)
assert not conf.should_expose(entity_entry3.entity_id)
assert not conf.should_expose(entity_entry4.entity_id)
# this has been hidden
assert not conf.should_expose(entity_entry5.entity_id)
# exposed by default
assert conf.should_expose(entity_entry6.entity_id)
expose_entity(hass, entity_entry5.entity_id, True)
assert conf.should_expose(entity_entry5.entity_id)
expose_entity(hass, entity_entry5.entity_id, None)
assert not conf.should_expose(entity_entry5.entity_id)
assert "alexa" not in hass.config.components
await hass.async_block_till_done()
assert "alexa" in hass.config.components
assert not conf.should_expose(entity_entry5.entity_id)
async def test_alexa_config_report_state(
hass: HomeAssistant, cloud_prefs: CloudPreferences, cloud_stub: Mock
) -> None:
"""Test Alexa config should expose using prefs."""
assert await async_setup_component(hass, "homeassistant", {})
await cloud_prefs.async_update(
alexa_report_state=False,
)
conf = alexa_config.CloudAlexaConfig(
hass, ALEXA_SCHEMA({}), "mock-user-id", cloud_prefs, cloud_stub
)
await conf.async_initialize()
await conf.set_authorized(True)
assert cloud_prefs.alexa_report_state is False
assert conf.should_report_state is False
assert conf.is_reporting_states is False
with patch.object(conf, "async_get_access_token", AsyncMock(return_value="hello")):
await cloud_prefs.async_update(alexa_report_state=True)
await hass.async_block_till_done()
assert cloud_prefs.alexa_report_state is True
assert conf.should_report_state is True
assert conf.is_reporting_states is True
await cloud_prefs.async_update(alexa_report_state=False)
await hass.async_block_till_done()
assert cloud_prefs.alexa_report_state is False
assert conf.should_report_state is False
assert conf.is_reporting_states is False
async def test_alexa_config_invalidate_token(
hass: HomeAssistant,
cloud_prefs: CloudPreferences,
aioclient_mock: AiohttpClientMocker,
) -> None:
"""Test Alexa config should expose using prefs."""
assert await async_setup_component(hass, "homeassistant", {})
aioclient_mock.post(
"https://example/access_token",
json={
"access_token": "mock-token",
"event_endpoint": "http://example.com/alexa_endpoint",
"expires_in": 30,
},
)
conf = alexa_config.CloudAlexaConfig(
hass,
ALEXA_SCHEMA({}),
"mock-user-id",
cloud_prefs,
Mock(
alexa_server="example",
auth=Mock(async_check_token=AsyncMock()),
websession=async_get_clientsession(hass),
),
)
token = await conf.async_get_access_token()
assert token == "mock-token"
assert len(aioclient_mock.mock_calls) == 1
token = await conf.async_get_access_token()
assert token == "mock-token"
assert len(aioclient_mock.mock_calls) == 1
assert conf._token_valid is not None
conf.async_invalidate_access_token()
assert conf._token_valid is None
token = await conf.async_get_access_token()
assert token == "mock-token"
assert len(aioclient_mock.mock_calls) == 2
@pytest.mark.parametrize(
("reject_reason", "expected_exception"),
[
("RefreshTokenNotFound", errors.RequireRelink),
("UnknownRegion", errors.RequireRelink),
("OtherReason", errors.NoTokenAvailable),
],
)
async def test_alexa_config_fail_refresh_token(
hass: HomeAssistant,
cloud_prefs: CloudPreferences,
aioclient_mock: AiohttpClientMocker,
entity_registry: er.EntityRegistry,
reject_reason: str,
expected_exception: type[Exception],
) -> None:
"""Test Alexa config failing to refresh token."""
assert await async_setup_component(hass, "homeassistant", {})
# Enable exposing new entities to Alexa
expose_new(hass, True)
# Register a fan entity
entity_entry = entity_registry.async_get_or_create(
"fan", "test", "unique", suggested_object_id="test_fan"
)
aioclient_mock.post(
"https://example/access_token",
json={
"access_token": "mock-token",
"event_endpoint": "http://example.com/alexa_endpoint",
"expires_in": 30,
},
)
aioclient_mock.post("http://example.com/alexa_endpoint", text="", status=202)
await cloud_prefs.async_update(
alexa_report_state=False,
)
conf = alexa_config.CloudAlexaConfig(
hass,
ALEXA_SCHEMA({}),
"mock-user-id",
cloud_prefs,
Mock(
alexa_server="example",
auth=Mock(async_check_token=AsyncMock()),
websession=async_get_clientsession(hass),
),
)
await conf.async_initialize()
await conf.set_authorized(True)
assert cloud_prefs.alexa_report_state is False
assert conf.should_report_state is False
assert conf.is_reporting_states is False
hass.states.async_set(entity_entry.entity_id, "off")
# Enable state reporting
await cloud_prefs.async_update(alexa_report_state=True)
await hass.async_block_till_done()
assert cloud_prefs.alexa_report_state is True
assert conf.should_report_state is True
assert conf.is_reporting_states is True
# Change states to trigger event listener
hass.states.async_set(entity_entry.entity_id, "on")
await hass.async_block_till_done()
# Invalidate the token and try to fetch another
conf.async_invalidate_access_token()
aioclient_mock.clear_requests()
aioclient_mock.post(
"https://example/access_token",
json={"reason": reject_reason},
status=400,
)
# Change states to trigger event listener
hass.states.async_set(entity_entry.entity_id, "off")
await hass.async_block_till_done()
# Check state reporting is still wanted in cloud prefs, but disabled for Alexa
assert cloud_prefs.alexa_report_state is True
assert conf.should_report_state is False
assert conf.is_reporting_states is False
# Simulate we're again authorized, but token update fails
with pytest.raises(expected_exception):
await conf.set_authorized(True)
assert cloud_prefs.alexa_report_state is True
assert conf.should_report_state is False
assert conf.is_reporting_states is False
# Simulate we're again authorized and token update succeeds
# State reporting should now be re-enabled for Alexa
aioclient_mock.clear_requests()
aioclient_mock.post(
"https://example/access_token",
json={
"access_token": "mock-token",
"event_endpoint": "http://example.com/alexa_endpoint",
"expires_in": 30,
},
)
await conf.set_authorized(True)
assert cloud_prefs.alexa_report_state is True
assert conf.should_report_state is True
assert conf.is_reporting_states is True
@contextlib.contextmanager
def patch_sync_helper():
"""Patch sync helper."""
to_update = []
to_remove = []
def sync_helper(to_upd, to_rem):
to_update.extend([ent_id for ent_id in to_upd if ent_id not in to_update])
to_remove.extend([ent_id for ent_id in to_rem if ent_id not in to_remove])
return True
with (
patch("homeassistant.components.cloud.alexa_config.SYNC_DELAY", 0),
patch(
"homeassistant.components.cloud.alexa_config.CloudAlexaConfig._sync_helper",
side_effect=sync_helper,
),
):
yield to_update, to_remove
async def test_alexa_update_expose_trigger_sync(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
cloud_prefs: CloudPreferences,
cloud_stub: Mock,
) -> None:
"""Test Alexa config responds to updating exposed entities."""
assert await async_setup_component(hass, "homeassistant", {})
# Enable exposing new entities to Alexa
expose_new(hass, True)
# Register entities
binary_sensor_entry = entity_registry.async_get_or_create(
"binary_sensor", "test", "unique", suggested_object_id="door"
)
sensor_entry = entity_registry.async_get_or_create(
"sensor", "test", "unique", suggested_object_id="temp"
)
light_entry = entity_registry.async_get_or_create(
"light", "test", "unique", suggested_object_id="kitchen"
)
hass.states.async_set(binary_sensor_entry.entity_id, "on")
hass.states.async_set(
sensor_entry.entity_id,
"23",
{"device_class": "temperature", "unit_of_measurement": "°C"},
)
hass.states.async_set(light_entry.entity_id, "off")
await cloud_prefs.async_update(
alexa_enabled=True,
alexa_report_state=False,
)
conf = alexa_config.CloudAlexaConfig(
hass, ALEXA_SCHEMA({}), "mock-user-id", cloud_prefs, cloud_stub
)
await conf.async_initialize()
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
await hass.async_block_till_done()
with patch_sync_helper() as (to_update, to_remove):
expose_entity(hass, light_entry.entity_id, True)
await hass.async_block_till_done()
async_fire_time_changed(hass, fire_all=True)
await hass.async_block_till_done()
assert conf._alexa_sync_unsub is None
assert to_update == [light_entry.entity_id]
assert to_remove == []
with patch_sync_helper() as (to_update, to_remove):
expose_entity(hass, light_entry.entity_id, False)
expose_entity(hass, binary_sensor_entry.entity_id, True)
expose_entity(hass, sensor_entry.entity_id, True)
await hass.async_block_till_done()
async_fire_time_changed(hass, fire_all=True)
await hass.async_block_till_done()
assert conf._alexa_sync_unsub is None
assert sorted(to_update) == [binary_sensor_entry.entity_id, sensor_entry.entity_id]
assert to_remove == [light_entry.entity_id]
with patch_sync_helper() as (to_update, to_remove):
await cloud_prefs.async_update(
alexa_enabled=False,
)
await hass.async_block_till_done()
assert conf._alexa_sync_unsub is None
assert to_update == []
assert to_remove == [
binary_sensor_entry.entity_id,
sensor_entry.entity_id,
light_entry.entity_id,
]
@pytest.mark.usefixtures("mock_cloud_login")
async def test_alexa_entity_registry_sync(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
cloud_prefs: CloudPreferences,
) -> None:
"""Test Alexa config responds to entity registry."""
# Enable exposing new entities to Alexa
expose_new(hass, True)
await alexa_config.CloudAlexaConfig(
hass, ALEXA_SCHEMA({}), "mock-user-id", cloud_prefs, hass.data[DATA_CLOUD]
).async_initialize()
with patch_sync_helper() as (to_update, to_remove):
entry = entity_registry.async_get_or_create(
"light", "test", "unique", suggested_object_id="kitchen"
)
await hass.async_block_till_done()
assert to_update == [entry.entity_id]
assert to_remove == []
with patch_sync_helper() as (to_update, to_remove):
hass.bus.async_fire(
er.EVENT_ENTITY_REGISTRY_UPDATED,
{"action": "remove", "entity_id": entry.entity_id},
)
await hass.async_block_till_done()
assert to_update == []
assert to_remove == [entry.entity_id]
with patch_sync_helper() as (to_update, to_remove):
hass.bus.async_fire(
er.EVENT_ENTITY_REGISTRY_UPDATED,
{
"action": "update",
"entity_id": entry.entity_id,
"changes": ["entity_id"],
"old_entity_id": "light.living_room",
},
)
await hass.async_block_till_done()
assert to_update == [entry.entity_id]
assert to_remove == ["light.living_room"]
with patch_sync_helper() as (to_update, to_remove):
hass.bus.async_fire(
er.EVENT_ENTITY_REGISTRY_UPDATED,
{"action": "update", "entity_id": entry.entity_id, "changes": ["icon"]},
)
await hass.async_block_till_done()
assert to_update == []
assert to_remove == []
async def test_alexa_update_report_state(
hass: HomeAssistant, cloud_prefs: CloudPreferences, cloud_stub: Mock
) -> None:
"""Test Alexa config responds to reporting state."""
assert await async_setup_component(hass, "homeassistant", {})
await cloud_prefs.async_update(
alexa_report_state=False,
)
conf = alexa_config.CloudAlexaConfig(
hass, ALEXA_SCHEMA({}), "mock-user-id", cloud_prefs, cloud_stub
)
await conf.async_initialize()
await conf.set_authorized(True)
with (
patch(
"homeassistant.components.cloud.alexa_config.CloudAlexaConfig.async_sync_entities",
) as mock_sync,
patch(
"homeassistant.components.cloud.alexa_config.CloudAlexaConfig.async_enable_proactive_mode",
),
):
await cloud_prefs.async_update(alexa_report_state=True)
await hass.async_block_till_done()
assert len(mock_sync.mock_calls) == 1
@pytest.mark.usefixtures("mock_expired_cloud_login")
def test_enabled_requires_valid_sub(
hass: HomeAssistant, cloud_prefs: CloudPreferences
) -> None:
"""Test that alexa config enabled requires a valid Cloud sub."""
assert cloud_prefs.alexa_enabled
assert hass.data[DATA_CLOUD].is_logged_in
assert hass.data[DATA_CLOUD].subscription_expired
config = alexa_config.CloudAlexaConfig(
hass, ALEXA_SCHEMA({}), "mock-user-id", cloud_prefs, hass.data[DATA_CLOUD]
)
assert not config.enabled
async def test_alexa_handle_logout(
hass: HomeAssistant, cloud_prefs: CloudPreferences, cloud_stub: Mock
) -> None:
"""Test Alexa config responds to logging out."""
assert await async_setup_component(hass, "homeassistant", {})
aconf = alexa_config.CloudAlexaConfig(
hass, ALEXA_SCHEMA({}), "mock-user-id", cloud_prefs, cloud_stub
)
await aconf.async_initialize()
with patch(
"homeassistant.components.alexa.config.async_enable_proactive_mode",
return_value=Mock(),
) as mock_enable:
await aconf.async_enable_proactive_mode()
await hass.async_block_till_done()
assert len(aconf._on_deinitialize) == 5
# This will trigger a prefs update when we logout.
await cloud_prefs.get_cloud_user()
cloud_stub.is_logged_in = False
with patch.object(
cloud_stub.auth,
"async_check_token",
side_effect=AssertionError("Should not be called"),
):
# Fake logging out; CloudClient.logout_cleanups sets username to None
# and deinitializes the Google config.
await cloud_prefs.async_set_username(None)
aconf.async_deinitialize()
await hass.async_block_till_done()
# Check listeners are removed:
assert not aconf._on_deinitialize
assert len(mock_enable.return_value.mock_calls) == 1
@pytest.mark.parametrize("alexa_settings_version", [1, 2])
async def test_alexa_config_migrate_expose_entity_prefs(
hass: HomeAssistant,
cloud_prefs: CloudPreferences,
cloud_stub: Mock,
entity_registry: er.EntityRegistry,
alexa_settings_version: int,
) -> None:
"""Test migrating Alexa entity config."""
hass.set_state(CoreState.starting)
assert await async_setup_component(hass, "homeassistant", {})
hass.states.async_set("light.state_only", "on")
entity_exposed = entity_registry.async_get_or_create(
"light",
"test",
"light_exposed",
suggested_object_id="exposed",
)
entity_migrated = entity_registry.async_get_or_create(
"light",
"test",
"light_migrated",
suggested_object_id="migrated",
)
entity_config = entity_registry.async_get_or_create(
"light",
"test",
"light_config",
suggested_object_id="config",
entity_category=EntityCategory.CONFIG,
)
entity_default = entity_registry.async_get_or_create(
"light",
"test",
"light_default",
suggested_object_id="default",
)
entity_blocked = entity_registry.async_get_or_create(
"group",
"test",
"group_all_locks",
suggested_object_id="all_locks",
)
assert entity_blocked.entity_id == "group.all_locks"
await cloud_prefs.async_update(
alexa_enabled=True,
alexa_report_state=False,
alexa_settings_version=alexa_settings_version,
)
expose_entity(hass, entity_migrated.entity_id, False)
cloud_prefs._prefs[PREF_ALEXA_ENTITY_CONFIGS]["light.unknown"] = {
PREF_SHOULD_EXPOSE: True
}
cloud_prefs._prefs[PREF_ALEXA_ENTITY_CONFIGS]["light.state_only"] = {
PREF_SHOULD_EXPOSE: False
}
cloud_prefs._prefs[PREF_ALEXA_ENTITY_CONFIGS][entity_exposed.entity_id] = {
PREF_SHOULD_EXPOSE: True
}
cloud_prefs._prefs[PREF_ALEXA_ENTITY_CONFIGS][entity_migrated.entity_id] = {
PREF_SHOULD_EXPOSE: True
}
conf = alexa_config.CloudAlexaConfig(
hass, ALEXA_SCHEMA({}), "mock-user-id", cloud_prefs, cloud_stub
)
await conf.async_initialize()
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
await hass.async_block_till_done()
assert async_get_entity_settings(hass, "light.unknown") == {
"cloud.alexa": {"should_expose": True}
}
assert async_get_entity_settings(hass, "light.state_only") == {
"cloud.alexa": {"should_expose": False}
}
assert async_get_entity_settings(hass, entity_exposed.entity_id) == {
"cloud.alexa": {"should_expose": True}
}
assert async_get_entity_settings(hass, entity_migrated.entity_id) == {
"cloud.alexa": {"should_expose": True}
}
assert async_get_entity_settings(hass, entity_config.entity_id) == {
"cloud.alexa": {"should_expose": False}
}
assert async_get_entity_settings(hass, entity_default.entity_id) == {
"cloud.alexa": {"should_expose": True}
}
assert async_get_entity_settings(hass, entity_blocked.entity_id) == {
"cloud.alexa": {"should_expose": False}
}
async def test_alexa_config_migrate_expose_entity_prefs_v2_no_exposed(
hass: HomeAssistant,
cloud_prefs: CloudPreferences,
entity_registry: er.EntityRegistry,
) -> None:
"""Test migrating Alexa entity config from v2 to v3 when no entity is exposed."""
hass.set_state(CoreState.starting)
assert await async_setup_component(hass, "homeassistant", {})
hass.states.async_set("light.state_only", "on")
entity_migrated = entity_registry.async_get_or_create(
"light",
"test",
"light_migrated",
suggested_object_id="migrated",
)
await cloud_prefs.async_update(
alexa_enabled=True,
alexa_report_state=False,
alexa_settings_version=2,
)
expose_entity(hass, "light.state_only", False)
expose_entity(hass, entity_migrated.entity_id, False)
cloud_prefs._prefs[PREF_ALEXA_ENTITY_CONFIGS]["light.state_only"] = {
PREF_SHOULD_EXPOSE: True
}
cloud_prefs._prefs[PREF_ALEXA_ENTITY_CONFIGS][entity_migrated.entity_id] = {
PREF_SHOULD_EXPOSE: True
}
conf = alexa_config.CloudAlexaConfig(
hass, ALEXA_SCHEMA({}), "mock-user-id", cloud_prefs, Mock(is_logged_in=False)
)
await conf.async_initialize()
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
await hass.async_block_till_done()
assert async_get_entity_settings(hass, "light.state_only") == {
"cloud.alexa": {"should_expose": True}
}
assert async_get_entity_settings(hass, entity_migrated.entity_id) == {
"cloud.alexa": {"should_expose": True}
}
async def test_alexa_config_migrate_expose_entity_prefs_v2_exposed(
hass: HomeAssistant,
cloud_prefs: CloudPreferences,
entity_registry: er.EntityRegistry,
) -> None:
"""Test migrating Alexa entity config from v2 to v3 when an entity is exposed."""
hass.set_state(CoreState.starting)
assert await async_setup_component(hass, "homeassistant", {})
hass.states.async_set("light.state_only", "on")
entity_migrated = entity_registry.async_get_or_create(
"light",
"test",
"light_migrated",
suggested_object_id="migrated",
)
await cloud_prefs.async_update(
alexa_enabled=True,
alexa_report_state=False,
alexa_settings_version=2,
)
expose_entity(hass, "light.state_only", False)
expose_entity(hass, entity_migrated.entity_id, True)
cloud_prefs._prefs[PREF_ALEXA_ENTITY_CONFIGS]["light.state_only"] = {
PREF_SHOULD_EXPOSE: True
}
cloud_prefs._prefs[PREF_ALEXA_ENTITY_CONFIGS][entity_migrated.entity_id] = {
PREF_SHOULD_EXPOSE: True
}
conf = alexa_config.CloudAlexaConfig(
hass, ALEXA_SCHEMA({}), "mock-user-id", cloud_prefs, Mock(is_logged_in=False)
)
await conf.async_initialize()
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
await hass.async_block_till_done()
assert async_get_entity_settings(hass, "light.state_only") == {
"cloud.alexa": {"should_expose": False}
}
assert async_get_entity_settings(hass, entity_migrated.entity_id) == {
"cloud.alexa": {"should_expose": True}
}
async def test_alexa_config_migrate_expose_entity_prefs_default_none(
hass: HomeAssistant,
cloud_prefs: CloudPreferences,
cloud_stub: Mock,
entity_registry: er.EntityRegistry,
) -> None:
"""Test migrating Alexa entity config."""
hass.set_state(CoreState.starting)
assert await async_setup_component(hass, "homeassistant", {})
entity_default = entity_registry.async_get_or_create(
"light",
"test",
"light_default",
suggested_object_id="default",
)
await cloud_prefs.async_update(
alexa_enabled=True,
alexa_report_state=False,
alexa_settings_version=1,
)
cloud_prefs._prefs[PREF_ALEXA_DEFAULT_EXPOSE] = None
conf = alexa_config.CloudAlexaConfig(
hass, ALEXA_SCHEMA({}), "mock-user-id", cloud_prefs, cloud_stub
)
await conf.async_initialize()
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
await hass.async_block_till_done()
assert async_get_entity_settings(hass, entity_default.entity_id) == {
"cloud.alexa": {"should_expose": True}
}
async def test_alexa_config_migrate_expose_entity_prefs_default(
hass: HomeAssistant,
cloud_prefs: CloudPreferences,
cloud_stub: Mock,
entity_registry: er.EntityRegistry,
) -> None:
"""Test migrating Alexa entity config."""
hass.set_state(CoreState.starting)
assert await async_setup_component(hass, "homeassistant", {})
binary_sensor_supported = entity_registry.async_get_or_create(
"binary_sensor",
"test",
"binary_sensor_supported",
original_device_class="door",
suggested_object_id="supported",
)
binary_sensor_unsupported = entity_registry.async_get_or_create(
"binary_sensor",
"test",
"binary_sensor_unsupported",
original_device_class="battery",
suggested_object_id="unsupported",
)
light = entity_registry.async_get_or_create(
"light",
"test",
"unique",
suggested_object_id="light",
)
sensor_supported = entity_registry.async_get_or_create(
"sensor",
"test",
"sensor_supported",
original_device_class="temperature",
suggested_object_id="supported",
)
sensor_unsupported = entity_registry.async_get_or_create(
"sensor",
"test",
"sensor_unsupported",
original_device_class="battery",
suggested_object_id="unsupported",
)
water_heater = entity_registry.async_get_or_create(
"water_heater",
"test",
"unique",
suggested_object_id="water_heater",
)
await cloud_prefs.async_update(
alexa_enabled=True,
alexa_report_state=False,
alexa_settings_version=1,
)
cloud_prefs._prefs[PREF_ALEXA_DEFAULT_EXPOSE] = [
"binary_sensor",
"light",
"sensor",
"water_heater",
]
conf = alexa_config.CloudAlexaConfig(
hass, ALEXA_SCHEMA({}), "mock-user-id", cloud_prefs, cloud_stub
)
await conf.async_initialize()
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
await hass.async_block_till_done()
assert async_get_entity_settings(hass, binary_sensor_supported.entity_id) == {
"cloud.alexa": {"should_expose": True}
}
assert async_get_entity_settings(hass, binary_sensor_unsupported.entity_id) == {
"cloud.alexa": {"should_expose": False}
}
assert async_get_entity_settings(hass, light.entity_id) == {
"cloud.alexa": {"should_expose": True}
}
assert async_get_entity_settings(hass, sensor_supported.entity_id) == {
"cloud.alexa": {"should_expose": True}
}
assert async_get_entity_settings(hass, sensor_unsupported.entity_id) == {
"cloud.alexa": {"should_expose": False}
}
assert async_get_entity_settings(hass, water_heater.entity_id) == {
"cloud.alexa": {"should_expose": False}
}

View File

@@ -0,0 +1,19 @@
"""Test the cloud assist pipeline."""
import pytest
from homeassistant.components.cloud.assist_pipeline import (
async_migrate_cloud_pipeline_engine,
)
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
async def test_migrate_pipeline_invalid_platform(hass: HomeAssistant) -> None:
"""Test migrate pipeline with invalid platform."""
await async_setup_component(hass, "assist_pipeline", {})
with pytest.raises(ValueError):
await async_migrate_cloud_pipeline_engine(
hass, Platform.BINARY_SENSOR, "test-engine-id"
)

View File

@@ -0,0 +1,652 @@
"""Test the cloud backup platform."""
from collections.abc import AsyncGenerator, AsyncIterator, Generator
from io import StringIO
from typing import Any
from unittest.mock import Mock, PropertyMock, patch
from aiohttp import ClientError
from hass_nabucasa import CloudError
import pytest
from yarl import URL
from homeassistant.components.backup import (
DOMAIN as BACKUP_DOMAIN,
AddonInfo,
AgentBackup,
Folder,
)
from homeassistant.components.cloud import DOMAIN
from homeassistant.components.cloud.backup import async_register_backup_agents_listener
from homeassistant.components.cloud.const import EVENT_CLOUD_EVENT
from homeassistant.core import HomeAssistant
from homeassistant.helpers.dispatcher import async_dispatcher_send
from homeassistant.setup import async_setup_component
from tests.test_util.aiohttp import AiohttpClientMocker
from tests.typing import ClientSessionGenerator, MagicMock, WebSocketGenerator
@pytest.fixture(autouse=True)
async def setup_integration(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
cloud: MagicMock,
cloud_logged_in: None,
) -> AsyncGenerator[None]:
"""Set up cloud integration."""
with (
patch("homeassistant.components.backup.is_hassio", return_value=False),
patch("homeassistant.components.backup.store.STORE_DELAY_SAVE", 0),
):
assert await async_setup_component(hass, BACKUP_DOMAIN, {BACKUP_DOMAIN: {}})
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
await hass.async_block_till_done()
yield
@pytest.fixture
def mock_delete_file() -> Generator[MagicMock]:
"""Mock list files."""
with patch(
"homeassistant.components.cloud.backup.async_files_delete_file",
spec_set=True,
) as delete_file:
yield delete_file
@pytest.fixture
def mock_get_download_details() -> Generator[MagicMock]:
"""Mock list files."""
with patch(
"homeassistant.components.cloud.backup.async_files_download_details",
spec_set=True,
) as download_details:
download_details.return_value = {
"url": (
"https://blabla.cloudflarestorage.com/blabla/backup/"
"462e16810d6841228828d9dd2f9e341e.tar?X-Amz-Algorithm=blah"
),
}
yield download_details
@pytest.fixture
def mock_get_upload_details() -> Generator[MagicMock]:
"""Mock list files."""
with patch(
"homeassistant.components.cloud.backup.async_files_upload_details",
spec_set=True,
) as download_details:
download_details.return_value = {
"url": (
"https://blabla.cloudflarestorage.com/blabla/backup/"
"ea5c969e492c49df89d432a1483b8dc3.tar?X-Amz-Algorithm=blah"
),
"headers": {
"content-md5": "HOhSM3WZkpHRYGiz4YRGIQ==",
"x-amz-meta-storage-type": "backup",
"x-amz-meta-b64json": (
"eyJhZGRvbnMiOltdLCJiYWNrdXBfaWQiOiJjNDNiNWU2MCIsImRhdGUiOiIyMDI0LT"
"EyLTAzVDA0OjI1OjUwLjMyMDcwMy0wNTowMCIsImRhdGFiYXNlX2luY2x1ZGVkIjpm"
"YWxzZSwiZm9sZGVycyI6W10sImhvbWVhc3Npc3RhbnRfaW5jbHVkZWQiOnRydWUsIm"
"hvbWVhc3Npc3RhbnRfdmVyc2lvbiI6IjIwMjQuMTIuMC5kZXYwIiwibmFtZSI6ImVy"
"aWsiLCJwcm90ZWN0ZWQiOnRydWUsInNpemUiOjM1NjI0OTYwfQ=="
),
},
}
yield download_details
@pytest.fixture
def mock_list_files() -> Generator[MagicMock]:
"""Mock list files."""
with patch(
"homeassistant.components.cloud.backup.async_files_list", spec_set=True
) as list_files:
list_files.return_value = [
{
"Key": "462e16810d6841228828d9dd2f9e341e.tar",
"LastModified": "2024-11-22T10:49:01.182Z",
"Size": 34519040,
"Metadata": {
"addons": [],
"backup_id": "23e64aec",
"date": "2024-11-22T11:48:48.727189+01:00",
"database_included": True,
"extra_metadata": {},
"folders": [],
"homeassistant_included": True,
"homeassistant_version": "2024.12.0.dev0",
"name": "Core 2024.12.0.dev0",
"protected": False,
"size": 34519040,
"storage-type": "backup",
},
}
]
yield list_files
@pytest.fixture
def cloud_logged_in(cloud: MagicMock):
"""Mock cloud logged in."""
type(cloud).is_logged_in = PropertyMock(return_value=True)
async def test_agents_info(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test backup agent info."""
client = await hass_ws_client(hass)
await client.send_json_auto_id({"type": "backup/agents/info"})
response = await client.receive_json()
assert response["success"]
assert response["result"] == {
"agents": [{"agent_id": "backup.local"}, {"agent_id": "cloud.cloud"}],
}
async def test_agents_list_backups(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
cloud: MagicMock,
mock_list_files: Mock,
) -> None:
"""Test agent list backups."""
client = await hass_ws_client(hass)
await client.send_json_auto_id({"type": "backup/info"})
response = await client.receive_json()
mock_list_files.assert_called_once_with(cloud, storage_type="backup")
assert response["success"]
assert response["result"]["agent_errors"] == {}
assert response["result"]["backups"] == [
{
"addons": [],
"backup_id": "23e64aec",
"date": "2024-11-22T11:48:48.727189+01:00",
"database_included": True,
"folders": [],
"homeassistant_included": True,
"homeassistant_version": "2024.12.0.dev0",
"name": "Core 2024.12.0.dev0",
"protected": False,
"size": 34519040,
"agent_ids": ["cloud.cloud"],
"failed_agent_ids": [],
"with_automatic_settings": None,
}
]
@pytest.mark.parametrize("side_effect", [ClientError, CloudError])
async def test_agents_list_backups_fail_cloud(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
cloud: MagicMock,
mock_list_files: Mock,
side_effect: Exception,
) -> None:
"""Test agent list backups."""
client = await hass_ws_client(hass)
mock_list_files.side_effect = side_effect
await client.send_json_auto_id({"type": "backup/info"})
response = await client.receive_json()
assert response["success"]
assert response["result"] == {
"agent_errors": {"cloud.cloud": "Failed to list backups"},
"backups": [],
"last_attempted_automatic_backup": None,
"last_completed_automatic_backup": None,
}
@pytest.mark.parametrize(
("backup_id", "expected_result"),
[
(
"23e64aec",
{
"addons": [],
"backup_id": "23e64aec",
"date": "2024-11-22T11:48:48.727189+01:00",
"database_included": True,
"folders": [],
"homeassistant_included": True,
"homeassistant_version": "2024.12.0.dev0",
"name": "Core 2024.12.0.dev0",
"protected": False,
"size": 34519040,
"agent_ids": ["cloud.cloud"],
"failed_agent_ids": [],
"with_automatic_settings": None,
},
),
(
"12345",
None,
),
],
ids=["found", "not_found"],
)
async def test_agents_get_backup(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
cloud: MagicMock,
backup_id: str,
expected_result: dict[str, Any] | None,
mock_list_files: Mock,
) -> None:
"""Test agent get backup."""
client = await hass_ws_client(hass)
await client.send_json_auto_id({"type": "backup/details", "backup_id": backup_id})
response = await client.receive_json()
mock_list_files.assert_called_once_with(cloud, storage_type="backup")
assert response["success"]
assert response["result"]["agent_errors"] == {}
assert response["result"]["backup"] == expected_result
@pytest.mark.usefixtures("cloud_logged_in", "mock_list_files")
async def test_agents_download(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
aioclient_mock: AiohttpClientMocker,
mock_get_download_details: Mock,
) -> None:
"""Test agent download backup."""
client = await hass_client()
backup_id = "23e64aec"
aioclient_mock.get(
mock_get_download_details.return_value["url"], content=b"backup data"
)
resp = await client.get(f"/api/backup/download/{backup_id}?agent_id=cloud.cloud")
assert resp.status == 200
assert await resp.content.read() == b"backup data"
@pytest.mark.parametrize("side_effect", [ClientError, CloudError])
@pytest.mark.usefixtures("cloud_logged_in", "mock_list_files")
async def test_agents_download_fail_cloud(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
mock_get_download_details: Mock,
side_effect: Exception,
) -> None:
"""Test agent download backup, when cloud user is logged in."""
client = await hass_client()
backup_id = "23e64aec"
mock_get_download_details.side_effect = side_effect
resp = await client.get(f"/api/backup/download/{backup_id}?agent_id=cloud.cloud")
assert resp.status == 500
content = await resp.content.read()
assert "Failed to get download details" in content.decode()
@pytest.mark.usefixtures("cloud_logged_in", "mock_list_files")
async def test_agents_download_fail_get(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
aioclient_mock: AiohttpClientMocker,
mock_get_download_details: Mock,
) -> None:
"""Test agent download backup, when cloud user is logged in."""
client = await hass_client()
backup_id = "23e64aec"
aioclient_mock.get(mock_get_download_details.return_value["url"], status=500)
resp = await client.get(f"/api/backup/download/{backup_id}?agent_id=cloud.cloud")
assert resp.status == 500
content = await resp.content.read()
assert "Failed to download backup" in content.decode()
@pytest.mark.usefixtures("cloud_logged_in", "mock_list_files")
async def test_agents_download_not_found(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
) -> None:
"""Test agent download backup raises error if not found."""
client = await hass_client()
backup_id = "1234"
resp = await client.get(f"/api/backup/download/{backup_id}?agent_id=cloud.cloud")
assert resp.status == 404
assert await resp.content.read() == b""
@pytest.mark.usefixtures("cloud_logged_in", "mock_list_files")
async def test_agents_upload(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
caplog: pytest.LogCaptureFixture,
aioclient_mock: AiohttpClientMocker,
mock_get_upload_details: Mock,
) -> None:
"""Test agent upload backup."""
client = await hass_client()
backup_id = "test-backup"
test_backup = AgentBackup(
addons=[AddonInfo(name="Test", slug="test", version="1.0.0")],
backup_id=backup_id,
database_included=True,
date="1970-01-01T00:00:00.000Z",
extra_metadata={},
folders=[Folder.MEDIA, Folder.SHARE],
homeassistant_included=True,
homeassistant_version="2024.12.0",
name="Test",
protected=True,
size=0,
)
aioclient_mock.put(mock_get_upload_details.return_value["url"])
with (
patch(
"homeassistant.components.backup.manager.BackupManager.async_get_backup",
) as fetch_backup,
patch(
"homeassistant.components.backup.manager.read_backup",
return_value=test_backup,
),
patch("pathlib.Path.open") as mocked_open,
):
mocked_open.return_value.read = Mock(side_effect=[b"test", b""])
fetch_backup.return_value = test_backup
resp = await client.post(
"/api/backup/upload?agent_id=cloud.cloud",
data={"file": StringIO("test")},
)
assert len(aioclient_mock.mock_calls) == 1
assert aioclient_mock.mock_calls[-1][0] == "PUT"
assert aioclient_mock.mock_calls[-1][1] == URL(
mock_get_upload_details.return_value["url"]
)
assert isinstance(aioclient_mock.mock_calls[-1][2], AsyncIterator)
assert resp.status == 201
assert f"Uploading backup {backup_id}" in caplog.text
@pytest.mark.parametrize("put_mock_kwargs", [{"status": 500}, {"exc": TimeoutError}])
@pytest.mark.usefixtures("cloud_logged_in", "mock_list_files")
async def test_agents_upload_fail_put(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
hass_storage: dict[str, Any],
aioclient_mock: AiohttpClientMocker,
mock_get_upload_details: Mock,
put_mock_kwargs: dict[str, Any],
caplog: pytest.LogCaptureFixture,
) -> None:
"""Test agent upload backup fails."""
client = await hass_client()
backup_id = "test-backup"
test_backup = AgentBackup(
addons=[AddonInfo(name="Test", slug="test", version="1.0.0")],
backup_id=backup_id,
database_included=True,
date="1970-01-01T00:00:00.000Z",
extra_metadata={},
folders=[Folder.MEDIA, Folder.SHARE],
homeassistant_included=True,
homeassistant_version="2024.12.0",
name="Test",
protected=True,
size=0,
)
aioclient_mock.put(mock_get_upload_details.return_value["url"], **put_mock_kwargs)
with (
patch(
"homeassistant.components.backup.manager.BackupManager.async_get_backup",
) as fetch_backup,
patch(
"homeassistant.components.backup.manager.read_backup",
return_value=test_backup,
),
patch("pathlib.Path.open") as mocked_open,
patch("homeassistant.components.cloud.backup.asyncio.sleep"),
patch("homeassistant.components.cloud.backup.random.randint", return_value=60),
patch("homeassistant.components.cloud.backup._RETRY_LIMIT", 2),
):
mocked_open.return_value.read = Mock(side_effect=[b"test", b""])
fetch_backup.return_value = test_backup
resp = await client.post(
"/api/backup/upload?agent_id=cloud.cloud",
data={"file": StringIO("test")},
)
await hass.async_block_till_done()
assert len(aioclient_mock.mock_calls) == 2
assert "Failed to upload backup, retrying (2/2) in 60s" in caplog.text
assert resp.status == 201
store_backups = hass_storage[BACKUP_DOMAIN]["data"]["backups"]
assert len(store_backups) == 1
stored_backup = store_backups[0]
assert stored_backup["backup_id"] == backup_id
assert stored_backup["failed_agent_ids"] == ["cloud.cloud"]
@pytest.mark.parametrize("side_effect", [ClientError, CloudError])
@pytest.mark.usefixtures("cloud_logged_in")
async def test_agents_upload_fail_cloud(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
hass_storage: dict[str, Any],
mock_get_upload_details: Mock,
side_effect: Exception,
) -> None:
"""Test agent upload backup, when cloud user is logged in."""
client = await hass_client()
backup_id = "test-backup"
mock_get_upload_details.side_effect = side_effect
test_backup = AgentBackup(
addons=[AddonInfo(name="Test", slug="test", version="1.0.0")],
backup_id=backup_id,
database_included=True,
date="1970-01-01T00:00:00.000Z",
extra_metadata={},
folders=[Folder.MEDIA, Folder.SHARE],
homeassistant_included=True,
homeassistant_version="2024.12.0",
name="Test",
protected=True,
size=0,
)
with (
patch(
"homeassistant.components.backup.manager.BackupManager.async_get_backup",
) as fetch_backup,
patch(
"homeassistant.components.backup.manager.read_backup",
return_value=test_backup,
),
patch("pathlib.Path.open") as mocked_open,
patch("homeassistant.components.cloud.backup.asyncio.sleep"),
):
mocked_open.return_value.read = Mock(side_effect=[b"test", b""])
fetch_backup.return_value = test_backup
resp = await client.post(
"/api/backup/upload?agent_id=cloud.cloud",
data={"file": StringIO("test")},
)
await hass.async_block_till_done()
assert resp.status == 201
store_backups = hass_storage[BACKUP_DOMAIN]["data"]["backups"]
assert len(store_backups) == 1
stored_backup = store_backups[0]
assert stored_backup["backup_id"] == backup_id
assert stored_backup["failed_agent_ids"] == ["cloud.cloud"]
async def test_agents_upload_not_protected(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
hass_storage: dict[str, Any],
) -> None:
"""Test agent upload backup, when cloud user is logged in."""
client = await hass_client()
backup_id = "test-backup"
test_backup = AgentBackup(
addons=[AddonInfo(name="Test", slug="test", version="1.0.0")],
backup_id=backup_id,
database_included=True,
date="1970-01-01T00:00:00.000Z",
extra_metadata={},
folders=[Folder.MEDIA, Folder.SHARE],
homeassistant_included=True,
homeassistant_version="2024.12.0",
name="Test",
protected=False,
size=0,
)
with (
patch("pathlib.Path.open"),
patch(
"homeassistant.components.backup.manager.read_backup",
return_value=test_backup,
),
):
resp = await client.post(
"/api/backup/upload?agent_id=cloud.cloud",
data={"file": StringIO("test")},
)
await hass.async_block_till_done()
assert resp.status == 201
store_backups = hass_storage[BACKUP_DOMAIN]["data"]["backups"]
assert len(store_backups) == 1
stored_backup = store_backups[0]
assert stored_backup["backup_id"] == backup_id
assert stored_backup["failed_agent_ids"] == ["cloud.cloud"]
@pytest.mark.usefixtures("cloud_logged_in", "mock_list_files")
async def test_agents_delete(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
mock_delete_file: Mock,
) -> None:
"""Test agent delete backup."""
client = await hass_ws_client(hass)
backup_id = "23e64aec"
await client.send_json_auto_id(
{
"type": "backup/delete",
"backup_id": backup_id,
}
)
response = await client.receive_json()
assert response["success"]
assert response["result"] == {"agent_errors": {}}
mock_delete_file.assert_called_once()
@pytest.mark.parametrize("side_effect", [ClientError, CloudError])
@pytest.mark.usefixtures("cloud_logged_in", "mock_list_files")
async def test_agents_delete_fail_cloud(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
mock_delete_file: Mock,
side_effect: Exception,
) -> None:
"""Test agent delete backup."""
client = await hass_ws_client(hass)
backup_id = "23e64aec"
mock_delete_file.side_effect = side_effect
await client.send_json_auto_id(
{
"type": "backup/delete",
"backup_id": backup_id,
}
)
response = await client.receive_json()
assert response["success"]
assert response["result"] == {
"agent_errors": {"cloud.cloud": "Failed to delete backup"}
}
@pytest.mark.usefixtures("cloud_logged_in", "mock_list_files")
async def test_agents_delete_not_found(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test agent download backup raises error if not found."""
client = await hass_ws_client(hass)
backup_id = "1234"
await client.send_json_auto_id(
{
"type": "backup/delete",
"backup_id": backup_id,
}
)
response = await client.receive_json()
assert response["success"]
assert response["result"] == {"agent_errors": {}}
@pytest.mark.parametrize("event_type", ["login", "logout"])
async def test_calling_listener_on_login_logout(
hass: HomeAssistant,
event_type: str,
) -> None:
"""Test calling listener for login and logout events."""
listener = MagicMock()
async_register_backup_agents_listener(hass, listener=listener)
assert listener.call_count == 0
async_dispatcher_send(hass, EVENT_CLOUD_EVENT, {"type": event_type})
await hass.async_block_till_done()
assert listener.call_count == 1
async def test_not_calling_listener_after_unsub(hass: HomeAssistant) -> None:
"""Test only calling listener until unsub."""
listener = MagicMock()
unsub = async_register_backup_agents_listener(hass, listener=listener)
assert listener.call_count == 0
async_dispatcher_send(hass, EVENT_CLOUD_EVENT, {"type": "login"})
await hass.async_block_till_done()
assert listener.call_count == 1
unsub()
async_dispatcher_send(hass, EVENT_CLOUD_EVENT, {"type": "login"})
await hass.async_block_till_done()
assert listener.call_count == 1
async def test_not_calling_listener_with_unknown_event_type(
hass: HomeAssistant,
) -> None:
"""Test not calling listener if we did not get the expected event type."""
listener = MagicMock()
async_register_backup_agents_listener(hass, listener=listener)
assert listener.call_count == 0
async_dispatcher_send(hass, EVENT_CLOUD_EVENT, {"type": "unknown"})
await hass.async_block_till_done()
assert listener.call_count == 0

View File

@@ -0,0 +1,69 @@
"""Tests for the cloud binary sensor."""
from collections.abc import Generator
from unittest.mock import MagicMock, patch
from hass_nabucasa.const import DISPATCH_REMOTE_CONNECT, DISPATCH_REMOTE_DISCONNECT
import pytest
from homeassistant.core import HomeAssistant
from homeassistant.helpers.entity_registry import EntityRegistry
from homeassistant.setup import async_setup_component
@pytest.fixture(autouse=True)
def mock_wait_until() -> Generator[None]:
"""Mock WAIT_UNTIL_CHANGE to execute callback immediately."""
with patch("homeassistant.components.cloud.binary_sensor.WAIT_UNTIL_CHANGE", 0):
yield
async def test_remote_connection_sensor(
hass: HomeAssistant,
cloud: MagicMock,
entity_registry: EntityRegistry,
) -> None:
"""Test the remote connection sensor."""
entity_id = "binary_sensor.remote_ui"
cloud.remote.certificate = None
assert await async_setup_component(hass, "cloud", {"cloud": {}})
await hass.async_block_till_done()
assert hass.states.get(entity_id) is None
on_start_callback = cloud.register_on_start.call_args[0][0]
await on_start_callback()
state = hass.states.get(entity_id)
assert state is not None
assert state.state == "unavailable"
cloud.remote.is_connected = False
cloud.remote.certificate = object()
cloud.client.dispatcher_message(DISPATCH_REMOTE_DISCONNECT)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state is not None
assert state.state == "off"
cloud.remote.is_connected = True
cloud.client.dispatcher_message(DISPATCH_REMOTE_CONNECT)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state is not None
assert state.state == "on"
# Test that a state is not set if the entity is removed.
entity_registry.async_remove(entity_id)
await hass.async_block_till_done()
assert hass.states.get(entity_id) is None
cloud.remote.is_connected = False
cloud.client.dispatcher_message(DISPATCH_REMOTE_DISCONNECT)
await hass.async_block_till_done()
assert hass.states.get(entity_id) is None

View File

@@ -0,0 +1,568 @@
"""Test the cloud.iot module."""
from collections.abc import Callable, Coroutine
from datetime import timedelta
from typing import Any
from unittest.mock import AsyncMock, MagicMock, Mock, PropertyMock, patch
import aiohttp
from aiohttp import web
from hass_nabucasa.client import RemoteActivationNotAllowed
import pytest
from homeassistant.components import webhook
from homeassistant.components.cloud import DOMAIN
from homeassistant.components.cloud.client import (
VALID_REPAIR_TRANSLATION_KEYS,
CloudClient,
)
from homeassistant.components.cloud.const import (
DATA_CLOUD,
PREF_ALEXA_REPORT_STATE,
PREF_ENABLE_ALEXA,
PREF_ENABLE_GOOGLE,
)
from homeassistant.components.cloud.prefs import CloudPreferences
from homeassistant.components.homeassistant.exposed_entities import (
DATA_EXPOSED_ENTITIES,
async_expose_entity,
)
from homeassistant.const import CONTENT_TYPE_JSON, __version__ as HA_VERSION
from homeassistant.core import HomeAssistant, State
from homeassistant.helpers import entity_registry as er, issue_registry as ir
from homeassistant.setup import async_setup_component
from homeassistant.util import dt as dt_util
from . import mock_cloud, mock_cloud_prefs
from tests.common import async_fire_time_changed
from tests.components.alexa import test_smart_home as test_alexa
@pytest.fixture
def mock_cloud_inst() -> MagicMock:
"""Mock cloud class."""
return MagicMock(subscription_expired=False)
async def test_handler_alexa(hass: HomeAssistant) -> None:
"""Test handler Alexa."""
hass.states.async_set("switch.test", "on", {"friendly_name": "Test switch"})
hass.states.async_set("switch.test2", "on", {"friendly_name": "Test switch 2"})
await mock_cloud(
hass,
{
"alexa": {
"filter": {"exclude_entities": "switch.test2"},
"entity_config": {
"switch.test": {
"name": "Config name",
"description": "Config description",
"display_categories": "LIGHT",
}
},
}
},
)
mock_cloud_prefs(hass, {PREF_ALEXA_REPORT_STATE: False})
cloud = hass.data[DATA_CLOUD]
resp = await cloud.client.async_alexa_message(
test_alexa.get_new_request("Alexa.Discovery", "Discover")
)
endpoints = resp["event"]["payload"]["endpoints"]
assert len(endpoints) == 1
device = endpoints[0]
assert device["description"] == "Config description via Home Assistant"
assert device["friendlyName"] == "Config name"
assert device["displayCategories"] == ["LIGHT"]
assert device["manufacturerName"] == "Home Assistant"
async def test_handler_alexa_disabled(
hass: HomeAssistant, mock_cloud_fixture: CloudPreferences
) -> None:
"""Test handler Alexa when user has disabled it."""
mock_cloud_fixture._prefs[PREF_ENABLE_ALEXA] = False
cloud = hass.data[DATA_CLOUD]
resp = await cloud.client.async_alexa_message(
test_alexa.get_new_request("Alexa.Discovery", "Discover")
)
assert resp["event"]["header"]["namespace"] == "Alexa"
assert resp["event"]["header"]["name"] == "ErrorResponse"
assert resp["event"]["payload"]["type"] == "BRIDGE_UNREACHABLE"
async def test_handler_google_actions(hass: HomeAssistant) -> None:
"""Test handler Google Actions."""
hass.states.async_set("switch.test", "on", {"friendly_name": "Test switch"})
hass.states.async_set("switch.test2", "on", {"friendly_name": "Test switch 2"})
hass.states.async_set("group.all_locks", "on", {"friendly_name": "Evil locks"})
await mock_cloud(
hass,
{
"google_actions": {
"filter": {"exclude_entities": "switch.test2"},
"entity_config": {
"switch.test": {
"name": "Config name",
"aliases": "Config alias",
"room": "living room",
}
},
}
},
)
mock_cloud_prefs(hass, {})
cloud = hass.data[DATA_CLOUD]
reqid = "5711642932632160983"
data = {"requestId": reqid, "inputs": [{"intent": "action.devices.SYNC"}]}
with patch(
"hass_nabucasa.Cloud._decode_claims",
return_value={"cognito:username": "myUserName"},
):
await cloud.client.get_google_config()
resp = await cloud.client.async_google_message(data)
assert resp["requestId"] == reqid
payload = resp["payload"]
assert payload["agentUserId"] == "myUserName"
devices = payload["devices"]
assert len(devices) == 1
device = devices[0]
assert device["id"] == "switch.test"
assert device["name"]["name"] == "Config name"
assert device["name"]["nicknames"] == ["Config name", "Config alias"]
assert device["type"] == "action.devices.types.SWITCH"
assert device["roomHint"] == "living room"
@pytest.mark.parametrize(
("intent", "response_payload"),
[
("action.devices.SYNC", {"agentUserId": "myUserName", "devices": []}),
("action.devices.QUERY", {"errorCode": "deviceTurnedOff"}),
],
)
async def test_handler_google_actions_disabled(
hass: HomeAssistant,
mock_cloud_fixture: CloudPreferences,
intent: str,
response_payload: dict[str, Any],
) -> None:
"""Test handler Google Actions when user has disabled it."""
mock_cloud_fixture._prefs[PREF_ENABLE_GOOGLE] = False
with patch("hass_nabucasa.Cloud.initialize"):
assert await async_setup_component(hass, "cloud", {})
reqid = "5711642932632160983"
data = {"requestId": reqid, "inputs": [{"intent": intent}]}
cloud = hass.data[DATA_CLOUD]
with patch(
"hass_nabucasa.Cloud._decode_claims",
return_value={"cognito:username": "myUserName"},
):
resp = await cloud.client.async_google_message(data)
assert resp["requestId"] == reqid
assert resp["payload"] == response_payload
async def test_handler_ice_servers(
hass: HomeAssistant,
cloud: MagicMock,
set_cloud_prefs: Callable[[dict[str, Any]], Coroutine[Any, Any, None]],
) -> None:
"""Test handler ICE servers."""
assert await async_setup_component(hass, "cloud", {"cloud": {}})
await hass.async_block_till_done()
# make sure that preferences will not be reset
await cloud.client.prefs.async_set_username(cloud.username)
await set_cloud_prefs(
{
"alexa_enabled": False,
"google_enabled": False,
}
)
await cloud.login("test-user", "test-pass")
await cloud.client.cloud_connected()
assert cloud.client._cloud_ice_servers_listener is not None
assert cloud.client._cloud_ice_servers_listener() == "mock-unregister"
async def test_handler_ice_servers_disabled(
hass: HomeAssistant,
cloud: MagicMock,
set_cloud_prefs: Callable[[dict[str, Any]], Coroutine[Any, Any, None]],
) -> None:
"""Test handler ICE servers when user has disabled it."""
assert await async_setup_component(hass, "cloud", {"cloud": {}})
await hass.async_block_till_done()
# make sure that preferences will not be reset
await cloud.client.prefs.async_set_username(cloud.username)
await set_cloud_prefs(
{
"alexa_enabled": False,
"google_enabled": False,
}
)
await cloud.login("test-user", "test-pass")
await cloud.client.cloud_connected()
await set_cloud_prefs(
{
"cloud_ice_servers_enabled": False,
}
)
assert cloud.client._cloud_ice_servers_listener is None
async def test_webhook_msg(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test webhook msg."""
with patch("hass_nabucasa.Cloud.initialize"):
setup = await async_setup_component(hass, "cloud", {"cloud": {}})
assert setup
cloud = hass.data[DATA_CLOUD]
await cloud.client.prefs.async_initialize()
await cloud.client.prefs.async_update(
cloudhooks={
"mock-webhook-id": {
"webhook_id": "mock-webhook-id",
"cloudhook_id": "mock-cloud-id",
},
"no-longere-existing": {
"webhook_id": "no-longere-existing",
"cloudhook_id": "mock-nonexisting-id",
},
}
)
received = []
async def handler(
hass: HomeAssistant, webhook_id: str, request: web.Request
) -> web.Response:
"""Handle a webhook."""
received.append(request)
return web.json_response({"from": "handler"})
webhook.async_register(hass, "test", "Test", "mock-webhook-id", handler)
response = await cloud.client.async_webhook_message(
{
"cloudhook_id": "mock-cloud-id",
"body": '{"hello": "world"}',
"headers": {"content-type": CONTENT_TYPE_JSON},
"method": "POST",
"query": None,
}
)
assert response == {
"status": 200,
"body": '{"from": "handler"}',
"headers": {"Content-Type": CONTENT_TYPE_JSON},
}
assert len(received) == 1
assert await received[0].json() == {"hello": "world"}
# Non existing webhook
caplog.clear()
response = await cloud.client.async_webhook_message(
{
"cloudhook_id": "mock-nonexisting-id",
"body": '{"nonexisting": "payload"}',
"headers": {"content-type": CONTENT_TYPE_JSON},
"method": "POST",
"query": None,
}
)
assert response == {
"status": 200,
"body": None,
"headers": {"Content-Type": "application/octet-stream"},
}
assert (
"Received message for unregistered webhook no-longere-existing from cloud"
in caplog.text
)
assert '{"nonexisting": "payload"}' in caplog.text
@pytest.mark.usefixtures("mock_cloud_setup", "mock_cloud_login")
async def test_google_config_expose_entity(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
) -> None:
"""Test Google config exposing entity method uses latest config."""
# Enable exposing new entities to Google
exposed_entities = hass.data[DATA_EXPOSED_ENTITIES]
exposed_entities.async_set_expose_new_entities("cloud.google_assistant", True)
# Register a light entity
entity_entry = entity_registry.async_get_or_create(
"light", "test", "unique", suggested_object_id="kitchen"
)
cloud_client = hass.data[DATA_CLOUD].client
state = State(entity_entry.entity_id, "on")
gconf = await cloud_client.get_google_config()
assert gconf.should_expose(state)
async_expose_entity(hass, "cloud.google_assistant", entity_entry.entity_id, False)
assert not gconf.should_expose(state)
@pytest.mark.usefixtures("mock_cloud_setup", "mock_cloud_login")
async def test_google_config_should_2fa(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
) -> None:
"""Test Google config disabling 2FA method uses latest config."""
# Register a light entity
entity_entry = entity_registry.async_get_or_create(
"light", "test", "unique", suggested_object_id="kitchen"
)
cloud_client = hass.data[DATA_CLOUD].client
gconf = await cloud_client.get_google_config()
state = State(entity_entry.entity_id, "on")
assert gconf.should_2fa(state)
entity_registry.async_update_entity_options(
entity_entry.entity_id, "cloud.google_assistant", {"disable_2fa": True}
)
assert not gconf.should_2fa(state)
async def test_set_username(hass: HomeAssistant) -> None:
"""Test we set username during login."""
prefs = MagicMock(
alexa_enabled=False,
google_enabled=False,
async_set_username=AsyncMock(return_value=None),
)
client = CloudClient(hass, prefs, None, {}, {})
client.cloud = MagicMock(is_logged_in=True, username="mock-username")
await client.cloud_connected()
assert len(prefs.async_set_username.mock_calls) == 1
assert prefs.async_set_username.mock_calls[0][1][0] == "mock-username"
async def test_login_recovers_bad_internet(
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
) -> None:
"""Test Alexa can recover bad auth."""
prefs = Mock(
alexa_enabled=True,
google_enabled=False,
async_set_username=AsyncMock(return_value=None),
)
client = CloudClient(hass, prefs, None, {}, {})
client.cloud = Mock()
client._alexa_config = Mock(
async_enable_proactive_mode=Mock(side_effect=aiohttp.ClientError)
)
await client.cloud_connected()
assert len(client._alexa_config.async_enable_proactive_mode.mock_calls) == 1
assert "Unable to activate Alexa Report State" in caplog.text
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=30))
await hass.async_block_till_done()
assert len(client._alexa_config.async_enable_proactive_mode.mock_calls) == 2
async def test_system_msg(hass: HomeAssistant) -> None:
"""Test system msg."""
with patch("hass_nabucasa.Cloud.initialize"):
setup = await async_setup_component(hass, "cloud", {"cloud": {}})
assert setup
cloud = hass.data[DATA_CLOUD]
assert cloud.client.relayer_region is None
response = await cloud.client.async_system_message(
{
"region": "xx-earth-616",
}
)
assert response is None
assert cloud.client.relayer_region == "xx-earth-616"
async def test_cloud_connection_info(hass: HomeAssistant) -> None:
"""Test connection info msg."""
with (
patch("hass_nabucasa.Cloud.initialize"),
patch("uuid.UUID.hex", new_callable=PropertyMock) as hexmock,
):
hexmock.return_value = "12345678901234567890"
setup = await async_setup_component(hass, "cloud", {"cloud": {}})
assert setup
cloud = hass.data[DATA_CLOUD]
response = await cloud.client.async_cloud_connection_info({})
assert response == {
"instance_id": "12345678901234567890",
"name": "test home",
"remote": {
"alias": None,
"can_enable": True,
"connected": False,
"enabled": False,
"instance_domain": None,
},
"version": HA_VERSION,
}
@pytest.mark.parametrize(
"translation_key",
sorted(VALID_REPAIR_TRANSLATION_KEYS),
)
async def test_async_create_repair_issue_known(
cloud: MagicMock,
mock_cloud_setup: None,
issue_registry: ir.IssueRegistry,
translation_key: str,
) -> None:
"""Test create repair issue for known repairs."""
identifier = f"test_identifier_{translation_key}"
await cloud.client.async_create_repair_issue(
identifier=identifier,
translation_key=translation_key,
placeholders={"custom_domains": "example.com"},
severity="warning",
)
issue = issue_registry.async_get_issue(domain=DOMAIN, issue_id=identifier)
assert issue is not None
async def test_async_create_repair_issue_unknown(
cloud: MagicMock,
mock_cloud_setup: None,
issue_registry: ir.IssueRegistry,
) -> None:
"""Test not creating repair issue for unknown repairs."""
identifier = "abc123"
with pytest.raises(
ValueError,
match="Invalid translation key unknown_translation_key",
):
await cloud.client.async_create_repair_issue(
identifier=identifier,
translation_key="unknown_translation_key",
placeholders={"custom_domains": "example.com"},
severity="error",
)
issue = issue_registry.async_get_issue(domain=DOMAIN, issue_id=identifier)
assert issue is None
async def test_disconnected(hass: HomeAssistant) -> None:
"""Test cleanup when disconnected from the cloud."""
prefs = MagicMock(
alexa_enabled=False,
google_enabled=True,
async_set_username=AsyncMock(return_value=None),
)
client = CloudClient(hass, prefs, None, {}, {})
client.cloud = MagicMock(is_logged_in=True, username="mock-username")
client._google_config = Mock()
client._google_config.async_disable_local_sdk.assert_not_called()
await client.cloud_disconnected()
client._google_config.async_disable_local_sdk.assert_called_once_with()
async def test_logged_out(
hass: HomeAssistant,
cloud: MagicMock,
) -> None:
"""Test cleanup when logged out from the cloud."""
assert await async_setup_component(hass, "cloud", {"cloud": {}})
await hass.async_block_till_done()
await cloud.login("test-user", "test-pass")
alexa_config_mock = Mock(async_enable_proactive_mode=AsyncMock())
google_config_mock = Mock(async_sync_entities=AsyncMock())
cloud.client._alexa_config = alexa_config_mock
cloud.client._google_config = google_config_mock
await cloud.client.cloud_connected()
await hass.async_block_till_done()
assert cloud.client._cloud_ice_servers_listener is not None
# Simulate logged out
await cloud.logout()
await hass.async_block_till_done()
# Check we clean up Alexa, Google and ICE servers
assert cloud.client._alexa_config is None
assert cloud.client._google_config is None
assert cloud.client._cloud_ice_servers_listener is None
google_config_mock.async_deinitialize.assert_called_once_with()
alexa_config_mock.async_deinitialize.assert_called_once_with()
async def test_remote_enable(hass: HomeAssistant) -> None:
"""Test enabling remote UI."""
prefs = MagicMock(async_update=AsyncMock(return_value=None))
client = CloudClient(hass, prefs, None, {}, {})
client.cloud = MagicMock(is_logged_in=True, username="mock-username")
await client.async_cloud_connect_update(True)
prefs.async_update.assert_called_once_with(remote_enabled=True)
async def test_remote_enable_not_allowed(hass: HomeAssistant) -> None:
"""Test enabling remote UI."""
prefs = MagicMock(
async_update=AsyncMock(return_value=None),
remote_allow_remote_enable=False,
)
client = CloudClient(hass, prefs, None, {}, {})
client.cloud = MagicMock(is_logged_in=True, username="mock-username")
with pytest.raises(RemoteActivationNotAllowed):
await client.async_cloud_connect_update(True)
prefs.async_update.assert_not_called()

View File

@@ -0,0 +1,45 @@
"""Test the Home Assistant Cloud config flow."""
from unittest.mock import patch
from homeassistant.components.cloud.const import DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from tests.common import MockConfigEntry
async def test_config_flow(hass: HomeAssistant) -> None:
"""Test create cloud entry."""
with (
patch(
"homeassistant.components.cloud.async_setup", return_value=True
) as mock_setup,
patch(
"homeassistant.components.cloud.async_setup_entry",
return_value=True,
) as mock_setup_entry,
):
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "system"}
)
assert result["type"] is FlowResultType.CREATE_ENTRY
assert result["title"] == "Home Assistant Cloud"
assert result["data"] == {}
await hass.async_block_till_done()
assert len(mock_setup.mock_calls) == 1
assert len(mock_setup_entry.mock_calls) == 1
async def test_multiple_entries(hass: HomeAssistant) -> None:
"""Test creating multiple cloud entries."""
config_entry = MockConfigEntry(domain=DOMAIN)
config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": "system"}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "single_instance_allowed"

View File

@@ -0,0 +1,920 @@
"""Test the Cloud Google Config."""
from http import HTTPStatus
from unittest.mock import Mock, PropertyMock, patch
from freezegun import freeze_time
import pytest
from homeassistant.components.cloud import GACTIONS_SCHEMA
from homeassistant.components.cloud.const import (
DATA_CLOUD,
PREF_DISABLE_2FA,
PREF_GOOGLE_DEFAULT_EXPOSE,
PREF_GOOGLE_ENTITY_CONFIGS,
PREF_SHOULD_EXPOSE,
)
from homeassistant.components.cloud.google_config import CloudGoogleConfig
from homeassistant.components.cloud.prefs import CloudPreferences
from homeassistant.components.google_assistant import helpers as ga_helpers
from homeassistant.components.homeassistant.exposed_entities import (
DATA_EXPOSED_ENTITIES,
async_expose_entity,
async_get_entity_settings,
)
from homeassistant.const import (
EVENT_HOMEASSISTANT_START,
EVENT_HOMEASSISTANT_STARTED,
EntityCategory,
)
from homeassistant.core import CoreState, HomeAssistant, State
from homeassistant.helpers import device_registry as dr, entity_registry as er
from homeassistant.setup import async_setup_component
from homeassistant.util.dt import utcnow
from tests.common import async_fire_time_changed
@pytest.fixture
def mock_conf(hass: HomeAssistant, cloud_prefs: CloudPreferences) -> CloudGoogleConfig:
"""Mock Google conf."""
return CloudGoogleConfig(
hass,
GACTIONS_SCHEMA({}),
"mock-user-id",
cloud_prefs,
Mock(username="abcdefghjkl"),
)
def expose_new(hass: HomeAssistant, expose_new: bool) -> None:
"""Enable exposing new entities to Google."""
exposed_entities = hass.data[DATA_EXPOSED_ENTITIES]
exposed_entities.async_set_expose_new_entities("cloud.google_assistant", expose_new)
def expose_entity(hass: HomeAssistant, entity_id: str, should_expose: bool) -> None:
"""Expose an entity to Google."""
async_expose_entity(hass, "cloud.google_assistant", entity_id, should_expose)
async def test_google_update_report_state(
mock_conf: CloudGoogleConfig, hass: HomeAssistant, cloud_prefs: CloudPreferences
) -> None:
"""Test Google config responds to updating preference."""
assert await async_setup_component(hass, "homeassistant", {})
await mock_conf.async_initialize()
await mock_conf.async_connect_agent_user("mock-user-id")
mock_conf._cloud.subscription_expired = False
with (
patch.object(mock_conf, "async_sync_entities") as mock_sync,
patch(
"homeassistant.components.google_assistant.report_state.async_enable_report_state"
) as mock_report_state,
):
await cloud_prefs.async_update(google_report_state=True)
await hass.async_block_till_done()
assert len(mock_sync.mock_calls) == 1
assert len(mock_report_state.mock_calls) == 1
async def test_google_update_report_state_subscription_expired(
mock_conf: CloudGoogleConfig, hass: HomeAssistant, cloud_prefs: CloudPreferences
) -> None:
"""Test Google config not reporting state when subscription has expired."""
assert await async_setup_component(hass, "homeassistant", {})
await mock_conf.async_initialize()
await mock_conf.async_connect_agent_user("mock-user-id")
assert mock_conf._cloud.subscription_expired
with (
patch.object(mock_conf, "async_sync_entities") as mock_sync,
patch(
"homeassistant.components.google_assistant.report_state.async_enable_report_state"
) as mock_report_state,
):
await cloud_prefs.async_update(google_report_state=True)
await hass.async_block_till_done()
assert len(mock_sync.mock_calls) == 0
assert len(mock_report_state.mock_calls) == 0
async def test_sync_entities(
mock_conf: CloudGoogleConfig, hass: HomeAssistant, cloud_prefs: CloudPreferences
) -> None:
"""Test sync devices."""
assert await async_setup_component(hass, "homeassistant", {})
await mock_conf.async_initialize()
assert len(mock_conf.async_get_agent_users()) == 0
await mock_conf.async_connect_agent_user("mock-user-id")
assert len(mock_conf.async_get_agent_users()) == 1
with patch(
"hass_nabucasa.cloud_api.async_google_actions_request_sync",
return_value=Mock(status=HTTPStatus.NOT_FOUND),
) as mock_request_sync:
assert (
await mock_conf.async_sync_entities("mock-user-id") == HTTPStatus.NOT_FOUND
)
assert len(mock_conf.async_get_agent_users()) == 0
assert len(mock_request_sync.mock_calls) == 1
async def test_google_update_expose_trigger_sync(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
cloud_prefs: CloudPreferences,
) -> None:
"""Test Google config responds to updating exposed entities."""
assert await async_setup_component(hass, "homeassistant", {})
# Enable exposing new entities to Google
expose_new(hass, True)
# Register entities
binary_sensor_entry = entity_registry.async_get_or_create(
"binary_sensor", "test", "unique", suggested_object_id="door"
)
sensor_entry = entity_registry.async_get_or_create(
"sensor", "test", "unique", suggested_object_id="temp"
)
light_entry = entity_registry.async_get_or_create(
"light", "test", "unique", suggested_object_id="kitchen"
)
with freeze_time(utcnow()):
config = CloudGoogleConfig(
hass,
GACTIONS_SCHEMA({}),
"mock-user-id",
cloud_prefs,
Mock(username="abcdefghjkl"),
)
await config.async_initialize()
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
await hass.async_block_till_done()
await config.async_connect_agent_user("mock-user-id")
with (
patch.object(config, "async_sync_entities") as mock_sync,
patch.object(ga_helpers, "SYNC_DELAY", 0),
):
expose_entity(hass, light_entry.entity_id, True)
await hass.async_block_till_done()
async_fire_time_changed(hass, utcnow())
await hass.async_block_till_done()
assert len(mock_sync.mock_calls) == 1
with (
patch.object(config, "async_sync_entities") as mock_sync,
patch.object(ga_helpers, "SYNC_DELAY", 0),
):
expose_entity(hass, light_entry.entity_id, False)
expose_entity(hass, binary_sensor_entry.entity_id, True)
expose_entity(hass, sensor_entry.entity_id, True)
await hass.async_block_till_done()
async_fire_time_changed(hass, utcnow())
await hass.async_block_till_done()
assert len(mock_sync.mock_calls) == 1
@pytest.mark.usefixtures("mock_cloud_login")
async def test_google_entity_registry_sync(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
cloud_prefs: CloudPreferences,
) -> None:
"""Test Google config responds to entity registry."""
# Enable exposing new entities to Google
expose_new(hass, True)
config = CloudGoogleConfig(
hass, GACTIONS_SCHEMA({}), "mock-user-id", cloud_prefs, hass.data[DATA_CLOUD]
)
await config.async_initialize()
await config.async_connect_agent_user("mock-user-id")
with (
patch.object(config, "async_schedule_google_sync_all") as mock_sync,
patch.object(config, "async_sync_entities_all"),
patch.object(ga_helpers, "SYNC_DELAY", 0),
):
# Created entity
entry = entity_registry.async_get_or_create(
"light", "test", "unique", suggested_object_id="kitchen"
)
await hass.async_block_till_done()
assert len(mock_sync.mock_calls) == 1
# Removed entity
hass.bus.async_fire(
er.EVENT_ENTITY_REGISTRY_UPDATED,
{"action": "remove", "entity_id": entry.entity_id},
)
await hass.async_block_till_done()
assert len(mock_sync.mock_calls) == 2
# Entity registry updated with relevant changes
hass.bus.async_fire(
er.EVENT_ENTITY_REGISTRY_UPDATED,
{
"action": "update",
"entity_id": entry.entity_id,
"changes": ["entity_id"],
},
)
await hass.async_block_till_done()
assert len(mock_sync.mock_calls) == 3
# Entity registry updated with non-relevant changes
hass.bus.async_fire(
er.EVENT_ENTITY_REGISTRY_UPDATED,
{"action": "update", "entity_id": entry.entity_id, "changes": ["icon"]},
)
await hass.async_block_till_done()
assert len(mock_sync.mock_calls) == 3
# When hass is not started yet we wait till started
hass.set_state(CoreState.starting)
hass.bus.async_fire(
er.EVENT_ENTITY_REGISTRY_UPDATED,
{"action": "create", "entity_id": entry.entity_id},
)
await hass.async_block_till_done()
assert len(mock_sync.mock_calls) == 3
@pytest.mark.usefixtures("mock_cloud_login")
async def test_google_device_registry_sync(
hass: HomeAssistant,
entity_registry: er.EntityRegistry,
cloud_prefs: CloudPreferences,
) -> None:
"""Test Google config responds to device registry."""
config = CloudGoogleConfig(
hass, GACTIONS_SCHEMA({}), "mock-user-id", cloud_prefs, hass.data[DATA_CLOUD]
)
# Enable exposing new entities to Google
expose_new(hass, True)
entity_entry = entity_registry.async_get_or_create(
"light", "hue", "1234", device_id="1234"
)
entity_entry = entity_registry.async_update_entity(
entity_entry.entity_id, area_id="ABCD"
)
with patch.object(config, "async_sync_entities_all"):
await config.async_initialize()
await hass.async_block_till_done()
await config.async_connect_agent_user("mock-user-id")
await hass.async_block_till_done()
with patch.object(config, "async_schedule_google_sync_all") as mock_sync:
# Device registry updated with non-relevant changes
hass.bus.async_fire(
dr.EVENT_DEVICE_REGISTRY_UPDATED,
{
"action": "update",
"device_id": "1234",
"changes": ["manufacturer"],
},
)
await hass.async_block_till_done()
assert len(mock_sync.mock_calls) == 0
# Device registry updated with relevant changes
# but entity has area ID so not impacted
hass.bus.async_fire(
dr.EVENT_DEVICE_REGISTRY_UPDATED,
{
"action": "update",
"device_id": "1234",
"changes": ["area_id"],
},
)
await hass.async_block_till_done()
assert len(mock_sync.mock_calls) == 0
entity_registry.async_update_entity(entity_entry.entity_id, area_id=None)
# Device registry updated with relevant changes
# but entity has area ID so not impacted
hass.bus.async_fire(
dr.EVENT_DEVICE_REGISTRY_UPDATED,
{
"action": "update",
"device_id": "1234",
"changes": ["area_id"],
},
)
await hass.async_block_till_done()
assert len(mock_sync.mock_calls) == 1
@pytest.mark.usefixtures("mock_cloud_login")
async def test_sync_google_when_started(
hass: HomeAssistant, cloud_prefs: CloudPreferences
) -> None:
"""Test Google config syncs on init."""
config = CloudGoogleConfig(
hass, GACTIONS_SCHEMA({}), "mock-user-id", cloud_prefs, hass.data[DATA_CLOUD]
)
with patch.object(config, "async_sync_entities_all") as mock_sync:
await config.async_initialize()
await hass.async_block_till_done()
assert len(mock_sync.mock_calls) == 1
@pytest.mark.usefixtures("mock_cloud_login")
async def test_sync_google_on_home_assistant_start(
hass: HomeAssistant, cloud_prefs: CloudPreferences
) -> None:
"""Test Google config syncs when home assistant started."""
config = CloudGoogleConfig(
hass, GACTIONS_SCHEMA({}), "mock-user-id", cloud_prefs, hass.data[DATA_CLOUD]
)
hass.set_state(CoreState.not_running)
with patch.object(config, "async_sync_entities_all") as mock_sync:
await config.async_initialize()
await hass.async_block_till_done()
assert len(mock_sync.mock_calls) == 0
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
assert len(mock_sync.mock_calls) == 1
async def test_google_config_expose_entity_prefs(
hass: HomeAssistant,
mock_conf: CloudGoogleConfig,
cloud_prefs: CloudPreferences,
entity_registry: er.EntityRegistry,
) -> None:
"""Test Google config should expose using prefs."""
assert await async_setup_component(hass, "homeassistant", {})
entity_entry1 = entity_registry.async_get_or_create(
"light",
"test",
"light_config_id",
suggested_object_id="config_light",
entity_category=EntityCategory.CONFIG,
)
entity_entry2 = entity_registry.async_get_or_create(
"light",
"test",
"light_diagnostic_id",
suggested_object_id="diagnostic_light",
entity_category=EntityCategory.DIAGNOSTIC,
)
entity_entry3 = entity_registry.async_get_or_create(
"light",
"test",
"light_hidden_integration_id",
suggested_object_id="hidden_integration_light",
hidden_by=er.RegistryEntryHider.INTEGRATION,
)
entity_entry4 = entity_registry.async_get_or_create(
"light",
"test",
"light_hidden_user_id",
suggested_object_id="hidden_user_light",
hidden_by=er.RegistryEntryHider.USER,
)
entity_entry5 = entity_registry.async_get_or_create(
"light",
"test",
"light_basement_id",
suggested_object_id="basement",
)
entity_entry6 = entity_registry.async_get_or_create(
"light",
"test",
"light_entrance_id",
suggested_object_id="entrance",
)
expose_new(hass, True)
expose_entity(hass, entity_entry5.entity_id, False)
state = State("light.kitchen", "on")
state_config = State(entity_entry1.entity_id, "on")
state_diagnostic = State(entity_entry2.entity_id, "on")
state_hidden_integration = State(entity_entry3.entity_id, "on")
state_hidden_user = State(entity_entry4.entity_id, "on")
state_not_exposed = State(entity_entry5.entity_id, "on")
state_exposed_default = State(entity_entry6.entity_id, "on")
# an entity which is not in the entity registry can be exposed
expose_entity(hass, "light.kitchen", True)
assert mock_conf.should_expose(state)
# categorized and hidden entities should not be exposed
assert not mock_conf.should_expose(state_config)
assert not mock_conf.should_expose(state_diagnostic)
assert not mock_conf.should_expose(state_hidden_integration)
assert not mock_conf.should_expose(state_hidden_user)
# this has been hidden
assert not mock_conf.should_expose(state_not_exposed)
# exposed by default
assert mock_conf.should_expose(state_exposed_default)
expose_entity(hass, entity_entry5.entity_id, True)
assert mock_conf.should_expose(state_not_exposed)
expose_entity(hass, entity_entry5.entity_id, None)
assert not mock_conf.should_expose(state_not_exposed)
@pytest.mark.usefixtures("mock_expired_cloud_login")
def test_enabled_requires_valid_sub(
hass: HomeAssistant, cloud_prefs: CloudPreferences
) -> None:
"""Test that google config enabled requires a valid Cloud sub."""
assert cloud_prefs.google_enabled
assert hass.data[DATA_CLOUD].is_logged_in
assert hass.data[DATA_CLOUD].subscription_expired
config = CloudGoogleConfig(
hass, GACTIONS_SCHEMA({}), "mock-user-id", cloud_prefs, hass.data[DATA_CLOUD]
)
assert not config.enabled
async def test_setup_google_assistant(
hass: HomeAssistant, mock_conf: CloudGoogleConfig, cloud_prefs: CloudPreferences
) -> None:
"""Test that we set up the google_assistant integration if enabled in cloud."""
assert await async_setup_component(hass, "homeassistant", {})
mock_conf._cloud.subscription_expired = False
assert "google_assistant" not in hass.config.components
await mock_conf.async_initialize()
await hass.async_block_till_done()
assert "google_assistant" in hass.config.components
hass.config.components.remove("google_assistant")
await cloud_prefs.async_update()
await hass.async_block_till_done()
assert "google_assistant" in hass.config.components
@pytest.mark.usefixtures("mock_cloud_login")
async def test_google_handle_logout(
hass: HomeAssistant, cloud_prefs: CloudPreferences
) -> None:
"""Test Google config responds to logging out."""
gconf = CloudGoogleConfig(
hass, GACTIONS_SCHEMA({}), "mock-user-id", cloud_prefs, Mock(is_logged_in=False)
)
await gconf.async_initialize()
with patch(
"homeassistant.components.google_assistant.report_state.async_enable_report_state",
) as mock_enable:
gconf.async_enable_report_state()
await hass.async_block_till_done()
assert len(mock_enable.mock_calls) == 1
assert len(gconf._on_deinitialize) == 6
# This will trigger a prefs update when we logout.
await cloud_prefs.get_cloud_user()
with patch.object(
hass.data[DATA_CLOUD].auth,
"async_check_token",
side_effect=AssertionError("Should not be called"),
):
# Fake logging out; CloudClient.logout_cleanups sets username to None
# and deinitializes the Google config.
await cloud_prefs.async_set_username(None)
gconf.async_deinitialize()
await hass.async_block_till_done()
# Check listeners are removed:
assert not gconf._on_deinitialize
assert len(mock_enable.return_value.mock_calls) == 1
@pytest.mark.parametrize("google_settings_version", [1, 2])
async def test_google_config_migrate_expose_entity_prefs(
hass: HomeAssistant,
cloud_prefs: CloudPreferences,
entity_registry: er.EntityRegistry,
google_settings_version: int,
) -> None:
"""Test migrating Google entity config."""
hass.set_state(CoreState.not_running)
assert await async_setup_component(hass, "homeassistant", {})
hass.states.async_set("light.state_only", "on")
entity_exposed = entity_registry.async_get_or_create(
"light",
"test",
"light_exposed",
suggested_object_id="exposed",
)
entity_no_2fa_exposed = entity_registry.async_get_or_create(
"light",
"test",
"light_no_2fa_exposed",
suggested_object_id="no_2fa_exposed",
)
entity_migrated = entity_registry.async_get_or_create(
"light",
"test",
"light_migrated",
suggested_object_id="migrated",
)
entity_config = entity_registry.async_get_or_create(
"light",
"test",
"light_config",
suggested_object_id="config",
entity_category=EntityCategory.CONFIG,
)
entity_default = entity_registry.async_get_or_create(
"light",
"test",
"light_default",
suggested_object_id="default",
)
entity_blocked = entity_registry.async_get_or_create(
"group",
"test",
"group_all_locks",
suggested_object_id="all_locks",
)
assert entity_blocked.entity_id == "group.all_locks"
await cloud_prefs.async_update(
google_enabled=True,
google_report_state=False,
google_settings_version=google_settings_version,
)
expose_entity(hass, entity_migrated.entity_id, False)
cloud_prefs._prefs[PREF_GOOGLE_ENTITY_CONFIGS]["light.unknown"] = {
PREF_SHOULD_EXPOSE: True,
PREF_DISABLE_2FA: True,
}
cloud_prefs._prefs[PREF_GOOGLE_ENTITY_CONFIGS]["light.state_only"] = {
PREF_SHOULD_EXPOSE: False
}
cloud_prefs._prefs[PREF_GOOGLE_ENTITY_CONFIGS][entity_exposed.entity_id] = {
PREF_SHOULD_EXPOSE: True
}
cloud_prefs._prefs[PREF_GOOGLE_ENTITY_CONFIGS][entity_no_2fa_exposed.entity_id] = {
PREF_SHOULD_EXPOSE: True,
PREF_DISABLE_2FA: True,
}
cloud_prefs._prefs[PREF_GOOGLE_ENTITY_CONFIGS][entity_migrated.entity_id] = {
PREF_SHOULD_EXPOSE: True
}
conf = CloudGoogleConfig(
hass, GACTIONS_SCHEMA({}), "mock-user-id", cloud_prefs, Mock(is_logged_in=False)
)
await conf.async_initialize()
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
await hass.async_block_till_done()
assert async_get_entity_settings(hass, "light.unknown") == {
"cloud.google_assistant": {"disable_2fa": True, "should_expose": True}
}
assert async_get_entity_settings(hass, "light.state_only") == {
"cloud.google_assistant": {"should_expose": False}
}
assert async_get_entity_settings(hass, entity_exposed.entity_id) == {
"cloud.google_assistant": {"should_expose": True}
}
assert async_get_entity_settings(hass, entity_migrated.entity_id) == {
"cloud.google_assistant": {"should_expose": True}
}
assert async_get_entity_settings(hass, entity_no_2fa_exposed.entity_id) == {
"cloud.google_assistant": {"disable_2fa": True, "should_expose": True}
}
assert async_get_entity_settings(hass, entity_config.entity_id) == {
"cloud.google_assistant": {"should_expose": False}
}
assert async_get_entity_settings(hass, entity_default.entity_id) == {
"cloud.google_assistant": {"should_expose": True}
}
assert async_get_entity_settings(hass, entity_blocked.entity_id) == {
"cloud.google_assistant": {"should_expose": False}
}
async def test_google_config_migrate_expose_entity_prefs_v2_no_exposed(
hass: HomeAssistant,
cloud_prefs: CloudPreferences,
entity_registry: er.EntityRegistry,
) -> None:
"""Test migrating Google entity config from v2 to v3 when no entity is exposed."""
hass.set_state(CoreState.not_running)
assert await async_setup_component(hass, "homeassistant", {})
hass.states.async_set("light.state_only", "on")
entity_migrated = entity_registry.async_get_or_create(
"light",
"test",
"light_migrated",
suggested_object_id="migrated",
)
await cloud_prefs.async_update(
google_enabled=True,
google_report_state=False,
google_settings_version=2,
)
expose_entity(hass, "light.state_only", False)
expose_entity(hass, entity_migrated.entity_id, False)
cloud_prefs._prefs[PREF_GOOGLE_ENTITY_CONFIGS]["light.state_only"] = {
PREF_SHOULD_EXPOSE: True
}
cloud_prefs._prefs[PREF_GOOGLE_ENTITY_CONFIGS][entity_migrated.entity_id] = {
PREF_SHOULD_EXPOSE: True
}
conf = CloudGoogleConfig(
hass, GACTIONS_SCHEMA({}), "mock-user-id", cloud_prefs, Mock(is_logged_in=False)
)
await conf.async_initialize()
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
await hass.async_block_till_done()
assert async_get_entity_settings(hass, "light.state_only") == {
"cloud.google_assistant": {"should_expose": True}
}
assert async_get_entity_settings(hass, entity_migrated.entity_id) == {
"cloud.google_assistant": {"should_expose": True}
}
async def test_google_config_migrate_expose_entity_prefs_v2_exposed(
hass: HomeAssistant,
cloud_prefs: CloudPreferences,
entity_registry: er.EntityRegistry,
) -> None:
"""Test migrating Google entity config from v2 to v3 when an entity is exposed."""
hass.set_state(CoreState.not_running)
assert await async_setup_component(hass, "homeassistant", {})
hass.states.async_set("light.state_only", "on")
entity_migrated = entity_registry.async_get_or_create(
"light",
"test",
"light_migrated",
suggested_object_id="migrated",
)
await cloud_prefs.async_update(
google_enabled=True,
google_report_state=False,
google_settings_version=2,
)
expose_entity(hass, "light.state_only", False)
expose_entity(hass, entity_migrated.entity_id, True)
cloud_prefs._prefs[PREF_GOOGLE_ENTITY_CONFIGS]["light.state_only"] = {
PREF_SHOULD_EXPOSE: True
}
cloud_prefs._prefs[PREF_GOOGLE_ENTITY_CONFIGS][entity_migrated.entity_id] = {
PREF_SHOULD_EXPOSE: True
}
conf = CloudGoogleConfig(
hass, GACTIONS_SCHEMA({}), "mock-user-id", cloud_prefs, Mock(is_logged_in=False)
)
await conf.async_initialize()
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
await hass.async_block_till_done()
assert async_get_entity_settings(hass, "light.state_only") == {
"cloud.google_assistant": {"should_expose": False}
}
assert async_get_entity_settings(hass, entity_migrated.entity_id) == {
"cloud.google_assistant": {"should_expose": True}
}
async def test_google_config_migrate_expose_entity_prefs_default_none(
hass: HomeAssistant,
cloud_prefs: CloudPreferences,
entity_registry: er.EntityRegistry,
) -> None:
"""Test migrating Google entity config."""
hass.set_state(CoreState.not_running)
assert await async_setup_component(hass, "homeassistant", {})
entity_default = entity_registry.async_get_or_create(
"light",
"test",
"light_default",
suggested_object_id="default",
)
await cloud_prefs.async_update(
google_enabled=True,
google_report_state=False,
google_settings_version=1,
)
cloud_prefs._prefs[PREF_GOOGLE_DEFAULT_EXPOSE] = None
conf = CloudGoogleConfig(
hass, GACTIONS_SCHEMA({}), "mock-user-id", cloud_prefs, Mock(is_logged_in=False)
)
await conf.async_initialize()
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
await hass.async_block_till_done()
assert async_get_entity_settings(hass, entity_default.entity_id) == {
"cloud.google_assistant": {"should_expose": True}
}
async def test_google_config_migrate_expose_entity_prefs_default(
hass: HomeAssistant,
cloud_prefs: CloudPreferences,
entity_registry: er.EntityRegistry,
) -> None:
"""Test migrating Google entity config."""
hass.set_state(CoreState.not_running)
assert await async_setup_component(hass, "homeassistant", {})
binary_sensor_supported = entity_registry.async_get_or_create(
"binary_sensor",
"test",
"binary_sensor_supported",
original_device_class="door",
suggested_object_id="supported",
)
binary_sensor_unsupported = entity_registry.async_get_or_create(
"binary_sensor",
"test",
"binary_sensor_unsupported",
original_device_class="battery",
suggested_object_id="unsupported",
)
light = entity_registry.async_get_or_create(
"light",
"test",
"unique",
suggested_object_id="light",
)
sensor_supported = entity_registry.async_get_or_create(
"sensor",
"test",
"sensor_supported",
original_device_class="temperature",
suggested_object_id="supported",
)
sensor_unsupported = entity_registry.async_get_or_create(
"sensor",
"test",
"sensor_unsupported",
original_device_class="battery",
suggested_object_id="unsupported",
)
water_heater = entity_registry.async_get_or_create(
"water_heater",
"test",
"unique",
suggested_object_id="water_heater",
)
await cloud_prefs.async_update(
google_enabled=True,
google_report_state=False,
google_settings_version=1,
)
cloud_prefs._prefs[PREF_GOOGLE_DEFAULT_EXPOSE] = [
"binary_sensor",
"light",
"sensor",
"water_heater",
]
conf = CloudGoogleConfig(
hass, GACTIONS_SCHEMA({}), "mock-user-id", cloud_prefs, Mock(is_logged_in=False)
)
await conf.async_initialize()
hass.bus.async_fire(EVENT_HOMEASSISTANT_START)
await hass.async_block_till_done()
hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED)
await hass.async_block_till_done()
assert async_get_entity_settings(hass, binary_sensor_supported.entity_id) == {
"cloud.google_assistant": {"should_expose": True}
}
assert async_get_entity_settings(hass, binary_sensor_unsupported.entity_id) == {
"cloud.google_assistant": {"should_expose": False}
}
assert async_get_entity_settings(hass, light.entity_id) == {
"cloud.google_assistant": {"should_expose": True}
}
assert async_get_entity_settings(hass, sensor_supported.entity_id) == {
"cloud.google_assistant": {"should_expose": True}
}
assert async_get_entity_settings(hass, sensor_unsupported.entity_id) == {
"cloud.google_assistant": {"should_expose": False}
}
assert async_get_entity_settings(hass, water_heater.entity_id) == {
"cloud.google_assistant": {"should_expose": False}
}
@pytest.mark.usefixtures("mock_cloud_login")
async def test_google_config_get_agent_user_id(
hass: HomeAssistant, cloud_prefs: CloudPreferences
) -> None:
"""Test overridden get_agent_user_id_from_webhook method."""
config = CloudGoogleConfig(
hass, GACTIONS_SCHEMA({}), "mock-user-id", cloud_prefs, hass.data[DATA_CLOUD]
)
assert (
config.get_agent_user_id_from_webhook(cloud_prefs.google_local_webhook_id)
== config.agent_user_id
)
assert config.get_agent_user_id_from_webhook("other_id") != config.agent_user_id
@pytest.mark.usefixtures("mock_cloud_login")
async def test_google_config_get_agent_users(
hass: HomeAssistant, cloud_prefs: CloudPreferences
) -> None:
"""Test overridden async_get_agent_users method."""
username_mock = PropertyMock(return_value="blah")
# We should not call Cloud.username when not logged in
cloud_prefs._prefs["google_connected"] = True
assert cloud_prefs.google_connected
mock_cloud = Mock(is_logged_in=False)
type(mock_cloud).username = username_mock
config = CloudGoogleConfig(
hass, GACTIONS_SCHEMA({}), "mock-user-id", cloud_prefs, mock_cloud
)
assert config.async_get_agent_users() == ()
username_mock.assert_not_called()
# We should not call Cloud.username when not connected
cloud_prefs._prefs["google_connected"] = False
assert not cloud_prefs.google_connected
mock_cloud = Mock(is_logged_in=True)
type(mock_cloud).username = username_mock
config = CloudGoogleConfig(
hass, GACTIONS_SCHEMA({}), "mock-user-id", cloud_prefs, mock_cloud
)
assert config.async_get_agent_users() == ()
username_mock.assert_not_called()
# Logged in and connected
cloud_prefs._prefs["google_connected"] = True
assert cloud_prefs.google_connected
mock_cloud = Mock(is_logged_in=True)
type(mock_cloud).username = username_mock
config = CloudGoogleConfig(
hass, GACTIONS_SCHEMA({}), "mock-user-id", cloud_prefs, mock_cloud
)
assert config.async_get_agent_users() == ("blah",)
username_mock.assert_called()

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,307 @@
"""Test the cloud component."""
from collections.abc import Callable, Coroutine
from typing import Any
from unittest.mock import MagicMock, patch
import pytest
from homeassistant.components.cloud import (
CloudConnectionState,
CloudNotAvailable,
CloudNotConnected,
async_get_or_create_cloudhook,
async_listen_connection_change,
async_remote_ui_url,
)
from homeassistant.components.cloud.const import (
DATA_CLOUD,
DOMAIN,
MODE_DEV,
PREF_CLOUDHOOKS,
)
from homeassistant.components.cloud.prefs import STORAGE_KEY
from homeassistant.const import CONF_MODE, EVENT_HOMEASSISTANT_STOP
from homeassistant.core import Context, HomeAssistant
from homeassistant.exceptions import Unauthorized
from homeassistant.setup import async_setup_component
from tests.common import MockConfigEntry, MockUser
async def test_constructor_loads_info_from_config(hass: HomeAssistant) -> None:
"""Test non-dev mode loads info from SERVERS constant."""
with patch("hass_nabucasa.Cloud.initialize"):
result = await async_setup_component(
hass,
"cloud",
{
"http": {},
"cloud": {
CONF_MODE: MODE_DEV,
"cognito_client_id": "test-cognito_client_id",
"user_pool_id": "test-user_pool_id",
"region": "test-region",
"relayer_server": "test-relayer-server",
"accounts_server": "test-acounts-server",
"cloudhook_server": "test-cloudhook-server",
"alexa_server": "test-alexa-server",
"acme_server": "test-acme-server",
"remotestate_server": "test-remotestate-server",
},
},
)
assert result
cl = hass.data[DATA_CLOUD]
assert cl.mode == MODE_DEV
assert cl.cognito_client_id == "test-cognito_client_id"
assert cl.user_pool_id == "test-user_pool_id"
assert cl.region == "test-region"
assert cl.relayer_server == "test-relayer-server"
assert cl.iot.ws_server_url == "wss://test-relayer-server/websocket"
assert cl.accounts_server == "test-acounts-server"
assert cl.cloudhook_server == "test-cloudhook-server"
assert cl.alexa_server == "test-alexa-server"
assert cl.acme_server == "test-acme-server"
assert cl.remotestate_server == "test-remotestate-server"
@pytest.mark.usefixtures("mock_cloud_fixture")
async def test_remote_services(
hass: HomeAssistant, hass_read_only_user: MockUser
) -> None:
"""Setup cloud component and test services."""
cloud = hass.data[DATA_CLOUD]
assert hass.services.has_service(DOMAIN, "remote_connect")
assert hass.services.has_service(DOMAIN, "remote_disconnect")
with patch("hass_nabucasa.remote.RemoteUI.connect") as mock_connect:
await hass.services.async_call(DOMAIN, "remote_connect", blocking=True)
await hass.async_block_till_done()
assert mock_connect.called
assert cloud.client.remote_autostart
with patch("hass_nabucasa.remote.RemoteUI.disconnect") as mock_disconnect:
await hass.services.async_call(DOMAIN, "remote_disconnect", blocking=True)
await hass.async_block_till_done()
assert mock_disconnect.called
assert not cloud.client.remote_autostart
# Test admin access required
non_admin_context = Context(user_id=hass_read_only_user.id)
with (
patch("hass_nabucasa.remote.RemoteUI.connect") as mock_connect,
pytest.raises(Unauthorized),
):
await hass.services.async_call(
DOMAIN, "remote_connect", blocking=True, context=non_admin_context
)
assert mock_connect.called is False
with (
patch("hass_nabucasa.remote.RemoteUI.disconnect") as mock_disconnect,
pytest.raises(Unauthorized),
):
await hass.services.async_call(
DOMAIN, "remote_disconnect", blocking=True, context=non_admin_context
)
assert mock_disconnect.called is False
@pytest.mark.usefixtures("mock_cloud_fixture")
async def test_shutdown_event(hass: HomeAssistant) -> None:
"""Test if the cloud will stop on shutdown event."""
with patch("hass_nabucasa.Cloud.stop") as mock_stop:
hass.bus.async_fire(EVENT_HOMEASSISTANT_STOP)
await hass.async_block_till_done()
assert mock_stop.called
async def test_setup_existing_cloud_user(
hass: HomeAssistant, hass_storage: dict[str, Any]
) -> None:
"""Test setup with API push default data."""
user = await hass.auth.async_create_system_user("Cloud test")
hass_storage[STORAGE_KEY] = {"version": 1, "data": {"cloud_user": user.id}}
with patch("hass_nabucasa.Cloud.initialize"):
result = await async_setup_component(
hass,
"cloud",
{
"http": {},
"cloud": {
CONF_MODE: MODE_DEV,
"cognito_client_id": "test-cognito_client_id",
"user_pool_id": "test-user_pool_id",
"region": "test-region",
"relayer_server": "test-relayer-serer",
},
},
)
assert result
assert hass_storage[STORAGE_KEY]["data"]["cloud_user"] == user.id
@pytest.mark.usefixtures("mock_cloud_fixture")
async def test_on_connect(hass: HomeAssistant) -> None:
"""Test cloud on connect triggers."""
cl = hass.data[DATA_CLOUD]
assert len(cl.iot._on_connect) == 3
assert len(hass.states.async_entity_ids("binary_sensor")) == 0
cloud_states = []
def handle_state(cloud_state):
nonlocal cloud_states
cloud_states.append(cloud_state)
async_listen_connection_change(hass, handle_state)
assert "async_setup" in str(cl.iot._on_connect[-1])
await cl.iot._on_connect[-1]()
await hass.async_block_till_done()
assert len(hass.states.async_entity_ids("binary_sensor")) == 0
# The on_start callback discovers the binary sensor platform
assert "async_setup" in str(cl._on_start[-1])
await cl._on_start[-1]()
await hass.async_block_till_done()
assert len(hass.states.async_entity_ids("binary_sensor")) == 1
with patch("homeassistant.helpers.discovery.async_load_platform") as mock_load:
await cl._on_start[-1]()
await hass.async_block_till_done()
assert len(mock_load.mock_calls) == 0
assert len(cloud_states) == 1
assert cloud_states[-1] == CloudConnectionState.CLOUD_CONNECTED
await cl.iot._on_connect[-1]()
await hass.async_block_till_done()
assert len(cloud_states) == 2
assert cloud_states[-1] == CloudConnectionState.CLOUD_CONNECTED
assert len(cl.iot._on_disconnect) == 2
assert "async_setup" in str(cl.iot._on_disconnect[-1])
await cl.iot._on_disconnect[-1]()
await hass.async_block_till_done()
assert len(cloud_states) == 3
assert cloud_states[-1] == CloudConnectionState.CLOUD_DISCONNECTED
await cl.iot._on_disconnect[-1]()
await hass.async_block_till_done()
assert len(cloud_states) == 4
assert cloud_states[-1] == CloudConnectionState.CLOUD_DISCONNECTED
@pytest.mark.usefixtures("mock_cloud_fixture")
async def test_remote_ui_url(hass: HomeAssistant) -> None:
"""Test getting remote ui url."""
cl = hass.data[DATA_CLOUD]
# Not logged in
with pytest.raises(CloudNotAvailable):
async_remote_ui_url(hass)
with patch("homeassistant.components.cloud.async_is_logged_in", return_value=True):
# Remote not enabled
with pytest.raises(CloudNotAvailable):
async_remote_ui_url(hass)
with patch.object(cl.remote, "connect"):
await cl.client.prefs.async_update(remote_enabled=True)
await hass.async_block_till_done()
# No instance domain
with pytest.raises(CloudNotAvailable):
async_remote_ui_url(hass)
# Remote finished initializing
cl.client.prefs._prefs["remote_domain"] = "example.com"
assert async_remote_ui_url(hass) == "https://example.com"
async def test_async_get_or_create_cloudhook(
hass: HomeAssistant,
cloud: MagicMock,
set_cloud_prefs: Callable[[dict[str, Any]], Coroutine[Any, Any, None]],
) -> None:
"""Test async_get_or_create_cloudhook."""
assert await async_setup_component(hass, "cloud", {"cloud": {}})
await hass.async_block_till_done()
await cloud.login("test-user", "test-pass")
webhook_id = "mock-webhook-id"
cloudhook_url = "https://cloudhook.nabu.casa/abcdefg"
with patch(
"homeassistant.components.cloud.async_create_cloudhook",
return_value=cloudhook_url,
) as async_create_cloudhook_mock:
# create cloudhook as it does not exist
assert (await async_get_or_create_cloudhook(hass, webhook_id)) == cloudhook_url
async_create_cloudhook_mock.assert_called_once_with(hass, webhook_id)
await set_cloud_prefs(
{
PREF_CLOUDHOOKS: {
webhook_id: {
"webhook_id": webhook_id,
"cloudhook_id": "random-id",
"cloudhook_url": cloudhook_url,
"managed": True,
}
}
}
)
async_create_cloudhook_mock.reset_mock()
# get cloudhook as it exists
assert await async_get_or_create_cloudhook(hass, webhook_id) == cloudhook_url
async_create_cloudhook_mock.assert_not_called()
# Simulate logged out
await cloud.logout()
# Not logged in
with pytest.raises(CloudNotAvailable):
await async_get_or_create_cloudhook(hass, webhook_id)
# Simulate disconnected
cloud.iot.state = "disconnected"
# Not connected
with pytest.raises(CloudNotConnected):
await async_get_or_create_cloudhook(hass, webhook_id)
async def test_cloud_logout(
hass: HomeAssistant,
cloud: MagicMock,
) -> None:
"""Test cloud setup with existing config entry when user is logged out."""
assert cloud.is_logged_in is False
mock_config_entry = MockConfigEntry(domain=DOMAIN)
mock_config_entry.add_to_hass(hass)
assert await async_setup_component(hass, DOMAIN, {"cloud": {}})
await hass.async_block_till_done()
assert cloud.is_logged_in is False

View File

@@ -0,0 +1,176 @@
"""Test Cloud preferences."""
from typing import Any
from unittest.mock import ANY, MagicMock, patch
import pytest
from homeassistant.auth.const import GROUP_ID_ADMIN
from homeassistant.components.cloud.const import DOMAIN, PREF_TTS_DEFAULT_VOICE
from homeassistant.components.cloud.prefs import STORAGE_KEY, CloudPreferences
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
async def test_set_username(hass: HomeAssistant) -> None:
"""Test we clear config if we set different username."""
prefs = CloudPreferences(hass)
await prefs.async_initialize()
assert prefs.google_enabled
await prefs.async_update(google_enabled=False)
assert not prefs.google_enabled
await prefs.async_set_username("new-username")
assert prefs.google_enabled
async def test_erase_config(hass: HomeAssistant) -> None:
"""Test erasing config."""
prefs = CloudPreferences(hass)
await prefs.async_initialize()
assert prefs._prefs == {
**prefs._empty_config(""),
"google_local_webhook_id": ANY,
"instance_id": ANY,
}
await prefs.async_update(google_enabled=False)
assert prefs._prefs == {
**prefs._empty_config(""),
"google_enabled": False,
"google_local_webhook_id": ANY,
"instance_id": ANY,
}
await prefs.async_erase_config()
assert prefs._prefs == {
**prefs._empty_config(""),
"google_local_webhook_id": ANY,
"instance_id": ANY,
}
async def test_set_username_migration(hass: HomeAssistant) -> None:
"""Test we do not clear config if we had no username."""
prefs = CloudPreferences(hass)
with patch.object(prefs, "_empty_config", return_value=prefs._empty_config(None)):
await prefs.async_initialize()
assert prefs.google_enabled
await prefs.async_update(google_enabled=False)
assert not prefs.google_enabled
await prefs.async_set_username("new-username")
assert not prefs.google_enabled
async def test_set_new_username(
hass: HomeAssistant, hass_storage: dict[str, Any]
) -> None:
"""Test if setting new username returns true."""
hass_storage[STORAGE_KEY] = {"version": 1, "data": {"username": "old-user"}}
prefs = CloudPreferences(hass)
await prefs.async_initialize()
assert not await prefs.async_set_username("old-user")
assert await prefs.async_set_username("new-user")
async def test_load_invalid_cloud_user(
hass: HomeAssistant, hass_storage: dict[str, Any]
) -> None:
"""Test loading cloud user with invalid storage."""
hass_storage[STORAGE_KEY] = {"version": 1, "data": {"cloud_user": "non-existing"}}
prefs = CloudPreferences(hass)
await prefs.async_initialize()
cloud_user_id = await prefs.get_cloud_user()
assert cloud_user_id != "non-existing"
cloud_user = await hass.auth.async_get_user(
hass_storage[STORAGE_KEY]["data"]["cloud_user"]
)
assert cloud_user
assert cloud_user.groups[0].id == GROUP_ID_ADMIN
async def test_setup_remove_cloud_user(
hass: HomeAssistant, hass_storage: dict[str, Any]
) -> None:
"""Test creating and removing cloud user."""
hass_storage[STORAGE_KEY] = {"version": 1, "data": {"cloud_user": None}}
prefs = CloudPreferences(hass)
await prefs.async_initialize()
await prefs.async_set_username("user1")
cloud_user = await hass.auth.async_get_user(await prefs.get_cloud_user())
assert cloud_user
assert cloud_user.groups[0].id == GROUP_ID_ADMIN
await prefs.async_set_username("user2")
cloud_user2 = await hass.auth.async_get_user(await prefs.get_cloud_user())
assert cloud_user2
assert cloud_user2.groups[0].id == GROUP_ID_ADMIN
assert cloud_user2.id != cloud_user.id
@pytest.mark.parametrize(
("google_assistant_users", "google_connected"),
[([], False), (["cloud-user"], True), (["other-user"], False)],
)
async def test_import_google_assistant_settings(
hass: HomeAssistant,
hass_storage: dict[str, Any],
google_assistant_users: list[str],
google_connected: bool,
) -> None:
"""Test importing from the google assistant store."""
hass_storage[STORAGE_KEY] = {"version": 1, "data": {"username": "cloud-user"}}
with patch(
"homeassistant.components.cloud.prefs.async_get_google_assistant_users"
) as mock_get_users:
mock_get_users.return_value = google_assistant_users
prefs = CloudPreferences(hass)
await prefs.async_initialize()
assert prefs.google_connected == google_connected
@pytest.mark.parametrize(
("stored_language", "expected_language", "voice"),
[("en-US", "en-US", "GuyNeural"), ("missing_language", "en-US", "JennyNeural")],
)
async def test_tts_default_voice_legacy_gender(
hass: HomeAssistant,
cloud: MagicMock,
hass_storage: dict[str, Any],
stored_language: str,
expected_language: str,
voice: str,
) -> None:
"""Test tts with legacy gender as default tts voice setting in storage."""
hass_storage[STORAGE_KEY] = {
"version": 1,
"data": {PREF_TTS_DEFAULT_VOICE: [stored_language, "male"]},
}
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
await hass.async_block_till_done()
assert cloud.client.prefs.tts_default_voice == (expected_language, voice)

View File

@@ -0,0 +1,244 @@
"""Test cloud repairs."""
from datetime import timedelta
from http import HTTPStatus
from unittest.mock import patch
import pytest
from homeassistant.components.cloud.const import DOMAIN
from homeassistant.components.cloud.repairs import (
async_manage_legacy_subscription_issue,
)
from homeassistant.components.repairs import DOMAIN as REPAIRS_DOMAIN
from homeassistant.core import HomeAssistant
import homeassistant.helpers.issue_registry as ir
from homeassistant.setup import async_setup_component
from homeassistant.util import dt as dt_util
from . import mock_cloud
from tests.common import async_fire_time_changed
from tests.test_util.aiohttp import AiohttpClientMocker
from tests.typing import ClientSessionGenerator
async def test_do_not_create_repair_issues_at_startup_if_not_logged_in(
hass: HomeAssistant,
issue_registry: ir.IssueRegistry,
) -> None:
"""Test that we create repair issue at startup if we are logged in."""
with patch("homeassistant.components.cloud.Cloud.is_logged_in", False):
await mock_cloud(hass)
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1))
await hass.async_block_till_done()
assert not issue_registry.async_get_issue(
domain="cloud", issue_id="legacy_subscription"
)
@pytest.mark.usefixtures("mock_auth")
async def test_create_repair_issues_at_startup_if_logged_in(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
issue_registry: ir.IssueRegistry,
) -> None:
"""Test that we create repair issue at startup if we are logged in."""
aioclient_mock.get(
"https://accounts.nabucasa.com/payments/subscription_info",
json={"provider": "legacy"},
)
with patch("homeassistant.components.cloud.Cloud.is_logged_in", True):
await mock_cloud(hass)
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(hours=1))
await hass.async_block_till_done()
assert issue_registry.async_get_issue(
domain="cloud", issue_id="legacy_subscription"
)
async def test_legacy_subscription_delete_issue_if_no_longer_legacy(
hass: HomeAssistant,
issue_registry: ir.IssueRegistry,
) -> None:
"""Test that we delete the legacy subscription issue if no longer legacy."""
async_manage_legacy_subscription_issue(hass, {"provider": "legacy"})
assert issue_registry.async_get_issue(
domain="cloud", issue_id="legacy_subscription"
)
async_manage_legacy_subscription_issue(hass, {})
assert not issue_registry.async_get_issue(
domain="cloud", issue_id="legacy_subscription"
)
@pytest.mark.usefixtures("mock_auth")
async def test_legacy_subscription_repair_flow(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
hass_client: ClientSessionGenerator,
issue_registry: ir.IssueRegistry,
) -> None:
"""Test desired flow of the fix flow for legacy subscription."""
aioclient_mock.get(
"https://accounts.nabucasa.com/payments/subscription_info",
json={"provider": None},
)
aioclient_mock.post(
"https://accounts.nabucasa.com/payments/migrate_paypal_agreement",
json={"url": "https://paypal.com"},
)
async_manage_legacy_subscription_issue(hass, {"provider": "legacy"})
repair_issue = issue_registry.async_get_issue(
domain="cloud", issue_id="legacy_subscription"
)
assert repair_issue
assert await async_setup_component(hass, REPAIRS_DOMAIN, {REPAIRS_DOMAIN: {}})
await mock_cloud(hass)
await hass.async_block_till_done()
await hass.async_start()
client = await hass_client()
resp = await client.post(
"/api/repairs/issues/fix",
json={"handler": DOMAIN, "issue_id": repair_issue.issue_id},
)
assert resp.status == HTTPStatus.OK
data = await resp.json()
flow_id = data["flow_id"]
assert data == {
"type": "form",
"flow_id": flow_id,
"handler": DOMAIN,
"step_id": "confirm_change_plan",
"data_schema": [],
"errors": None,
"description_placeholders": None,
"last_step": None,
"preview": None,
}
resp = await client.post(f"/api/repairs/issues/fix/{flow_id}")
assert resp.status == HTTPStatus.OK
data = await resp.json()
flow_id = data["flow_id"]
assert data == {
"type": "external",
"flow_id": flow_id,
"handler": DOMAIN,
"step_id": "change_plan",
"url": "https://paypal.com",
"description_placeholders": None,
}
resp = await client.post(f"/api/repairs/issues/fix/{flow_id}")
assert resp.status == HTTPStatus.OK
data = await resp.json()
flow_id = data["flow_id"]
assert data == {
"type": "create_entry",
"flow_id": flow_id,
"handler": DOMAIN,
"description": None,
"description_placeholders": None,
}
assert not issue_registry.async_get_issue(
domain="cloud", issue_id="legacy_subscription"
)
@pytest.mark.usefixtures("mock_auth")
async def test_legacy_subscription_repair_flow_timeout(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
aioclient_mock: AiohttpClientMocker,
issue_registry: ir.IssueRegistry,
) -> None:
"""Test timeout flow of the fix flow for legacy subscription."""
aioclient_mock.post(
"https://accounts.nabucasa.com/payments/migrate_paypal_agreement",
status=403,
)
async_manage_legacy_subscription_issue(hass, {"provider": "legacy"})
repair_issue = issue_registry.async_get_issue(
domain="cloud", issue_id="legacy_subscription"
)
assert repair_issue
assert await async_setup_component(hass, REPAIRS_DOMAIN, {REPAIRS_DOMAIN: {}})
await mock_cloud(hass)
await hass.async_block_till_done()
await hass.async_start()
client = await hass_client()
resp = await client.post(
"/api/repairs/issues/fix",
json={"handler": DOMAIN, "issue_id": repair_issue.issue_id},
)
assert resp.status == HTTPStatus.OK
data = await resp.json()
flow_id = data["flow_id"]
assert data == {
"type": "form",
"flow_id": flow_id,
"handler": DOMAIN,
"step_id": "confirm_change_plan",
"data_schema": [],
"errors": None,
"description_placeholders": None,
"last_step": None,
"preview": None,
}
with patch("homeassistant.components.cloud.repairs.MAX_RETRIES", new=0):
resp = await client.post(f"/api/repairs/issues/fix/{flow_id}")
assert resp.status == HTTPStatus.OK
data = await resp.json()
flow_id = data["flow_id"]
assert data == {
"type": "external",
"flow_id": flow_id,
"handler": DOMAIN,
"step_id": "change_plan",
"url": "https://account.nabucasa.com/",
"description_placeholders": None,
}
resp = await client.post(f"/api/repairs/issues/fix/{flow_id}")
assert resp.status == HTTPStatus.OK
data = await resp.json()
flow_id = data["flow_id"]
assert data == {
"type": "abort",
"flow_id": flow_id,
"handler": "cloud",
"reason": "operation_took_too_long",
"description_placeholders": None,
"result": None,
}
assert issue_registry.async_get_issue(
domain="cloud", issue_id="legacy_subscription"
)

View File

@@ -0,0 +1,150 @@
"""Test the speech-to-text platform for the cloud integration."""
from collections.abc import AsyncGenerator
from copy import deepcopy
from http import HTTPStatus
from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch
from hass_nabucasa.voice import STTResponse, VoiceError
import pytest
from homeassistant.components.assist_pipeline.pipeline import STORAGE_KEY
from homeassistant.components.cloud.const import DOMAIN
from homeassistant.const import STATE_UNAVAILABLE, STATE_UNKNOWN
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from . import PIPELINE_DATA
from tests.typing import ClientSessionGenerator
@pytest.fixture(autouse=True)
async def delay_save_fixture() -> AsyncGenerator[None]:
"""Load the homeassistant integration."""
with patch("homeassistant.helpers.collection.SAVE_DELAY", new=0):
yield
@pytest.mark.parametrize(
("mock_process_stt", "expected_response_data"),
[
(
AsyncMock(return_value=STTResponse(True, "Turn the Kitchen Lights on")),
{"text": "Turn the Kitchen Lights on", "result": "success"},
),
(AsyncMock(side_effect=VoiceError("Boom!")), {"text": None, "result": "error"}),
],
)
async def test_cloud_speech(
hass: HomeAssistant,
cloud: MagicMock,
hass_client: ClientSessionGenerator,
mock_process_stt: AsyncMock,
expected_response_data: dict[str, Any],
) -> None:
"""Test cloud text-to-speech."""
cloud.voice.process_stt = mock_process_stt
assert await async_setup_component(hass, DOMAIN, {"cloud": {}})
await hass.async_block_till_done()
on_start_callback = cloud.register_on_start.call_args[0][0]
await on_start_callback()
state = hass.states.get("stt.home_assistant_cloud")
assert state
assert state.state == STATE_UNKNOWN
client = await hass_client()
response = await client.post(
"/api/stt/stt.home_assistant_cloud",
headers={
"X-Speech-Content": (
"format=wav; codec=pcm; sample_rate=16000; bit_rate=16; channel=1;"
" language=de-DE"
)
},
data=b"Test",
)
response_data = await response.json()
assert mock_process_stt.call_count == 1
assert (
mock_process_stt.call_args.kwargs["content_type"]
== "audio/wav; codecs=audio/pcm; samplerate=16000"
)
assert mock_process_stt.call_args.kwargs["language"] == "de-DE"
assert response.status == HTTPStatus.OK
assert response_data == expected_response_data
state = hass.states.get("stt.home_assistant_cloud")
assert state
assert state.state not in (STATE_UNAVAILABLE, STATE_UNKNOWN)
async def test_migrating_pipelines(
hass: HomeAssistant,
cloud: MagicMock,
hass_client: ClientSessionGenerator,
hass_storage: dict[str, Any],
) -> None:
"""Test migrating pipelines when cloud stt entity is added."""
entity_id = "stt.home_assistant_cloud"
cloud.voice.process_stt = AsyncMock(
return_value=STTResponse(True, "Turn the Kitchen Lights on")
)
hass_storage[STORAGE_KEY] = {
"version": 1,
"minor_version": 1,
"key": "assist_pipeline.pipelines",
"data": deepcopy(PIPELINE_DATA),
}
assert await async_setup_component(hass, "assist_pipeline", {})
assert await async_setup_component(hass, DOMAIN, {"cloud": {}})
await hass.async_block_till_done()
await cloud.login("test-user", "test-pass")
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_UNKNOWN
# The stt/tts engines should have been updated to the new cloud engine ids.
assert hass_storage[STORAGE_KEY]["data"]["items"][0]["stt_engine"] == entity_id
assert (
hass_storage[STORAGE_KEY]["data"]["items"][0]["tts_engine"]
== "tts.home_assistant_cloud"
)
# The other items should stay the same.
assert (
hass_storage[STORAGE_KEY]["data"]["items"][0]["conversation_engine"]
== "conversation_engine_1"
)
assert (
hass_storage[STORAGE_KEY]["data"]["items"][0]["conversation_language"]
== "language_1"
)
assert (
hass_storage[STORAGE_KEY]["data"]["items"][0]["id"]
== "01GX8ZWBAQYWNB1XV3EXEZ75DY"
)
assert hass_storage[STORAGE_KEY]["data"]["items"][0]["language"] == "language_1"
assert (
hass_storage[STORAGE_KEY]["data"]["items"][0]["name"] == "Home Assistant Cloud"
)
assert hass_storage[STORAGE_KEY]["data"]["items"][0]["stt_language"] == "language_1"
assert hass_storage[STORAGE_KEY]["data"]["items"][0]["tts_language"] == "language_1"
assert (
hass_storage[STORAGE_KEY]["data"]["items"][0]["tts_voice"]
== "Arnold Schwarzenegger"
)
assert hass_storage[STORAGE_KEY]["data"]["items"][0]["wake_word_entity"] is None
assert hass_storage[STORAGE_KEY]["data"]["items"][0]["wake_word_id"] is None
assert hass_storage[STORAGE_KEY]["data"]["items"][1] == PIPELINE_DATA["items"][1]
assert hass_storage[STORAGE_KEY]["data"]["items"][2] == PIPELINE_DATA["items"][2]

View File

@@ -0,0 +1,61 @@
"""Test cloud subscription functions."""
from unittest.mock import AsyncMock, Mock
from hass_nabucasa import Cloud
import pytest
from homeassistant.components.cloud.subscription import (
async_migrate_paypal_agreement,
async_subscription_info,
)
from homeassistant.core import HomeAssistant
from homeassistant.helpers.aiohttp_client import async_get_clientsession
from tests.test_util.aiohttp import AiohttpClientMocker
@pytest.fixture(name="mocked_cloud")
async def mocked_cloud_object(hass: HomeAssistant) -> Cloud:
"""Mock cloud object."""
return Mock(
accounts_server="accounts.nabucasa.com",
auth=Mock(async_check_token=AsyncMock()),
websession=async_get_clientsession(hass),
)
async def test_fetching_subscription_with_timeout_error(
aioclient_mock: AiohttpClientMocker,
caplog: pytest.LogCaptureFixture,
mocked_cloud: Cloud,
) -> None:
"""Test that we handle timeout error."""
aioclient_mock.get(
"https://accounts.nabucasa.com/payments/subscription_info",
exc=TimeoutError(),
)
assert await async_subscription_info(mocked_cloud) is None
assert (
"A timeout of 10 was reached while trying to fetch subscription information"
in caplog.text
)
async def test_migrate_paypal_agreement_with_timeout_error(
aioclient_mock: AiohttpClientMocker,
caplog: pytest.LogCaptureFixture,
mocked_cloud: Cloud,
) -> None:
"""Test that we handle timeout error."""
aioclient_mock.post(
"https://accounts.nabucasa.com/payments/migrate_paypal_agreement",
exc=TimeoutError(),
)
assert await async_migrate_paypal_agreement(mocked_cloud) is None
assert (
"A timeout of 10 was reached while trying to start agreement migration"
in caplog.text
)

View File

@@ -0,0 +1,83 @@
"""Test cloud system health."""
import asyncio
from collections.abc import Callable, Coroutine
from typing import Any
from unittest.mock import MagicMock
from aiohttp import ClientError
from hass_nabucasa.remote import CertificateStatus
from homeassistant.components.cloud.const import DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from tests.common import get_system_health_info
from tests.test_util.aiohttp import AiohttpClientMocker
async def test_cloud_system_health(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
cloud: MagicMock,
set_cloud_prefs: Callable[[dict[str, Any]], Coroutine[Any, Any, None]],
) -> None:
"""Test cloud system health."""
aioclient_mock.get("https://cloud.bla.com/status", text="")
aioclient_mock.get("https://cert-server/directory", text="")
aioclient_mock.get(
"https://cognito-idp.us-east-1.amazonaws.com/AAAA/.well-known/jwks.json",
exc=ClientError,
)
assert await async_setup_component(hass, "system_health", {})
assert await async_setup_component(
hass,
DOMAIN,
{
DOMAIN: {
"user_pool_id": "AAAA",
"region": "us-east-1",
"acme_server": "cert-server",
"relayer_server": "cloud.bla.com",
},
},
)
await hass.async_block_till_done()
await cloud.login("test-user", "test-pass")
cloud.remote.snitun_server = "us-west-1"
cloud.remote.certificate_status = CertificateStatus.READY
await cloud.client.async_system_message({"region": "xx-earth-616"})
await set_cloud_prefs(
{
"alexa_enabled": True,
"google_enabled": False,
"remote_enabled": True,
"cloud_ice_servers_enabled": True,
}
)
info = await get_system_health_info(hass, "cloud")
for key, val in info.items():
if asyncio.iscoroutine(val):
info[key] = await val
assert info == {
"logged_in": True,
"subscription_expiration": cloud.expiration_date,
"certificate_status": CertificateStatus.READY,
"relayer_connected": True,
"relayer_region": "xx-earth-616",
"remote_enabled": True,
"remote_connected": False,
"remote_server": "us-west-1",
"alexa_enabled": True,
"google_enabled": False,
"cloud_ice_servers_enabled": True,
"can_reach_cert_server": "ok",
"can_reach_cloud_auth": {"type": "failed", "error": "unreachable"},
"can_reach_cloud": "ok",
"instance_id": cloud.client.prefs.instance_id,
}

View File

@@ -0,0 +1,782 @@
"""Tests for cloud tts."""
from collections.abc import AsyncGenerator, Callable, Coroutine
from copy import deepcopy
from http import HTTPStatus
from typing import Any
from unittest.mock import AsyncMock, MagicMock, patch
from hass_nabucasa.voice import TTS_VOICES, VoiceError, VoiceTokenError
import pytest
import voluptuous as vol
from homeassistant.components.assist_pipeline.pipeline import STORAGE_KEY
from homeassistant.components.cloud.const import DEFAULT_TTS_DEFAULT_VOICE, DOMAIN
from homeassistant.components.cloud.tts import PLATFORM_SCHEMA, SUPPORT_LANGUAGES, Voice
from homeassistant.components.media_player import (
ATTR_MEDIA_CONTENT_ID,
DOMAIN as DOMAIN_MP,
SERVICE_PLAY_MEDIA,
)
from homeassistant.components.tts import (
ATTR_LANGUAGE,
ATTR_MEDIA_PLAYER_ENTITY_ID,
ATTR_MESSAGE,
DOMAIN as TTS_DOMAIN,
get_engine_instance,
)
from homeassistant.const import ATTR_ENTITY_ID, STATE_UNAVAILABLE, STATE_UNKNOWN
from homeassistant.core import HomeAssistant
from homeassistant.core_config import async_process_ha_core_config
from homeassistant.helpers import issue_registry as ir
from homeassistant.helpers.entity_registry import EntityRegistry
from homeassistant.setup import async_setup_component
from . import PIPELINE_DATA
from tests.common import async_mock_service
from tests.components.tts.common import get_media_source_url
from tests.typing import ClientSessionGenerator
@pytest.fixture(autouse=True)
async def delay_save_fixture() -> AsyncGenerator[None]:
"""Load the homeassistant integration."""
with patch("homeassistant.helpers.collection.SAVE_DELAY", new=0):
yield
@pytest.fixture(autouse=True)
async def internal_url_mock(hass: HomeAssistant) -> None:
"""Mock internal URL of the instance."""
await async_process_ha_core_config(
hass,
{"internal_url": "http://example.local:8123"},
)
def test_default_exists() -> None:
"""Test our default language exists."""
assert DEFAULT_TTS_DEFAULT_VOICE[0] in TTS_VOICES
assert DEFAULT_TTS_DEFAULT_VOICE[1] in TTS_VOICES[DEFAULT_TTS_DEFAULT_VOICE[0]]
def test_schema() -> None:
"""Test schema."""
assert "nl-NL" in SUPPORT_LANGUAGES
processed = PLATFORM_SCHEMA({"platform": "cloud", "language": "nl-NL"})
assert processed["gender"] == "female"
with pytest.raises(vol.Invalid):
PLATFORM_SCHEMA(
{"platform": "cloud", "language": "non-existing", "gender": "female"}
)
with pytest.raises(vol.Invalid):
PLATFORM_SCHEMA(
{"platform": "cloud", "language": "nl-NL", "gender": "not-supported"}
)
# Should not raise
PLATFORM_SCHEMA({"platform": "cloud", "language": "nl-NL", "gender": "female"})
PLATFORM_SCHEMA({"platform": "cloud"})
@pytest.mark.parametrize(
("engine_id", "platform_config"),
[
(
DOMAIN,
None,
),
(
DOMAIN,
{
"platform": DOMAIN,
"service_name": "yaml",
"language": "fr-FR",
"gender": "female",
},
),
(
"tts.home_assistant_cloud",
None,
),
],
)
async def test_prefs_default_voice(
hass: HomeAssistant,
cloud: MagicMock,
set_cloud_prefs: Callable[[dict[str, Any]], Coroutine[Any, Any, None]],
engine_id: str,
platform_config: dict[str, Any] | None,
) -> None:
"""Test cloud provider uses the preferences."""
assert await async_setup_component(hass, "homeassistant", {})
assert await async_setup_component(hass, TTS_DOMAIN, {TTS_DOMAIN: platform_config})
await hass.async_block_till_done()
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
await hass.async_block_till_done()
assert cloud.client.prefs.tts_default_voice == ("en-US", "JennyNeural")
on_start_callback = cloud.register_on_start.call_args[0][0]
await on_start_callback()
await hass.async_block_till_done()
engine = get_engine_instance(hass, engine_id)
assert engine is not None
# The platform config provider will be overridden by the discovery info provider.
assert engine.default_language == "en-US"
assert engine.default_options == {"audio_output": "mp3"}
await set_cloud_prefs({"tts_default_voice": ("nl-NL", "MaartenNeural")})
await hass.async_block_till_done()
assert engine.default_language == "nl-NL"
assert engine.default_options == {"audio_output": "mp3"}
async def test_deprecated_platform_config(
hass: HomeAssistant,
issue_registry: ir.IssueRegistry,
cloud: MagicMock,
) -> None:
"""Test cloud provider uses the preferences."""
assert await async_setup_component(
hass, TTS_DOMAIN, {TTS_DOMAIN: {"platform": DOMAIN}}
)
await hass.async_block_till_done()
issue = issue_registry.async_get_issue(DOMAIN, "deprecated_tts_platform_config")
assert issue is not None
assert issue.breaks_in_ha_version == "2024.9.0"
assert issue.is_fixable is False
assert issue.is_persistent is False
assert issue.severity == ir.IssueSeverity.WARNING
assert issue.translation_key == "deprecated_tts_platform_config"
@pytest.mark.parametrize(
"engine_id",
[
DOMAIN,
"tts.home_assistant_cloud",
],
)
async def test_provider_properties(
hass: HomeAssistant,
cloud: MagicMock,
engine_id: str,
) -> None:
"""Test cloud provider."""
assert await async_setup_component(hass, "homeassistant", {})
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
await hass.async_block_till_done()
on_start_callback = cloud.register_on_start.call_args[0][0]
await on_start_callback()
engine = get_engine_instance(hass, engine_id)
assert engine is not None
assert engine.supported_options == ["gender", "voice", "audio_output"]
assert "nl-NL" in engine.supported_languages
supported_voices = engine.async_get_supported_voices("nl-NL")
assert supported_voices is not None
assert Voice("ColetteNeural", "ColetteNeural") in supported_voices
supported_voices = engine.async_get_supported_voices("missing_language")
assert supported_voices is None
@pytest.mark.parametrize(
("data", "expected_url_suffix"),
[
({"platform": DOMAIN}, DOMAIN),
({"engine_id": DOMAIN}, DOMAIN),
({"engine_id": "tts.home_assistant_cloud"}, "tts.home_assistant_cloud"),
],
)
@pytest.mark.parametrize(
("mock_process_tts_return_value", "mock_process_tts_side_effect"),
[
(b"", None),
(None, VoiceError("Boom!")),
],
)
async def test_get_tts_audio(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
cloud: MagicMock,
data: dict[str, Any],
expected_url_suffix: str,
mock_process_tts_return_value: bytes | None,
mock_process_tts_side_effect: Exception | None,
) -> None:
"""Test cloud provider."""
mock_process_tts = AsyncMock(
return_value=mock_process_tts_return_value,
side_effect=mock_process_tts_side_effect,
)
cloud.voice.process_tts = mock_process_tts
assert await async_setup_component(hass, "homeassistant", {})
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
await hass.async_block_till_done()
on_start_callback = cloud.register_on_start.call_args[0][0]
await on_start_callback()
client = await hass_client()
with patch(
"homeassistant.components.tts.secrets.token_urlsafe", return_value="test_token"
):
url = "/api/tts_get_url"
data |= {"message": "There is someone at the door."}
req = await client.post(url, json=data)
assert req.status == HTTPStatus.OK
response = await req.json()
assert response == {
"url": ("http://example.local:8123/api/tts_proxy/test_token.mp3"),
"path": ("/api/tts_proxy/test_token.mp3"),
}
await hass.async_block_till_done()
assert mock_process_tts.call_count == 1
assert mock_process_tts.call_args is not None
assert mock_process_tts.call_args.kwargs["text"] == "There is someone at the door."
assert mock_process_tts.call_args.kwargs["language"] == "en-US"
assert mock_process_tts.call_args.kwargs["gender"] is None
assert mock_process_tts.call_args.kwargs["voice"] == "JennyNeural"
assert mock_process_tts.call_args.kwargs["output"] == "mp3"
@pytest.mark.parametrize(
("data", "expected_url_suffix"),
[
({"platform": DOMAIN}, DOMAIN),
({"engine_id": DOMAIN}, DOMAIN),
],
)
async def test_get_tts_audio_logged_out(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
cloud: MagicMock,
data: dict[str, Any],
expected_url_suffix: str,
) -> None:
"""Test cloud get tts audio when user is logged out."""
mock_process_tts = AsyncMock(
side_effect=VoiceTokenError("No token!"),
)
cloud.voice.process_tts = mock_process_tts
assert await async_setup_component(hass, "homeassistant", {})
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
await hass.async_block_till_done()
client = await hass_client()
with patch(
"homeassistant.components.tts.secrets.token_urlsafe", return_value="test_token"
):
url = "/api/tts_get_url"
data |= {"message": "There is someone at the door."}
req = await client.post(url, json=data)
assert req.status == HTTPStatus.OK
response = await req.json()
assert response == {
"url": ("http://example.local:8123/api/tts_proxy/test_token.mp3"),
"path": ("/api/tts_proxy/test_token.mp3"),
}
await hass.async_block_till_done()
assert mock_process_tts.call_count == 1
assert mock_process_tts.call_args is not None
assert mock_process_tts.call_args.kwargs["text"] == "There is someone at the door."
assert mock_process_tts.call_args.kwargs["language"] == "en-US"
assert mock_process_tts.call_args.kwargs["gender"] is None
assert mock_process_tts.call_args.kwargs["voice"] == "JennyNeural"
assert mock_process_tts.call_args.kwargs["output"] == "mp3"
@pytest.mark.parametrize(
("mock_process_tts_return_value", "mock_process_tts_side_effect"),
[
(b"", None),
(None, VoiceError("Boom!")),
],
)
async def test_tts_entity(
hass: HomeAssistant,
hass_client: ClientSessionGenerator,
entity_registry: EntityRegistry,
cloud: MagicMock,
mock_process_tts_return_value: bytes | None,
mock_process_tts_side_effect: Exception | None,
) -> None:
"""Test text-to-speech entity."""
mock_process_tts = AsyncMock(
return_value=mock_process_tts_return_value,
side_effect=mock_process_tts_side_effect,
)
cloud.voice.process_tts = mock_process_tts
assert await async_setup_component(hass, "homeassistant", {})
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
await hass.async_block_till_done()
on_start_callback = cloud.register_on_start.call_args[0][0]
await on_start_callback()
client = await hass_client()
entity_id = "tts.home_assistant_cloud"
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_UNKNOWN
with patch(
"homeassistant.components.tts.secrets.token_urlsafe", return_value="test_token"
):
url = "/api/tts_get_url"
data = {
"engine_id": entity_id,
"message": "There is someone at the door.",
}
req = await client.post(url, json=data)
assert req.status == HTTPStatus.OK
response = await req.json()
assert response == {
"url": ("http://example.local:8123/api/tts_proxy/test_token.mp3"),
"path": ("/api/tts_proxy/test_token.mp3"),
}
await hass.async_block_till_done()
assert mock_process_tts.call_count == 1
assert mock_process_tts.call_args is not None
assert mock_process_tts.call_args.kwargs["text"] == "There is someone at the door."
assert mock_process_tts.call_args.kwargs["language"] == "en-US"
assert mock_process_tts.call_args.kwargs["gender"] is None
assert mock_process_tts.call_args.kwargs["voice"] == "JennyNeural"
assert mock_process_tts.call_args.kwargs["output"] == "mp3"
state = hass.states.get(entity_id)
assert state
assert state.state not in (STATE_UNAVAILABLE, STATE_UNKNOWN)
# Test removing the entity
entity_registry.async_remove(entity_id)
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state is None
async def test_migrating_pipelines(
hass: HomeAssistant,
cloud: MagicMock,
hass_client: ClientSessionGenerator,
hass_storage: dict[str, Any],
) -> None:
"""Test migrating pipelines when cloud tts entity is added."""
entity_id = "tts.home_assistant_cloud"
mock_process_tts = AsyncMock(
return_value=b"",
)
cloud.voice.process_tts = mock_process_tts
hass_storage[STORAGE_KEY] = {
"version": 1,
"minor_version": 1,
"key": "assist_pipeline.pipelines",
"data": deepcopy(PIPELINE_DATA),
}
assert await async_setup_component(hass, "assist_pipeline", {})
assert await async_setup_component(hass, DOMAIN, {"cloud": {}})
await hass.async_block_till_done()
await cloud.login("test-user", "test-pass")
await hass.async_block_till_done()
state = hass.states.get(entity_id)
assert state
assert state.state == STATE_UNKNOWN
# The stt/tts engines should have been updated to the new cloud engine ids.
assert (
hass_storage[STORAGE_KEY]["data"]["items"][0]["stt_engine"]
== "stt.home_assistant_cloud"
)
assert hass_storage[STORAGE_KEY]["data"]["items"][0]["tts_engine"] == entity_id
# The other items should stay the same.
assert (
hass_storage[STORAGE_KEY]["data"]["items"][0]["conversation_engine"]
== "conversation_engine_1"
)
assert (
hass_storage[STORAGE_KEY]["data"]["items"][0]["conversation_language"]
== "language_1"
)
assert (
hass_storage[STORAGE_KEY]["data"]["items"][0]["id"]
== "01GX8ZWBAQYWNB1XV3EXEZ75DY"
)
assert hass_storage[STORAGE_KEY]["data"]["items"][0]["language"] == "language_1"
assert (
hass_storage[STORAGE_KEY]["data"]["items"][0]["name"] == "Home Assistant Cloud"
)
assert hass_storage[STORAGE_KEY]["data"]["items"][0]["stt_language"] == "language_1"
assert hass_storage[STORAGE_KEY]["data"]["items"][0]["tts_language"] == "language_1"
assert (
hass_storage[STORAGE_KEY]["data"]["items"][0]["tts_voice"]
== "Arnold Schwarzenegger"
)
assert hass_storage[STORAGE_KEY]["data"]["items"][0]["wake_word_entity"] is None
assert hass_storage[STORAGE_KEY]["data"]["items"][0]["wake_word_id"] is None
assert hass_storage[STORAGE_KEY]["data"]["items"][1] == PIPELINE_DATA["items"][1]
assert hass_storage[STORAGE_KEY]["data"]["items"][2] == PIPELINE_DATA["items"][2]
@pytest.mark.parametrize(
("data", "expected_url_suffix"),
[
({"platform": DOMAIN}, DOMAIN),
({"engine_id": DOMAIN}, DOMAIN),
({"engine_id": "tts.home_assistant_cloud"}, "tts.home_assistant_cloud"),
],
)
async def test_deprecated_voice(
hass: HomeAssistant,
issue_registry: ir.IssueRegistry,
cloud: MagicMock,
hass_client: ClientSessionGenerator,
data: dict[str, Any],
expected_url_suffix: str,
) -> None:
"""Test we create an issue when a deprecated voice is used for text-to-speech."""
language = "zh-CN"
deprecated_voice = "XiaoxuanNeural"
replacement_voice = "XiaozhenNeural"
mock_process_tts = AsyncMock(
return_value=b"",
)
cloud.voice.process_tts = mock_process_tts
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
await hass.async_block_till_done()
await cloud.login("test-user", "test-pass")
client = await hass_client()
# Test with non deprecated voice.
with patch(
"homeassistant.components.tts.secrets.token_urlsafe", return_value="test_token"
):
url = "/api/tts_get_url"
data |= {
"message": "There is someone at the door.",
"language": language,
"options": {"voice": replacement_voice},
}
req = await client.post(url, json=data)
assert req.status == HTTPStatus.OK
response = await req.json()
assert response == {
"url": ("http://example.local:8123/api/tts_proxy/test_token.mp3"),
"path": ("/api/tts_proxy/test_token.mp3"),
}
await hass.async_block_till_done()
assert mock_process_tts.call_count == 1
assert mock_process_tts.call_args is not None
assert mock_process_tts.call_args.kwargs["text"] == "There is someone at the door."
assert mock_process_tts.call_args.kwargs["language"] == language
assert mock_process_tts.call_args.kwargs["gender"] is None
assert mock_process_tts.call_args.kwargs["voice"] == replacement_voice
assert mock_process_tts.call_args.kwargs["output"] == "mp3"
issue = issue_registry.async_get_issue(
"cloud", f"deprecated_voice_{replacement_voice}"
)
assert issue is None
mock_process_tts.reset_mock()
# Test with deprecated voice.
data["options"] = {"voice": deprecated_voice}
with patch(
"homeassistant.components.tts.secrets.token_urlsafe", return_value="test_token"
):
req = await client.post(url, json=data)
assert req.status == HTTPStatus.OK
response = await req.json()
assert response == {
"url": ("http://example.local:8123/api/tts_proxy/test_token.mp3"),
"path": ("/api/tts_proxy/test_token.mp3"),
}
await hass.async_block_till_done()
issue_id = f"deprecated_voice_{deprecated_voice}"
assert mock_process_tts.call_count == 1
assert mock_process_tts.call_args is not None
assert mock_process_tts.call_args.kwargs["text"] == "There is someone at the door."
assert mock_process_tts.call_args.kwargs["language"] == language
assert mock_process_tts.call_args.kwargs["gender"] is None
assert mock_process_tts.call_args.kwargs["voice"] == replacement_voice
assert mock_process_tts.call_args.kwargs["output"] == "mp3"
issue = issue_registry.async_get_issue("cloud", issue_id)
assert issue is not None
assert issue.breaks_in_ha_version == "2024.8.0"
assert issue.is_fixable is True
assert issue.is_persistent is True
assert issue.severity == ir.IssueSeverity.WARNING
assert issue.translation_key == "deprecated_voice"
assert issue.translation_placeholders == {
"deprecated_voice": deprecated_voice,
"replacement_voice": replacement_voice,
}
resp = await client.post(
"/api/repairs/issues/fix",
json={"handler": DOMAIN, "issue_id": issue.issue_id},
)
assert resp.status == HTTPStatus.OK
data = await resp.json()
flow_id = data["flow_id"]
assert data == {
"type": "form",
"flow_id": flow_id,
"handler": DOMAIN,
"step_id": "confirm",
"data_schema": [],
"errors": None,
"description_placeholders": {
"deprecated_voice": "XiaoxuanNeural",
"replacement_voice": "XiaozhenNeural",
},
"last_step": None,
"preview": None,
}
resp = await client.post(f"/api/repairs/issues/fix/{flow_id}")
assert resp.status == HTTPStatus.OK
data = await resp.json()
flow_id = data["flow_id"]
assert data == {
"type": "create_entry",
"flow_id": flow_id,
"handler": DOMAIN,
"description": None,
"description_placeholders": None,
}
assert not issue_registry.async_get_issue(DOMAIN, issue_id)
@pytest.mark.parametrize(
("data", "expected_url_suffix"),
[
({"platform": DOMAIN}, DOMAIN),
({"engine_id": DOMAIN}, DOMAIN),
({"engine_id": "tts.home_assistant_cloud"}, "tts.home_assistant_cloud"),
],
)
async def test_deprecated_gender(
hass: HomeAssistant,
issue_registry: ir.IssueRegistry,
cloud: MagicMock,
hass_client: ClientSessionGenerator,
data: dict[str, Any],
expected_url_suffix: str,
) -> None:
"""Test we create an issue when a deprecated gender is used for text-to-speech."""
language = "zh-CN"
gender_option = "male"
mock_process_tts = AsyncMock(
return_value=b"",
)
cloud.voice.process_tts = mock_process_tts
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
await hass.async_block_till_done()
await cloud.login("test-user", "test-pass")
client = await hass_client()
# Test without deprecated gender option.
with patch(
"homeassistant.components.tts.secrets.token_urlsafe", return_value="test_token"
):
url = "/api/tts_get_url"
data |= {
"message": "There is someone at the door.",
"language": language,
}
req = await client.post(url, json=data)
assert req.status == HTTPStatus.OK
response = await req.json()
assert response == {
"url": ("http://example.local:8123/api/tts_proxy/test_token.mp3"),
"path": ("/api/tts_proxy/test_token.mp3"),
}
await hass.async_block_till_done()
assert mock_process_tts.call_count == 1
assert mock_process_tts.call_args is not None
assert mock_process_tts.call_args.kwargs["text"] == "There is someone at the door."
assert mock_process_tts.call_args.kwargs["language"] == language
assert mock_process_tts.call_args.kwargs["voice"] == "XiaoxiaoNeural"
assert mock_process_tts.call_args.kwargs["output"] == "mp3"
issue = issue_registry.async_get_issue("cloud", "deprecated_gender")
assert issue is None
mock_process_tts.reset_mock()
# Test with deprecated gender option.
data["options"] = {"gender": gender_option}
with patch(
"homeassistant.components.tts.secrets.token_urlsafe", return_value="test_token"
):
req = await client.post(url, json=data)
assert req.status == HTTPStatus.OK
response = await req.json()
assert response == {
"url": ("http://example.local:8123/api/tts_proxy/test_token.mp3"),
"path": ("/api/tts_proxy/test_token.mp3"),
}
await hass.async_block_till_done()
issue_id = "deprecated_gender"
assert mock_process_tts.call_count == 1
assert mock_process_tts.call_args is not None
assert mock_process_tts.call_args.kwargs["text"] == "There is someone at the door."
assert mock_process_tts.call_args.kwargs["language"] == language
assert mock_process_tts.call_args.kwargs["gender"] == gender_option
assert mock_process_tts.call_args.kwargs["voice"] == "XiaoxiaoNeural"
assert mock_process_tts.call_args.kwargs["output"] == "mp3"
issue = issue_registry.async_get_issue("cloud", issue_id)
assert issue is not None
assert issue.breaks_in_ha_version == "2024.10.0"
assert issue.is_fixable is True
assert issue.is_persistent is True
assert issue.severity == ir.IssueSeverity.WARNING
assert issue.translation_key == "deprecated_gender"
assert issue.translation_placeholders == {
"integration_name": "Home Assistant Cloud",
"deprecated_option": "gender",
"replacement_option": "voice",
}
resp = await client.post(
"/api/repairs/issues/fix",
json={"handler": DOMAIN, "issue_id": issue.issue_id},
)
assert resp.status == HTTPStatus.OK
data = await resp.json()
flow_id = data["flow_id"]
assert data == {
"type": "form",
"flow_id": flow_id,
"handler": DOMAIN,
"step_id": "confirm",
"data_schema": [],
"errors": None,
"description_placeholders": {
"integration_name": "Home Assistant Cloud",
"deprecated_option": "gender",
"replacement_option": "voice",
},
"last_step": None,
"preview": None,
}
resp = await client.post(f"/api/repairs/issues/fix/{flow_id}")
assert resp.status == HTTPStatus.OK
data = await resp.json()
flow_id = data["flow_id"]
assert data == {
"type": "create_entry",
"flow_id": flow_id,
"handler": DOMAIN,
"description": None,
"description_placeholders": None,
}
assert not issue_registry.async_get_issue(DOMAIN, issue_id)
@pytest.mark.parametrize(
("service", "service_data"),
[
(
"speak",
{
ATTR_ENTITY_ID: "tts.home_assistant_cloud",
ATTR_LANGUAGE: "id-ID",
ATTR_MEDIA_PLAYER_ENTITY_ID: "media_player.something",
ATTR_MESSAGE: "There is someone at the door.",
},
),
(
"cloud_say",
{
ATTR_ENTITY_ID: "media_player.something",
ATTR_LANGUAGE: "id-ID",
ATTR_MESSAGE: "There is someone at the door.",
},
),
],
)
async def test_tts_services(
hass: HomeAssistant,
cloud: MagicMock,
hass_client: ClientSessionGenerator,
service: str,
service_data: dict[str, Any],
) -> None:
"""Test tts services."""
calls = async_mock_service(hass, DOMAIN_MP, SERVICE_PLAY_MEDIA)
mock_process_tts = AsyncMock(return_value=b"")
cloud.voice.process_tts = mock_process_tts
assert await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
await hass.async_block_till_done()
await cloud.login("test-user", "test-pass")
client = await hass_client()
await hass.services.async_call(
domain=TTS_DOMAIN,
service=service,
service_data=service_data,
blocking=True,
)
assert len(calls) == 1
url = await get_media_source_url(hass, calls[0].data[ATTR_MEDIA_CONTENT_ID])
await hass.async_block_till_done()
response = await client.get(url)
assert response.status == HTTPStatus.OK
await hass.async_block_till_done()
assert mock_process_tts.call_count == 1
assert mock_process_tts.call_args is not None
assert mock_process_tts.call_args.kwargs["text"] == "There is someone at the door."
assert mock_process_tts.call_args.kwargs["language"] == service_data[ATTR_LANGUAGE]
assert mock_process_tts.call_args.kwargs["voice"] == "GadisNeural"
assert mock_process_tts.call_args.kwargs["output"] == "mp3"