1
0
mirror of https://github.com/home-assistant/core.git synced 2025-08-11 06:20:01 +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
aosmith
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
blue_current
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
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
dremel_3d_printer
drop_connect
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
fastdotcom
feedreader
ffmpeg
fibaro
fido
file
file_upload
filesize
filter
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
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
holiday
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
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
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
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
motionmount
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
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
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
rachio
radarr
radio_browser
radiotherm
rainbird
rainforest_eagle
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
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
__init__.py
test_device_action.py
test_device_condition.py
test_device_trigger.py
test_init.py
test_recorder.py
test_reproduce_state.py
test_significant_change.py
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
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
telegram
telegram_bot
tellduslive
temper
template
tesla_wall_connector
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
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
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
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_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
.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/select/test_device_condition.py
2023-10-24 23:37:16 +02:00

376 lines
12 KiB
Python

"""The tests for Select device conditions."""
from __future__ import annotations
import pytest
from pytest_unordered import unordered
import voluptuous_serialize
from homeassistant.components import automation
from homeassistant.components.device_automation import DeviceAutomationType
from homeassistant.components.select import DOMAIN
from homeassistant.components.select.device_condition import (
async_get_condition_capabilities,
)
from homeassistant.const import EntityCategory
from homeassistant.core import HomeAssistant, ServiceCall
from homeassistant.helpers import (
config_validation as cv,
device_registry as dr,
entity_registry as er,
)
from homeassistant.setup import async_setup_component
from tests.common import (
MockConfigEntry,
async_get_device_automations,
async_mock_service,
)
@pytest.fixture
def calls(hass: HomeAssistant) -> list[ServiceCall]:
"""Track calls to a mock service."""
return async_mock_service(hass, "test", "automation")
async def test_get_conditions(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test we get the expected conditions from a select."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_entry = entity_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
expected_conditions = [
{
"condition": "device",
"domain": DOMAIN,
"type": "selected_option",
"device_id": device_entry.id,
"entity_id": entity_entry.id,
"metadata": {"secondary": False},
}
]
conditions = await async_get_device_automations(
hass, DeviceAutomationType.CONDITION, device_entry.id
)
assert conditions == unordered(expected_conditions)
@pytest.mark.parametrize(
("hidden_by", "entity_category"),
(
(er.RegistryEntryHider.INTEGRATION, None),
(er.RegistryEntryHider.USER, None),
(None, EntityCategory.CONFIG),
(None, EntityCategory.DIAGNOSTIC),
),
)
async def test_get_conditions_hidden_auxiliary(
hass: HomeAssistant,
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
hidden_by,
entity_category,
) -> None:
"""Test we get the expected conditions from a hidden or auxiliary entity."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_entry = entity_registry.async_get_or_create(
DOMAIN,
"test",
"5678",
device_id=device_entry.id,
entity_category=entity_category,
hidden_by=hidden_by,
)
expected_conditions = [
{
"condition": "device",
"domain": DOMAIN,
"type": condition,
"device_id": device_entry.id,
"entity_id": entity_entry.id,
"metadata": {"secondary": True},
}
for condition in ["selected_option"]
]
conditions = await async_get_device_automations(
hass, DeviceAutomationType.CONDITION, device_entry.id
)
assert conditions == unordered(expected_conditions)
async def test_if_selected_option(
hass: HomeAssistant,
calls: list[ServiceCall],
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test for selected_option conditions."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entry = entity_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {"platform": "event", "event_type": "test_event1"},
"condition": [
{
"condition": "device",
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.id,
"type": "selected_option",
"option": "option1",
}
],
"action": {
"service": "test.automation",
"data": {
"result": "option1 - {{ trigger.platform }} - {{ trigger.event.event_type }}"
},
},
},
{
"trigger": {"platform": "event", "event_type": "test_event2"},
"condition": [
{
"condition": "device",
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.id,
"type": "selected_option",
"option": "option2",
}
],
"action": {
"service": "test.automation",
"data": {
"result": "option2 - {{ trigger.platform }} - {{ trigger.event.event_type }}"
},
},
},
]
},
)
# Test with non existing entity
hass.bus.async_fire("test_event1")
hass.bus.async_fire("test_event2")
await hass.async_block_till_done()
assert len(calls) == 0
hass.states.async_set(
entry.entity_id, "option1", {"options": ["option1", "option2"]}
)
hass.bus.async_fire("test_event1")
hass.bus.async_fire("test_event2")
await hass.async_block_till_done()
assert len(calls) == 1
assert calls[0].data["result"] == "option1 - event - test_event1"
hass.states.async_set(
entry.entity_id, "option2", {"options": ["option1", "option2"]}
)
hass.bus.async_fire("test_event1")
hass.bus.async_fire("test_event2")
await hass.async_block_till_done()
assert len(calls) == 2
assert calls[1].data["result"] == "option2 - event - test_event2"
async def test_if_selected_option_legacy(
hass: HomeAssistant,
calls: list[ServiceCall],
device_registry: dr.DeviceRegistry,
entity_registry: er.EntityRegistry,
) -> None:
"""Test for selected_option conditions."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_registry.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(dr.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entry = entity_registry.async_get_or_create(
DOMAIN, "test", "5678", device_id=device_entry.id
)
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {"platform": "event", "event_type": "test_event1"},
"condition": [
{
"condition": "device",
"domain": DOMAIN,
"device_id": device_entry.id,
"entity_id": entry.entity_id,
"type": "selected_option",
"option": "option1",
}
],
"action": {
"service": "test.automation",
"data": {
"result": "option1 - {{ trigger.platform }} - {{ trigger.event.event_type }}"
},
},
},
]
},
)
hass.states.async_set(
entry.entity_id, "option1", {"options": ["option1", "option2"]}
)
hass.bus.async_fire("test_event1")
await hass.async_block_till_done()
assert len(calls) == 1
assert calls[0].data["result"] == "option1 - event - test_event1"
async def test_get_condition_capabilities(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test we get the expected capabilities from a select condition."""
entry = entity_registry.async_get_or_create(DOMAIN, "test", "5678")
config = {
"platform": "device",
"domain": DOMAIN,
"type": "selected_option",
"entity_id": entry.id,
"option": "option1",
}
# Test when entity doesn't exists
capabilities = await async_get_condition_capabilities(hass, config)
assert capabilities
assert "extra_fields" in capabilities
assert voluptuous_serialize.convert(
capabilities["extra_fields"], custom_serializer=cv.custom_serializer
) == [
{
"name": "option",
"required": True,
"type": "select",
"options": [],
},
{
"name": "for",
"optional": True,
"type": "positive_time_period_dict",
},
]
# Mock an entity
hass.states.async_set(
entry.entity_id, "option1", {"options": ["option1", "option2"]}
)
# Test if we get the right capabilities now
capabilities = await async_get_condition_capabilities(hass, config)
assert capabilities
assert "extra_fields" in capabilities
assert voluptuous_serialize.convert(
capabilities["extra_fields"], custom_serializer=cv.custom_serializer
) == [
{
"name": "option",
"required": True,
"type": "select",
"options": [("option1", "option1"), ("option2", "option2")],
},
{
"name": "for",
"optional": True,
"type": "positive_time_period_dict",
},
]
async def test_get_condition_capabilities_legacy(
hass: HomeAssistant, entity_registry: er.EntityRegistry
) -> None:
"""Test we get the expected capabilities from a select condition."""
entry = entity_registry.async_get_or_create(DOMAIN, "test", "5678")
config = {
"platform": "device",
"domain": DOMAIN,
"type": "selected_option",
"entity_id": entry.entity_id,
"option": "option1",
}
# Test when entity doesn't exists
capabilities = await async_get_condition_capabilities(hass, config)
assert capabilities
assert "extra_fields" in capabilities
assert voluptuous_serialize.convert(
capabilities["extra_fields"], custom_serializer=cv.custom_serializer
) == [
{
"name": "option",
"required": True,
"type": "select",
"options": [],
},
{
"name": "for",
"optional": True,
"type": "positive_time_period_dict",
},
]
# Mock an entity
hass.states.async_set(
entry.entity_id, "option1", {"options": ["option1", "option2"]}
)
# Test if we get the right capabilities now
capabilities = await async_get_condition_capabilities(hass, config)
assert capabilities
assert "extra_fields" in capabilities
assert voluptuous_serialize.convert(
capabilities["extra_fields"], custom_serializer=cv.custom_serializer
) == [
{
"name": "option",
"required": True,
"type": "select",
"options": [("option1", "option1"), ("option2", "option2")],
},
{
"name": "for",
"optional": True,
"type": "positive_time_period_dict",
},
]