mirror of
https://github.com/home-assistant/core.git
synced 2025-08-22 03:40:02 +00:00
.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
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
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
hko
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
__init__.py
test_init.py
test_recorder.py
test_reproduce_state.py
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
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
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
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
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
tedee
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
531 lines
16 KiB
Python
531 lines
16 KiB
Python
"""The tests for the Input text component."""
|
|
from unittest.mock import patch
|
|
|
|
import pytest
|
|
|
|
from homeassistant.components.input_text import (
|
|
ATTR_MAX,
|
|
ATTR_MIN,
|
|
ATTR_MODE,
|
|
ATTR_VALUE,
|
|
CONF_INITIAL,
|
|
CONF_MAX_VALUE,
|
|
CONF_MIN_VALUE,
|
|
DOMAIN,
|
|
MODE_TEXT,
|
|
SERVICE_SET_VALUE,
|
|
)
|
|
from homeassistant.const import (
|
|
ATTR_EDITABLE,
|
|
ATTR_ENTITY_ID,
|
|
ATTR_FRIENDLY_NAME,
|
|
ATTR_NAME,
|
|
SERVICE_RELOAD,
|
|
)
|
|
from homeassistant.core import Context, CoreState, HomeAssistant, State
|
|
from homeassistant.exceptions import Unauthorized
|
|
from homeassistant.helpers import entity_registry as er
|
|
from homeassistant.setup import async_setup_component
|
|
|
|
from tests.common import MockUser, mock_restore_cache
|
|
from tests.typing import WebSocketGenerator
|
|
|
|
TEST_VAL_MIN = 2
|
|
TEST_VAL_MAX = 22
|
|
|
|
|
|
@pytest.fixture
|
|
def storage_setup(hass, hass_storage):
|
|
"""Storage setup."""
|
|
|
|
async def _storage(items=None, config=None):
|
|
if items is None:
|
|
hass_storage[DOMAIN] = {
|
|
"key": DOMAIN,
|
|
"version": 1,
|
|
"data": {
|
|
"items": [
|
|
{
|
|
"id": "from_storage",
|
|
"name": "from storage",
|
|
"initial": "loaded from storage",
|
|
ATTR_MAX: TEST_VAL_MAX,
|
|
ATTR_MIN: TEST_VAL_MIN,
|
|
ATTR_MODE: MODE_TEXT,
|
|
}
|
|
]
|
|
},
|
|
}
|
|
else:
|
|
hass_storage[DOMAIN] = {
|
|
"key": DOMAIN,
|
|
"version": 1,
|
|
"data": {"items": items},
|
|
}
|
|
if config is None:
|
|
config = {DOMAIN: {}}
|
|
return await async_setup_component(hass, DOMAIN, config)
|
|
|
|
return _storage
|
|
|
|
|
|
async def async_set_value(hass, entity_id, value):
|
|
"""Set input_text to value."""
|
|
await hass.services.async_call(
|
|
DOMAIN,
|
|
SERVICE_SET_VALUE,
|
|
{ATTR_ENTITY_ID: entity_id, ATTR_VALUE: value},
|
|
blocking=True,
|
|
)
|
|
|
|
|
|
async def test_config(hass: HomeAssistant) -> None:
|
|
"""Test config."""
|
|
invalid_configs = [
|
|
None,
|
|
{},
|
|
{"name with space": None},
|
|
{"test_1": {"min": 50, "max": 50}},
|
|
]
|
|
for cfg in invalid_configs:
|
|
assert not await async_setup_component(hass, DOMAIN, {DOMAIN: cfg})
|
|
|
|
|
|
async def test_set_value(hass: HomeAssistant) -> None:
|
|
"""Test set_value method."""
|
|
assert await async_setup_component(
|
|
hass,
|
|
DOMAIN,
|
|
{
|
|
DOMAIN: {
|
|
"test_1": {"initial": "test", "min": 3, "max": 10},
|
|
"test_2": {},
|
|
}
|
|
},
|
|
)
|
|
entity_id = "input_text.test_1"
|
|
entity_id_2 = "input_text.test_2"
|
|
assert hass.states.get(entity_id).state == "test"
|
|
assert hass.states.get(entity_id_2).state == "unknown"
|
|
|
|
for entity in (entity_id, entity_id_2):
|
|
await async_set_value(hass, entity, "testing")
|
|
assert hass.states.get(entity).state == "testing"
|
|
|
|
# Too long for entity 1
|
|
await async_set_value(hass, entity, "testing too long")
|
|
assert hass.states.get(entity_id).state == "testing"
|
|
|
|
# Set to empty string
|
|
await async_set_value(hass, entity_id_2, "")
|
|
assert hass.states.get(entity_id_2).state == ""
|
|
|
|
|
|
async def test_mode(hass: HomeAssistant) -> None:
|
|
"""Test mode settings."""
|
|
assert await async_setup_component(
|
|
hass,
|
|
DOMAIN,
|
|
{
|
|
DOMAIN: {
|
|
"test_default_text": {"initial": "test", "min": 3, "max": 10},
|
|
"test_explicit_text": {
|
|
"initial": "test",
|
|
"min": 3,
|
|
"max": 10,
|
|
"mode": "text",
|
|
},
|
|
"test_explicit_password": {
|
|
"initial": "test",
|
|
"min": 3,
|
|
"max": 10,
|
|
"mode": "password",
|
|
},
|
|
}
|
|
},
|
|
)
|
|
|
|
state = hass.states.get("input_text.test_default_text")
|
|
assert state
|
|
assert state.attributes["mode"] == "text"
|
|
|
|
state = hass.states.get("input_text.test_explicit_text")
|
|
assert state
|
|
assert state.attributes["mode"] == "text"
|
|
|
|
state = hass.states.get("input_text.test_explicit_password")
|
|
assert state
|
|
assert state.attributes["mode"] == "password"
|
|
|
|
|
|
async def test_restore_state(hass: HomeAssistant) -> None:
|
|
"""Ensure states are restored on startup."""
|
|
mock_restore_cache(
|
|
hass,
|
|
(State("input_text.b1", "test"), State("input_text.b2", "testing too long")),
|
|
)
|
|
|
|
hass.state = CoreState.starting
|
|
|
|
assert await async_setup_component(
|
|
hass, DOMAIN, {DOMAIN: {"b1": None, "b2": {"min": 0, "max": 10}}}
|
|
)
|
|
|
|
state = hass.states.get("input_text.b1")
|
|
assert state
|
|
assert str(state.state) == "test"
|
|
|
|
state = hass.states.get("input_text.b2")
|
|
assert state
|
|
assert str(state.state) == "unknown"
|
|
|
|
|
|
async def test_initial_state_overrules_restore_state(hass: HomeAssistant) -> None:
|
|
"""Ensure states are restored on startup."""
|
|
mock_restore_cache(
|
|
hass,
|
|
(State("input_text.b1", "testing"), State("input_text.b2", "testing too long")),
|
|
)
|
|
|
|
hass.state = CoreState.starting
|
|
|
|
await async_setup_component(
|
|
hass,
|
|
DOMAIN,
|
|
{
|
|
DOMAIN: {
|
|
"b1": {"initial": "test", "min": 0, "max": 10},
|
|
"b2": {"initial": "test", "min": 0, "max": 10},
|
|
}
|
|
},
|
|
)
|
|
|
|
state = hass.states.get("input_text.b1")
|
|
assert state
|
|
assert str(state.state) == "test"
|
|
|
|
state = hass.states.get("input_text.b2")
|
|
assert state
|
|
assert str(state.state) == "test"
|
|
|
|
|
|
async def test_no_initial_state_and_no_restore_state(hass: HomeAssistant) -> None:
|
|
"""Ensure that entity is create without initial and restore feature."""
|
|
hass.state = CoreState.starting
|
|
|
|
await async_setup_component(hass, DOMAIN, {DOMAIN: {"b1": {"min": 0, "max": 100}}})
|
|
|
|
state = hass.states.get("input_text.b1")
|
|
assert state
|
|
assert str(state.state) == "unknown"
|
|
|
|
|
|
async def test_input_text_context(
|
|
hass: HomeAssistant, hass_admin_user: MockUser
|
|
) -> None:
|
|
"""Test that input_text context works."""
|
|
assert await async_setup_component(
|
|
hass, "input_text", {"input_text": {"t1": {"initial": "bla"}}}
|
|
)
|
|
|
|
state = hass.states.get("input_text.t1")
|
|
assert state is not None
|
|
|
|
await hass.services.async_call(
|
|
"input_text",
|
|
"set_value",
|
|
{"entity_id": state.entity_id, "value": "new_value"},
|
|
True,
|
|
Context(user_id=hass_admin_user.id),
|
|
)
|
|
|
|
state2 = hass.states.get("input_text.t1")
|
|
assert state2 is not None
|
|
assert state.state != state2.state
|
|
assert state2.context.user_id == hass_admin_user.id
|
|
|
|
|
|
async def test_config_none(hass: HomeAssistant) -> None:
|
|
"""Set up input_text without any config."""
|
|
await async_setup_component(hass, DOMAIN, {DOMAIN: {"b1": None}})
|
|
|
|
state = hass.states.get("input_text.b1")
|
|
assert state
|
|
assert str(state.state) == "unknown"
|
|
|
|
# with empty config we still should have the defaults
|
|
assert state.attributes[ATTR_MODE] == MODE_TEXT
|
|
assert state.attributes[ATTR_MAX] == CONF_MAX_VALUE
|
|
assert state.attributes[ATTR_MIN] == CONF_MIN_VALUE
|
|
|
|
|
|
async def test_reload(
|
|
hass: HomeAssistant, hass_admin_user: MockUser, hass_read_only_user: MockUser
|
|
) -> None:
|
|
"""Test reload service."""
|
|
count_start = len(hass.states.async_entity_ids())
|
|
|
|
assert await async_setup_component(
|
|
hass,
|
|
DOMAIN,
|
|
{DOMAIN: {"test_1": {"initial": "test 1"}, "test_2": {"initial": "test 2"}}},
|
|
)
|
|
|
|
assert count_start + 2 == len(hass.states.async_entity_ids())
|
|
|
|
state_1 = hass.states.get("input_text.test_1")
|
|
state_2 = hass.states.get("input_text.test_2")
|
|
state_3 = hass.states.get("input_text.test_3")
|
|
|
|
assert state_1 is not None
|
|
assert state_2 is not None
|
|
assert state_3 is None
|
|
assert state_1.state == "test 1"
|
|
assert state_2.state == "test 2"
|
|
assert state_1.attributes[ATTR_MIN] == 0
|
|
assert state_2.attributes[ATTR_MAX] == 100
|
|
|
|
with patch(
|
|
"homeassistant.config.load_yaml_config_file",
|
|
autospec=True,
|
|
return_value={
|
|
DOMAIN: {
|
|
"test_2": {"initial": "test reloaded", ATTR_MIN: 12},
|
|
"test_3": {"initial": "test 3", ATTR_MAX: 21},
|
|
}
|
|
},
|
|
):
|
|
with pytest.raises(Unauthorized):
|
|
await hass.services.async_call(
|
|
DOMAIN,
|
|
SERVICE_RELOAD,
|
|
blocking=True,
|
|
context=Context(user_id=hass_read_only_user.id),
|
|
)
|
|
await hass.services.async_call(
|
|
DOMAIN,
|
|
SERVICE_RELOAD,
|
|
blocking=True,
|
|
context=Context(user_id=hass_admin_user.id),
|
|
)
|
|
await hass.async_block_till_done()
|
|
|
|
assert count_start + 2 == len(hass.states.async_entity_ids())
|
|
|
|
state_1 = hass.states.get("input_text.test_1")
|
|
state_2 = hass.states.get("input_text.test_2")
|
|
state_3 = hass.states.get("input_text.test_3")
|
|
|
|
assert state_1 is None
|
|
assert state_2 is not None
|
|
assert state_3 is not None
|
|
assert state_2.attributes[ATTR_MIN] == 12
|
|
assert state_3.attributes[ATTR_MAX] == 21
|
|
|
|
|
|
async def test_load_from_storage(hass: HomeAssistant, storage_setup) -> None:
|
|
"""Test set up from storage."""
|
|
assert await storage_setup()
|
|
state = hass.states.get(f"{DOMAIN}.from_storage")
|
|
assert state.state == "loaded from storage"
|
|
assert state.attributes.get(ATTR_EDITABLE)
|
|
assert state.attributes[ATTR_MAX] == TEST_VAL_MAX
|
|
assert state.attributes[ATTR_MIN] == TEST_VAL_MIN
|
|
|
|
|
|
async def test_editable_state_attribute(hass: HomeAssistant, storage_setup) -> None:
|
|
"""Test editable attribute."""
|
|
assert await storage_setup(
|
|
config={
|
|
DOMAIN: {
|
|
"from_yaml": {
|
|
"initial": "yaml initial value",
|
|
ATTR_MODE: MODE_TEXT,
|
|
ATTR_MAX: 33,
|
|
ATTR_MIN: 3,
|
|
ATTR_NAME: "yaml friendly name",
|
|
}
|
|
}
|
|
}
|
|
)
|
|
|
|
state = hass.states.get(f"{DOMAIN}.from_storage")
|
|
assert state.state == "loaded from storage"
|
|
assert state.attributes.get(ATTR_EDITABLE)
|
|
assert state.attributes[ATTR_MAX] == TEST_VAL_MAX
|
|
assert state.attributes[ATTR_MIN] == TEST_VAL_MIN
|
|
|
|
state = hass.states.get(f"{DOMAIN}.from_yaml")
|
|
assert state.state == "yaml initial value"
|
|
assert not state.attributes[ATTR_EDITABLE]
|
|
assert state.attributes[ATTR_MAX] == 33
|
|
assert state.attributes[ATTR_MIN] == 3
|
|
|
|
|
|
async def test_ws_list(
|
|
hass: HomeAssistant, hass_ws_client: WebSocketGenerator, storage_setup
|
|
) -> None:
|
|
"""Test listing via WS."""
|
|
assert await storage_setup(
|
|
config={
|
|
DOMAIN: {
|
|
"from_yaml": {
|
|
"initial": "yaml initial value",
|
|
ATTR_MODE: MODE_TEXT,
|
|
ATTR_MAX: 33,
|
|
ATTR_MIN: 3,
|
|
ATTR_NAME: "yaml friendly name",
|
|
}
|
|
}
|
|
}
|
|
)
|
|
|
|
client = await hass_ws_client(hass)
|
|
|
|
await client.send_json({"id": 6, "type": f"{DOMAIN}/list"})
|
|
resp = await client.receive_json()
|
|
assert resp["success"]
|
|
|
|
storage_ent = "from_storage"
|
|
yaml_ent = "from_yaml"
|
|
result = {item["id"]: item for item in resp["result"]}
|
|
|
|
assert len(result) == 1
|
|
assert storage_ent in result
|
|
assert yaml_ent not in result
|
|
assert result[storage_ent][ATTR_NAME] == "from storage"
|
|
|
|
|
|
async def test_ws_delete(
|
|
hass: HomeAssistant,
|
|
entity_registry: er.EntityRegistry,
|
|
hass_ws_client: WebSocketGenerator,
|
|
storage_setup,
|
|
) -> None:
|
|
"""Test WS delete cleans up entity registry."""
|
|
assert await storage_setup()
|
|
|
|
input_id = "from_storage"
|
|
input_entity_id = f"{DOMAIN}.{input_id}"
|
|
|
|
state = hass.states.get(input_entity_id)
|
|
assert state is not None
|
|
assert entity_registry.async_get_entity_id(DOMAIN, DOMAIN, input_id) is not None
|
|
|
|
client = await hass_ws_client(hass)
|
|
|
|
await client.send_json(
|
|
{"id": 6, "type": f"{DOMAIN}/delete", f"{DOMAIN}_id": f"{input_id}"}
|
|
)
|
|
resp = await client.receive_json()
|
|
assert resp["success"]
|
|
|
|
state = hass.states.get(input_entity_id)
|
|
assert state is None
|
|
assert entity_registry.async_get_entity_id(DOMAIN, DOMAIN, input_id) is None
|
|
|
|
|
|
async def test_update(
|
|
hass: HomeAssistant,
|
|
entity_registry: er.EntityRegistry,
|
|
hass_ws_client: WebSocketGenerator,
|
|
storage_setup,
|
|
) -> None:
|
|
"""Test updating min/max updates the state."""
|
|
|
|
assert await storage_setup()
|
|
|
|
input_id = "from_storage"
|
|
input_entity_id = f"{DOMAIN}.{input_id}"
|
|
|
|
state = hass.states.get(input_entity_id)
|
|
assert state.attributes[ATTR_FRIENDLY_NAME] == "from storage"
|
|
assert state.attributes[ATTR_MODE] == MODE_TEXT
|
|
assert state.state == "loaded from storage"
|
|
assert entity_registry.async_get_entity_id(DOMAIN, DOMAIN, input_id) is not None
|
|
|
|
client = await hass_ws_client(hass)
|
|
|
|
updated_settings = {
|
|
ATTR_NAME: "even newer name",
|
|
CONF_INITIAL: "newer option",
|
|
ATTR_MAX: TEST_VAL_MAX,
|
|
ATTR_MIN: 6,
|
|
ATTR_MODE: "password",
|
|
}
|
|
await client.send_json(
|
|
{
|
|
"id": 6,
|
|
"type": f"{DOMAIN}/update",
|
|
f"{DOMAIN}_id": f"{input_id}",
|
|
**updated_settings,
|
|
}
|
|
)
|
|
resp = await client.receive_json()
|
|
assert resp["success"]
|
|
assert resp["result"] == {"id": "from_storage"} | updated_settings
|
|
|
|
state = hass.states.get(input_entity_id)
|
|
assert state.state == "loaded from storage"
|
|
assert state.attributes[ATTR_FRIENDLY_NAME] == "even newer name"
|
|
assert state.attributes[ATTR_MODE] == "password"
|
|
assert state.attributes[ATTR_MIN] == 6
|
|
assert state.attributes[ATTR_MAX] == TEST_VAL_MAX
|
|
|
|
|
|
async def test_ws_create(
|
|
hass: HomeAssistant,
|
|
entity_registry: er.EntityRegistry,
|
|
hass_ws_client: WebSocketGenerator,
|
|
storage_setup,
|
|
) -> None:
|
|
"""Test create WS."""
|
|
assert await storage_setup(items=[])
|
|
|
|
input_id = "new_input"
|
|
input_entity_id = f"{DOMAIN}.{input_id}"
|
|
|
|
state = hass.states.get(input_entity_id)
|
|
assert state is None
|
|
assert entity_registry.async_get_entity_id(DOMAIN, DOMAIN, input_id) is None
|
|
|
|
client = await hass_ws_client(hass)
|
|
|
|
await client.send_json(
|
|
{
|
|
"id": 6,
|
|
"type": f"{DOMAIN}/create",
|
|
"name": "New Input",
|
|
"initial": "even newer option",
|
|
ATTR_MAX: 44,
|
|
}
|
|
)
|
|
resp = await client.receive_json()
|
|
assert resp["success"]
|
|
|
|
state = hass.states.get(input_entity_id)
|
|
assert state.state == "even newer option"
|
|
assert state.attributes[ATTR_FRIENDLY_NAME] == "New Input"
|
|
assert state.attributes[ATTR_EDITABLE]
|
|
assert state.attributes[ATTR_MAX] == 44
|
|
assert state.attributes[ATTR_MIN] == 0
|
|
|
|
|
|
async def test_setup_no_config(hass: HomeAssistant, hass_admin_user: MockUser) -> None:
|
|
"""Test component setup with no config."""
|
|
count_start = len(hass.states.async_entity_ids())
|
|
assert await async_setup_component(hass, DOMAIN, {})
|
|
|
|
with patch(
|
|
"homeassistant.config.load_yaml_config_file", autospec=True, return_value={}
|
|
):
|
|
await hass.services.async_call(
|
|
DOMAIN,
|
|
SERVICE_RELOAD,
|
|
blocking=True,
|
|
context=Context(user_id=hass_admin_user.id),
|
|
)
|
|
await hass.async_block_till_done()
|
|
|
|
assert count_start == len(hass.states.async_entity_ids())
|