1
0
mirror of https://github.com/home-assistant/core.git synced 2025-08-13 07:20:01 +00:00
Files
.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
airthings
airtouch4
airvisual
airzone
aladdin_connect
alarm_control_panel
alarmdecoder
alert
alexa
almond
ambee
amberelectric
ambiclimate
ambient_station
analytics
androidtv
apache_kafka
api
api_streams
apple_tv
application_credentials
apprise
aprs
arcam_fmj
aseko_pool_live
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
blueprint
bluetooth_le_tracker
bmw_connected_drive
bond
bosch_shc
braviatv
broadlink
brother
brunt
bsblan
buienradar
button
caldav
calendar
camera
canary
cast
cert_expiry
climacell
climate
cloud
cloudflare
co2signal
coinbase
color_extractor
comfoconnect
command_line
compensation
config
configurator
control4
conversation
coolmaster
coronavirus
counter
cover
cpuspeed
crownstone
daikin
darksky
datadog
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
dlna_dmr
dlna_dms
dnsip
doorbird
dsmr
dte_energy_bridge
duckdns
dunehd
dynalite
eafm
ecobee
econet
efergy
elgato
elkm1
elmax
emonitor
emulated_hue
emulated_kasa
emulated_roku
energy
enocean
enphase_envoy
environment_canada
epson
esphome
everlights
evil_genius_labs
ezviz
faa_delays
facebook
facebox
fail2ban
fan
feedreader
ffmpeg
fibaro
fido
file
filesize
filter
fireservicerota
firmata
fivem
fjaraskupan
flic
flick_electric
flipr
flo
flume
flunearyou
flux
flux_led
folder
folder_watcher
foobot
forecast_solar
forked_daapd
foscam
freebox
freedns
freedompro
fritz
fritzbox
fritzbox_callmonitor
fronius
frontend
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
google_domains
google_pubsub
google_translate
google_travel_time
google_wifi
gpslogger
graphite
gree
greeneye_monitor
group
growatt_server
guardian
habitica
hangouts
hardkernel
hardware
harmony
hassio
hddtemp
heos
here_travel_time
hisense_aehw4a1
history
history_stats
hive
hlk_sw16
home_connect
home_plus_control
homeassistant
homekit
homekit_controller
homematic
homematicip_cloud
homewizard
honeywell
html5
http
huawei_lte
hue
huisbaasje
humidifier
__init__.py
test_device_action.py
test_device_condition.py
test_device_trigger.py
test_init.py
test_intent.py
test_recorder.py
test_reproduce_state.py
hunterdouglas_powerview
hvv_departures
hyperion
ialarm
iaqualink
icloud
ifttt
ign_sismologia
image
image_processing
imap_email_content
influxdb
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
kaleidescape
keenetic_ndms2
kira
kmtronic
knx
kodi
konnected
kostal_plenticore
kraken
kulersky
lastfm
launch_library
laundrify
lcn
light
litejet
litterrobot
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
maxcube
mazda
meater
media_player
media_source
melcloud
melissa
meraki
met
met_eireann
meteo_france
meteoclimatic
metoffice
mfi
microsoft_face
microsoft_face_detect
microsoft_face_identify
mikrotik
mill
min_max
minecraft_server
minio
mjpeg
mobile_app
mochad
modbus
modem_callerid
modern_forms
moehlenhoff_alpha2
mold_indicator
monoprice
moon
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
nfandroidtv
nightscout
nina
nmap_tracker
no_ip
notify
notify_events
notion
nsw_fuel_station
nsw_rural_fire_service_feed
nuheat
nuki
numato
number
nut
nws
nx584
nzbget
octoprint
omnilogic
onboarding
oncue
ondilo_ico
onewire
onvif
open_meteo
openalpr_cloud
openalpr_local
openerz
opengarage
openhardwaremonitor
opentherm_gw
openuv
openweathermap
opnsense
overkiz
ovo_energy
owntracks
p1_monitor
panasonic_viera
panel_custom
panel_iframe
peco
persistent_notification
person
philips_js
pi_hole
picnic
pilight
ping
plaato
plant
plex
plugwise
plum_lightpad
point
poolsense
powerwall
profiler
progettihwsw
prometheus
prosegur
proximity
ps4
pure_energie
push
pushbullet
pvoutput
pvpc_hourly_pricing
python_script
qld_bushfire
qnap_qsw
qwikswitch
rachio
radarr
radio_browser
radiotherm
rainforest_eagle
rainmachine
random
raspberry_pi
rdw
recollect_waste
recorder
reddit
remember_the_milk
remote
renault
rest
rest_command
rflink
rfxtrx
ridwell
ring
risco
rituals_perfume_genie
rmvtransport
roku
roomba
roon
rpi_power
rss_feed_template
rtsp_to_webrtc
ruckus_unleashed
sabnzbd
safe_mode
samsungtv
scene
scrape
screenlogic
script
search
season
select
sense
senseme
sensibo
sensor
sentry
senz
seventeentrack
sharkiq
shell_command
shelly
shopping_list
sia
sigfox
sighthound
signal_messenger
simplisafe
simulated
siren
skybell
slack
sleepiq
slimproto
sma
smappee
smart_meter_texas
smartthings
smarttub
smhi
smtp
snips
solaredge
solarlog
solax
soma
somfy
somfy_mylink
sonarr
songpal
sonos
soundtouch
spaceapi
spc
speedtestdotnet
spider
spotify
sql
squeezebox
srp_energy
ssdp
starline
startca
statistics
statsd
steam_online
steamist
stookalert
stream
stt
subaru
sun
surepetcare
switch
switch_as_x
switchbot
switcher_kis
syncthing
syncthru
synology_dsm
system_bridge
system_health
system_log
tado
tag
tailscale
tankerkoenig
tasmota
tautulli
tcp
telegram
telegram_bot
tellduslive
template
tesla_wall_connector
threshold
tibber
tile
time_date
timer
tod
todoist
tolo
tomato
tomorrowio
toon
totalconnect
tplink
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
volumio
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
xbox
xiaomi
xiaomi_aqara
xiaomi_miio
yale_smart_alarm
yamaha
yamaha_musiccast
yandex_transport
yandextts
yeelight
yolink
youless
zeroconf
zerproc
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
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
.core_files.yaml
.coveragerc
.dockerignore
.gitattributes
.gitignore
.hadolint.yaml
.ignore
.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
tox.ini
core/tests/components/humidifier/test_device_condition.py

462 lines
13 KiB
Python

"""The tests for Humidifier device conditions."""
import pytest
import voluptuous_serialize
import homeassistant.components.automation as automation
from homeassistant.components.device_automation import DeviceAutomationType
from homeassistant.components.humidifier import DOMAIN, const, device_condition
from homeassistant.const import ATTR_MODE, STATE_OFF, STATE_ON
from homeassistant.helpers import config_validation as cv, device_registry
from homeassistant.helpers.entity import EntityCategory
from homeassistant.helpers.entity_registry import RegistryEntryHider
from homeassistant.setup import async_setup_component
from tests.common import (
MockConfigEntry,
assert_lists_same,
async_get_device_automations,
async_mock_service,
mock_device_registry,
mock_registry,
)
from tests.components.blueprint.conftest import stub_blueprint_populate # noqa: F401
@pytest.fixture
def device_reg(hass):
"""Return an empty, loaded, registry."""
return mock_device_registry(hass)
@pytest.fixture
def entity_reg(hass):
"""Return an empty, loaded, registry."""
return mock_registry(hass)
@pytest.fixture
def calls(hass):
"""Track calls to a mock service."""
return async_mock_service(hass, "test", "automation")
@pytest.mark.parametrize(
"set_state,features_reg,features_state,expected_condition_types",
[
(False, 0, 0, []),
(False, const.HumidifierEntityFeature.MODES, 0, ["is_mode"]),
(True, 0, 0, []),
(True, 0, const.HumidifierEntityFeature.MODES, ["is_mode"]),
],
)
async def test_get_conditions(
hass,
device_reg,
entity_reg,
set_state,
features_reg,
features_state,
expected_condition_types,
):
"""Test we get the expected conditions from a humidifier."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_reg.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(device_registry.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_reg.async_get_or_create(
DOMAIN,
"test",
"5678",
device_id=device_entry.id,
supported_features=features_reg,
)
if set_state:
hass.states.async_set(
f"{DOMAIN}.test_5678", "attributes", {"supported_features": features_state}
)
expected_conditions = []
basic_condition_types = ["is_on", "is_off"]
expected_conditions += [
{
"condition": "device",
"domain": DOMAIN,
"type": condition,
"device_id": device_entry.id,
"entity_id": f"{DOMAIN}.test_5678",
"metadata": {"secondary": False},
}
for condition in basic_condition_types
]
expected_conditions += [
{
"condition": "device",
"domain": DOMAIN,
"type": condition,
"device_id": device_entry.id,
"entity_id": f"{DOMAIN}.test_5678",
"metadata": {"secondary": False},
}
for condition in expected_condition_types
]
conditions = await async_get_device_automations(
hass, DeviceAutomationType.CONDITION, device_entry.id
)
assert_lists_same(conditions, expected_conditions)
@pytest.mark.parametrize(
"hidden_by,entity_category",
(
(RegistryEntryHider.INTEGRATION, None),
(RegistryEntryHider.USER, None),
(None, EntityCategory.CONFIG),
(None, EntityCategory.DIAGNOSTIC),
),
)
async def test_get_conditions_hidden_auxiliary(
hass,
device_reg,
entity_reg,
hidden_by,
entity_category,
):
"""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_reg.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(device_registry.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_reg.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": f"{DOMAIN}.test_5678",
"metadata": {"secondary": True},
}
for condition in ["is_off", "is_on"]
]
conditions = await async_get_device_automations(
hass, DeviceAutomationType.CONDITION, device_entry.id
)
assert_lists_same(conditions, expected_conditions)
async def test_if_state(hass, calls):
"""Test for turn_on and turn_off conditions."""
hass.states.async_set("humidifier.entity", STATE_ON, {ATTR_MODE: const.MODE_AWAY})
assert await async_setup_component(
hass,
automation.DOMAIN,
{
automation.DOMAIN: [
{
"trigger": {"platform": "event", "event_type": "test_event1"},
"condition": [
{
"condition": "device",
"domain": DOMAIN,
"device_id": "",
"entity_id": "humidifier.entity",
"type": "is_on",
}
],
"action": {
"service": "test.automation",
"data_template": {
"some": "is_on {{ trigger.%s }}"
% "}} - {{ trigger.".join(("platform", "event.event_type"))
},
},
},
{
"trigger": {"platform": "event", "event_type": "test_event2"},
"condition": [
{
"condition": "device",
"domain": DOMAIN,
"device_id": "",
"entity_id": "humidifier.entity",
"type": "is_off",
}
],
"action": {
"service": "test.automation",
"data_template": {
"some": "is_off {{ trigger.%s }}"
% "}} - {{ trigger.".join(("platform", "event.event_type"))
},
},
},
{
"trigger": {"platform": "event", "event_type": "test_event3"},
"condition": [
{
"condition": "device",
"domain": DOMAIN,
"device_id": "",
"entity_id": "humidifier.entity",
"type": "is_mode",
"mode": "away",
}
],
"action": {
"service": "test.automation",
"data_template": {
"some": "is_mode - {{ trigger.platform }} - {{ trigger.event.event_type }}"
},
},
},
]
},
)
await hass.async_block_till_done()
assert hass.states.get("humidifier.entity").state == STATE_ON
assert len(calls) == 0
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["some"] == "is_on event - test_event1"
hass.states.async_set("humidifier.entity", STATE_OFF)
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["some"] == "is_off event - test_event2"
hass.states.async_set("humidifier.entity", STATE_ON, {ATTR_MODE: const.MODE_AWAY})
hass.bus.async_fire("test_event3")
await hass.async_block_till_done()
assert len(calls) == 3
assert calls[2].data["some"] == "is_mode - event - test_event3"
hass.states.async_set("humidifier.entity", STATE_ON, {ATTR_MODE: const.MODE_HOME})
# Should not fire
hass.bus.async_fire("test_event3")
await hass.async_block_till_done()
assert len(calls) == 3
@pytest.mark.parametrize(
"set_state,capabilities_reg,capabilities_state,condition,expected_capabilities",
[
(
False,
{},
{},
"is_mode",
[
{
"name": "mode",
"options": [],
"required": True,
"type": "select",
}
],
),
(
False,
{const.ATTR_AVAILABLE_MODES: [const.MODE_HOME, const.MODE_AWAY]},
{},
"is_mode",
[
{
"name": "mode",
"options": [("home", "home"), ("away", "away")],
"required": True,
"type": "select",
}
],
),
(
False,
{},
{},
"is_off",
[
{
"name": "for",
"optional": True,
"type": "positive_time_period_dict",
}
],
),
(
False,
{},
{},
"is_on",
[
{
"name": "for",
"optional": True,
"type": "positive_time_period_dict",
}
],
),
(
True,
{},
{},
"is_mode",
[
{
"name": "mode",
"options": [],
"required": True,
"type": "select",
}
],
),
(
True,
{},
{const.ATTR_AVAILABLE_MODES: [const.MODE_HOME, const.MODE_AWAY]},
"is_mode",
[
{
"name": "mode",
"options": [("home", "home"), ("away", "away")],
"required": True,
"type": "select",
}
],
),
(
True,
{},
{},
"is_off",
[
{
"name": "for",
"optional": True,
"type": "positive_time_period_dict",
}
],
),
(
True,
{},
{},
"is_on",
[
{
"name": "for",
"optional": True,
"type": "positive_time_period_dict",
}
],
),
],
)
async def test_capabilities(
hass,
device_reg,
entity_reg,
set_state,
capabilities_reg,
capabilities_state,
condition,
expected_capabilities,
):
"""Test getting capabilities."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
device_entry = device_reg.async_get_or_create(
config_entry_id=config_entry.entry_id,
connections={(device_registry.CONNECTION_NETWORK_MAC, "12:34:56:AB:CD:EF")},
)
entity_reg.async_get_or_create(
DOMAIN,
"test",
"5678",
device_id=device_entry.id,
capabilities=capabilities_reg,
)
if set_state:
hass.states.async_set(
f"{DOMAIN}.test_5678",
STATE_ON,
capabilities_state,
)
capabilities = await device_condition.async_get_condition_capabilities(
hass,
{
"domain": DOMAIN,
"device_id": "abcdefgh",
"entity_id": f"{DOMAIN}.test_5678",
"type": condition,
},
)
assert capabilities and "extra_fields" in capabilities
assert (
voluptuous_serialize.convert(
capabilities["extra_fields"], custom_serializer=cv.custom_serializer
)
== expected_capabilities
)
@pytest.mark.parametrize(
"condition,capability_name,extra",
[
("is_mode", "mode", {"type": "select", "options": []}),
],
)
async def test_capabilities_missing_entity(
hass, device_reg, entity_reg, condition, capability_name, extra
):
"""Test getting capabilities."""
config_entry = MockConfigEntry(domain="test", data={})
config_entry.add_to_hass(hass)
capabilities = await device_condition.async_get_condition_capabilities(
hass,
{
"domain": DOMAIN,
"device_id": "abcdefgh",
"entity_id": f"{DOMAIN}.test_5678",
"type": condition,
},
)
expected_capabilities = [
{
"name": capability_name,
"required": True,
**extra,
}
]
assert capabilities and "extra_fields" in capabilities
assert (
voluptuous_serialize.convert(
capabilities["extra_fields"], custom_serializer=cv.custom_serializer
)
== expected_capabilities
)