Google assistant storage of connected agents (#29158)
* Make async_report_state take agent_user_id * Attempt to store synced agents * Drop now not needed initialization * Make sure cloud uses the all sync on changed preferences * Some more places to use all version of sync * Get the agent_user_id from the request context if available * Minor cleanup * Remove the old fixed agent_user_id for cloud Instead pass along cloud_user where appropriate. * async_delay_save takes a function * Adjust test for delayed store * Remove unused save function * Add login check.
This commit is contained in:
1 parent
434b783b4c
commit
2569c4ae37
16 files changed
+260
-83
No files matched your search
@@ -1,7 +1,18 @@
|
||||
"""Tests for the Google Assistant integration."""
|
||||
from asynctest.mock import MagicMock
|
||||
from homeassistant.components.google_assistant import helpers
|
||||
|
||||
|
||||
def mock_google_config_store(agent_user_ids=None):
|
||||
"""Fake a storage for google assistant."""
|
||||
store = MagicMock(spec=helpers.GoogleConfigStore)
|
||||
if agent_user_ids is not None:
|
||||
store.agent_user_ids = agent_user_ids
|
||||
else:
|
||||
store.agent_user_ids = {}
|
||||
return store
|
||||
|
||||
|
||||
class MockConfig(helpers.AbstractConfig):
|
||||
"""Fake config that always exposes everything."""
|
||||
|
||||
@@ -15,6 +26,7 @@ class MockConfig(helpers.AbstractConfig):
|
||||
local_sdk_webhook_id=None,
|
||||
local_sdk_user_id=None,
|
||||
enabled=True,
|
||||
agent_user_ids=None,
|
||||
):
|
||||
"""Initialize config."""
|
||||
super().__init__(hass)
|
||||
@@ -24,6 +36,7 @@ class MockConfig(helpers.AbstractConfig):
|
||||
self._local_sdk_webhook_id = local_sdk_webhook_id
|
||||
self._local_sdk_user_id = local_sdk_user_id
|
||||
self._enabled = enabled
|
||||
self._store = mock_google_config_store(agent_user_ids)
|
||||
|
||||
@property
|
||||
def enabled(self):
|
||||
|
||||
@@ -1,11 +1,18 @@
|
||||
"""Test Google Assistant helpers."""
|
||||
from unittest.mock import Mock
|
||||
from asynctest.mock import Mock, patch, call
|
||||
from datetime import timedelta
|
||||
import pytest
|
||||
from homeassistant.setup import async_setup_component
|
||||
from homeassistant.components.google_assistant import helpers
|
||||
from homeassistant.components.google_assistant.const import EVENT_COMMAND_RECEIVED
|
||||
from homeassistant.util import dt
|
||||
from . import MockConfig
|
||||
|
||||
from tests.common import async_capture_events, async_mock_service
|
||||
from tests.common import (
|
||||
async_capture_events,
|
||||
async_mock_service,
|
||||
async_fire_time_changed,
|
||||
)
|
||||
|
||||
|
||||
async def test_google_entity_sync_serialize_with_local_sdk(hass):
|
||||
@@ -19,13 +26,13 @@ async def test_google_entity_sync_serialize_with_local_sdk(hass):
|
||||
)
|
||||
entity = helpers.GoogleEntity(hass, config, hass.states.get("light.ceiling_lights"))
|
||||
|
||||
serialized = await entity.sync_serialize()
|
||||
serialized = await entity.sync_serialize(None)
|
||||
assert "otherDeviceIds" not in serialized
|
||||
assert "customData" not in serialized
|
||||
|
||||
config.async_enable_local_sdk()
|
||||
|
||||
serialized = await entity.sync_serialize()
|
||||
serialized = await entity.sync_serialize(None)
|
||||
assert serialized["otherDeviceIds"] == [{"deviceId": "light.ceiling_lights"}]
|
||||
assert serialized["customData"] == {
|
||||
"httpPort": 1234,
|
||||
@@ -128,3 +135,84 @@ async def test_config_local_sdk_if_disabled(hass, hass_client):
|
||||
resp = await client.post("/api/webhook/mock-webhook-id")
|
||||
assert resp.status == 200
|
||||
assert await resp.read() == b""
|
||||
|
||||
|
||||
async def test_agent_user_id_storage(hass, hass_storage):
|
||||
"""Test a disconnect message."""
|
||||
|
||||
hass_storage["google_assistant"] = {
|
||||
"version": 1,
|
||||
"key": "google_assistant",
|
||||
"data": {"agent_user_ids": {"agent_1": {}}},
|
||||
}
|
||||
|
||||
store = helpers.GoogleConfigStore(hass)
|
||||
await store.async_load()
|
||||
|
||||
assert hass_storage["google_assistant"] == {
|
||||
"version": 1,
|
||||
"key": "google_assistant",
|
||||
"data": {"agent_user_ids": {"agent_1": {}}},
|
||||
}
|
||||
|
||||
async def _check_after_delay(data):
|
||||
async_fire_time_changed(hass, dt.utcnow() + timedelta(seconds=2))
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert hass_storage["google_assistant"] == {
|
||||
"version": 1,
|
||||
"key": "google_assistant",
|
||||
"data": data,
|
||||
}
|
||||
|
||||
store.add_agent_user_id("agent_2")
|
||||
await _check_after_delay({"agent_user_ids": {"agent_1": {}, "agent_2": {}}})
|
||||
|
||||
store.pop_agent_user_id("agent_1")
|
||||
await _check_after_delay({"agent_user_ids": {"agent_2": {}}})
|
||||
|
||||
|
||||
async def test_agent_user_id_connect():
|
||||
"""Test the connection and disconnection of users."""
|
||||
config = MockConfig()
|
||||
store = config._store
|
||||
|
||||
await config.async_connect_agent_user("agent_2")
|
||||
assert store.add_agent_user_id.call_args == call("agent_2")
|
||||
|
||||
await config.async_connect_agent_user("agent_1")
|
||||
assert store.add_agent_user_id.call_args == call("agent_1")
|
||||
|
||||
await config.async_disconnect_agent_user("agent_2")
|
||||
assert store.pop_agent_user_id.call_args == call("agent_2")
|
||||
|
||||
await config.async_disconnect_agent_user("agent_1")
|
||||
assert store.pop_agent_user_id.call_args == call("agent_1")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("agents", [{}, {"1"}, {"1", "2"}])
|
||||
async def test_report_state_all(agents):
|
||||
"""Test a disconnect message."""
|
||||
config = MockConfig(agent_user_ids=agents)
|
||||
data = {}
|
||||
with patch.object(config, "async_report_state") as mock:
|
||||
await config.async_report_state_all(data)
|
||||
assert sorted(mock.mock_calls) == sorted(
|
||||
[call(data, agent) for agent in agents]
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
"agents, result", [({}, 204), ({"1": 200}, 200), ({"1": 200, "2": 300}, 300)],
|
||||
)
|
||||
async def test_sync_entities_all(agents, result):
|
||||
"""Test sync entities ."""
|
||||
config = MockConfig(agent_user_ids=set(agents.keys()))
|
||||
with patch.object(
|
||||
config,
|
||||
"async_sync_entities",
|
||||
side_effect=lambda agent_user_id: agents[agent_user_id],
|
||||
) as mock:
|
||||
res = await config.async_sync_entities_all()
|
||||
assert sorted(mock.mock_calls) == sorted([call(agent) for agent in agents])
|
||||
assert res == result
|
||||
@@ -12,7 +12,6 @@ from homeassistant.components.google_assistant.const import (
|
||||
REPORT_STATE_BASE_URL,
|
||||
HOMEGRAPH_TOKEN_URL,
|
||||
)
|
||||
from homeassistant.auth.models import User
|
||||
|
||||
DUMMY_CONFIG = GOOGLE_ASSISTANT_SCHEMA(
|
||||
{
|
||||
@@ -67,6 +66,7 @@ async def test_update_access_token(hass):
|
||||
jwt = "dummyjwt"
|
||||
|
||||
config = GoogleConfig(hass, DUMMY_CONFIG)
|
||||
await config.async_initialize()
|
||||
|
||||
base_time = datetime(2019, 10, 14, tzinfo=timezone.utc)
|
||||
with patch(
|
||||
@@ -99,6 +99,8 @@ async def test_update_access_token(hass):
|
||||
async def test_call_homegraph_api(hass, aioclient_mock, hass_storage):
|
||||
"""Test the function to call the homegraph api."""
|
||||
config = GoogleConfig(hass, DUMMY_CONFIG)
|
||||
await config.async_initialize()
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.google_assistant.http._get_homegraph_token"
|
||||
) as mock_get_token:
|
||||
@@ -120,6 +122,8 @@ async def test_call_homegraph_api(hass, aioclient_mock, hass_storage):
|
||||
async def test_call_homegraph_api_retry(hass, aioclient_mock, hass_storage):
|
||||
"""Test the that the calls get retried with new token on 401."""
|
||||
config = GoogleConfig(hass, DUMMY_CONFIG)
|
||||
await config.async_initialize()
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.google_assistant.http._get_homegraph_token"
|
||||
) as mock_get_token:
|
||||
@@ -143,8 +147,10 @@ async def test_call_homegraph_api_retry(hass, aioclient_mock, hass_storage):
|
||||
async def test_call_homegraph_api_key(hass, aioclient_mock, hass_storage):
|
||||
"""Test the function to call the homegraph api."""
|
||||
config = GoogleConfig(
|
||||
hass, GOOGLE_ASSISTANT_SCHEMA({"project_id": "1234", "api_key": "dummy_key"})
|
||||
hass, GOOGLE_ASSISTANT_SCHEMA({"project_id": "1234", "api_key": "dummy_key"}),
|
||||
)
|
||||
await config.async_initialize()
|
||||
|
||||
aioclient_mock.post(MOCK_URL, status=200, json={})
|
||||
|
||||
res = await config.async_call_homegraph_api_key(MOCK_URL, MOCK_JSON)
|
||||
@@ -159,8 +165,10 @@ async def test_call_homegraph_api_key(hass, aioclient_mock, hass_storage):
|
||||
async def test_call_homegraph_api_key_fail(hass, aioclient_mock, hass_storage):
|
||||
"""Test the function to call the homegraph api."""
|
||||
config = GoogleConfig(
|
||||
hass, GOOGLE_ASSISTANT_SCHEMA({"project_id": "1234", "api_key": "dummy_key"})
|
||||
hass, GOOGLE_ASSISTANT_SCHEMA({"project_id": "1234", "api_key": "dummy_key"}),
|
||||
)
|
||||
await config.async_initialize()
|
||||
|
||||
aioclient_mock.post(MOCK_URL, status=666, json={})
|
||||
|
||||
res = await config.async_call_homegraph_api_key(MOCK_URL, MOCK_JSON)
|
||||
@@ -170,17 +178,16 @@ async def test_call_homegraph_api_key_fail(hass, aioclient_mock, hass_storage):
|
||||
|
||||
async def test_report_state(hass, aioclient_mock, hass_storage):
|
||||
"""Test the report state function."""
|
||||
agent_user_id = "user"
|
||||
config = GoogleConfig(hass, DUMMY_CONFIG)
|
||||
await config.async_initialize()
|
||||
|
||||
await config.async_connect_agent_user(agent_user_id)
|
||||
message = {"devices": {}}
|
||||
owner = User(name="Test User", perm_lookup=None, groups=[], is_owner=True)
|
||||
|
||||
with patch.object(config, "async_call_homegraph_api") as mock_call, patch.object(
|
||||
hass.auth, "async_get_owner"
|
||||
) as mock_get_owner:
|
||||
mock_get_owner.return_value = owner
|
||||
|
||||
await config.async_report_state(message)
|
||||
with patch.object(config, "async_call_homegraph_api") as mock_call:
|
||||
await config.async_report_state(message, agent_user_id)
|
||||
mock_call.assert_called_once_with(
|
||||
REPORT_STATE_BASE_URL,
|
||||
{"requestId": ANY, "agentUserId": owner.id, "payload": message},
|
||||
{"requestId": ANY, "agentUserId": agent_user_id, "payload": message},
|
||||
)
|
||||
@@ -16,7 +16,7 @@ async def test_report_state(hass, caplog):
|
||||
hass.states.async_set("switch.ac", "on")
|
||||
|
||||
with patch.object(
|
||||
BASIC_CONFIG, "async_report_state", side_effect=mock_coro
|
||||
BASIC_CONFIG, "async_report_state_all", side_effect=mock_coro
|
||||
) as mock_report, patch.object(report_state, "INITIAL_REPORT_DELAY", 0):
|
||||
unsub = report_state.async_enable_report_state(hass, BASIC_CONFIG)
|
||||
|
||||
@@ -35,7 +35,7 @@ async def test_report_state(hass, caplog):
|
||||
}
|
||||
|
||||
with patch.object(
|
||||
BASIC_CONFIG, "async_report_state", side_effect=mock_coro
|
||||
BASIC_CONFIG, "async_report_state_all", side_effect=mock_coro
|
||||
) as mock_report:
|
||||
hass.states.async_set("light.kitchen", "on")
|
||||
await hass.async_block_till_done()
|
||||
@@ -48,7 +48,7 @@ async def test_report_state(hass, caplog):
|
||||
# Test that state changes that change something that Google doesn't care about
|
||||
# do not trigger a state report.
|
||||
with patch.object(
|
||||
BASIC_CONFIG, "async_report_state", side_effect=mock_coro
|
||||
BASIC_CONFIG, "async_report_state_all", side_effect=mock_coro
|
||||
) as mock_report:
|
||||
hass.states.async_set(
|
||||
"light.kitchen", "on", {"irrelevant": "should_be_ignored"}
|
||||
@@ -59,7 +59,7 @@ async def test_report_state(hass, caplog):
|
||||
|
||||
# Test that entities that we can't query don't report a state
|
||||
with patch.object(
|
||||
BASIC_CONFIG, "async_report_state", side_effect=mock_coro
|
||||
BASIC_CONFIG, "async_report_state_all", side_effect=mock_coro
|
||||
) as mock_report, patch(
|
||||
"homeassistant.components.google_assistant.report_state.GoogleEntity.query_serialize",
|
||||
side_effect=error.SmartHomeError("mock-error", "mock-msg"),
|
||||
@@ -73,7 +73,7 @@ async def test_report_state(hass, caplog):
|
||||
unsub()
|
||||
|
||||
with patch.object(
|
||||
BASIC_CONFIG, "async_report_state", side_effect=mock_coro
|
||||
BASIC_CONFIG, "async_report_state_all", side_effect=mock_coro
|
||||
) as mock_report:
|
||||
hass.states.async_set("light.kitchen", "on")
|
||||
await hass.async_block_till_done()
|
||||
|
||||
@@ -455,7 +455,7 @@ async def test_serialize_input_boolean(hass):
|
||||
state = State("input_boolean.bla", "on")
|
||||
# pylint: disable=protected-access
|
||||
entity = sh.GoogleEntity(hass, BASIC_CONFIG, state)
|
||||
result = await entity.sync_serialize()
|
||||
result = await entity.sync_serialize(None)
|
||||
assert result == {
|
||||
"id": "input_boolean.bla",
|
||||
"attributes": {},
|
||||
@@ -664,8 +664,8 @@ async def test_query_disconnect(hass):
|
||||
config.async_enable_report_state()
|
||||
assert config._unsub_report_state is not None
|
||||
with patch.object(
|
||||
config, "async_deactivate_report_state", side_effect=mock_coro
|
||||
) as mock_deactivate:
|
||||
config, "async_disconnect_agent_user", side_effect=mock_coro
|
||||
) as mock_disconnect:
|
||||
result = await sh.async_handle_message(
|
||||
hass,
|
||||
config,
|
||||
@@ -673,7 +673,7 @@ async def test_query_disconnect(hass):
|
||||
{"inputs": [{"intent": "action.devices.DISCONNECT"}], "requestId": REQ_ID},
|
||||
)
|
||||
assert result is None
|
||||
assert len(mock_deactivate.mock_calls) == 1
|
||||
assert len(mock_disconnect.mock_calls) == 1
|
||||
|
||||
|
||||
async def test_trait_execute_adding_query_data(hass):
|
||||
@@ -741,10 +741,12 @@ async def test_trait_execute_adding_query_data(hass):
|
||||
|
||||
async def test_identify(hass):
|
||||
"""Test identify message."""
|
||||
user_agent_id = "mock-user-id"
|
||||
proxy_device_id = user_agent_id
|
||||
result = await sh.async_handle_message(
|
||||
hass,
|
||||
BASIC_CONFIG,
|
||||
None,
|
||||
user_agent_id,
|
||||
{
|
||||
"requestId": REQ_ID,
|
||||
"inputs": [
|
||||
@@ -778,7 +780,7 @@ async def test_identify(hass):
|
||||
"customData": {
|
||||
"httpPort": 8123,
|
||||
"httpSSL": False,
|
||||
"proxyDeviceId": BASIC_CONFIG.agent_user_id,
|
||||
"proxyDeviceId": proxy_device_id,
|
||||
"webhookId": "dde3b9800a905e886cc4d38e226a6e7e3f2a6993d2b9b9f63d13e42ee7de3219",
|
||||
},
|
||||
}
|
||||
@@ -790,7 +792,7 @@ async def test_identify(hass):
|
||||
"requestId": REQ_ID,
|
||||
"payload": {
|
||||
"device": {
|
||||
"id": BASIC_CONFIG.agent_user_id,
|
||||
"id": proxy_device_id,
|
||||
"isLocalOnly": True,
|
||||
"isProxy": True,
|
||||
"deviceInfo": {
|
||||
@@ -822,10 +824,13 @@ async def test_reachable_devices(hass):
|
||||
should_expose=lambda state: state.entity_id != "light.not_expose"
|
||||
)
|
||||
|
||||
user_agent_id = "mock-user-id"
|
||||
proxy_device_id = user_agent_id
|
||||
|
||||
result = await sh.async_handle_message(
|
||||
hass,
|
||||
config,
|
||||
None,
|
||||
user_agent_id,
|
||||
{
|
||||
"requestId": REQ_ID,
|
||||
"inputs": [
|
||||
@@ -834,7 +839,7 @@ async def test_reachable_devices(hass):
|
||||
"payload": {
|
||||
"device": {
|
||||
"proxyDevice": {
|
||||
"id": "6a04f0f7-6125-4356-a846-861df7e01497",
|
||||
"id": proxy_device_id,
|
||||
"customData": "{}",
|
||||
"proxyData": "{}",
|
||||
}
|
||||
@@ -849,7 +854,7 @@ async def test_reachable_devices(hass):
|
||||
"customData": {
|
||||
"httpPort": 8123,
|
||||
"httpSSL": False,
|
||||
"proxyDeviceId": BASIC_CONFIG.agent_user_id,
|
||||
"proxyDeviceId": proxy_device_id,
|
||||
"webhookId": "dde3b9800a905e886cc4d38e226a6e7e3f2a6993d2b9b9f63d13e42ee7de3219",
|
||||
},
|
||||
},
|
||||
@@ -858,11 +863,11 @@ async def test_reachable_devices(hass):
|
||||
"customData": {
|
||||
"httpPort": 8123,
|
||||
"httpSSL": False,
|
||||
"proxyDeviceId": BASIC_CONFIG.agent_user_id,
|
||||
"proxyDeviceId": proxy_device_id,
|
||||
"webhookId": "dde3b9800a905e886cc4d38e226a6e7e3f2a6993d2b9b9f63d13e42ee7de3219",
|
||||
},
|
||||
},
|
||||
{"id": BASIC_CONFIG.agent_user_id, "customData": {}},
|
||||
{"id": proxy_device_id, "customData": {}},
|
||||
],
|
||||
},
|
||||
)
|
||||
|
||||
Reference in new issue
Block a user