1
0
mirror of https://github.com/home-assistant/core.git synced 2025-08-13 15:30:03 +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
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
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
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
dremel_3d_printer
dsmr
dsmr_reader
dte_energy_bridge
duckdns
dunehd
duotecno
dwd_weather_warnings
dynalite
eafm
easyenergy
ecobee
ecoforest
econet
ecowitt
edl21
efergy
eight_sleep
electrasmart
electric_kiwi
elgato
elkm1
elmax
emonitor
emulated_hue
emulated_kasa
emulated_roku
energy
energyzero
enocean
enphase_envoy
environment_canada
epson
escea
esphome
eufylife_ble
event
everlights
evil_genius_labs
ezviz
faa_delays
facebook
facebox
fail2ban
fan
feedreader
ffmpeg
fibaro
fido
file
file_upload
filesize
filter
fireservicerota
firmata
fitbit
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
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
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_green
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
hydrawise
hyperion
ialarm
iaqualink
ibeacon
icloud
idasen_desk
ifttt
ign_sismologia
image
image_processing
image_upload
imap
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
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
komfovent
konnected
kostal_plenticore
kraken
kulersky
lacrosse_view
lametric
landisgyr_heat_meter
lastfm
launch_library
laundrify
lawn_mower
lcn
ld2410_ble
led_ble
lg_soundbar
lidarr
life360
lifx
light
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
lutron_caseta
lyric
mailbox
mailgun
manual
manual_mqtt
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
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
mystrom
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
openhome
opensky
opentherm_gw
openuv
openweathermap
opnsense
opower
oralb
otbr
overkiz
ovo_energy
owntracks
p1_monitor
panasonic_viera
panel_custom
panel_iframe
peco
pegel_online
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
rachio
radarr
radio_browser
radiotherm
rainbird
rainforest_eagle
rainmachine
random
rapt_ble
raspberry_pi
rdw
recollect_waste
recorder
recovery_mode
reddit
remember_the_milk
remote
renault
renson
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
samsungtv
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
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
switchbot_cloud
switcher_kis
syncthing
syncthru
synology_dsm
system_bridge
system_health
system_log
tado
tag
tailscale
tami4
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
todo
todoist
tolo
tomato
tomorrowio
toon
totalconnect
tplink
tplink_omada
traccar
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
unifi_direct
unifiprotect
universal
upb
upcloud
update
upnp
uptime
uptimerobot
usb
usgs_earthquakes_feed
utility_meter
uvc
v2c
vacuum
vallox
velbus
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
weatherkit
webhook
__init__.py
test_init.py
test_trigger.py
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
pylint
resources
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_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
.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/webhook/test_init.py
Franck Nijhof 3df71eca45 Ensure webhooks take HA cloud into account ()
* Ensure webhooks take HA cloud into account

* Avoid circular import
2023-08-06 23:23:52 -04:00

364 lines
11 KiB
Python

"""Test the webhook component."""
from http import HTTPStatus
from ipaddress import ip_address
from unittest.mock import Mock, patch
from aiohttp import web
import pytest
from homeassistant.components import webhook
from homeassistant.config import async_process_ha_core_config
from homeassistant.core import HomeAssistant
from homeassistant.setup import async_setup_component
from tests.typing import WebSocketGenerator
@pytest.fixture
def mock_client(hass, hass_client):
"""Create http client for webhooks."""
hass.loop.run_until_complete(async_setup_component(hass, "webhook", {}))
return hass.loop.run_until_complete(hass_client())
async def test_unregistering_webhook(hass: HomeAssistant, mock_client) -> None:
"""Test unregistering a webhook."""
hooks = []
webhook_id = webhook.async_generate_id()
async def handle(*args):
"""Handle webhook."""
hooks.append(args)
webhook.async_register(hass, "test", "Test hook", webhook_id, handle)
resp = await mock_client.post(f"/api/webhook/{webhook_id}")
assert resp.status == HTTPStatus.OK
assert len(hooks) == 1
webhook.async_unregister(hass, webhook_id)
resp = await mock_client.post(f"/api/webhook/{webhook_id}")
assert resp.status == HTTPStatus.OK
assert len(hooks) == 1
async def test_generate_webhook_url(hass: HomeAssistant) -> None:
"""Test we generate a webhook url correctly."""
await async_process_ha_core_config(
hass,
{"external_url": "https://example.com"},
)
url = webhook.async_generate_url(hass, "some_id")
assert url == "https://example.com/api/webhook/some_id"
async def test_async_generate_path(hass: HomeAssistant) -> None:
"""Test generating just the path component of the url correctly."""
path = webhook.async_generate_path("some_id")
assert path == "/api/webhook/some_id"
async def test_posting_webhook_nonexisting(hass: HomeAssistant, mock_client) -> None:
"""Test posting to a nonexisting webhook."""
resp = await mock_client.post("/api/webhook/non-existing")
assert resp.status == HTTPStatus.OK
async def test_posting_webhook_invalid_json(hass: HomeAssistant, mock_client) -> None:
"""Test posting to a nonexisting webhook."""
webhook.async_register(hass, "test", "Test hook", "hello", None)
resp = await mock_client.post("/api/webhook/hello", data="not-json")
assert resp.status == HTTPStatus.OK
async def test_posting_webhook_json(hass: HomeAssistant, mock_client) -> None:
"""Test posting a webhook with JSON data."""
hooks = []
webhook_id = webhook.async_generate_id()
async def handle(*args):
"""Handle webhook."""
hooks.append((args[0], args[1], await args[2].text()))
webhook.async_register(hass, "test", "Test hook", webhook_id, handle)
resp = await mock_client.post(f"/api/webhook/{webhook_id}", json={"data": True})
assert resp.status == HTTPStatus.OK
assert len(hooks) == 1
assert hooks[0][0] is hass
assert hooks[0][1] == webhook_id
assert hooks[0][2] == '{"data": true}'
async def test_posting_webhook_no_data(hass: HomeAssistant, mock_client) -> None:
"""Test posting a webhook with no data."""
hooks = []
webhook_id = webhook.async_generate_id()
async def handle(*args):
"""Handle webhook."""
hooks.append(args)
webhook.async_register(hass, "test", "Test hook", webhook_id, handle)
resp = await mock_client.post(f"/api/webhook/{webhook_id}")
assert resp.status == HTTPStatus.OK
assert len(hooks) == 1
assert hooks[0][0] is hass
assert hooks[0][1] == webhook_id
assert hooks[0][2].method == "POST"
assert await hooks[0][2].text() == ""
async def test_webhook_put(hass: HomeAssistant, mock_client) -> None:
"""Test sending a put request to a webhook."""
hooks = []
webhook_id = webhook.async_generate_id()
async def handle(*args):
"""Handle webhook."""
hooks.append(args)
webhook.async_register(hass, "test", "Test hook", webhook_id, handle)
resp = await mock_client.put(f"/api/webhook/{webhook_id}")
assert resp.status == HTTPStatus.OK
assert len(hooks) == 1
assert hooks[0][0] is hass
assert hooks[0][1] == webhook_id
assert hooks[0][2].method == "PUT"
async def test_webhook_head(hass: HomeAssistant, mock_client) -> None:
"""Test sending a head request to a webhook."""
hooks = []
webhook_id = webhook.async_generate_id()
async def handle(*args):
"""Handle webhook."""
hooks.append(args)
webhook.async_register(
hass, "test", "Test hook", webhook_id, handle, allowed_methods=["HEAD"]
)
resp = await mock_client.head(f"/api/webhook/{webhook_id}")
assert resp.status == HTTPStatus.OK
assert len(hooks) == 1
assert hooks[0][0] is hass
assert hooks[0][1] == webhook_id
assert hooks[0][2].method == "HEAD"
# Test that status is HTTPStatus.OK even when HEAD is not allowed.
webhook.async_unregister(hass, webhook_id)
webhook.async_register(
hass, "test", "Test hook", webhook_id, handle, allowed_methods=["PUT"]
)
resp = await mock_client.head(f"/api/webhook/{webhook_id}")
assert resp.status == HTTPStatus.OK
assert len(hooks) == 1 # Should not have been called
async def test_webhook_get(hass: HomeAssistant, mock_client) -> None:
"""Test sending a get request to a webhook."""
hooks = []
webhook_id = webhook.async_generate_id()
async def handle(*args):
"""Handle webhook."""
hooks.append(args)
webhook.async_register(
hass, "test", "Test hook", webhook_id, handle, allowed_methods=["GET"]
)
resp = await mock_client.get(f"/api/webhook/{webhook_id}")
assert resp.status == HTTPStatus.OK
assert len(hooks) == 1
assert hooks[0][0] is hass
assert hooks[0][1] == webhook_id
assert hooks[0][2].method == "GET"
# Test that status is HTTPStatus.METHOD_NOT_ALLOWED even when GET is not allowed.
webhook.async_unregister(hass, webhook_id)
webhook.async_register(
hass, "test", "Test hook", webhook_id, handle, allowed_methods=["PUT"]
)
resp = await mock_client.get(f"/api/webhook/{webhook_id}")
assert resp.status == HTTPStatus.METHOD_NOT_ALLOWED
assert len(hooks) == 1 # Should not have been called
async def test_webhook_not_allowed_method(hass: HomeAssistant) -> None:
"""Test that an exception is raised if an unsupported method is used."""
webhook_id = webhook.async_generate_id()
async def handle(*args):
pass
with pytest.raises(ValueError):
webhook.async_register(
hass, "test", "Test hook", webhook_id, handle, allowed_methods=["PATCH"]
)
async def test_webhook_local_only(hass: HomeAssistant, mock_client) -> None:
"""Test posting a webhook with local only."""
hass.config.components.add("cloud")
hooks = []
webhook_id = webhook.async_generate_id()
async def handle(*args):
"""Handle webhook."""
hooks.append((args[0], args[1], await args[2].text()))
webhook.async_register(
hass, "test", "Test hook", webhook_id, handle, local_only=True
)
resp = await mock_client.post(f"/api/webhook/{webhook_id}", json={"data": True})
assert resp.status == HTTPStatus.OK
assert len(hooks) == 1
assert hooks[0][0] is hass
assert hooks[0][1] == webhook_id
assert hooks[0][2] == '{"data": true}'
# Request from remote IP
with patch(
"homeassistant.components.webhook.ip_address",
return_value=ip_address("123.123.123.123"),
):
resp = await mock_client.post(f"/api/webhook/{webhook_id}", json={"data": True})
assert resp.status == HTTPStatus.OK
# No hook received
assert len(hooks) == 1
# Request from Home Assistant Cloud remote UI
with patch(
"hass_nabucasa.remote.is_cloud_request", Mock(get=Mock(return_value=True))
):
resp = await mock_client.post(f"/api/webhook/{webhook_id}", json={"data": True})
# No hook received
assert resp.status == HTTPStatus.OK
assert len(hooks) == 1
async def test_listing_webhook(
hass: HomeAssistant,
hass_ws_client: WebSocketGenerator,
hass_access_token: str,
enable_custom_integrations: None,
) -> None:
"""Test unregistering a webhook."""
assert await async_setup_component(hass, "webhook", {})
client = await hass_ws_client(hass, hass_access_token)
webhook.async_register(hass, "test", "Test hook", "my-id", None)
webhook.async_register(
hass,
"test",
"Test hook",
"my-2",
None,
local_only=True,
allowed_methods=["GET"],
)
await client.send_json({"id": 5, "type": "webhook/list"})
msg = await client.receive_json()
assert msg["id"] == 5
assert msg["success"]
assert msg["result"] == [
{
"webhook_id": "my-id",
"domain": "test",
"name": "Test hook",
"local_only": False,
"allowed_methods": ["POST", "PUT"],
},
{
"webhook_id": "my-2",
"domain": "test",
"name": "Test hook",
"local_only": True,
"allowed_methods": ["GET"],
},
]
async def test_ws_webhook(
hass: HomeAssistant,
caplog: pytest.LogCaptureFixture,
hass_ws_client: WebSocketGenerator,
) -> None:
"""Test sending webhook msg via WS API."""
assert await async_setup_component(hass, "webhook", {})
received = []
async def handler(hass, webhook_id, request):
"""Handle a webhook."""
received.append(request)
return web.json_response({"from": "handler"})
webhook.async_register(hass, "test", "Test", "mock-webhook-id", handler)
client = await hass_ws_client(hass)
await client.send_json(
{
"id": 5,
"type": "webhook/handle",
"webhook_id": "mock-webhook-id",
"method": "POST",
"headers": {"Content-Type": "application/json"},
"body": '{"hello": "world"}',
"query": "a=2",
}
)
result = await client.receive_json()
assert result["success"], result
assert result["result"] == {
"status": 200,
"body": '{"from": "handler"}',
"headers": {"Content-Type": "application/json"},
}
assert len(received) == 1
assert received[0].headers["content-type"] == "application/json"
assert received[0].query == {"a": "2"}
assert await received[0].json() == {"hello": "world"}
# Non existing webhook
caplog.clear()
await client.send_json(
{
"id": 6,
"type": "webhook/handle",
"webhook_id": "mock-nonexisting-id",
"method": "POST",
"body": '{"nonexisting": "payload"}',
}
)
result = await client.receive_json()
assert result["success"], result
assert result["result"] == {
"status": 200,
"body": None,
"headers": {"Content-Type": "application/octet-stream"},
}
assert (
"Received message for unregistered webhook mock-nonexisting-id from webhook/ws"
in caplog.text
)
assert '{"nonexisting": "payload"}' in caplog.text