1
0
mirror of https://github.com/home-assistant/core.git synced 2025-08-21 03:10:02 +00:00
Files
.devcontainer
.github
.vscode
homeassistant
machine
pylint
rootfs
script
tests
auth
components
abode
accuweather
acmeda
adax
adguard
advantage_air
aemet
aftership
agent_dvr
air_quality
airly
airnow
airq
airthings
airthings_ble
airtouch4
airtouch5
airvisual
airvisual_pro
airzone
airzone_cloud
aladdin_connect
alarm_control_panel
alarmdecoder
alert
alexa
amberelectric
ambiclimate
ambient_network
ambient_station
analytics
analytics_insights
android_ip_webcam
androidtv
androidtv_remote
anova
anthemav
aosmith
apache_kafka
apcupsd
api
api_streams
apple_tv
application_credentials
apprise
aprilaire
aprs
aranet
arcam_fmj
arve
aseko_pool_live
assist_pipeline
asterisk_mbox
asuswrt
atag
august
aurora
aurora_abb_powerone
aussie_broadband
auth
automation
awair
aws
axis
azure_devops
azure_event_hub
backup
baf
balboa
bang_olufsen
bayesian
binary_sensor
blackbird
blebox
blink
blue_current
bluemaestro
blueprint
bluetooth
bluetooth_adapters
bluetooth_le_tracker
bmw_connected_drive
bond
bosch_shc
braviatv
bring
broadlink
brother
brottsplatskartan
brunt
bsblan
bthome
buienradar
button
caldav
calendar
camera
canary
cast
ccm15
cert_expiry
clicksend_tts
climate
cloud
cloudflare
co2signal
coinbase
color_extractor
comelit
comfoconnect
command_line
compensation
config
configurator
control4
conversation
coolmaster
counter
cover
cpuspeed
crownstone
daikin
datadog
date
datetime
debugpy
deconz
default_config
deluge
demo
denonavr
derivative
devialet
device_automation
device_sun_light_trigger
device_tracker
devolo_home_control
devolo_home_network
dexcom
dhcp
diagnostics
dialogflow
directv
discord
discovergy
dlink
dlna_dmr
dlna_dms
dnsip
doorbird
dormakaba_dkey
downloader
dremel_3d_printer
drop_connect
dsmr
dsmr_reader
dte_energy_bridge
duckdns
dunehd
duotecno
dwd_weather_warnings
dynalite
eafm
easyenergy
ecobee
ecoforest
econet
ecovacs
ecowitt
edl21
efergy
eight_sleep
electrasmart
electric_kiwi
elgato
elkm1
elmax
elvia
emonitor
emulated_hue
emulated_kasa
emulated_roku
energenie_power_sockets
energy
energyzero
enigma2
enocean
enphase_envoy
environment_canada
epic_games_store
epion
epson
eq3btsmart
escea
esphome
eufylife_ble
event
everlights
evil_genius_labs
ezviz
faa_delays
facebook
fail2ban
fan
fastdotcom
feedreader
ffmpeg
fibaro
fido
file
file_upload
filesize
filter
fints
fireservicerota
firmata
fitbit
fivem
fjaraskupan
flexit_bacnet
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
fyta
garages_amsterdam
gardena_bluetooth
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
google_assistant_sdk
google_domains
google_generative_ai_conversation
google_mail
google_pubsub
google_sheets
google_tasks
google_translate
google_travel_time
google_wifi
govee_ble
govee_light_local
gpsd
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
hko
hlk_sw16
holiday
home_connect
homeassistant
homeassistant_alerts
homeassistant_green
homeassistant_hardware
homeassistant_sky_connect
homeassistant_yellow
homekit
homekit_controller
homematic
homematicip_cloud
homewizard
homeworks
honeywell
html5
http
huawei_lte
hue
huisbaasje
humidifier
hunterdouglas_powerview
husqvarna_automower
huum
hvv_departures
hydrawise
hyperion
ialarm
iaqualink
ibeacon
icloud
idasen_desk
ifttt
ign_sismologia
image
image_processing
image_upload
imap
imgw_pib
improv_ble
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
isal
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
lamarzocco
lametric
landisgyr_heat_meter
lastfm
launch_library
laundrify
lawn_mower
lcn
ld2410_ble
leaone
led_ble
lg_netcast
lg_soundbar
lidarr
life360
lifx
light
linear_garage_door
litejet
litterrobot
livisi
local_calendar
local_file
local_ip
local_todo
locative
lock
logbook
logentries
logger
logi_circle
london_air
london_underground
lookin
loqed
lovelace
luftdaten
lupusec
lutron
lutron_caseta
lyric
mailbox
mailgun
manual
manual_mqtt
map
marytts
matrix
matter
maxcube
mazda
meater
medcom_ble
media_extractor
media_player
media_source
melcloud
melissa
melnor
meraki
met
met_eireann
meteo_france
meteoclimatic
metoffice
mfi
microbees
microsoft
microsoft_face
microsoft_face_detect
microsoft_face_identify
mikrotik
mill
min_max
minecraft_server
minio
mjpeg
moat
mobile_app
__init__.py
conftest.py
const.py
test_binary_sensor.py
test_device_action.py
test_device_tracker.py
test_http_api.py
test_init.py
test_logbook.py
test_notify.py
test_sensor.py
test_webhook.py
mochad
modbus
modem_callerid
modern_forms
moehlenhoff_alpha2
mold_indicator
monoprice
moon
mopeka
motion_blinds
motionblinds_ble
motioneye
motionmount
mqtt
mqtt_eventstream
mqtt_json
mqtt_room
mqtt_statestream
mullvad
mutesync
my
myq
mysensors
mystrom
mythicbeastsdns
myuplink
nam
namecheapdns
nanoleaf
neato
ness_alarm
nest
netatmo
netgear
netgear_lte
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
ollama
omnilogic
onboarding
oncue
ondilo_ico
onewire
onvif
open_meteo
openai_conversation
openalpr_cloud
openerz
openexchangerates
opengarage
openhardwaremonitor
openhome
opensky
opentherm_gw
openuv
openweathermap
opnsense
opower
oralb
osoenergy
otbr
ourgroceries
overkiz
ovo_energy
owntracks
p1_monitor
panasonic_viera
panel_custom
panel_iframe
peco
pegel_online
permobil
persistent_notification
person
philips_js
pi_hole
picnic
pilight
ping
pjlink
plaato
plant
plex
plugwise
plum_lightpad
point
poolsense
powerwall
private_ble_device
profiler
progettihwsw
prometheus
prosegur
proximity
prusalink
ps4
pure_energie
purpleair
push
pushbullet
pushover
pvoutput
pvpc_hourly_pricing
python_script
qbittorrent
qingping
qld_bushfire
qnap
qnap_qsw
qwikswitch
rabbitair
rachio
radarr
radio_browser
radiotherm
rainbird
rainforest_eagle
rainforest_raven
rainmachine
random
rapt_ble
raspberry_pi
rdw
recollect_waste
recorder
recovery_mode
reddit
refoss
remember_the_milk
remote
renault
renson
reolink
repairs
rest
rest_command
rflink
rfxtrx
rhasspy
ridwell
ring
risco
rituals_perfume_genie
rmvtransport
roborock
roku
romy
roomba
roon
rova
rpi_power
rss_feed_template
rtsp_to_webrtc
ruckus_unleashed
ruuvi_gateway
ruuvitag_ble
rympro
sabnzbd
samsungtv
sanix
scene
schedule
schlage
scrape
screenlogic
script
search
season
select
sense
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
sms
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
streamlabswater
stt
subaru
suez_water
sun
sunweg
surepetcare
swiss_public_transport
switch
switch_as_x
switchbee
switchbot
switchbot_cloud
switcher_kis
syncthing
syncthru
synology_dsm
system_bridge
system_health
system_log
systemmonitor
tado
tag
tailscale
tailwind
tami4
tankerkoenig
tasmota
tautulli
tcp
technove
tedee
telegram
telegram_bot
tellduslive
temper
template
tesla_wall_connector
teslemetry
tessie
text
thermobeacon
thermopro
thread
threshold
tibber
tile
tilt_ble
time
time_date
timer
tod
todo
todoist
tolo
tomato
tomorrowio
toon
totalconnect
tplink
tplink_omada
traccar
traccar_server
trace
tractive
tradfri
trafikverket_camera
trafikverket_ferry
trafikverket_train
trafikverket_weatherstation
transmission
transport_nsw
trend
tts
tuya
twentemilieu
twilio
twinkly
twitch
uk_transport
ukraine_alarm
unifi
unifiprotect
universal
upb
upcloud
update
upnp
uptime
uptimerobot
usb
usgs_earthquakes_feed
utility_meter
uvc
v2c
vacuum
vallox
valve
velbus
velux
venstar
vera
verisure
version
vesync
vicare
vilfo
vizio
vlc_telnet
vodafone_station
voicerss
voip
volumio
volvooncall
vulcan
vultr
wake_on_lan
wake_word
wallbox
waqi
water_heater
watttime
waze_travel_time
weather
weatherflow
weatherflow_cloud
weatherkit
webhook
webmin
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
yardian
yeelight
yolink
youless
youtube
zamg
zeroconf
zerproc
zeversolar
zha
zodiac
zone
zwave_js
zwave_me
__init__.py
conftest.py
fixtures
hassfest
helpers
non_packaged_scripts
pylint
resources
script
scripts
snapshots
test_util
testing_config
util
__init__.py
common.py
conftest.py
ignore_uncaught_exceptions.py
patch_time.py
ruff.toml
syrupy.py
test_backports.py
test_block_async_io.py
test_bootstrap.py
test_circular_imports.py
test_config.py
test_config_entries.py
test_const.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
.git-blame-ignore-revs
.gitattributes
.gitignore
.hadolint.yaml
.pre-commit-config.yaml
.prettierignore
.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_test.txt
requirements_test_all.txt
requirements_test_pre_commit.txt
core/tests/components/mobile_app/test_notify.py

425 lines
13 KiB
Python

"""Notify platform tests for mobile_app."""
from datetime import datetime, timedelta
from unittest.mock import patch
import pytest
from homeassistant.components.mobile_app.const import DOMAIN
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import HomeAssistantError
from homeassistant.setup import async_setup_component
from tests.common import MockConfigEntry
from tests.test_util.aiohttp import AiohttpClientMocker
from tests.typing import WebSocketGenerator
@pytest.fixture
async def setup_push_receiver(hass, aioclient_mock, hass_admin_user):
"""Fixture that sets up a mocked push receiver."""
push_url = "https://mobile-push.home-assistant.dev/push"
now = datetime.now() + timedelta(hours=24)
iso_time = now.strftime("%Y-%m-%dT%H:%M:%SZ")
aioclient_mock.post(
push_url,
json={
"rateLimits": {
"attempts": 1,
"successful": 1,
"errors": 0,
"total": 1,
"maximum": 150,
"remaining": 149,
"resetsAt": iso_time,
}
},
)
entry = MockConfigEntry(
data={
"app_data": {"push_token": "PUSH_TOKEN", "push_url": push_url},
"app_id": "io.homeassistant.mobile_app",
"app_name": "mobile_app tests",
"app_version": "1.0",
"device_id": "4d5e6f",
"device_name": "Test",
"manufacturer": "Home Assistant",
"model": "mobile_app",
"os_name": "Linux",
"os_version": "5.0.6",
"secret": "123abc",
"supports_encryption": False,
"user_id": hass_admin_user.id,
"webhook_id": "mock-webhook_id",
},
domain=DOMAIN,
source="registration",
title="mobile_app test entry",
version=1,
)
entry.add_to_hass(hass)
await async_setup_component(hass, DOMAIN, {DOMAIN: {}})
await hass.async_block_till_done()
loaded_late_entry = MockConfigEntry(
data={
"app_data": {"push_token": "PUSH_TOKEN2", "push_url": f"{push_url}2"},
"app_id": "io.homeassistant.mobile_app",
"app_name": "mobile_app tests",
"app_version": "1.0",
"device_id": "4d5e6f2",
"device_name": "Loaded Late",
"manufacturer": "Home Assistant",
"model": "mobile_app",
"os_name": "Linux",
"os_version": "5.0.6",
"secret": "123abc2",
"supports_encryption": False,
"user_id": "1a2b3c2",
"webhook_id": "webhook_id_2",
},
domain=DOMAIN,
source="registration",
title="mobile_app 2 test entry",
version=1,
)
loaded_late_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(loaded_late_entry.entry_id)
await hass.async_block_till_done()
assert hass.services.has_service("notify", "mobile_app_loaded_late")
assert await hass.config_entries.async_remove(loaded_late_entry.entry_id)
await hass.async_block_till_done()
assert hass.services.has_service("notify", "mobile_app_test")
assert not hass.services.has_service("notify", "mobile_app_loaded_late")
loaded_late_entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(loaded_late_entry.entry_id)
await hass.async_block_till_done()
assert hass.services.has_service("notify", "mobile_app_test")
assert hass.services.has_service("notify", "mobile_app_loaded_late")
@pytest.fixture
async def setup_websocket_channel_only_push(hass, hass_admin_user):
"""Set up local push."""
entry = MockConfigEntry(
data={
"app_data": {"push_websocket_channel": True},
"app_id": "io.homeassistant.mobile_app",
"app_name": "mobile_app tests",
"app_version": "1.0",
"device_id": "websocket-push-device-id",
"device_name": "Websocket Push Name",
"manufacturer": "Home Assistant",
"model": "mobile_app",
"os_name": "Linux",
"os_version": "5.0.6",
"secret": "123abc2",
"supports_encryption": False,
"user_id": hass_admin_user.id,
"webhook_id": "websocket-push-webhook-id",
},
domain=DOMAIN,
source="registration",
title="websocket push test entry",
version=1,
)
entry.add_to_hass(hass)
assert await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert hass.services.has_service("notify", "mobile_app_websocket_push_name")
async def test_notify_works(
hass: HomeAssistant, aioclient_mock: AiohttpClientMocker, setup_push_receiver
) -> None:
"""Test notify works."""
assert hass.services.has_service("notify", "mobile_app_test") is True
await hass.services.async_call(
"notify", "mobile_app_test", {"message": "Hello world"}, blocking=True
)
assert len(aioclient_mock.mock_calls) == 1
call = aioclient_mock.mock_calls
call_json = call[0][2]
assert call_json["push_token"] == "PUSH_TOKEN"
assert call_json["message"] == "Hello world"
assert call_json["registration_info"]["app_id"] == "io.homeassistant.mobile_app"
assert call_json["registration_info"]["app_version"] == "1.0"
assert call_json["registration_info"]["webhook_id"] == "mock-webhook_id"
async def test_notify_ws_works(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
setup_push_receiver,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test notify works."""
client = await hass_ws_client(hass)
await client.send_json(
{
"id": 5,
"type": "mobile_app/push_notification_channel",
"webhook_id": "mock-webhook_id",
}
)
sub_result = await client.receive_json()
assert sub_result["success"]
# Subscribe twice, it should forward all messages to 2nd subscription
await client.send_json(
{
"id": 6,
"type": "mobile_app/push_notification_channel",
"webhook_id": "mock-webhook_id",
}
)
sub_result = await client.receive_json()
assert sub_result["success"]
await hass.services.async_call(
"notify", "mobile_app_test", {"message": "Hello world"}, blocking=True
)
assert len(aioclient_mock.mock_calls) == 0
msg_result = await client.receive_json()
assert msg_result["event"] == {"message": "Hello world"}
assert msg_result["id"] == 6 # This is the new subscription
# Unsubscribe, now it should go over http
await client.send_json(
{
"id": 7,
"type": "unsubscribe_events",
"subscription": 6,
}
)
sub_result = await client.receive_json()
assert sub_result["success"]
await hass.services.async_call(
"notify", "mobile_app_test", {"message": "Hello world 2"}, blocking=True
)
assert len(aioclient_mock.mock_calls) == 1
# Test non-existing webhook ID
await client.send_json(
{
"id": 8,
"type": "mobile_app/push_notification_channel",
"webhook_id": "non-existing",
}
)
sub_result = await client.receive_json()
assert not sub_result["success"]
assert sub_result["error"] == {
"code": "not_found",
"message": "Webhook ID not found",
}
# Test webhook ID linked to other user
await client.send_json(
{
"id": 9,
"type": "mobile_app/push_notification_channel",
"webhook_id": "webhook_id_2",
}
)
sub_result = await client.receive_json()
assert not sub_result["success"]
assert sub_result["error"] == {
"code": "unauthorized",
"message": "User not linked to this webhook ID",
}
async def test_notify_ws_confirming_works(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
setup_push_receiver,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test notify confirming works."""
client = await hass_ws_client(hass)
await client.send_json(
{
"id": 5,
"type": "mobile_app/push_notification_channel",
"webhook_id": "mock-webhook_id",
"support_confirm": True,
}
)
sub_result = await client.receive_json()
assert sub_result["success"]
# Sent a message that will be delivered locally
await hass.services.async_call(
"notify", "mobile_app_test", {"message": "Hello world"}, blocking=True
)
msg_result = await client.receive_json()
confirm_id = msg_result["event"].pop("hass_confirm_id")
assert confirm_id is not None
assert msg_result["event"] == {"message": "Hello world"}
# Try to confirm with incorrect confirm ID
await client.send_json(
{
"id": 6,
"type": "mobile_app/push_notification_confirm",
"webhook_id": "mock-webhook_id",
"confirm_id": "incorrect-confirm-id",
}
)
result = await client.receive_json()
assert not result["success"]
assert result["error"] == {
"code": "not_found",
"message": "Push notification channel not found",
}
# Confirm with correct confirm ID
await client.send_json(
{
"id": 7,
"type": "mobile_app/push_notification_confirm",
"webhook_id": "mock-webhook_id",
"confirm_id": confirm_id,
}
)
result = await client.receive_json()
assert result["success"]
# Drop local push channel and try to confirm another message
await client.send_json(
{
"id": 8,
"type": "unsubscribe_events",
"subscription": 5,
}
)
sub_result = await client.receive_json()
assert sub_result["success"]
await client.send_json(
{
"id": 9,
"type": "mobile_app/push_notification_confirm",
"webhook_id": "mock-webhook_id",
"confirm_id": confirm_id,
}
)
result = await client.receive_json()
assert not result["success"]
assert result["error"] == {
"code": "not_found",
"message": "Push notification channel not found",
}
async def test_notify_ws_not_confirming(
hass: HomeAssistant,
aioclient_mock: AiohttpClientMocker,
setup_push_receiver,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test we go via cloud when failed to confirm."""
client = await hass_ws_client(hass)
await client.send_json(
{
"id": 5,
"type": "mobile_app/push_notification_channel",
"webhook_id": "mock-webhook_id",
"support_confirm": True,
}
)
sub_result = await client.receive_json()
assert sub_result["success"]
await hass.services.async_call(
"notify", "mobile_app_test", {"message": "Hello world 1"}, blocking=True
)
with patch(
"homeassistant.components.mobile_app.push_notification.PUSH_CONFIRM_TIMEOUT", 0
):
await hass.services.async_call(
"notify", "mobile_app_test", {"message": "Hello world 2"}, blocking=True
)
await hass.async_block_till_done()
await hass.async_block_till_done()
# When we fail, all unconfirmed ones and failed one are sent via cloud
assert len(aioclient_mock.mock_calls) == 2
# All future ones also go via cloud
await hass.services.async_call(
"notify", "mobile_app_test", {"message": "Hello world 3"}, blocking=True
)
assert len(aioclient_mock.mock_calls) == 3
async def test_local_push_only(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
setup_websocket_channel_only_push,
) -> None:
"""Test a local only push registration."""
with pytest.raises(HomeAssistantError) as e_info:
await hass.services.async_call(
"notify",
"mobile_app_websocket_push_name",
{"message": "Not connected"},
blocking=True,
)
assert str(e_info.value) == "Device not connected to local push notifications"
client = await hass_ws_client(hass)
await client.send_json(
{
"id": 5,
"type": "mobile_app/push_notification_channel",
"webhook_id": "websocket-push-webhook-id",
}
)
sub_result = await client.receive_json()
assert sub_result["success"]
await hass.services.async_call(
"notify",
"mobile_app_websocket_push_name",
{"message": "Hello world 1"},
blocking=True,
)
msg = await client.receive_json()
assert msg == {"id": 5, "type": "event", "event": {"message": "Hello world 1"}}