init home-assistant
This commit is contained in:
452
home-assistant/tests/components/google_assistant/__init__.py
Normal file
452
home-assistant/tests/components/google_assistant/__init__.py
Normal file
@@ -0,0 +1,452 @@
|
||||
"""Tests for the Google Assistant integration."""
|
||||
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
from homeassistant.components.google_assistant import http
|
||||
from homeassistant.core import HomeAssistant
|
||||
|
||||
|
||||
def mock_google_config_store(agent_user_ids=None):
|
||||
"""Fake a storage for google assistant."""
|
||||
store = MagicMock(spec=http.GoogleConfigStore)
|
||||
if agent_user_ids is not None:
|
||||
store.agent_user_ids = agent_user_ids
|
||||
else:
|
||||
store.agent_user_ids = {}
|
||||
return store
|
||||
|
||||
|
||||
class MockConfig(http.GoogleConfig):
|
||||
"""Fake config that always exposes everything."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
*,
|
||||
agent_user_ids=None,
|
||||
enabled=True,
|
||||
entity_config=None,
|
||||
hass: HomeAssistant | None = None,
|
||||
secure_devices_pin=None,
|
||||
should_2fa=None,
|
||||
should_expose=None,
|
||||
should_report_state=False,
|
||||
) -> None:
|
||||
"""Initialize config."""
|
||||
super().__init__(hass, None)
|
||||
self._enabled = enabled
|
||||
self._entity_config = entity_config or {}
|
||||
self._secure_devices_pin = secure_devices_pin
|
||||
self._should_2fa = should_2fa
|
||||
self._should_expose = should_expose
|
||||
self._should_report_state = should_report_state
|
||||
self._store = mock_google_config_store(agent_user_ids)
|
||||
|
||||
@property
|
||||
def enabled(self):
|
||||
"""Return if Google is enabled."""
|
||||
return self._enabled
|
||||
|
||||
@property
|
||||
def secure_devices_pin(self):
|
||||
"""Return secure devices pin."""
|
||||
return self._secure_devices_pin
|
||||
|
||||
@property
|
||||
def entity_config(self):
|
||||
"""Return secure devices pin."""
|
||||
return self._entity_config
|
||||
|
||||
def get_agent_user_id_from_context(self, context):
|
||||
"""Get agent user ID making request."""
|
||||
return context.user_id
|
||||
|
||||
def should_expose(self, state):
|
||||
"""Expose it all."""
|
||||
return self._should_expose is None or self._should_expose(state)
|
||||
|
||||
@property
|
||||
def should_report_state(self):
|
||||
"""Return if states should be proactively reported."""
|
||||
return self._should_report_state
|
||||
|
||||
def should_2fa(self, state):
|
||||
"""Expose it all."""
|
||||
return self._should_2fa is None or self._should_2fa(state)
|
||||
|
||||
|
||||
BASIC_CONFIG = MockConfig()
|
||||
|
||||
DEMO_DEVICES = [
|
||||
{
|
||||
"id": "light.kitchen_lights",
|
||||
"name": {"name": "Kitchen Lights"},
|
||||
"traits": [
|
||||
"action.devices.traits.OnOff",
|
||||
"action.devices.traits.Brightness",
|
||||
"action.devices.traits.ColorSetting",
|
||||
],
|
||||
"type": "action.devices.types.LIGHT",
|
||||
"willReportState": False,
|
||||
},
|
||||
{
|
||||
"id": "switch.ac",
|
||||
"name": {"name": "AC"},
|
||||
"traits": ["action.devices.traits.OnOff"],
|
||||
"type": "action.devices.types.OUTLET",
|
||||
"willReportState": False,
|
||||
},
|
||||
{
|
||||
"id": "switch.decorative_lights",
|
||||
"name": {"name": "Decorative Lights"},
|
||||
"traits": ["action.devices.traits.OnOff"],
|
||||
"type": "action.devices.types.SWITCH",
|
||||
"willReportState": False,
|
||||
},
|
||||
{
|
||||
"id": "light.ceiling_lights",
|
||||
"name": {
|
||||
"name": "Roof Lights",
|
||||
"nicknames": ["Roof Lights", "top lights", "ceiling lights"],
|
||||
},
|
||||
"traits": [
|
||||
"action.devices.traits.OnOff",
|
||||
"action.devices.traits.Brightness",
|
||||
"action.devices.traits.ColorSetting",
|
||||
],
|
||||
"type": "action.devices.types.LIGHT",
|
||||
"willReportState": False,
|
||||
},
|
||||
{
|
||||
"id": "light.bed_light",
|
||||
"name": {"name": "Bed Light"},
|
||||
"traits": [
|
||||
"action.devices.traits.OnOff",
|
||||
"action.devices.traits.Brightness",
|
||||
"action.devices.traits.ColorSetting",
|
||||
"action.devices.traits.Modes",
|
||||
],
|
||||
"type": "action.devices.types.LIGHT",
|
||||
"willReportState": False,
|
||||
},
|
||||
{
|
||||
"id": "cover.living_room_window",
|
||||
"name": {"name": "Living Room Window"},
|
||||
"traits": [
|
||||
"action.devices.traits.StartStop",
|
||||
"action.devices.traits.OpenClose",
|
||||
],
|
||||
"type": "action.devices.types.BLINDS",
|
||||
"willReportState": False,
|
||||
},
|
||||
{
|
||||
"id": "cover.pergola_roof",
|
||||
"name": {"name": "Pergola Roof"},
|
||||
"traits": [
|
||||
"action.devices.traits.OpenClose",
|
||||
],
|
||||
"type": "action.devices.types.BLINDS",
|
||||
"willReportState": False,
|
||||
},
|
||||
{
|
||||
"id": "cover.hall_window",
|
||||
"name": {"name": "Hall Window"},
|
||||
"traits": [
|
||||
"action.devices.traits.StartStop",
|
||||
"action.devices.traits.OpenClose",
|
||||
],
|
||||
"type": "action.devices.types.BLINDS",
|
||||
"willReportState": False,
|
||||
},
|
||||
{
|
||||
"id": "cover.garage_door",
|
||||
"name": {"name": "Garage Door"},
|
||||
"traits": ["action.devices.traits.OpenClose"],
|
||||
"type": "action.devices.types.GARAGE",
|
||||
"willReportState": False,
|
||||
},
|
||||
{
|
||||
"id": "cover.kitchen_window",
|
||||
"name": {"name": "Kitchen Window"},
|
||||
"traits": [
|
||||
"action.devices.traits.StartStop",
|
||||
"action.devices.traits.OpenClose",
|
||||
],
|
||||
"type": "action.devices.types.BLINDS",
|
||||
"willReportState": False,
|
||||
},
|
||||
{
|
||||
"id": "media_player.bedroom",
|
||||
"name": {"name": "Bedroom"},
|
||||
"traits": [
|
||||
"action.devices.traits.OnOff",
|
||||
"action.devices.traits.Volume",
|
||||
"action.devices.traits.Modes",
|
||||
"action.devices.traits.TransportControl",
|
||||
"action.devices.traits.MediaState",
|
||||
],
|
||||
"type": "action.devices.types.SETTOP",
|
||||
"willReportState": False,
|
||||
},
|
||||
{
|
||||
"id": "media_player.kitchen",
|
||||
"name": {"name": "Kitchen"},
|
||||
"traits": [
|
||||
"action.devices.traits.OnOff",
|
||||
"action.devices.traits.Volume",
|
||||
"action.devices.traits.Modes",
|
||||
"action.devices.traits.TransportControl",
|
||||
"action.devices.traits.MediaState",
|
||||
],
|
||||
"type": "action.devices.types.SETTOP",
|
||||
"willReportState": False,
|
||||
},
|
||||
{
|
||||
"id": "media_player.living_room",
|
||||
"name": {"name": "Living Room"},
|
||||
"traits": [
|
||||
"action.devices.traits.OnOff",
|
||||
"action.devices.traits.Volume",
|
||||
"action.devices.traits.Modes",
|
||||
"action.devices.traits.TransportControl",
|
||||
"action.devices.traits.MediaState",
|
||||
],
|
||||
"type": "action.devices.types.SETTOP",
|
||||
"willReportState": False,
|
||||
},
|
||||
{
|
||||
"id": "media_player.lounge_room",
|
||||
"name": {"name": "Lounge room"},
|
||||
"traits": [
|
||||
"action.devices.traits.InputSelector",
|
||||
"action.devices.traits.OnOff",
|
||||
"action.devices.traits.Modes",
|
||||
"action.devices.traits.TransportControl",
|
||||
"action.devices.traits.MediaState",
|
||||
],
|
||||
"type": "action.devices.types.TV",
|
||||
"willReportState": False,
|
||||
},
|
||||
{
|
||||
"id": "media_player.walkman",
|
||||
"name": {"name": "Walkman"},
|
||||
"traits": [
|
||||
"action.devices.traits.OnOff",
|
||||
"action.devices.traits.Volume",
|
||||
"action.devices.traits.Modes",
|
||||
"action.devices.traits.TransportControl",
|
||||
"action.devices.traits.MediaState",
|
||||
],
|
||||
"type": "action.devices.types.SETTOP",
|
||||
"willReportState": False,
|
||||
},
|
||||
{
|
||||
"id": "media_player.browse",
|
||||
"name": {"name": "Browse"},
|
||||
"traits": ["action.devices.traits.MediaState", "action.devices.traits.OnOff"],
|
||||
"type": "action.devices.types.SETTOP",
|
||||
"willReportState": False,
|
||||
},
|
||||
{
|
||||
"id": "media_player.group",
|
||||
"name": {"name": "Group"},
|
||||
"traits": [
|
||||
"action.devices.traits.OnOff",
|
||||
"action.devices.traits.Volume",
|
||||
"action.devices.traits.Modes",
|
||||
"action.devices.traits.TransportControl",
|
||||
"action.devices.traits.MediaState",
|
||||
],
|
||||
"type": "action.devices.types.SETTOP",
|
||||
"willReportState": False,
|
||||
},
|
||||
{
|
||||
"id": "fan.living_room_fan",
|
||||
"name": {"name": "Living Room Fan"},
|
||||
"traits": [
|
||||
"action.devices.traits.FanSpeed",
|
||||
"action.devices.traits.OnOff",
|
||||
],
|
||||
"type": "action.devices.types.FAN",
|
||||
"willReportState": False,
|
||||
},
|
||||
{
|
||||
"id": "fan.ceiling_fan",
|
||||
"name": {"name": "Ceiling Fan"},
|
||||
"traits": [
|
||||
"action.devices.traits.FanSpeed",
|
||||
"action.devices.traits.OnOff",
|
||||
],
|
||||
"type": "action.devices.types.FAN",
|
||||
"willReportState": False,
|
||||
},
|
||||
{
|
||||
"id": "fan.percentage_full_fan",
|
||||
"name": {"name": "Percentage Full Fan"},
|
||||
"traits": ["action.devices.traits.FanSpeed", "action.devices.traits.OnOff"],
|
||||
"type": "action.devices.types.FAN",
|
||||
"willReportState": False,
|
||||
},
|
||||
{
|
||||
"id": "fan.percentage_limited_fan",
|
||||
"name": {"name": "Percentage Limited Fan"},
|
||||
"traits": ["action.devices.traits.FanSpeed", "action.devices.traits.OnOff"],
|
||||
"type": "action.devices.types.FAN",
|
||||
"willReportState": False,
|
||||
},
|
||||
{
|
||||
"id": "fan.preset_only_limited_fan",
|
||||
"name": {"name": "Preset Only Limited Fan"},
|
||||
"traits": [
|
||||
"action.devices.traits.OnOff",
|
||||
"action.devices.traits.Modes",
|
||||
],
|
||||
"type": "action.devices.types.FAN",
|
||||
"willReportState": False,
|
||||
},
|
||||
{
|
||||
"id": "climate.hvac",
|
||||
"name": {"name": "Hvac"},
|
||||
"traits": [
|
||||
"action.devices.traits.OnOff",
|
||||
"action.devices.traits.TemperatureSetting",
|
||||
"action.devices.traits.FanSpeed",
|
||||
],
|
||||
"type": "action.devices.types.THERMOSTAT",
|
||||
"willReportState": False,
|
||||
"attributes": {
|
||||
"availableThermostatModes": [
|
||||
"off",
|
||||
"heat",
|
||||
"cool",
|
||||
"heatcool",
|
||||
"auto",
|
||||
"dry",
|
||||
"fan-only",
|
||||
],
|
||||
"thermostatTemperatureUnit": "C",
|
||||
},
|
||||
},
|
||||
{
|
||||
"id": "climate.heatpump",
|
||||
"name": {"name": "HeatPump"},
|
||||
"traits": [
|
||||
"action.devices.traits.OnOff",
|
||||
"action.devices.traits.TemperatureSetting",
|
||||
],
|
||||
"type": "action.devices.types.THERMOSTAT",
|
||||
"willReportState": False,
|
||||
},
|
||||
{
|
||||
"id": "climate.ecobee",
|
||||
"name": {"name": "Ecobee"},
|
||||
"traits": [
|
||||
"action.devices.traits.OnOff",
|
||||
"action.devices.traits.TemperatureSetting",
|
||||
"action.devices.traits.FanSpeed",
|
||||
],
|
||||
"type": "action.devices.types.THERMOSTAT",
|
||||
"willReportState": False,
|
||||
},
|
||||
{
|
||||
"id": "humidifier.humidifier",
|
||||
"name": {"name": "Humidifier"},
|
||||
"traits": [
|
||||
"action.devices.traits.HumiditySetting",
|
||||
"action.devices.traits.OnOff",
|
||||
],
|
||||
"type": "action.devices.types.HUMIDIFIER",
|
||||
"willReportState": False,
|
||||
"attributes": {"humiditySetpointRange": {"minPercent": 0, "maxPercent": 100}},
|
||||
},
|
||||
{
|
||||
"id": "humidifier.dehumidifier",
|
||||
"name": {"name": "Dehumidifier"},
|
||||
"traits": [
|
||||
"action.devices.traits.HumiditySetting",
|
||||
"action.devices.traits.OnOff",
|
||||
],
|
||||
"type": "action.devices.types.DEHUMIDIFIER",
|
||||
"willReportState": False,
|
||||
"attributes": {"humiditySetpointRange": {"minPercent": 0, "maxPercent": 100}},
|
||||
},
|
||||
{
|
||||
"id": "humidifier.hygrostat",
|
||||
"name": {"name": "Hygrostat"},
|
||||
"traits": [
|
||||
"action.devices.traits.HumiditySetting",
|
||||
"action.devices.traits.Modes",
|
||||
"action.devices.traits.OnOff",
|
||||
],
|
||||
"type": "action.devices.types.HUMIDIFIER",
|
||||
"willReportState": False,
|
||||
"attributes": {"humiditySetpointRange": {"minPercent": 0, "maxPercent": 100}},
|
||||
},
|
||||
{
|
||||
"id": "lock.front_door",
|
||||
"name": {"name": "Front Door"},
|
||||
"traits": ["action.devices.traits.LockUnlock"],
|
||||
"type": "action.devices.types.LOCK",
|
||||
"willReportState": False,
|
||||
},
|
||||
{
|
||||
"id": "lock.kitchen_door",
|
||||
"name": {"name": "Kitchen Door"},
|
||||
"traits": ["action.devices.traits.LockUnlock"],
|
||||
"type": "action.devices.types.LOCK",
|
||||
"willReportState": False,
|
||||
},
|
||||
{
|
||||
"id": "lock.openable_lock",
|
||||
"name": {"name": "Openable Lock"},
|
||||
"traits": ["action.devices.traits.LockUnlock"],
|
||||
"type": "action.devices.types.LOCK",
|
||||
"willReportState": False,
|
||||
},
|
||||
{
|
||||
"id": "lock.poorly_installed_door",
|
||||
"name": {"name": "Poorly Installed Door"},
|
||||
"traits": ["action.devices.traits.LockUnlock"],
|
||||
"type": "action.devices.types.LOCK",
|
||||
"willReportState": False,
|
||||
},
|
||||
{
|
||||
"id": "alarm_control_panel.security",
|
||||
"name": {"name": "Security"},
|
||||
"traits": ["action.devices.traits.ArmDisarm"],
|
||||
"type": "action.devices.types.SECURITYSYSTEM",
|
||||
"willReportState": False,
|
||||
},
|
||||
{
|
||||
"id": "light.living_room_rgbww_lights",
|
||||
"name": {"name": "Living Room RGBWW Lights"},
|
||||
"traits": [
|
||||
"action.devices.traits.OnOff",
|
||||
"action.devices.traits.Brightness",
|
||||
"action.devices.traits.ColorSetting",
|
||||
],
|
||||
"type": "action.devices.types.LIGHT",
|
||||
"willReportState": False,
|
||||
},
|
||||
{
|
||||
"id": "light.office_rgbw_lights",
|
||||
"name": {"name": "Office RGBW Lights"},
|
||||
"traits": [
|
||||
"action.devices.traits.OnOff",
|
||||
"action.devices.traits.Brightness",
|
||||
"action.devices.traits.ColorSetting",
|
||||
],
|
||||
"type": "action.devices.types.LIGHT",
|
||||
"willReportState": False,
|
||||
},
|
||||
{
|
||||
"id": "light.entrance_color_white_lights",
|
||||
"name": {"name": "Entrance Color + White Lights"},
|
||||
"traits": [
|
||||
"action.devices.traits.OnOff",
|
||||
"action.devices.traits.Brightness",
|
||||
"action.devices.traits.ColorSetting",
|
||||
],
|
||||
"type": "action.devices.types.LIGHT",
|
||||
"willReportState": False,
|
||||
},
|
||||
]
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,116 @@
|
||||
# serializer version: 1
|
||||
# name: test_diagnostics
|
||||
dict({
|
||||
'config_entry': dict({
|
||||
'data': dict({
|
||||
'project_id': '1234',
|
||||
}),
|
||||
'disabled_by': None,
|
||||
'discovery_keys': dict({
|
||||
}),
|
||||
'domain': 'google_assistant',
|
||||
'minor_version': 1,
|
||||
'options': dict({
|
||||
}),
|
||||
'pref_disable_new_entities': False,
|
||||
'pref_disable_polling': False,
|
||||
'source': 'import',
|
||||
'title': '1234',
|
||||
'unique_id': '1234',
|
||||
'version': 1,
|
||||
}),
|
||||
'query': dict({
|
||||
'devices': dict({
|
||||
'switch.ac': dict({
|
||||
'on': False,
|
||||
'online': True,
|
||||
}),
|
||||
'switch.decorative_lights': dict({
|
||||
'on': True,
|
||||
'online': True,
|
||||
}),
|
||||
}),
|
||||
}),
|
||||
'sync': dict({
|
||||
'agentUserId': '**REDACTED**',
|
||||
'devices': list([
|
||||
dict({
|
||||
'attributes': dict({
|
||||
'commandOnlyOnOff': True,
|
||||
}),
|
||||
'customData': dict({
|
||||
'httpPort': 8123,
|
||||
'uuid': '**REDACTED**',
|
||||
'webhookId': None,
|
||||
}),
|
||||
'id': 'switch.decorative_lights',
|
||||
'name': dict({
|
||||
'name': 'Decorative Lights',
|
||||
}),
|
||||
'otherDeviceIds': list([
|
||||
dict({
|
||||
'deviceId': 'switch.decorative_lights',
|
||||
}),
|
||||
]),
|
||||
'traits': list([
|
||||
'action.devices.traits.OnOff',
|
||||
]),
|
||||
'type': 'action.devices.types.SWITCH',
|
||||
'willReportState': False,
|
||||
}),
|
||||
dict({
|
||||
'attributes': dict({
|
||||
}),
|
||||
'customData': dict({
|
||||
'httpPort': 8123,
|
||||
'uuid': '**REDACTED**',
|
||||
'webhookId': None,
|
||||
}),
|
||||
'id': 'switch.ac',
|
||||
'name': dict({
|
||||
'name': 'AC',
|
||||
}),
|
||||
'otherDeviceIds': list([
|
||||
dict({
|
||||
'deviceId': 'switch.ac',
|
||||
}),
|
||||
]),
|
||||
'traits': list([
|
||||
'action.devices.traits.OnOff',
|
||||
]),
|
||||
'type': 'action.devices.types.OUTLET',
|
||||
'willReportState': False,
|
||||
}),
|
||||
]),
|
||||
}),
|
||||
'yaml_config': dict({
|
||||
'expose_by_default': True,
|
||||
'exposed_domains': list([
|
||||
'alarm_control_panel',
|
||||
'binary_sensor',
|
||||
'climate',
|
||||
'cover',
|
||||
'event',
|
||||
'fan',
|
||||
'group',
|
||||
'humidifier',
|
||||
'input_boolean',
|
||||
'input_select',
|
||||
'light',
|
||||
'lock',
|
||||
'media_player',
|
||||
'scene',
|
||||
'script',
|
||||
'select',
|
||||
'sensor',
|
||||
'switch',
|
||||
'vacuum',
|
||||
'valve',
|
||||
'water_heater',
|
||||
]),
|
||||
'project_id': '1234',
|
||||
'report_state': False,
|
||||
'service_account': '**REDACTED**',
|
||||
}),
|
||||
})
|
||||
# ---
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Test buttons."""
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from homeassistant.components import google_assistant as ga
|
||||
from homeassistant.core import Context, HomeAssistant
|
||||
from homeassistant.exceptions import HomeAssistantError
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
from .test_http import DUMMY_CONFIG
|
||||
|
||||
from tests.common import MockUser
|
||||
|
||||
|
||||
async def test_sync_button(hass: HomeAssistant, hass_owner_user: MockUser) -> None:
|
||||
"""Test sync button."""
|
||||
|
||||
await async_setup_component(
|
||||
hass,
|
||||
ga.DOMAIN,
|
||||
{"google_assistant": DUMMY_CONFIG},
|
||||
)
|
||||
|
||||
await hass.async_block_till_done()
|
||||
|
||||
state = hass.states.get("button.google_assistant_synchronize_devices")
|
||||
assert state
|
||||
|
||||
config_entry = hass.config_entries.async_entries("google_assistant")[0]
|
||||
google_config: ga.GoogleConfig = hass.data[ga.DOMAIN][config_entry.entry_id]
|
||||
|
||||
with patch.object(google_config, "async_sync_entities") as mock_sync_entities:
|
||||
mock_sync_entities.return_value = 200
|
||||
context = Context(user_id=hass_owner_user.id)
|
||||
await hass.services.async_call(
|
||||
"button",
|
||||
"press",
|
||||
{"entity_id": "button.google_assistant_synchronize_devices"},
|
||||
blocking=True,
|
||||
context=context,
|
||||
)
|
||||
mock_sync_entities.assert_called_once_with(hass_owner_user.id)
|
||||
|
||||
mock_sync_entities.return_value = 400
|
||||
with pytest.raises(HomeAssistantError):
|
||||
await hass.services.async_call(
|
||||
"button",
|
||||
"press",
|
||||
{"entity_id": "button.google_assistant_synchronize_devices"},
|
||||
blocking=True,
|
||||
context=context,
|
||||
)
|
||||
@@ -0,0 +1,15 @@
|
||||
"""Test data redaction helpers."""
|
||||
|
||||
import json
|
||||
|
||||
from homeassistant.components.google_assistant.data_redaction import async_redact_msg
|
||||
|
||||
from tests.common import load_fixture
|
||||
|
||||
|
||||
def test_redact_msg() -> None:
|
||||
"""Test async_redact_msg."""
|
||||
messages = json.loads(load_fixture("data_redaction.json", "google_assistant"))
|
||||
agent_user_id = "333dee20-1234-1234-1234-2225a0d70d4c"
|
||||
for item in messages:
|
||||
assert async_redact_msg(item["raw"], agent_user_id) == item["redacted"]
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Test diagnostics."""
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
from syrupy import SnapshotAssertion
|
||||
from syrupy.filters import props
|
||||
|
||||
from homeassistant import setup
|
||||
from homeassistant.components import google_assistant as ga, switch
|
||||
from homeassistant.const import Platform
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
from .test_http import DUMMY_CONFIG
|
||||
|
||||
from tests.components.diagnostics import get_diagnostics_for_config_entry
|
||||
from tests.typing import ClientSessionGenerator
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
async def switch_only() -> None:
|
||||
"""Enable only the switch platform."""
|
||||
with patch(
|
||||
"homeassistant.components.demo.COMPONENTS_WITH_CONFIG_ENTRY_DEMO_PLATFORM",
|
||||
[Platform.SWITCH],
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
async def test_diagnostics(
|
||||
hass: HomeAssistant,
|
||||
hass_client: ClientSessionGenerator,
|
||||
snapshot: SnapshotAssertion,
|
||||
) -> None:
|
||||
"""Test diagnostics v1."""
|
||||
|
||||
await async_setup_component(hass, "homeassistant", {})
|
||||
await setup.async_setup_component(
|
||||
hass, switch.DOMAIN, {"switch": [{"platform": "demo"}]}
|
||||
)
|
||||
|
||||
await async_setup_component(
|
||||
hass,
|
||||
ga.DOMAIN,
|
||||
{"google_assistant": DUMMY_CONFIG},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
config_entry = hass.config_entries.async_entries("google_assistant")[0]
|
||||
assert await get_diagnostics_for_config_entry(
|
||||
hass, hass_client, config_entry
|
||||
) == snapshot(exclude=props("entry_id", "created_at", "modified_at"))
|
||||
@@ -0,0 +1,512 @@
|
||||
"""The tests for the Google Assistant component."""
|
||||
|
||||
from asyncio import AbstractEventLoop
|
||||
from http import HTTPStatus
|
||||
import json
|
||||
from unittest.mock import patch
|
||||
|
||||
from aiohttp.hdrs import AUTHORIZATION
|
||||
from aiohttp.test_utils import TestClient
|
||||
import pytest
|
||||
|
||||
from homeassistant import const, core, setup
|
||||
from homeassistant.components import (
|
||||
google_assistant as ga,
|
||||
humidifier,
|
||||
light,
|
||||
media_player,
|
||||
)
|
||||
from homeassistant.const import (
|
||||
CLOUD_NEVER_EXPOSED_ENTITIES,
|
||||
EntityCategory,
|
||||
Platform,
|
||||
UnitOfTemperature,
|
||||
)
|
||||
from homeassistant.helpers import entity_registry as er
|
||||
|
||||
from . import DEMO_DEVICES
|
||||
|
||||
from tests.typing import ClientSessionGenerator
|
||||
|
||||
API_PASSWORD = "test1234"
|
||||
|
||||
PROJECT_ID = "hasstest-1234"
|
||||
CLIENT_ID = "helloworld"
|
||||
ACCESS_TOKEN = "superdoublesecret"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def auth_header(hass_access_token: str) -> dict[str, str]:
|
||||
"""Generate an HTTP header with bearer token authorization."""
|
||||
return {AUTHORIZATION: f"Bearer {hass_access_token}"}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def assistant_client(
|
||||
event_loop: AbstractEventLoop,
|
||||
hass: core.HomeAssistant,
|
||||
hass_client_no_auth: ClientSessionGenerator,
|
||||
) -> TestClient:
|
||||
"""Create web client for the Google Assistant API."""
|
||||
loop = event_loop
|
||||
loop.run_until_complete(
|
||||
setup.async_setup_component(
|
||||
hass,
|
||||
"google_assistant",
|
||||
{
|
||||
"google_assistant": {
|
||||
"project_id": PROJECT_ID,
|
||||
"entity_config": {
|
||||
"light.ceiling_lights": {
|
||||
"aliases": ["top lights", "ceiling lights"],
|
||||
"name": "Roof Lights",
|
||||
}
|
||||
},
|
||||
}
|
||||
},
|
||||
)
|
||||
)
|
||||
|
||||
return loop.run_until_complete(hass_client_no_auth())
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
async def wanted_platforms_only() -> None:
|
||||
"""Enable only the wanted demo platforms."""
|
||||
with patch(
|
||||
"homeassistant.components.demo.COMPONENTS_WITH_CONFIG_ENTRY_DEMO_PLATFORM",
|
||||
[
|
||||
Platform.ALARM_CONTROL_PANEL,
|
||||
Platform.CLIMATE,
|
||||
Platform.COVER,
|
||||
Platform.FAN,
|
||||
Platform.HUMIDIFIER,
|
||||
Platform.LIGHT,
|
||||
Platform.LOCK,
|
||||
Platform.MEDIA_PLAYER,
|
||||
Platform.SWITCH,
|
||||
],
|
||||
):
|
||||
yield
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def hass_fixture(
|
||||
event_loop: AbstractEventLoop, hass: core.HomeAssistant
|
||||
) -> core.HomeAssistant:
|
||||
"""Set up a Home Assistant instance for these tests."""
|
||||
loop = event_loop
|
||||
|
||||
# We need to do this to get access to homeassistant/turn_(on,off)
|
||||
loop.run_until_complete(setup.async_setup_component(hass, core.DOMAIN, {}))
|
||||
|
||||
loop.run_until_complete(setup.async_setup_component(hass, "demo", {}))
|
||||
|
||||
return hass
|
||||
|
||||
|
||||
async def test_sync_request(
|
||||
hass_fixture, assistant_client, auth_header, entity_registry: er.EntityRegistry
|
||||
) -> None:
|
||||
"""Test a sync request."""
|
||||
entity_entry1 = entity_registry.async_get_or_create(
|
||||
"switch",
|
||||
"test",
|
||||
"switch_config_id",
|
||||
suggested_object_id="config_switch",
|
||||
entity_category=EntityCategory.CONFIG,
|
||||
)
|
||||
entity_entry2 = entity_registry.async_get_or_create(
|
||||
"switch",
|
||||
"test",
|
||||
"switch_diagnostic_id",
|
||||
suggested_object_id="diagnostic_switch",
|
||||
entity_category=EntityCategory.DIAGNOSTIC,
|
||||
)
|
||||
entity_entry3 = entity_registry.async_get_or_create(
|
||||
"switch",
|
||||
"test",
|
||||
"switch_hidden_integration_id",
|
||||
suggested_object_id="hidden_integration_switch",
|
||||
hidden_by=er.RegistryEntryHider.INTEGRATION,
|
||||
)
|
||||
entity_entry4 = entity_registry.async_get_or_create(
|
||||
"switch",
|
||||
"test",
|
||||
"switch_hidden_user_id",
|
||||
suggested_object_id="hidden_user_switch",
|
||||
hidden_by=er.RegistryEntryHider.USER,
|
||||
)
|
||||
|
||||
# These should not show up in the sync request
|
||||
hass_fixture.states.async_set(entity_entry1.entity_id, "on")
|
||||
hass_fixture.states.async_set(entity_entry2.entity_id, "something_else")
|
||||
hass_fixture.states.async_set(entity_entry3.entity_id, "blah")
|
||||
hass_fixture.states.async_set(entity_entry4.entity_id, "foo")
|
||||
|
||||
reqid = "5711642932632160983"
|
||||
data = {"requestId": reqid, "inputs": [{"intent": "action.devices.SYNC"}]}
|
||||
result = await assistant_client.post(
|
||||
ga.const.GOOGLE_ASSISTANT_API_ENDPOINT,
|
||||
data=json.dumps(data),
|
||||
headers=auth_header,
|
||||
)
|
||||
assert result.status == HTTPStatus.OK
|
||||
body = await result.json()
|
||||
assert body.get("requestId") == reqid
|
||||
devices = body["payload"]["devices"]
|
||||
assert sorted(dev["id"] for dev in devices) == sorted(
|
||||
dev["id"] for dev in DEMO_DEVICES
|
||||
)
|
||||
|
||||
for dev in devices:
|
||||
assert dev["id"] not in CLOUD_NEVER_EXPOSED_ENTITIES
|
||||
|
||||
for dev, demo in zip(
|
||||
sorted(devices, key=lambda d: d["id"]),
|
||||
sorted(DEMO_DEVICES, key=lambda d: d["id"]),
|
||||
strict=False,
|
||||
):
|
||||
assert dev["name"] == demo["name"]
|
||||
assert set(dev["traits"]) == set(demo["traits"])
|
||||
assert dev["type"] == demo["type"]
|
||||
|
||||
|
||||
async def test_query_request(hass_fixture, assistant_client, auth_header) -> None:
|
||||
"""Test a query request."""
|
||||
reqid = "5711642932632160984"
|
||||
data = {
|
||||
"requestId": reqid,
|
||||
"inputs": [
|
||||
{
|
||||
"intent": "action.devices.QUERY",
|
||||
"payload": {
|
||||
"devices": [
|
||||
{"id": "light.ceiling_lights"},
|
||||
{"id": "light.bed_light"},
|
||||
{"id": "light.kitchen_lights"},
|
||||
{"id": "media_player.lounge_room"},
|
||||
]
|
||||
},
|
||||
}
|
||||
],
|
||||
}
|
||||
result = await assistant_client.post(
|
||||
ga.const.GOOGLE_ASSISTANT_API_ENDPOINT,
|
||||
data=json.dumps(data),
|
||||
headers=auth_header,
|
||||
)
|
||||
assert result.status == HTTPStatus.OK
|
||||
body = await result.json()
|
||||
assert body.get("requestId") == reqid
|
||||
devices = body["payload"]["devices"]
|
||||
assert len(devices) == 4
|
||||
assert devices["light.bed_light"]["on"] is False
|
||||
assert devices["light.ceiling_lights"]["on"] is True
|
||||
assert devices["light.ceiling_lights"]["brightness"] == 71
|
||||
assert devices["light.ceiling_lights"]["color"]["temperatureK"] == 2631
|
||||
assert devices["light.kitchen_lights"]["color"]["spectrumHsv"] == {
|
||||
"hue": 345,
|
||||
"saturation": 0.75,
|
||||
"value": 0.7058823529411765,
|
||||
}
|
||||
assert devices["media_player.lounge_room"]["on"] is True
|
||||
|
||||
|
||||
async def test_query_climate_request(
|
||||
hass_fixture, assistant_client, auth_header
|
||||
) -> None:
|
||||
"""Test a query request."""
|
||||
reqid = "5711642932632160984"
|
||||
data = {
|
||||
"requestId": reqid,
|
||||
"inputs": [
|
||||
{
|
||||
"intent": "action.devices.QUERY",
|
||||
"payload": {
|
||||
"devices": [
|
||||
{"id": "climate.hvac"},
|
||||
{"id": "climate.heatpump"},
|
||||
{"id": "climate.ecobee"},
|
||||
]
|
||||
},
|
||||
}
|
||||
],
|
||||
}
|
||||
result = await assistant_client.post(
|
||||
ga.const.GOOGLE_ASSISTANT_API_ENDPOINT,
|
||||
data=json.dumps(data),
|
||||
headers=auth_header,
|
||||
)
|
||||
assert result.status == HTTPStatus.OK
|
||||
body = await result.json()
|
||||
assert body.get("requestId") == reqid
|
||||
devices = body["payload"]["devices"]
|
||||
assert len(devices) == 3
|
||||
assert devices["climate.heatpump"] == {
|
||||
"online": True,
|
||||
"on": True,
|
||||
"thermostatTemperatureSetpoint": 20.0,
|
||||
"thermostatTemperatureAmbient": 25.0,
|
||||
"thermostatMode": "heat",
|
||||
}
|
||||
assert devices["climate.ecobee"] == {
|
||||
"online": True,
|
||||
"on": True,
|
||||
"thermostatTemperatureSetpointHigh": 24,
|
||||
"thermostatTemperatureAmbient": 23,
|
||||
"thermostatMode": "heatcool",
|
||||
"thermostatTemperatureSetpointLow": 21,
|
||||
"currentFanSpeedSetting": "auto_low",
|
||||
}
|
||||
assert devices["climate.hvac"] == {
|
||||
"online": True,
|
||||
"on": True,
|
||||
"thermostatTemperatureSetpoint": 21,
|
||||
"thermostatTemperatureAmbient": 22,
|
||||
"thermostatMode": "cool",
|
||||
"thermostatHumidityAmbient": 54.2,
|
||||
"currentFanSpeedSetting": "on_high",
|
||||
}
|
||||
|
||||
|
||||
async def test_query_climate_request_f(
|
||||
hass_fixture, assistant_client, auth_header
|
||||
) -> None:
|
||||
"""Test a query request."""
|
||||
# Mock demo devices as fahrenheit to see if we convert to celsius
|
||||
hass_fixture.config.units.temperature_unit = UnitOfTemperature.FAHRENHEIT
|
||||
for entity_id in ("climate.hvac", "climate.heatpump", "climate.ecobee"):
|
||||
state = hass_fixture.states.get(entity_id)
|
||||
attr = dict(state.attributes)
|
||||
hass_fixture.states.async_set(entity_id, state.state, attr)
|
||||
|
||||
reqid = "5711642932632160984"
|
||||
data = {
|
||||
"requestId": reqid,
|
||||
"inputs": [
|
||||
{
|
||||
"intent": "action.devices.QUERY",
|
||||
"payload": {
|
||||
"devices": [
|
||||
{"id": "climate.hvac"},
|
||||
{"id": "climate.heatpump"},
|
||||
{"id": "climate.ecobee"},
|
||||
]
|
||||
},
|
||||
}
|
||||
],
|
||||
}
|
||||
result = await assistant_client.post(
|
||||
ga.const.GOOGLE_ASSISTANT_API_ENDPOINT,
|
||||
data=json.dumps(data),
|
||||
headers=auth_header,
|
||||
)
|
||||
assert result.status == HTTPStatus.OK
|
||||
body = await result.json()
|
||||
assert body.get("requestId") == reqid
|
||||
devices = body["payload"]["devices"]
|
||||
assert len(devices) == 3
|
||||
assert devices["climate.heatpump"] == {
|
||||
"online": True,
|
||||
"on": True,
|
||||
"thermostatTemperatureSetpoint": -6.7,
|
||||
"thermostatTemperatureAmbient": -3.9,
|
||||
"thermostatMode": "heat",
|
||||
}
|
||||
assert devices["climate.ecobee"] == {
|
||||
"online": True,
|
||||
"on": True,
|
||||
"thermostatTemperatureSetpointHigh": -4.4,
|
||||
"thermostatTemperatureAmbient": -5,
|
||||
"thermostatMode": "heatcool",
|
||||
"thermostatTemperatureSetpointLow": -6.1,
|
||||
"currentFanSpeedSetting": "auto_low",
|
||||
}
|
||||
assert devices["climate.hvac"] == {
|
||||
"online": True,
|
||||
"on": True,
|
||||
"thermostatTemperatureSetpoint": -6.1,
|
||||
"thermostatTemperatureAmbient": -5.6,
|
||||
"thermostatMode": "cool",
|
||||
"thermostatHumidityAmbient": 54.2,
|
||||
"currentFanSpeedSetting": "on_high",
|
||||
}
|
||||
hass_fixture.config.units.temperature_unit = UnitOfTemperature.CELSIUS
|
||||
|
||||
|
||||
async def test_query_humidifier_request(
|
||||
hass_fixture, assistant_client, auth_header
|
||||
) -> None:
|
||||
"""Test a query request."""
|
||||
reqid = "5711642932632160984"
|
||||
data = {
|
||||
"requestId": reqid,
|
||||
"inputs": [
|
||||
{
|
||||
"intent": "action.devices.QUERY",
|
||||
"payload": {
|
||||
"devices": [
|
||||
{"id": "humidifier.humidifier"},
|
||||
{"id": "humidifier.dehumidifier"},
|
||||
{"id": "humidifier.hygrostat"},
|
||||
]
|
||||
},
|
||||
}
|
||||
],
|
||||
}
|
||||
result = await assistant_client.post(
|
||||
ga.const.GOOGLE_ASSISTANT_API_ENDPOINT,
|
||||
data=json.dumps(data),
|
||||
headers=auth_header,
|
||||
)
|
||||
assert result.status == HTTPStatus.OK
|
||||
body = await result.json()
|
||||
assert body.get("requestId") == reqid
|
||||
devices = body["payload"]["devices"]
|
||||
assert len(devices) == 3
|
||||
assert devices["humidifier.humidifier"] == {
|
||||
"on": True,
|
||||
"online": True,
|
||||
"humiditySetpointPercent": 68,
|
||||
"humidityAmbientPercent": 45,
|
||||
}
|
||||
assert devices["humidifier.dehumidifier"] == {
|
||||
"on": True,
|
||||
"online": True,
|
||||
"humiditySetpointPercent": 54.2,
|
||||
"humidityAmbientPercent": 59.4,
|
||||
}
|
||||
assert devices["humidifier.hygrostat"] == {
|
||||
"on": True,
|
||||
"online": True,
|
||||
"humiditySetpointPercent": 50,
|
||||
"currentModeSettings": {"mode": "home"},
|
||||
}
|
||||
|
||||
|
||||
async def test_execute_request(hass_fixture, assistant_client, auth_header) -> None:
|
||||
"""Test an execute request."""
|
||||
reqid = "5711642932632160985"
|
||||
data = {
|
||||
"requestId": reqid,
|
||||
"inputs": [
|
||||
{
|
||||
"intent": "action.devices.EXECUTE",
|
||||
"payload": {
|
||||
"commands": [
|
||||
{
|
||||
"devices": [
|
||||
{"id": "light.ceiling_lights"},
|
||||
{"id": "switch.decorative_lights"},
|
||||
{"id": "media_player.lounge_room"},
|
||||
],
|
||||
"execution": [
|
||||
{
|
||||
"command": "action.devices.commands.OnOff",
|
||||
"params": {"on": False},
|
||||
}
|
||||
],
|
||||
},
|
||||
{
|
||||
"devices": [{"id": "media_player.walkman"}],
|
||||
"execution": [
|
||||
{
|
||||
"command": "action.devices.commands.setVolume",
|
||||
"params": {"volumeLevel": 70},
|
||||
}
|
||||
],
|
||||
},
|
||||
{
|
||||
"devices": [{"id": "light.kitchen_lights"}],
|
||||
"execution": [
|
||||
{
|
||||
"command": "action.devices.commands.ColorAbsolute",
|
||||
"params": {"color": {"spectrumRGB": 16711680}},
|
||||
}
|
||||
],
|
||||
},
|
||||
{
|
||||
"devices": [{"id": "light.bed_light"}],
|
||||
"execution": [
|
||||
{
|
||||
"command": "action.devices.commands.ColorAbsolute",
|
||||
"params": {"color": {"spectrumRGB": 65280}},
|
||||
},
|
||||
{
|
||||
"command": "action.devices.commands.ColorAbsolute",
|
||||
"params": {"color": {"temperature": 4700}},
|
||||
},
|
||||
],
|
||||
},
|
||||
{
|
||||
"devices": [{"id": "humidifier.humidifier"}],
|
||||
"execution": [
|
||||
{
|
||||
"command": "action.devices.commands.OnOff",
|
||||
"params": {"on": False},
|
||||
}
|
||||
],
|
||||
},
|
||||
{
|
||||
"devices": [{"id": "humidifier.dehumidifier"}],
|
||||
"execution": [
|
||||
{
|
||||
"command": "action.devices.commands.SetHumidity",
|
||||
"params": {"humidity": 45},
|
||||
}
|
||||
],
|
||||
},
|
||||
{
|
||||
"devices": [{"id": "humidifier.hygrostat"}],
|
||||
"execution": [
|
||||
{
|
||||
"command": "action.devices.commands.SetModes",
|
||||
"params": {"updateModeSettings": {"mode": "eco"}},
|
||||
}
|
||||
],
|
||||
},
|
||||
]
|
||||
},
|
||||
}
|
||||
],
|
||||
}
|
||||
result = await assistant_client.post(
|
||||
ga.const.GOOGLE_ASSISTANT_API_ENDPOINT,
|
||||
data=json.dumps(data),
|
||||
headers=auth_header,
|
||||
)
|
||||
assert result.status == HTTPStatus.OK
|
||||
body = await result.json()
|
||||
assert body.get("requestId") == reqid
|
||||
commands = body["payload"]["commands"]
|
||||
assert len(commands) == 9
|
||||
|
||||
assert not any(result["status"] == "ERROR" for result in commands)
|
||||
|
||||
ceiling = hass_fixture.states.get("light.ceiling_lights")
|
||||
assert ceiling.state == "off"
|
||||
|
||||
kitchen = hass_fixture.states.get("light.kitchen_lights")
|
||||
assert kitchen.attributes.get(light.ATTR_RGB_COLOR) == (255, 0, 0)
|
||||
|
||||
bed = hass_fixture.states.get("light.bed_light")
|
||||
assert bed.attributes.get(light.ATTR_COLOR_TEMP_KELVIN) == 4700
|
||||
|
||||
assert hass_fixture.states.get("switch.decorative_lights").state == "off"
|
||||
|
||||
walkman = hass_fixture.states.get("media_player.walkman")
|
||||
assert walkman.state == "playing"
|
||||
assert walkman.attributes.get(media_player.ATTR_MEDIA_VOLUME_LEVEL) == 0.7
|
||||
|
||||
lounge = hass_fixture.states.get("media_player.lounge_room")
|
||||
assert lounge.state == "off"
|
||||
|
||||
humidifier_state = hass_fixture.states.get("humidifier.humidifier")
|
||||
assert humidifier_state.state == "off"
|
||||
|
||||
dehumidifier = hass_fixture.states.get("humidifier.dehumidifier")
|
||||
assert dehumidifier.attributes.get(humidifier.ATTR_HUMIDITY) == 45
|
||||
|
||||
hygrostat = hass_fixture.states.get("humidifier.hygrostat")
|
||||
assert hygrostat.attributes.get(const.ATTR_MODE) == "eco"
|
||||
507
home-assistant/tests/components/google_assistant/test_helpers.py
Normal file
507
home-assistant/tests/components/google_assistant/test_helpers.py
Normal file
@@ -0,0 +1,507 @@
|
||||
"""Test Google Assistant helpers."""
|
||||
|
||||
from datetime import timedelta
|
||||
from http import HTTPStatus
|
||||
from unittest.mock import Mock, call, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.google_assistant import helpers
|
||||
from homeassistant.components.google_assistant.const import (
|
||||
EVENT_COMMAND_RECEIVED,
|
||||
NOT_EXPOSE_LOCAL,
|
||||
SOURCE_CLOUD,
|
||||
SOURCE_LOCAL,
|
||||
STORE_GOOGLE_LOCAL_WEBHOOK_ID,
|
||||
)
|
||||
from homeassistant.components.matter import MatterDeviceInfo
|
||||
from homeassistant.core import HomeAssistant, State
|
||||
from homeassistant.core_config import async_process_ha_core_config
|
||||
from homeassistant.helpers import device_registry as dr, entity_registry as er
|
||||
from homeassistant.setup import async_setup_component
|
||||
from homeassistant.util import dt as dt_util
|
||||
|
||||
from . import MockConfig
|
||||
|
||||
from tests.common import MockConfigEntry, async_capture_events, async_mock_service
|
||||
from tests.typing import ClientSessionGenerator
|
||||
|
||||
|
||||
async def test_google_entity_sync_serialize_with_local_sdk(hass: HomeAssistant) -> None:
|
||||
"""Test sync serialize attributes of a GoogleEntity."""
|
||||
hass.states.async_set("light.ceiling_lights", "off")
|
||||
hass.config.api = Mock(port=1234, local_ip="192.168.123.123", use_ssl=False)
|
||||
await async_process_ha_core_config(
|
||||
hass,
|
||||
{"external_url": "https://hostname:1234"},
|
||||
)
|
||||
|
||||
hass.http = Mock(server_port=1234)
|
||||
config = MockConfig(
|
||||
hass=hass,
|
||||
agent_user_ids={
|
||||
"mock-user-id": {
|
||||
STORE_GOOGLE_LOCAL_WEBHOOK_ID: "mock-webhook-id",
|
||||
},
|
||||
},
|
||||
)
|
||||
entity = helpers.GoogleEntity(hass, config, hass.states.get("light.ceiling_lights"))
|
||||
|
||||
serialized = entity.sync_serialize(None, "mock-uuid")
|
||||
assert "otherDeviceIds" not in serialized
|
||||
assert "customData" not in serialized
|
||||
|
||||
config.async_enable_local_sdk()
|
||||
|
||||
serialized = entity.sync_serialize("mock-user-id", "abcdef")
|
||||
assert serialized["otherDeviceIds"] == [{"deviceId": "light.ceiling_lights"}]
|
||||
assert serialized["customData"] == {
|
||||
"httpPort": 1234,
|
||||
"webhookId": "mock-webhook-id",
|
||||
"uuid": "abcdef",
|
||||
}
|
||||
|
||||
for device_type in NOT_EXPOSE_LOCAL:
|
||||
with patch(
|
||||
"homeassistant.components.google_assistant.helpers.get_google_type",
|
||||
return_value=device_type,
|
||||
):
|
||||
serialized = entity.sync_serialize(None, "mock-uuid")
|
||||
assert "otherDeviceIds" not in serialized
|
||||
assert "customData" not in serialized
|
||||
|
||||
|
||||
async def test_google_entity_sync_serialize_with_matter(
|
||||
hass: HomeAssistant,
|
||||
device_registry: dr.DeviceRegistry,
|
||||
entity_registry: er.EntityRegistry,
|
||||
) -> None:
|
||||
"""Test sync serialize attributes of a GoogleEntity that is also a Matter device."""
|
||||
entry = MockConfigEntry()
|
||||
entry.add_to_hass(hass)
|
||||
device = device_registry.async_get_or_create(
|
||||
config_entry_id=entry.entry_id,
|
||||
manufacturer="Someone",
|
||||
model="Some model",
|
||||
sw_version="Some Version",
|
||||
identifiers={("matter", "12345678")},
|
||||
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
|
||||
)
|
||||
entity = entity_registry.async_get_or_create(
|
||||
"light",
|
||||
"test",
|
||||
"1235",
|
||||
suggested_object_id="ceiling_lights",
|
||||
device_id=device.id,
|
||||
)
|
||||
hass.states.async_set("light.ceiling_lights", "off")
|
||||
|
||||
entity = helpers.GoogleEntity(
|
||||
hass, MockConfig(hass=hass), hass.states.get("light.ceiling_lights")
|
||||
)
|
||||
|
||||
serialized = entity.sync_serialize(None, "mock-uuid")
|
||||
assert "matterUniqueId" not in serialized
|
||||
assert "matterOriginalVendorId" not in serialized
|
||||
assert "matterOriginalProductId" not in serialized
|
||||
|
||||
hass.config.components.add("matter")
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.matter.get_matter_device_info",
|
||||
return_value=MatterDeviceInfo(
|
||||
unique_id="mock-unique-id",
|
||||
vendor_id="mock-vendor-id",
|
||||
product_id="mock-product-id",
|
||||
),
|
||||
):
|
||||
serialized = entity.sync_serialize("mock-user-id", "abcdef")
|
||||
|
||||
assert serialized["matterUniqueId"] == "mock-unique-id"
|
||||
assert serialized["matterOriginalVendorId"] == "mock-vendor-id"
|
||||
assert serialized["matterOriginalProductId"] == "mock-product-id"
|
||||
|
||||
|
||||
async def test_config_local_sdk(
|
||||
hass: HomeAssistant, hass_client: ClientSessionGenerator
|
||||
) -> None:
|
||||
"""Test the local SDK."""
|
||||
command_events = async_capture_events(hass, EVENT_COMMAND_RECEIVED)
|
||||
turn_on_calls = async_mock_service(hass, "light", "turn_on")
|
||||
hass.states.async_set("light.ceiling_lights", "off")
|
||||
|
||||
assert await async_setup_component(hass, "webhook", {})
|
||||
|
||||
config = MockConfig(
|
||||
hass=hass,
|
||||
agent_user_ids={
|
||||
"mock-user-id": {
|
||||
STORE_GOOGLE_LOCAL_WEBHOOK_ID: "mock-webhook-id",
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
client = await hass_client()
|
||||
|
||||
assert config.is_local_connected is False
|
||||
config.async_enable_local_sdk()
|
||||
assert config.is_local_connected is False
|
||||
|
||||
resp = await client.post(
|
||||
"/api/webhook/mock-webhook-id",
|
||||
json={
|
||||
"inputs": [
|
||||
{
|
||||
"context": {"locale_country": "US", "locale_language": "en"},
|
||||
"intent": "action.devices.EXECUTE",
|
||||
"payload": {
|
||||
"commands": [
|
||||
{
|
||||
"devices": [{"id": "light.ceiling_lights"}],
|
||||
"execution": [
|
||||
{
|
||||
"command": "action.devices.commands.OnOff",
|
||||
"params": {"on": True},
|
||||
}
|
||||
],
|
||||
}
|
||||
],
|
||||
"structureData": {},
|
||||
},
|
||||
}
|
||||
],
|
||||
"requestId": "mock-req-id",
|
||||
},
|
||||
)
|
||||
|
||||
assert config.is_local_connected is True
|
||||
with patch(
|
||||
"homeassistant.components.google_assistant.helpers.utcnow",
|
||||
return_value=dt_util.utcnow() + timedelta(seconds=90),
|
||||
):
|
||||
assert config.is_local_connected is False
|
||||
|
||||
assert resp.status == HTTPStatus.OK
|
||||
result = await resp.json()
|
||||
assert result["requestId"] == "mock-req-id"
|
||||
|
||||
assert len(command_events) == 1
|
||||
assert command_events[0].context.user_id == "mock-user-id"
|
||||
|
||||
assert len(turn_on_calls) == 1
|
||||
assert turn_on_calls[0].context is command_events[0].context
|
||||
|
||||
config.async_disable_local_sdk()
|
||||
|
||||
# Webhook is no longer active
|
||||
resp = await client.post("/api/webhook/mock-webhook-id")
|
||||
assert resp.status == HTTPStatus.OK
|
||||
assert await resp.read() == b""
|
||||
|
||||
|
||||
async def test_config_local_sdk_if_disabled(
|
||||
hass: HomeAssistant, hass_client: ClientSessionGenerator
|
||||
) -> None:
|
||||
"""Test the local SDK."""
|
||||
assert await async_setup_component(hass, "webhook", {})
|
||||
|
||||
config = MockConfig(
|
||||
hass=hass,
|
||||
agent_user_ids={
|
||||
"mock-user-id": {
|
||||
STORE_GOOGLE_LOCAL_WEBHOOK_ID: "mock-webhook-id",
|
||||
},
|
||||
},
|
||||
enabled=False,
|
||||
)
|
||||
assert not config.is_local_sdk_active
|
||||
|
||||
client = await hass_client()
|
||||
|
||||
config.async_enable_local_sdk()
|
||||
assert config.is_local_sdk_active
|
||||
|
||||
resp = await client.post(
|
||||
"/api/webhook/mock-webhook-id", json={"requestId": "mock-req-id"}
|
||||
)
|
||||
assert resp.status == HTTPStatus.OK
|
||||
result = await resp.json()
|
||||
assert result == {
|
||||
"payload": {"errorCode": "deviceTurnedOff"},
|
||||
"requestId": "mock-req-id",
|
||||
}
|
||||
|
||||
config.async_disable_local_sdk()
|
||||
assert not config.is_local_sdk_active
|
||||
|
||||
# Webhook is no longer active
|
||||
resp = await client.post("/api/webhook/mock-webhook-id")
|
||||
assert resp.status == HTTPStatus.OK
|
||||
assert await resp.read() == b""
|
||||
|
||||
|
||||
async def test_config_local_sdk_if_ssl_enabled(
|
||||
hass: HomeAssistant, hass_client: ClientSessionGenerator
|
||||
) -> None:
|
||||
"""Test the local SDK is not enabled when SSL is enabled."""
|
||||
assert await async_setup_component(hass, "webhook", {})
|
||||
hass.config.api.use_ssl = True
|
||||
|
||||
config = MockConfig(
|
||||
hass=hass,
|
||||
agent_user_ids={
|
||||
"mock-user-id": {
|
||||
STORE_GOOGLE_LOCAL_WEBHOOK_ID: "mock-webhook-id",
|
||||
},
|
||||
},
|
||||
enabled=False,
|
||||
)
|
||||
assert not config.is_local_sdk_active
|
||||
|
||||
client = await hass_client()
|
||||
|
||||
config.async_enable_local_sdk()
|
||||
assert not config.is_local_sdk_active
|
||||
|
||||
# Webhook should not be activated
|
||||
resp = await client.post("/api/webhook/mock-webhook-id")
|
||||
assert resp.status == HTTPStatus.OK
|
||||
assert await resp.read() == b""
|
||||
|
||||
|
||||
async def test_agent_user_id_connect() -> None:
|
||||
"""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) -> None:
|
||||
"""Test sync of all states."""
|
||||
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", [{}, {"1"}, {"1", "2"}])
|
||||
async def test_sync_entities(agents) -> None:
|
||||
"""Test sync of all entities."""
|
||||
config = MockConfig(agent_user_ids=agents)
|
||||
with patch.object(
|
||||
config, "async_sync_entities", return_value=HTTPStatus.NO_CONTENT
|
||||
) as mock:
|
||||
await config.async_sync_entities_all()
|
||||
assert sorted(mock.mock_calls) == sorted(call(agent) for agent in agents)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("agents", [{}, {"1"}, {"1", "2"}])
|
||||
async def test_sync_notifications(agents) -> None:
|
||||
"""Test sync of notifications."""
|
||||
config = MockConfig(agent_user_ids=agents)
|
||||
with patch.object(
|
||||
config, "async_sync_notification", return_value=HTTPStatus.NO_CONTENT
|
||||
) as mock:
|
||||
await config.async_sync_notification_all("1234", {})
|
||||
assert not agents or bool(mock.mock_calls) and agents
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("agents", "result"),
|
||||
[({}, 204), ({"1": 200}, 200), ({"1": 200, "2": 300}, 300)],
|
||||
)
|
||||
async def test_sync_entities_all(agents, result) -> None:
|
||||
"""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
|
||||
|
||||
|
||||
def test_supported_features_string(caplog: pytest.LogCaptureFixture) -> None:
|
||||
"""Test bad supported features."""
|
||||
entity = helpers.GoogleEntity(
|
||||
None,
|
||||
MockConfig(),
|
||||
State("test.entity_id", "on", {"supported_features": "invalid"}),
|
||||
)
|
||||
assert entity.is_supported() is False
|
||||
assert (
|
||||
"Entity test.entity_id contains invalid supported_features value invalid"
|
||||
in caplog.text
|
||||
)
|
||||
|
||||
|
||||
def test_request_data() -> None:
|
||||
"""Test request data properties."""
|
||||
config = MockConfig()
|
||||
data = helpers.RequestData(
|
||||
config, "test_user", SOURCE_LOCAL, "test_request_id", None
|
||||
)
|
||||
assert data.is_local_request is True
|
||||
|
||||
data = helpers.RequestData(
|
||||
config, "test_user", SOURCE_CLOUD, "test_request_id", None
|
||||
)
|
||||
assert data.is_local_request is False
|
||||
|
||||
|
||||
async def test_config_local_sdk_allow_min_version(
|
||||
hass: HomeAssistant,
|
||||
hass_client: ClientSessionGenerator,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""Test the local SDK."""
|
||||
version = str(helpers.LOCAL_SDK_MIN_VERSION)
|
||||
assert await async_setup_component(hass, "webhook", {})
|
||||
|
||||
config = MockConfig(
|
||||
hass=hass,
|
||||
agent_user_ids={
|
||||
"mock-user-id": {
|
||||
STORE_GOOGLE_LOCAL_WEBHOOK_ID: "mock-webhook-id",
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
client = await hass_client()
|
||||
|
||||
assert config._local_sdk_version_warn is False
|
||||
config.async_enable_local_sdk()
|
||||
|
||||
await client.post(
|
||||
"/api/webhook/mock-webhook-id",
|
||||
headers={helpers.LOCAL_SDK_VERSION_HEADER: version},
|
||||
json={
|
||||
"inputs": [
|
||||
{
|
||||
"context": {"locale_country": "US", "locale_language": "en"},
|
||||
"intent": "action.devices.SYNC",
|
||||
}
|
||||
],
|
||||
"requestId": "mock-req-id",
|
||||
},
|
||||
)
|
||||
assert config._local_sdk_version_warn is False
|
||||
assert (
|
||||
f"Local SDK version is too old ({version}), check documentation on how "
|
||||
"to update to the latest version"
|
||||
) not in caplog.text
|
||||
|
||||
|
||||
@pytest.mark.parametrize("version", [None, "2.1.4"])
|
||||
async def test_config_local_sdk_warn_version(
|
||||
hass: HomeAssistant,
|
||||
hass_client: ClientSessionGenerator,
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
version,
|
||||
) -> None:
|
||||
"""Test the local SDK."""
|
||||
assert await async_setup_component(hass, "webhook", {})
|
||||
|
||||
config = MockConfig(
|
||||
hass=hass,
|
||||
agent_user_ids={
|
||||
"mock-user-id": {
|
||||
STORE_GOOGLE_LOCAL_WEBHOOK_ID: "mock-webhook-id",
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
client = await hass_client()
|
||||
|
||||
assert config._local_sdk_version_warn is False
|
||||
config.async_enable_local_sdk()
|
||||
|
||||
headers = {}
|
||||
if version:
|
||||
headers[helpers.LOCAL_SDK_VERSION_HEADER] = version
|
||||
|
||||
await client.post(
|
||||
"/api/webhook/mock-webhook-id",
|
||||
headers=headers,
|
||||
json={
|
||||
"inputs": [
|
||||
{
|
||||
"context": {"locale_country": "US", "locale_language": "en"},
|
||||
"intent": "action.devices.SYNC",
|
||||
}
|
||||
],
|
||||
"requestId": "mock-req-id",
|
||||
},
|
||||
)
|
||||
assert config._local_sdk_version_warn is True
|
||||
assert (
|
||||
f"Local SDK version is too old ({version}), check documentation on how "
|
||||
"to update to the latest version"
|
||||
) in caplog.text
|
||||
|
||||
|
||||
def test_async_get_entities_cached(hass: HomeAssistant) -> None:
|
||||
"""Test async_get_entities is cached."""
|
||||
config = MockConfig()
|
||||
|
||||
hass.states.async_set("light.ceiling_lights", "off")
|
||||
hass.states.async_set("light.bed_light", "off")
|
||||
hass.states.async_set("not_supported.not_supported", "off")
|
||||
|
||||
google_entities = helpers.async_get_entities(hass, config)
|
||||
assert len(google_entities) == 2
|
||||
assert config.is_supported_cache == {
|
||||
"light.bed_light": (None, True),
|
||||
"light.ceiling_lights": (None, True),
|
||||
"not_supported.not_supported": (None, False),
|
||||
}
|
||||
|
||||
with patch(
|
||||
"homeassistant.components.google_assistant.helpers.GoogleEntity.traits",
|
||||
return_value=RuntimeError("Should not be called"),
|
||||
):
|
||||
google_entities = helpers.async_get_entities(hass, config)
|
||||
|
||||
assert len(google_entities) == 2
|
||||
assert config.is_supported_cache == {
|
||||
"light.bed_light": (None, True),
|
||||
"light.ceiling_lights": (None, True),
|
||||
"not_supported.not_supported": (None, False),
|
||||
}
|
||||
|
||||
hass.states.async_set("light.new", "on")
|
||||
google_entities = helpers.async_get_entities(hass, config)
|
||||
|
||||
assert len(google_entities) == 3
|
||||
assert config.is_supported_cache == {
|
||||
"light.bed_light": (None, True),
|
||||
"light.new": (None, True),
|
||||
"light.ceiling_lights": (None, True),
|
||||
"not_supported.not_supported": (None, False),
|
||||
}
|
||||
|
||||
hass.states.async_set("light.new", "on", {"supported_features": 1})
|
||||
google_entities = helpers.async_get_entities(hass, config)
|
||||
|
||||
assert len(google_entities) == 3
|
||||
assert config.is_supported_cache == {
|
||||
"light.bed_light": (None, True),
|
||||
"light.new": (1, True),
|
||||
"light.ceiling_lights": (None, True),
|
||||
"not_supported.not_supported": (None, False),
|
||||
}
|
||||
662
home-assistant/tests/components/google_assistant/test_http.py
Normal file
662
home-assistant/tests/components/google_assistant/test_http.py
Normal file
@@ -0,0 +1,662 @@
|
||||
"""Test Google http services."""
|
||||
|
||||
from datetime import UTC, datetime, timedelta
|
||||
from http import HTTPStatus
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
from typing import Any
|
||||
from unittest.mock import ANY, patch
|
||||
from uuid import uuid4
|
||||
|
||||
import py
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.google_assistant import GOOGLE_ASSISTANT_SCHEMA
|
||||
from homeassistant.components.google_assistant.const import (
|
||||
DOMAIN,
|
||||
EVENT_COMMAND_RECEIVED,
|
||||
HOMEGRAPH_TOKEN_URL,
|
||||
REPORT_STATE_BASE_URL,
|
||||
STORE_AGENT_USER_IDS,
|
||||
STORE_GOOGLE_LOCAL_WEBHOOK_ID,
|
||||
)
|
||||
from homeassistant.components.google_assistant.http import (
|
||||
GoogleConfig,
|
||||
GoogleConfigStore,
|
||||
_get_homegraph_jwt,
|
||||
_get_homegraph_token,
|
||||
async_get_users,
|
||||
)
|
||||
from homeassistant.const import CLOUD_NEVER_EXPOSED_ENTITIES
|
||||
from homeassistant.core import HomeAssistant, State
|
||||
from homeassistant.setup import async_setup_component
|
||||
from homeassistant.util import dt as dt_util
|
||||
|
||||
from tests.common import (
|
||||
async_capture_events,
|
||||
async_fire_time_changed,
|
||||
async_mock_service,
|
||||
async_test_home_assistant,
|
||||
)
|
||||
from tests.test_util.aiohttp import AiohttpClientMocker
|
||||
from tests.typing import ClientSessionGenerator
|
||||
|
||||
DUMMY_CONFIG = GOOGLE_ASSISTANT_SCHEMA(
|
||||
{
|
||||
"project_id": "1234",
|
||||
"service_account": {
|
||||
"private_key": "-----BEGIN PRIVATE KEY-----\nMIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKYscIlwm7soDsHAz6L6YvUkCvkrX19rS6yeYOmovvhoK5WeYGWUsd8V72zmsyHB7XO94YgJVjvxfzn5K8bLePjFzwoSJjZvhBJ/ZQ05d8VmbvgyWUoPdG9oEa4fZ/lCYrXoaFdTot2xcJvrb/ZuiRl4s4eZpNeFYvVK/Am7UeFPAgMBAAECgYAUetOfzLYUudofvPCaKHu7tKZ5kQPfEa0w6BAPnBF1Mfl1JiDBRDMryFtKs6AOIAVwx00dY/Ex0BCbB3+Cr58H7t4NaPTJxCpmR09pK7o17B7xAdQv8+SynFNud9/5vQ5AEXMOLNwKiU7wpXT6Z7ZIibUBOR7ewsWgsHCDpN1iqQJBAOMODPTPSiQMwRAUHIc6GPleFSJnIz2PAoG3JOG9KFAL6RtIc19lob2ZXdbQdzKtjSkWo+O5W20WDNAl1k32h6MCQQC7W4ZCIY67mPbL6CxXfHjpSGF4Dr9VWJ7ZrKHr6XUoOIcEvsn/pHvWonjMdy93rQMSfOE8BKd/I1+GHRmNVgplAkAnSo4paxmsZVyfeKt7Jy2dMY+8tVZe17maUuQaAE7Sk00SgJYegwrbMYgQnWCTL39HBfj0dmYA2Zj8CCAuu6O7AkEAryFiYjaUAO9+4iNoL27+ZrFtypeeadyov7gKs0ZKaQpNyzW8A+Zwi7TbTeSqzic/E+z/bOa82q7p/6b7141xsQJBANCAcIwMcVb6KVCHlQbOtKspo5Eh4ZQi8bGl+IcwbQ6JSxeTx915IfAldgbuU047wOB04dYCFB2yLDiUGVXTifU=\n-----END PRIVATE KEY-----\n",
|
||||
"client_email": "dummy@dummy.iam.gserviceaccount.com",
|
||||
},
|
||||
}
|
||||
)
|
||||
MOCK_TOKEN = {"access_token": "dummtoken", "expires_in": 3600}
|
||||
MOCK_JSON = {"devices": {}}
|
||||
MOCK_URL = "https://dummy"
|
||||
MOCK_HEADER = {
|
||||
"Authorization": f"Bearer {MOCK_TOKEN['access_token']}",
|
||||
"X-GFE-SSL": "yes",
|
||||
}
|
||||
|
||||
|
||||
async def test_get_jwt(hass: HomeAssistant) -> None:
|
||||
"""Test signing of key."""
|
||||
|
||||
jwt = "eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJkdW1teUBkdW1teS5pYW0uZ3NlcnZpY2VhY2NvdW50LmNvbSIsInNjb3BlIjoiaHR0cHM6Ly93d3cuZ29vZ2xlYXBpcy5jb20vYXV0aC9ob21lZ3JhcGgiLCJhdWQiOiJodHRwczovL2FjY291bnRzLmdvb2dsZS5jb20vby9vYXV0aDIvdG9rZW4iLCJpYXQiOjE1NzEwMTEyMDAsImV4cCI6MTU3MTAxNDgwMH0.akHbMhOflXdIDHVvUVwO0AoJONVOPUdCghN6hAdVz4gxjarrQeGYc_Qn2r84bEvCU7t6EvimKKr0fyupyzBAzfvKULs5mTHO3h2CwSgvOBMv8LnILboJmbO4JcgdnRV7d9G3ktQs7wWSCXJsI5i5jUr1Wfi9zWwxn2ebaAAgrp8"
|
||||
res = _get_homegraph_jwt(
|
||||
datetime(2019, 10, 14, tzinfo=UTC),
|
||||
DUMMY_CONFIG["service_account"]["client_email"],
|
||||
DUMMY_CONFIG["service_account"]["private_key"],
|
||||
)
|
||||
assert res == jwt
|
||||
|
||||
|
||||
async def test_get_access_token(
|
||||
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker
|
||||
) -> None:
|
||||
"""Test the function to get access token."""
|
||||
jwt = "dummyjwt"
|
||||
|
||||
aioclient_mock.post(
|
||||
HOMEGRAPH_TOKEN_URL,
|
||||
status=HTTPStatus.OK,
|
||||
json={"access_token": "1234", "expires_in": 3600},
|
||||
)
|
||||
|
||||
await _get_homegraph_token(hass, jwt)
|
||||
assert aioclient_mock.call_count == 1
|
||||
assert aioclient_mock.mock_calls[0][3] == {
|
||||
"Authorization": f"Bearer {jwt}",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
}
|
||||
|
||||
|
||||
async def test_update_access_token(hass: HomeAssistant) -> None:
|
||||
"""Test the function to update access token when expired."""
|
||||
jwt = "dummyjwt"
|
||||
|
||||
config = GoogleConfig(hass, DUMMY_CONFIG)
|
||||
await config.async_initialize()
|
||||
|
||||
base_time = datetime(2019, 10, 14, tzinfo=UTC)
|
||||
with (
|
||||
patch(
|
||||
"homeassistant.components.google_assistant.http._get_homegraph_token"
|
||||
) as mock_get_token,
|
||||
patch(
|
||||
"homeassistant.components.google_assistant.http._get_homegraph_jwt"
|
||||
) as mock_get_jwt,
|
||||
patch(
|
||||
"homeassistant.core.dt_util.utcnow",
|
||||
) as mock_utcnow,
|
||||
):
|
||||
mock_utcnow.return_value = base_time
|
||||
mock_get_jwt.return_value = jwt
|
||||
mock_get_token.return_value = MOCK_TOKEN
|
||||
|
||||
await config._async_update_token()
|
||||
mock_get_token.assert_called_once()
|
||||
|
||||
mock_get_token.reset_mock()
|
||||
|
||||
mock_utcnow.return_value = base_time + timedelta(seconds=3600)
|
||||
await config._async_update_token()
|
||||
mock_get_token.assert_not_called()
|
||||
|
||||
mock_get_token.reset_mock()
|
||||
|
||||
mock_utcnow.return_value = base_time + timedelta(seconds=3601)
|
||||
await config._async_update_token()
|
||||
mock_get_token.assert_called_once()
|
||||
|
||||
|
||||
async def test_call_homegraph_api(
|
||||
hass: HomeAssistant,
|
||||
aioclient_mock: AiohttpClientMocker,
|
||||
hass_storage: dict[str, Any],
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""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:
|
||||
mock_get_token.return_value = MOCK_TOKEN
|
||||
|
||||
aioclient_mock.post(MOCK_URL, status=HTTPStatus.OK, json={})
|
||||
|
||||
res = await config.async_call_homegraph_api(MOCK_URL, MOCK_JSON)
|
||||
assert res == HTTPStatus.OK
|
||||
|
||||
assert mock_get_token.call_count == 1
|
||||
assert aioclient_mock.call_count == 1
|
||||
|
||||
call = aioclient_mock.mock_calls[0]
|
||||
assert call[2] == MOCK_JSON
|
||||
assert call[3] == MOCK_HEADER
|
||||
|
||||
|
||||
async def test_call_homegraph_api_retry(
|
||||
hass: HomeAssistant,
|
||||
aioclient_mock: AiohttpClientMocker,
|
||||
hass_storage: dict[str, Any],
|
||||
) -> None:
|
||||
"""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:
|
||||
mock_get_token.return_value = MOCK_TOKEN
|
||||
|
||||
aioclient_mock.post(MOCK_URL, status=HTTPStatus.UNAUTHORIZED, json={})
|
||||
|
||||
await config.async_call_homegraph_api(MOCK_URL, MOCK_JSON)
|
||||
|
||||
assert mock_get_token.call_count == 2
|
||||
assert aioclient_mock.call_count == 2
|
||||
|
||||
call = aioclient_mock.mock_calls[0]
|
||||
assert call[2] == MOCK_JSON
|
||||
assert call[3] == MOCK_HEADER
|
||||
call = aioclient_mock.mock_calls[1]
|
||||
assert call[2] == MOCK_JSON
|
||||
assert call[3] == MOCK_HEADER
|
||||
|
||||
|
||||
async def test_report_state(
|
||||
hass: HomeAssistant,
|
||||
aioclient_mock: AiohttpClientMocker,
|
||||
hass_storage: dict[str, Any],
|
||||
) -> None:
|
||||
"""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": {}}
|
||||
|
||||
with patch.object(config, "async_call_homegraph_api"):
|
||||
# Wait for google_assistant.helpers.async_initialize.sync_google to be called
|
||||
await hass.async_block_till_done()
|
||||
|
||||
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": agent_user_id, "payload": message},
|
||||
)
|
||||
|
||||
|
||||
async def test_report_event(
|
||||
hass: HomeAssistant,
|
||||
aioclient_mock: AiohttpClientMocker,
|
||||
hass_storage: dict[str, Any],
|
||||
) -> None:
|
||||
"""Test the report event 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": {}}
|
||||
|
||||
with patch.object(config, "async_call_homegraph_api"):
|
||||
# Wait for google_assistant.helpers.async_initialize.sync_google to be called
|
||||
await hass.async_block_till_done()
|
||||
|
||||
event_id = uuid4().hex
|
||||
with patch.object(config, "async_call_homegraph_api") as mock_call:
|
||||
# Wait for google_assistant.helpers.async_initialize.sync_google to be called
|
||||
await config.async_report_state(message, agent_user_id, event_id=event_id)
|
||||
mock_call.assert_called_once_with(
|
||||
REPORT_STATE_BASE_URL,
|
||||
{
|
||||
"requestId": ANY,
|
||||
"agentUserId": agent_user_id,
|
||||
"payload": message,
|
||||
"eventId": event_id,
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
async def test_google_config_local_fulfillment(
|
||||
hass: HomeAssistant,
|
||||
aioclient_mock: AiohttpClientMocker,
|
||||
hass_storage: dict[str, Any],
|
||||
) -> None:
|
||||
"""Test the google config for local fulfillment."""
|
||||
agent_user_id = "user"
|
||||
local_webhook_id = "webhook"
|
||||
|
||||
hass_storage["google_assistant"] = {
|
||||
"version": 1,
|
||||
"minor_version": 1,
|
||||
"key": "google_assistant",
|
||||
"data": {
|
||||
"agent_user_ids": {
|
||||
agent_user_id: {
|
||||
"local_webhook_id": local_webhook_id,
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
config = GoogleConfig(hass, DUMMY_CONFIG)
|
||||
await config.async_initialize()
|
||||
|
||||
with patch.object(config, "async_call_homegraph_api"):
|
||||
# Wait for google_assistant.helpers.async_initialize.sync_google to be called
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert config.get_local_webhook_id(agent_user_id) == local_webhook_id
|
||||
assert config.get_local_user_id(local_webhook_id) == agent_user_id
|
||||
assert config.get_local_user_id("INCORRECT") is None
|
||||
|
||||
|
||||
async def test_secure_device_pin_config(hass: HomeAssistant) -> None:
|
||||
"""Test the setting of the secure device pin configuration."""
|
||||
secure_pin = "TEST"
|
||||
secure_config = GOOGLE_ASSISTANT_SCHEMA(
|
||||
{
|
||||
"project_id": "1234",
|
||||
"service_account": {
|
||||
"private_key": "-----BEGIN PRIVATE KEY-----\nMIICdwIBADANBgkqhkiG9w0BAQEFAASCAmEwggJdAgEAAoGBAKYscIlwm7soDsHAz6L6YvUkCvkrX19rS6yeYOmovvhoK5WeYGWUsd8V72zmsyHB7XO94YgJVjvxfzn5K8bLePjFzwoSJjZvhBJ/ZQ05d8VmbvgyWUoPdG9oEa4fZ/lCYrXoaFdTot2xcJvrb/ZuiRl4s4eZpNeFYvVK/Am7UeFPAgMBAAECgYAUetOfzLYUudofvPCaKHu7tKZ5kQPfEa0w6BAPnBF1Mfl1JiDBRDMryFtKs6AOIAVwx00dY/Ex0BCbB3+Cr58H7t4NaPTJxCpmR09pK7o17B7xAdQv8+SynFNud9/5vQ5AEXMOLNwKiU7wpXT6Z7ZIibUBOR7ewsWgsHCDpN1iqQJBAOMODPTPSiQMwRAUHIc6GPleFSJnIz2PAoG3JOG9KFAL6RtIc19lob2ZXdbQdzKtjSkWo+O5W20WDNAl1k32h6MCQQC7W4ZCIY67mPbL6CxXfHjpSGF4Dr9VWJ7ZrKHr6XUoOIcEvsn/pHvWonjMdy93rQMSfOE8BKd/I1+GHRmNVgplAkAnSo4paxmsZVyfeKt7Jy2dMY+8tVZe17maUuQaAE7Sk00SgJYegwrbMYgQnWCTL39HBfj0dmYA2Zj8CCAuu6O7AkEAryFiYjaUAO9+4iNoL27+ZrFtypeeadyov7gKs0ZKaQpNyzW8A+Zwi7TbTeSqzic/E+z/bOa82q7p/6b7141xsQJBANCAcIwMcVb6KVCHlQbOtKspo5Eh4ZQi8bGl+IcwbQ6JSxeTx915IfAldgbuU047wOB04dYCFB2yLDiUGVXTifU=\n-----END PRIVATE KEY-----\n",
|
||||
"client_email": "dummy@dummy.iam.gserviceaccount.com",
|
||||
},
|
||||
"secure_devices_pin": secure_pin,
|
||||
}
|
||||
)
|
||||
config = GoogleConfig(hass, secure_config)
|
||||
|
||||
assert config.secure_devices_pin == secure_pin
|
||||
|
||||
|
||||
async def test_should_expose(hass: HomeAssistant) -> None:
|
||||
"""Test the google config should expose method."""
|
||||
config = GoogleConfig(hass, DUMMY_CONFIG)
|
||||
await config.async_initialize()
|
||||
|
||||
with patch.object(config, "async_call_homegraph_api"):
|
||||
# Wait for google_assistant.helpers.async_initialize.sync_google to be called
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert (
|
||||
config.should_expose(State(DOMAIN + ".mock", "mock", {"view": "not None"}))
|
||||
is False
|
||||
)
|
||||
|
||||
with patch.object(config, "async_call_homegraph_api"):
|
||||
# Wait for google_assistant.helpers.async_initialize.sync_google to be called
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert config.should_expose(State(CLOUD_NEVER_EXPOSED_ENTITIES[0], "mock")) is False
|
||||
|
||||
|
||||
async def test_missing_service_account(hass: HomeAssistant) -> None:
|
||||
"""Test the google config _async_request_sync_devices."""
|
||||
incorrect_config = GOOGLE_ASSISTANT_SCHEMA(
|
||||
{
|
||||
"project_id": "1234",
|
||||
}
|
||||
)
|
||||
config = GoogleConfig(hass, incorrect_config)
|
||||
await config.async_initialize()
|
||||
|
||||
with patch.object(config, "async_call_homegraph_api"):
|
||||
# Wait for google_assistant.helpers.async_initialize.sync_google to be called
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert (
|
||||
await config._async_request_sync_devices("mock")
|
||||
is HTTPStatus.INTERNAL_SERVER_ERROR
|
||||
)
|
||||
renew = config._access_token_renew
|
||||
await config._async_update_token()
|
||||
assert config._access_token_renew is renew
|
||||
|
||||
|
||||
async def test_async_enable_local_sdk(
|
||||
hass: HomeAssistant,
|
||||
hass_client: ClientSessionGenerator,
|
||||
hass_storage: dict[str, Any],
|
||||
caplog: pytest.LogCaptureFixture,
|
||||
) -> None:
|
||||
"""Test the google config enable and disable local sdk."""
|
||||
command_events = async_capture_events(hass, EVENT_COMMAND_RECEIVED)
|
||||
turn_on_calls = async_mock_service(hass, "light", "turn_on")
|
||||
hass.states.async_set("light.ceiling_lights", "off")
|
||||
|
||||
assert await async_setup_component(hass, "webhook", {})
|
||||
|
||||
hass_storage["google_assistant"] = {
|
||||
"version": 1,
|
||||
"minor_version": 1,
|
||||
"key": "google_assistant",
|
||||
"data": {
|
||||
"agent_user_ids": {
|
||||
"agent_1": {
|
||||
"local_webhook_id": "mock_webhook_id",
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
config = GoogleConfig(hass, DUMMY_CONFIG)
|
||||
await config.async_initialize()
|
||||
|
||||
with patch.object(config, "async_call_homegraph_api"):
|
||||
# Wait for google_assistant.helpers.async_initialize.sync_google to be called
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert config.is_local_sdk_active is True
|
||||
|
||||
client = await hass_client()
|
||||
|
||||
resp = await client.post(
|
||||
"/api/webhook/mock_webhook_id",
|
||||
json={
|
||||
"inputs": [
|
||||
{
|
||||
"context": {"locale_country": "US", "locale_language": "en"},
|
||||
"intent": "action.devices.EXECUTE",
|
||||
"payload": {
|
||||
"commands": [
|
||||
{
|
||||
"devices": [{"id": "light.ceiling_lights"}],
|
||||
"execution": [
|
||||
{
|
||||
"command": "action.devices.commands.OnOff",
|
||||
"params": {"on": True},
|
||||
}
|
||||
],
|
||||
}
|
||||
],
|
||||
"structureData": {},
|
||||
},
|
||||
}
|
||||
],
|
||||
"requestId": "mock_req_id",
|
||||
},
|
||||
)
|
||||
assert resp.status == HTTPStatus.OK
|
||||
result = await resp.json()
|
||||
assert result["requestId"] == "mock_req_id"
|
||||
|
||||
assert len(command_events) == 1
|
||||
assert command_events[0].context.user_id == "agent_1"
|
||||
|
||||
assert len(turn_on_calls) == 1
|
||||
assert turn_on_calls[0].context is command_events[0].context
|
||||
|
||||
config.async_disable_local_sdk()
|
||||
assert config.is_local_sdk_active is False
|
||||
|
||||
config._store._data = {
|
||||
STORE_AGENT_USER_IDS: {
|
||||
"agent_1": {STORE_GOOGLE_LOCAL_WEBHOOK_ID: "mock_webhook_id"},
|
||||
"agent_2": {STORE_GOOGLE_LOCAL_WEBHOOK_ID: "mock_webhook_id"},
|
||||
},
|
||||
}
|
||||
config.async_enable_local_sdk()
|
||||
assert config.is_local_sdk_active is False
|
||||
|
||||
config._store._data = {
|
||||
STORE_AGENT_USER_IDS: {
|
||||
"agent_1": {STORE_GOOGLE_LOCAL_WEBHOOK_ID: None},
|
||||
},
|
||||
}
|
||||
config.async_enable_local_sdk()
|
||||
assert config.is_local_sdk_active is False
|
||||
|
||||
config._store._data = {
|
||||
STORE_AGENT_USER_IDS: {
|
||||
"agent_2": {STORE_GOOGLE_LOCAL_WEBHOOK_ID: "mock_webhook_id"},
|
||||
"agent_1": {STORE_GOOGLE_LOCAL_WEBHOOK_ID: None},
|
||||
},
|
||||
}
|
||||
config.async_enable_local_sdk()
|
||||
assert config.is_local_sdk_active is False
|
||||
|
||||
config.async_disable_local_sdk()
|
||||
|
||||
config._store._data = {
|
||||
STORE_AGENT_USER_IDS: {
|
||||
"agent_1": {STORE_GOOGLE_LOCAL_WEBHOOK_ID: "mock_webhook_id"},
|
||||
},
|
||||
}
|
||||
config.async_enable_local_sdk()
|
||||
|
||||
config._store.pop_agent_user_id("agent_1")
|
||||
|
||||
caplog.clear()
|
||||
|
||||
resp = await client.post(
|
||||
"/api/webhook/mock_webhook_id",
|
||||
json={
|
||||
"inputs": [
|
||||
{
|
||||
"context": {"locale_country": "US", "locale_language": "en"},
|
||||
"intent": "action.devices.EXECUTE",
|
||||
"payload": {
|
||||
"commands": [
|
||||
{
|
||||
"devices": [{"id": "light.ceiling_lights"}],
|
||||
"execution": [
|
||||
{
|
||||
"command": "action.devices.commands.OnOff",
|
||||
"params": {"on": True},
|
||||
}
|
||||
],
|
||||
}
|
||||
],
|
||||
"structureData": {},
|
||||
},
|
||||
}
|
||||
],
|
||||
"requestId": "mock_req_id",
|
||||
},
|
||||
)
|
||||
assert resp.status == HTTPStatus.OK
|
||||
assert (
|
||||
"Cannot process request for webhook **REDACTED** as no linked agent user is found:"
|
||||
in caplog.text
|
||||
)
|
||||
|
||||
|
||||
async def test_agent_user_id_storage(
|
||||
hass: HomeAssistant, hass_storage: dict[str, Any]
|
||||
) -> None:
|
||||
"""Test a disconnect message."""
|
||||
|
||||
hass_storage["google_assistant"] = {
|
||||
"version": 1,
|
||||
"minor_version": 1,
|
||||
"key": "google_assistant",
|
||||
"data": {
|
||||
"agent_user_ids": {
|
||||
"agent_1": {
|
||||
"local_webhook_id": "test_webhook",
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
store = GoogleConfigStore(hass)
|
||||
await store.async_initialize()
|
||||
|
||||
assert hass_storage["google_assistant"] == {
|
||||
"version": 1,
|
||||
"minor_version": 2,
|
||||
"key": "google_assistant",
|
||||
"data": {
|
||||
"agent_user_ids": {
|
||||
"agent_1": {
|
||||
"local_webhook_id": "test_webhook",
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
async def _check_after_delay(data):
|
||||
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=2))
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert (
|
||||
list(hass_storage["google_assistant"]["data"]["agent_user_ids"].keys())
|
||||
== data
|
||||
)
|
||||
|
||||
store.add_agent_user_id("agent_2")
|
||||
await _check_after_delay(["agent_1", "agent_2"])
|
||||
|
||||
store.pop_agent_user_id("agent_1")
|
||||
await _check_after_delay(["agent_2"])
|
||||
|
||||
hass_storage["google_assistant"] = {
|
||||
"version": 1,
|
||||
"minor_version": 2,
|
||||
"key": "google_assistant",
|
||||
"data": {
|
||||
"agent_user_ids": {"agent_1": {}},
|
||||
},
|
||||
}
|
||||
store = GoogleConfigStore(hass)
|
||||
await store.async_initialize()
|
||||
|
||||
assert (
|
||||
STORE_GOOGLE_LOCAL_WEBHOOK_ID
|
||||
in hass_storage["google_assistant"]["data"]["agent_user_ids"]["agent_1"]
|
||||
)
|
||||
|
||||
|
||||
async def test_async_get_users_no_store(hass: HomeAssistant) -> None:
|
||||
"""Test async_get_users when there is no store."""
|
||||
assert await async_get_users(hass) == []
|
||||
|
||||
|
||||
async def test_async_get_users_from_store(tmpdir: py.path.local) -> None:
|
||||
"""Test async_get_users from a store.
|
||||
|
||||
This test ensures we can load from data saved by GoogleConfigStore.
|
||||
"""
|
||||
async with async_test_home_assistant() as hass:
|
||||
hass.config.config_dir = await hass.async_add_executor_job(
|
||||
tmpdir.mkdir, "temp_storage"
|
||||
)
|
||||
|
||||
store = GoogleConfigStore(hass)
|
||||
await store.async_initialize()
|
||||
|
||||
store.add_agent_user_id("agent_1")
|
||||
async_fire_time_changed(hass, dt_util.utcnow() + timedelta(seconds=2))
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert await async_get_users(hass) == ["agent_1"]
|
||||
|
||||
await hass.async_stop()
|
||||
|
||||
|
||||
VALID_STORE_DATA = json.dumps(
|
||||
{
|
||||
"version": 1,
|
||||
"minor_version": 2,
|
||||
"key": "google_assistant",
|
||||
"data": {
|
||||
"agent_user_ids": {"agent_1": {}},
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
NO_DATA = json.dumps(
|
||||
{
|
||||
"version": 1,
|
||||
"minor_version": 2,
|
||||
"key": "google_assistant",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
DATA_NOT_DICT = json.dumps(
|
||||
{
|
||||
"version": 1,
|
||||
"minor_version": 2,
|
||||
"key": "google_assistant",
|
||||
"data": "hello",
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
NO_AGENT_USER_IDS = json.dumps(
|
||||
{
|
||||
"version": 1,
|
||||
"minor_version": 2,
|
||||
"key": "google_assistant",
|
||||
"data": {},
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
AGENT_USER_IDS_NOT_DICT = json.dumps(
|
||||
{
|
||||
"version": 1,
|
||||
"minor_version": 2,
|
||||
"key": "google_assistant",
|
||||
"data": {
|
||||
"agent_user_ids": "hello",
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("store_data", "expected_users"),
|
||||
[
|
||||
(VALID_STORE_DATA, ["agent_1"]),
|
||||
("", []),
|
||||
("not_a_dict", []),
|
||||
(NO_DATA, []),
|
||||
(DATA_NOT_DICT, []),
|
||||
(NO_AGENT_USER_IDS, []),
|
||||
(AGENT_USER_IDS_NOT_DICT, []),
|
||||
],
|
||||
)
|
||||
async def test_async_get_users(
|
||||
tmpdir: py.path.local, store_data: str, expected_users: list[str]
|
||||
) -> None:
|
||||
"""Test async_get_users from stored JSON data."""
|
||||
async with async_test_home_assistant() as hass:
|
||||
hass.config.config_dir = await hass.async_add_executor_job(
|
||||
tmpdir.mkdir, "temp_storage"
|
||||
)
|
||||
path = hass.config.config_dir / ".storage" / GoogleConfigStore._STORAGE_KEY
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
await hass.async_add_executor_job(Path(path).write_text, store_data)
|
||||
assert await async_get_users(hass) == expected_users
|
||||
|
||||
await hass.async_stop()
|
||||
@@ -0,0 +1,75 @@
|
||||
"""The tests for google-assistant init."""
|
||||
|
||||
from http import HTTPStatus
|
||||
|
||||
from homeassistant.components import google_assistant as ga
|
||||
from homeassistant.core import Context, HomeAssistant
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
from .test_http import DUMMY_CONFIG
|
||||
|
||||
from tests.common import MockConfigEntry
|
||||
from tests.test_util.aiohttp import AiohttpClientMocker
|
||||
|
||||
|
||||
async def test_import(hass: HomeAssistant) -> None:
|
||||
"""Test import."""
|
||||
|
||||
await async_setup_component(
|
||||
hass,
|
||||
ga.DOMAIN,
|
||||
{"google_assistant": DUMMY_CONFIG},
|
||||
)
|
||||
|
||||
entries = hass.config_entries.async_entries("google_assistant")
|
||||
assert len(entries) == 1
|
||||
assert entries[0].data[ga.const.CONF_PROJECT_ID] == "1234"
|
||||
|
||||
|
||||
async def test_import_changed(hass: HomeAssistant) -> None:
|
||||
"""Test import with changed project id."""
|
||||
|
||||
old_entry = MockConfigEntry(
|
||||
domain=ga.DOMAIN, data={ga.const.CONF_PROJECT_ID: "4321"}, source="import"
|
||||
)
|
||||
old_entry.add_to_hass(hass)
|
||||
|
||||
await async_setup_component(
|
||||
hass,
|
||||
ga.DOMAIN,
|
||||
{"google_assistant": DUMMY_CONFIG},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
entries = hass.config_entries.async_entries("google_assistant")
|
||||
assert len(entries) == 1
|
||||
assert entries[0].data[ga.const.CONF_PROJECT_ID] == "1234"
|
||||
|
||||
|
||||
async def test_request_sync_service(
|
||||
aioclient_mock: AiohttpClientMocker, hass: HomeAssistant
|
||||
) -> None:
|
||||
"""Test that it posts to the request_sync url."""
|
||||
aioclient_mock.post(
|
||||
ga.const.HOMEGRAPH_TOKEN_URL,
|
||||
status=HTTPStatus.OK,
|
||||
json={"access_token": "1234", "expires_in": 3600},
|
||||
)
|
||||
|
||||
aioclient_mock.post(ga.const.REQUEST_SYNC_BASE_URL, status=HTTPStatus.OK)
|
||||
|
||||
await async_setup_component(
|
||||
hass,
|
||||
"google_assistant",
|
||||
{"google_assistant": DUMMY_CONFIG},
|
||||
)
|
||||
|
||||
assert aioclient_mock.call_count == 0
|
||||
await hass.services.async_call(
|
||||
ga.const.DOMAIN,
|
||||
ga.const.SERVICE_REQUEST_SYNC,
|
||||
blocking=True,
|
||||
context=Context(user_id="123"),
|
||||
)
|
||||
|
||||
assert aioclient_mock.call_count == 2 # token + request
|
||||
@@ -0,0 +1,71 @@
|
||||
"""The tests for Google Assistant logbook."""
|
||||
|
||||
from homeassistant.components.google_assistant.const import (
|
||||
DOMAIN,
|
||||
EVENT_COMMAND_RECEIVED,
|
||||
SOURCE_CLOUD,
|
||||
SOURCE_LOCAL,
|
||||
)
|
||||
from homeassistant.const import ATTR_ENTITY_ID, ATTR_FRIENDLY_NAME
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.setup import async_setup_component
|
||||
|
||||
from tests.components.logbook.common import MockRow, mock_humanify
|
||||
|
||||
|
||||
async def test_humanify_command_received(hass: HomeAssistant) -> None:
|
||||
"""Test humanifying command event."""
|
||||
hass.config.components.add("recorder")
|
||||
hass.config.components.add("frontend")
|
||||
hass.config.components.add("google_assistant")
|
||||
assert await async_setup_component(hass, "logbook", {})
|
||||
await hass.async_block_till_done()
|
||||
|
||||
hass.states.async_set(
|
||||
"light.kitchen", "on", {ATTR_FRIENDLY_NAME: "The Kitchen Lights"}
|
||||
)
|
||||
|
||||
events = mock_humanify(
|
||||
hass,
|
||||
[
|
||||
MockRow(
|
||||
EVENT_COMMAND_RECEIVED,
|
||||
{
|
||||
"request_id": "abcd",
|
||||
ATTR_ENTITY_ID: ["light.kitchen"],
|
||||
"execution": [
|
||||
{
|
||||
"command": "action.devices.commands.OnOff",
|
||||
"params": {"on": True},
|
||||
}
|
||||
],
|
||||
"source": SOURCE_LOCAL,
|
||||
},
|
||||
),
|
||||
MockRow(
|
||||
EVENT_COMMAND_RECEIVED,
|
||||
{
|
||||
"request_id": "abcd",
|
||||
ATTR_ENTITY_ID: ["light.non_existing"],
|
||||
"execution": [
|
||||
{
|
||||
"command": "action.devices.commands.OnOff",
|
||||
"params": {"on": False},
|
||||
}
|
||||
],
|
||||
"source": SOURCE_CLOUD,
|
||||
},
|
||||
),
|
||||
],
|
||||
)
|
||||
|
||||
assert len(events) == 2
|
||||
event1, event2 = events
|
||||
|
||||
assert event1["name"] == "Google Assistant"
|
||||
assert event1["domain"] == DOMAIN
|
||||
assert event1["message"] == "sent command OnOff (via local)"
|
||||
|
||||
assert event2["name"] == "Google Assistant"
|
||||
assert event2["domain"] == DOMAIN
|
||||
assert event2["message"] == "sent command OnOff"
|
||||
@@ -0,0 +1,294 @@
|
||||
"""Test Google report state."""
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from http import HTTPStatus
|
||||
from unittest.mock import AsyncMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from homeassistant.components.google_assistant import error, report_state
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.setup import async_setup_component
|
||||
from homeassistant.util.dt import utcnow
|
||||
|
||||
from . import BASIC_CONFIG, MockConfig
|
||||
|
||||
from tests.common import async_fire_time_changed
|
||||
|
||||
|
||||
async def test_report_state(
|
||||
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
"""Test report state works."""
|
||||
assert await async_setup_component(hass, "switch", {})
|
||||
hass.states.async_set("light.ceiling", "off")
|
||||
hass.states.async_set("switch.ac", "on")
|
||||
hass.states.async_set(
|
||||
"event.doorbell", "unknown", attributes={"device_class": "doorbell"}
|
||||
)
|
||||
|
||||
with (
|
||||
patch.object(
|
||||
BASIC_CONFIG, "async_report_state_all", AsyncMock()
|
||||
) as mock_report,
|
||||
patch.object(report_state, "INITIAL_REPORT_DELAY", 0),
|
||||
):
|
||||
unsub = report_state.async_enable_report_state(hass, BASIC_CONFIG)
|
||||
|
||||
async_fire_time_changed(hass, utcnow())
|
||||
await hass.async_block_till_done()
|
||||
|
||||
# Test that enabling report state does a report on all entities
|
||||
assert len(mock_report.mock_calls) == 1
|
||||
assert mock_report.mock_calls[0][1][0] == {
|
||||
"devices": {
|
||||
"states": {
|
||||
"light.ceiling": {"on": False, "online": True},
|
||||
"switch.ac": {"on": True, "online": True},
|
||||
"event.doorbell": {"online": True},
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
with patch.object(
|
||||
BASIC_CONFIG, "async_report_state_all", AsyncMock()
|
||||
) as mock_report:
|
||||
hass.states.async_set("light.kitchen", "on")
|
||||
await hass.async_block_till_done()
|
||||
|
||||
hass.states.async_set("light.kitchen_2", "on")
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert len(mock_report.mock_calls) == 0
|
||||
|
||||
async_fire_time_changed(
|
||||
hass, utcnow() + timedelta(seconds=report_state.REPORT_STATE_WINDOW)
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert len(mock_report.mock_calls) == 1
|
||||
assert mock_report.mock_calls[0][1][0] == {
|
||||
"devices": {
|
||||
"states": {
|
||||
"light.kitchen": {"on": True, "online": True},
|
||||
"light.kitchen_2": {"on": True, "online": True},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
# Test that if serialize returns same value, we don't send
|
||||
with (
|
||||
patch(
|
||||
"homeassistant.components.google_assistant.helpers.GoogleEntity.query_serialize",
|
||||
return_value={"same": "info"},
|
||||
),
|
||||
patch.object(
|
||||
BASIC_CONFIG, "async_report_state_all", AsyncMock()
|
||||
) as mock_report,
|
||||
):
|
||||
# New state, so reported
|
||||
hass.states.async_set("light.double_report", "on")
|
||||
await hass.async_block_till_done()
|
||||
|
||||
# Changed, but serialize is same, so filtered out by extra check
|
||||
hass.states.async_set("light.double_report", "off")
|
||||
async_fire_time_changed(
|
||||
hass, utcnow() + timedelta(seconds=report_state.REPORT_STATE_WINDOW)
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert len(mock_report.mock_calls) == 1
|
||||
assert mock_report.mock_calls[0][1][0] == {
|
||||
"devices": {"states": {"light.double_report": {"same": "info"}}}
|
||||
}
|
||||
|
||||
# Test that only significant state changes are reported
|
||||
with patch.object(
|
||||
BASIC_CONFIG, "async_report_state_all", AsyncMock()
|
||||
) as mock_report:
|
||||
hass.states.async_set("switch.ac", "on", {"something": "else"})
|
||||
async_fire_time_changed(
|
||||
hass, utcnow() + timedelta(seconds=report_state.REPORT_STATE_WINDOW)
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert len(mock_report.mock_calls) == 0
|
||||
|
||||
# Test that entities that we can't query don't report a state
|
||||
with (
|
||||
patch.object(
|
||||
BASIC_CONFIG, "async_report_state_all", AsyncMock()
|
||||
) as mock_report,
|
||||
patch(
|
||||
"homeassistant.components.google_assistant.helpers.GoogleEntity.query_serialize",
|
||||
side_effect=error.SmartHomeError("mock-error", "mock-msg"),
|
||||
),
|
||||
):
|
||||
hass.states.async_set("light.kitchen", "off")
|
||||
async_fire_time_changed(
|
||||
hass, utcnow() + timedelta(seconds=report_state.REPORT_STATE_WINDOW)
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert "Not reporting state for light.kitchen: mock-error" in caplog.text
|
||||
assert len(mock_report.mock_calls) == 0
|
||||
|
||||
unsub()
|
||||
|
||||
with patch.object(
|
||||
BASIC_CONFIG, "async_report_state_all", AsyncMock()
|
||||
) as mock_report:
|
||||
hass.states.async_set("light.kitchen", "on")
|
||||
async_fire_time_changed(
|
||||
hass, utcnow() + timedelta(seconds=report_state.REPORT_STATE_WINDOW)
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert len(mock_report.mock_calls) == 0
|
||||
|
||||
|
||||
@pytest.mark.freeze_time("2023-08-01 00:00:00+00:00")
|
||||
async def test_report_notifications(
|
||||
hass: HomeAssistant, caplog: pytest.LogCaptureFixture
|
||||
) -> None:
|
||||
"""Test report state works."""
|
||||
config = MockConfig(agent_user_ids={"1"})
|
||||
|
||||
assert await async_setup_component(hass, "event", {})
|
||||
hass.states.async_set(
|
||||
"event.doorbell", "unknown", attributes={"device_class": "doorbell"}
|
||||
)
|
||||
|
||||
with (
|
||||
patch.object(config, "async_report_state_all", AsyncMock()) as mock_report,
|
||||
patch.object(report_state, "INITIAL_REPORT_DELAY", 0),
|
||||
):
|
||||
report_state.async_enable_report_state(hass, config)
|
||||
|
||||
async_fire_time_changed(
|
||||
hass, datetime.fromisoformat("2023-08-01T00:01:00+00:00")
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
# Test that enabling report state does a report on event entities
|
||||
assert len(mock_report.mock_calls) == 1
|
||||
assert mock_report.mock_calls[0][1][0] == {
|
||||
"devices": {
|
||||
"states": {
|
||||
"event.doorbell": {"online": True},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
with patch.object(
|
||||
config, "async_report_state", return_value=HTTPStatus(200)
|
||||
) as mock_report_state:
|
||||
event_time = datetime.fromisoformat("2023-08-01T00:02:57+00:00")
|
||||
epoc_event_time = event_time.timestamp()
|
||||
hass.states.async_set(
|
||||
"event.doorbell",
|
||||
"2023-08-01T00:02:57+00:00",
|
||||
attributes={"device_class": "doorbell"},
|
||||
)
|
||||
async_fire_time_changed(
|
||||
hass, datetime.fromisoformat("2023-08-01T00:03:00+00:00")
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert len(mock_report_state.mock_calls) == 1
|
||||
notifications_payload = mock_report_state.mock_calls[0][1][0]["devices"][
|
||||
"notifications"
|
||||
]["event.doorbell"]
|
||||
assert notifications_payload == {
|
||||
"ObjectDetection": {
|
||||
"objects": {"unclassified": 1},
|
||||
"priority": 0,
|
||||
"detectionTimestamp": epoc_event_time * 1000,
|
||||
}
|
||||
}
|
||||
assert "Sending event notification for entity event.doorbell" in caplog.text
|
||||
assert "Unable to send notification with result code" not in caplog.text
|
||||
|
||||
hass.states.async_set(
|
||||
"event.doorbell", "unknown", attributes={"device_class": "doorbell"}
|
||||
)
|
||||
async_fire_time_changed(
|
||||
hass, datetime.fromisoformat("2023-08-01T01:01:00+00:00")
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
for call in mock_report_state.mock_calls:
|
||||
if "states" in call[1][0]["devices"]:
|
||||
states = call[1][0]["devices"]["states"]
|
||||
assert states["event.doorbell"] == {"online": True}
|
||||
|
||||
# Test the notification request failed
|
||||
caplog.clear()
|
||||
with patch.object(
|
||||
config, "async_report_state", return_value=HTTPStatus(500)
|
||||
) as mock_report_state:
|
||||
event_time = datetime.fromisoformat("2023-08-01T01:02:57+00:00")
|
||||
epoc_event_time = event_time.timestamp()
|
||||
hass.states.async_set(
|
||||
"event.doorbell",
|
||||
"2023-08-01T01:02:57+00:00",
|
||||
attributes={"device_class": "doorbell"},
|
||||
)
|
||||
async_fire_time_changed(
|
||||
hass, datetime.fromisoformat("2023-08-01T01:03:00+00:00")
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
assert len(mock_report_state.mock_calls) == 1
|
||||
for call in mock_report_state.mock_calls:
|
||||
if "notifications" in call[1][0]["devices"]:
|
||||
notifications = call[1][0]["devices"]["notifications"]
|
||||
assert notifications["event.doorbell"] == {
|
||||
"ObjectDetection": {
|
||||
"objects": {"unclassified": 1},
|
||||
"priority": 0,
|
||||
"detectionTimestamp": epoc_event_time * 1000,
|
||||
}
|
||||
}
|
||||
assert "Sending event notification for entity event.doorbell" in caplog.text
|
||||
assert (
|
||||
"Unable to send notification with result code: 500, check log for more info"
|
||||
in caplog.text
|
||||
)
|
||||
|
||||
# Test disconnecting agent user
|
||||
caplog.clear()
|
||||
with (
|
||||
patch.object(
|
||||
config, "async_report_state", return_value=HTTPStatus.NOT_FOUND
|
||||
) as mock_report_state,
|
||||
patch.object(config, "async_disconnect_agent_user"),
|
||||
):
|
||||
event_time = datetime.fromisoformat("2023-08-01T01:03:57+00:00")
|
||||
epoc_event_time = event_time.timestamp()
|
||||
hass.states.async_set(
|
||||
"event.doorbell",
|
||||
"2023-08-01T01:03:57+00:00",
|
||||
attributes={"device_class": "doorbell"},
|
||||
)
|
||||
async_fire_time_changed(
|
||||
hass, datetime.fromisoformat("2023-08-01T01:04:00+00:00")
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
assert len(mock_report_state.mock_calls) == 2
|
||||
for call in mock_report_state.mock_calls:
|
||||
if "notifications" in call[1][0]["devices"]:
|
||||
notifications = call[1][0]["devices"]["notifications"]
|
||||
elif "states" in call[1][0]["devices"]:
|
||||
states = call[1][0]["devices"]["states"]
|
||||
assert notifications["event.doorbell"] == {
|
||||
"ObjectDetection": {
|
||||
"objects": {"unclassified": 1},
|
||||
"priority": 0,
|
||||
"detectionTimestamp": epoc_event_time * 1000,
|
||||
}
|
||||
}
|
||||
assert states["event.doorbell"] == {"online": True}
|
||||
assert "Sending event notification for entity event.doorbell" in caplog.text
|
||||
assert (
|
||||
"Unable to send notification with result code: 404, check log for more info"
|
||||
in caplog.text
|
||||
)
|
||||
1587
home-assistant/tests/components/google_assistant/test_smart_home.py
Normal file
1587
home-assistant/tests/components/google_assistant/test_smart_home.py
Normal file
File diff suppressed because it is too large
Load Diff
4160
home-assistant/tests/components/google_assistant/test_trait.py
Normal file
4160
home-assistant/tests/components/google_assistant/test_trait.py
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user