mirror of
https://github.com/home-assistant/core.git
synced 2025-08-21 19:30:02 +00:00
.devcontainer
.github
.vscode
docs
homeassistant
machine
pylint
rootfs
script
tests
auth
backports
components
abode
accuweather
acmeda
adax
adguard
advantage_air
aemet
agent_dvr
air_quality
airly
airnow
airq
airthings
airthings_ble
airtouch4
airvisual
airvisual_pro
airzone
airzone_cloud
aladdin_connect
alarm_control_panel
alarmdecoder
alert
alexa
amberelectric
ambiclimate
ambient_station
analytics
android_ip_webcam
androidtv
androidtv_remote
anova
anthemav
apache_kafka
apcupsd
api
api_streams
apple_tv
application_credentials
apprise
aprs
aranet
arcam_fmj
aseko_pool_live
assist_pipeline
asuswrt
atag
august
aurora
aurora_abb_powerone
aussie_broadband
auth
automation
awair
aws
axis
azure_devops
azure_event_hub
backup
baf
balboa
bayesian
binary_sensor
blackbird
blebox
blink
bluemaestro
blueprint
bluetooth
bluetooth_adapters
bluetooth_le_tracker
bmw_connected_drive
bond
bosch_shc
braviatv
broadlink
brother
brottsplatskartan
brunt
bsblan
bthome
buienradar
button
caldav
calendar
camera
canary
cast
cert_expiry
clicksend_tts
climate
cloud
cloudflare
co2signal
coinbase
color_extractor
comfoconnect
command_line
compensation
config
configurator
control4
conversation
coolmaster
counter
cover
cpuspeed
crownstone
daikin
datadog
date
debugpy
deconz
default_config
deluge
demo
denonavr
derivative
device_automation
device_sun_light_trigger
device_tracker
devolo_home_control
devolo_home_network
dexcom
dhcp
diagnostics
dialogflow
directv
discord
discovery
dlink
dlna_dmr
dlna_dms
dnsip
doorbird
dormakaba_dkey
dsmr
dsmr_reader
dte_energy_bridge
duckdns
dunehd
dwd_weather_warnings
dynalite
eafm
easyenergy
ecobee
econet
ecowitt
edl21
efergy
eight_sleep
electrasmart
elgato
elkm1
elmax
emonitor
emulated_hue
emulated_kasa
emulated_roku
energy
energyzero
enocean
enphase_envoy
environment_canada
epson
escea
esphome
eufylife_ble
everlights
evil_genius_labs
ezviz
faa_delays
facebook
facebox
fail2ban
fan
feedreader
ffmpeg
fibaro
fido
file
file_upload
filesize
filter
fireservicerota
firmata
fivem
fjaraskupan
flic
flick_electric
flipr
flo
flume
flux
flux_led
folder
folder_watcher
foobot
forecast_solar
forked_daapd
foscam
freebox
freedns
freedompro
fritz
fritzbox
fritzbox_callmonitor
fronius
frontend
frontier_silicon
fully_kiosk
garages_amsterdam
gdacs
generic
generic_hygrostat
generic_thermostat
geo_json_events
geo_location
geo_rss_events
geocaching
geofency
geonetnz_quakes
geonetnz_volcano
gios
github
glances
goalzero
gogogate2
goodwe
google
google_assistant
__init__.py
test_button.py
test_diagnostics.py
test_google_assistant.py
test_helpers.py
test_http.py
test_init.py
test_logbook.py
test_report_state.py
test_smart_home.py
test_trait.py
google_assistant_sdk
google_domains
google_generative_ai_conversation
google_mail
google_pubsub
google_sheets
google_translate
google_travel_time
google_wifi
govee_ble
gpslogger
graphite
gree
greeneye_monitor
group
growatt_server
guardian
habitica
hardkernel
hardware
harmony
hassio
hddtemp
hdmi_cec
heos
here_travel_time
hisense_aehw4a1
history
history_stats
hive
hlk_sw16
home_connect
home_plus_control
homeassistant
homeassistant_alerts
homeassistant_hardware
homeassistant_sky_connect
homeassistant_yellow
homekit
homekit_controller
homematic
homematicip_cloud
homewizard
honeywell
html5
http
huawei_lte
hue
huisbaasje
humidifier
hunterdouglas_powerview
hvv_departures
hyperion
ialarm
iaqualink
ibeacon
icloud
ifttt
ign_sismologia
image_processing
image_upload
imap
imap_email_content
influxdb
inkbird
input_boolean
input_button
input_datetime
input_number
input_select
input_text
insteon
integration
intellifire
intent
intent_script
ios
iotawatt
ipma
ipp
iqvia
islamic_prayer_times
iss
isy994
izone
jellyfin
jewish_calendar
juicenet
justnimbus
jvc_projector
kaleidescape
keenetic_ndms2
kegtron
keymitt_ble
kira
kitchen_sink
kmtronic
knx
kodi
konnected
kostal_plenticore
kraken
kulersky
lacrosse_view
lametric
landisgyr_heat_meter
lastfm
launch_library
laundrify
lcn
ld2410_ble
led_ble
lg_soundbar
lidarr
life360
lifx
light
litejet
litterrobot
livisi
local_calendar
local_file
local_ip
locative
lock
logbook
logentries
logger
logi_circle
london_air
lookin
lovelace
luftdaten
lutron_caseta
lyric
mailbox
mailgun
manual
manual_mqtt
marytts
matter
maxcube
mazda
meater
media_player
media_source
melcloud
melissa
melnor
meraki
met
met_eireann
meteo_france
meteoclimatic
metoffice
mfi
microsoft
microsoft_face
microsoft_face_detect
microsoft_face_identify
mikrotik
mill
min_max
minecraft_server
minio
mjpeg
moat
mobile_app
mochad
modbus
modem_callerid
modern_forms
moehlenhoff_alpha2
mold_indicator
monoprice
moon
mopeka
motion_blinds
motioneye
mqtt
mqtt_eventstream
mqtt_json
mqtt_room
mqtt_statestream
mullvad
mutesync
my
myq
mysensors
mythicbeastsdns
nam
namecheapdns
nanoleaf
neato
ness_alarm
nest
netatmo
netgear
network
nexia
nextbus
nextcloud
nextdns
nfandroidtv
nibe_heatpump
nightscout
nina
nmap_tracker
no_ip
nobo_hub
notify
notify_events
notion
nsw_fuel_station
nsw_rural_fire_service_feed
nuheat
nuki
numato
number
nut
nws
nx584
nzbget
obihai
octoprint
omnilogic
onboarding
oncue
ondilo_ico
onewire
onvif
open_meteo
openai_conversation
openalpr_cloud
openerz
openexchangerates
opengarage
openhardwaremonitor
opentherm_gw
openuv
openweathermap
opnsense
oralb
otbr
overkiz
ovo_energy
owntracks
p1_monitor
panasonic_viera
panel_custom
panel_iframe
peco
persistent_notification
person
philips_js
pi_hole
picnic
pilight
ping
pjlink
plaato
plant
plex
plugwise
plum_lightpad
point
poolsense
powerwall
profiler
progettihwsw
prometheus
prosegur
proximity
prusalink
ps4
pure_energie
purpleair
push
pushbullet
pushover
pvoutput
pvpc_hourly_pricing
python_script
qbittorrent
qingping
qld_bushfire
qnap_qsw
qwikswitch
rachio
radarr
radio_browser
radiotherm
rainbird
rainforest_eagle
rainmachine
random
rapt_ble
raspberry_pi
rdw
recollect_waste
recorder
reddit
remember_the_milk
remote
renault
reolink
repairs
rest
rest_command
rflink
rfxtrx
rhasspy
ridwell
ring
risco
rituals_perfume_genie
rmvtransport
roborock
roku
roomba
roon
rpi_power
rss_feed_template
rtsp_to_webrtc
ruckus_unleashed
ruuvi_gateway
ruuvitag_ble
rympro
sabnzbd
safe_mode
samsungtv
scene
schedule
scrape
screenlogic
script
search
season
select
sense
senseme
sensibo
sensirion_ble
sensor
sensorpro
sensorpush
sentry
senz
seventeentrack
sfr_box
sharkiq
shell_command
shelly
shopping_list
sia
sigfox
sighthound
signal_messenger
simplepush
simplisafe
simulated
siren
skybell
slack
sleepiq
slimproto
sma
smappee
smart_meter_texas
smartthings
smarttub
smhi
smtp
snapcast
snips
snmp
snooz
solaredge
solarlog
solax
soma
somfy_mylink
sonarr
songpal
sonos
soundtouch
spaceapi
spc
speedtestdotnet
spider
spotify
sql
squeezebox
srp_energy
ssdp
starline
starlink
startca
statistics
statsd
steam_online
steamist
stookalert
stookwijzer
stream
stt
subaru
sun
surepetcare
switch
switch_as_x
switchbee
switchbot
switcher_kis
syncthing
syncthru
synology_dsm
system_bridge
system_health
system_log
tado
tag
tailscale
tankerkoenig
tasmota
tautulli
tcp
telegram
telegram_bot
tellduslive
temper
template
tesla_wall_connector
text
thermobeacon
thermopro
thread
threshold
tibber
tile
tilt_ble
time
time_date
timer
tod
todoist
tolo
tomato
tomorrowio
toon
totalconnect
tplink
tplink_omada
traccar
trace
tractive
tradfri
trafikverket_ferry
trafikverket_train
trafikverket_weatherstation
transmission
transport_nsw
trend
tts
tuya
twentemilieu
twilio
twinkly
twitch
uk_transport
ukraine_alarm
unifi
unifi_direct
unifiprotect
universal
upb
upcloud
update
upnp
uptime
uptimerobot
usb
usgs_earthquakes_feed
utility_meter
uvc
vacuum
vallox
velbus
venstar
vera
verisure
version
vesync
vicare
vilfo
vizio
vlc_telnet
voicerss
voip
volumio
volvooncall
vulcan
vultr
wake_on_lan
wallbox
water_heater
watttime
waze_travel_time
weather
webhook
webostv
websocket_api
wemo
whirlpool
whois
wiffi
wilight
withings
wiz
wled
wolflink
workday
worldclock
ws66i
wsdot
wyoming
xbox
xiaomi
xiaomi_aqara
xiaomi_ble
xiaomi_miio
yale_smart_alarm
yalexs_ble
yamaha
yamaha_musiccast
yandex_transport
yandextts
yeelight
yolink
youless
zamg
zeroconf
zerproc
zeversolar
zha
zodiac
zone
zwave_js
zwave_me
__init__.py
conftest.py
fixtures
hassfest
helpers
pylint
resources
scripts
test_util
testing_config
util
__init__.py
bandit.yaml
common.py
conftest.py
ignore_uncaught_exceptions.py
ruff.toml
syrupy.py
test_bootstrap.py
test_config.py
test_config_entries.py
test_core.py
test_data_entry_flow.py
test_exceptions.py
test_loader.py
test_main.py
test_requirements.py
test_runner.py
test_setup.py
test_test_fixtures.py
typing.py
.core_files.yaml
.coveragerc
.dockerignore
.gitattributes
.gitignore
.hadolint.yaml
.pre-commit-config.yaml
.prettierignore
.readthedocs.yml
.strict-typing
.yamllint
CLA.md
CODEOWNERS
CODE_OF_CONDUCT.md
CONTRIBUTING.md
Dockerfile
Dockerfile.dev
LICENSE.md
MANIFEST.in
README.rst
build.yaml
codecov.yml
mypy.ini
pyproject.toml
requirements.txt
requirements_all.txt
requirements_docs.txt
requirements_test.txt
requirements_test_all.txt
requirements_test_pre_commit.txt
setup.cfg
439 lines
16 KiB
Python
439 lines
16 KiB
Python
"""Test Google http services."""
|
|
from datetime import datetime, timedelta, timezone
|
|
from http import HTTPStatus
|
|
from typing import Any
|
|
from unittest.mock import ANY, patch
|
|
|
|
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,
|
|
_get_homegraph_jwt,
|
|
_get_homegraph_token,
|
|
)
|
|
from homeassistant.const import CLOUD_NEVER_EXPOSED_ENTITIES
|
|
from homeassistant.core import HomeAssistant, State
|
|
from homeassistant.setup import async_setup_component
|
|
|
|
from tests.common import async_capture_events, async_mock_service
|
|
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=timezone.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=timezone.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_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_agent_user_id(local_webhook_id) == agent_user_id
|
|
assert config.get_local_agent_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 mock_webhook_id as no linked agent user is found:"
|
|
in caplog.text
|
|
)
|