mirror of
https://github.com/home-assistant/core.git
synced 2025-09-22 19:39:36 +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
airgradient
airly
airnow
airq
airthings
airthings_ble
airtouch4
airtouch5
airvisual
airvisual_pro
airzone
airzone_cloud
aladdin_connect
alarm_control_panel
alarmdecoder
alert
alexa
amberelectric
ambient_network
ambient_station
analytics
analytics_insights
android_ip_webcam
androidtv
androidtv_remote
anova
anthemav
anthropic
aosmith
apache_kafka
apcupsd
api
api_streams
apple_tv
application_credentials
apprise
aprilaire
aprs
apsystems
aquacell
aranet
arcam_fmj
arve
aseko_pool_live
assist_pipeline
assist_satellite
asuswrt
atag
august
aurora
aurora_abb_powerone
aussie_broadband
autarco
auth
automation
awair
aws
axis
azure_data_explorer
azure_devops
azure_event_hub
backup
baf
balboa
bang_olufsen
bayesian
binary_sensor
blackbird
blebox
blink
blue_current
bluemaestro
blueprint
bluesound
bluetooth
bluetooth_adapters
bluetooth_le_tracker
bmw_connected_drive
bond
bosch_shc
braviatv
bring
broadlink
brother
brottsplatskartan
brunt
bryant_evolution
bsblan
bthome
buienradar
button
caldav
calendar
cambridge_audio
camera
canary
cast
ccm15
cert_expiry
chacon_dio
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
deako
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
duke_energy
dunehd
duotecno
dwd_weather_warnings
dynalite
eafm
easyenergy
ecobee
ecoforest
econet
ecovacs
ecowitt
edl21
efergy
eight_sleep
electrasmart
electric_kiwi
elevenlabs
elgato
elkm1
elmax
elvia
emoncms
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
evohome
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
fujitsu_fglair
fully_kiosk
fyta
garages_amsterdam
gardena_bluetooth
gdacs
generic
generic_hygrostat
generic_thermostat
geniushub
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_cloud
google_domains
google_generative_ai_conversation
google_mail
google_photos
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
incomfort
influxdb
inkbird
input_boolean
input_button
input_datetime
input_number
input_select
input_text
insteon
integration
intellifire
intent
intent_script
ios
iotawatt
iotty
ipma
ipp
iqvia
iron_os
isal
iskra
islamic_prayer_times
israel_rail
iss
ista_ecotrend
isy994
izone
jellyfin
jewish_calendar
juicenet
justnimbus
jvc_projector
kaleidescape
keenetic_ndms2
kegtron
keymitt_ble
kira
kitchen_sink
kmtronic
knocki
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
lektrico
lg_netcast
lg_soundbar
lg_thinq
lidarr
life360
lifx
light
linear_garage_door
linkplay
litejet
litterrobot
livisi
local_calendar
local_file
local_ip
local_todo
locative
lock
logbook
logentries
logger
london_air
london_underground
lookin
loqed
lovelace
luftdaten
lupusec
lutron
lutron_caseta
lyric
madvr
mailgun
manual
manual_mqtt
map
marytts
mastodon
matrix
matter
maxcube
mazda
mealie
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
mochad
modbus
modem_callerid
modern_forms
moehlenhoff_alpha2
mold_indicator
monarch_money
monoprice
monzo
moon
mopeka
motion_blinds
motionblinds_ble
motioneye
motionmount
mpd
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
nice_go
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
otp
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
pyload
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
russound_rio
ruuvi_gateway
ruuvitag_ble
rympro
sabnzbd
samsungtv
sanix
scene
schedule
schlage
scrape
screenlogic
script
search
season
select
sense
sensibo
sensirion_ble
sensor
sensorpro
sensorpush
sensoterra
sentry
senz
seventeentrack
sfr_box
sharkiq
shell_command
shelly
shopping_list
sia
sigfox
sighthound
signal_messenger
simplefin
simplepush
simplisafe
simulated
siren
skybell
slack
sleepiq
slimproto
sma
smappee
smart_meter_texas
smartthings
__init__.py
conftest.py
test_binary_sensor.py
test_climate.py
test_config_flow.py
test_cover.py
test_fan.py
test_init.py
test_light.py
test_lock.py
test_scene.py
test_sensor.py
test_smartapp.py
test_switch.py
smarttub
smhi
smlight
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_fleet
tesla_wall_connector
teslemetry
tessie
text
thermobeacon
thermopro
thethingsnetwork
thread
threshold
tibber
tile
tilt_ble
time
time_date
timer
tod
todo
todoist
tolo
tomato
tomorrowio
toon
totalconnect
touchline_sl
tplink
tplink_omada
traccar
traccar_server
trace
tractive
tradfri
trafikverket_camera
trafikverket_ferry
trafikverket_train
trafikverket_weatherstation
transmission
transport_nsw
trend
triggercmd
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
weheat
wemo
whirlpool
whois
wiffi
wilight
withings
wiz
wled
wmspro
wolflink
workday
worldclock
ws66i
wsdot
wyoming
xbox
xiaomi
xiaomi_aqara
xiaomi_ble
xiaomi_miio
yale
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_recorder.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
.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
308 lines
12 KiB
Python
308 lines
12 KiB
Python
"""Test for the SmartThings sensors platform.
|
|
|
|
The only mocking required is of the underlying SmartThings API object so
|
|
real HTTP calls are not initiated during testing.
|
|
"""
|
|
|
|
from pysmartthings import ATTRIBUTES, CAPABILITIES, Attribute, Capability
|
|
|
|
from homeassistant.components.sensor import (
|
|
DEVICE_CLASSES,
|
|
DOMAIN as SENSOR_DOMAIN,
|
|
STATE_CLASSES,
|
|
)
|
|
from homeassistant.components.smartthings import sensor
|
|
from homeassistant.components.smartthings.const import DOMAIN, SIGNAL_SMARTTHINGS_UPDATE
|
|
from homeassistant.config_entries import ConfigEntryState
|
|
from homeassistant.const import (
|
|
ATTR_FRIENDLY_NAME,
|
|
ATTR_UNIT_OF_MEASUREMENT,
|
|
PERCENTAGE,
|
|
STATE_UNAVAILABLE,
|
|
STATE_UNKNOWN,
|
|
EntityCategory,
|
|
)
|
|
from homeassistant.core import HomeAssistant
|
|
from homeassistant.helpers import device_registry as dr, entity_registry as er
|
|
from homeassistant.helpers.dispatcher import async_dispatcher_send
|
|
|
|
from .conftest import setup_platform
|
|
|
|
|
|
async def test_mapping_integrity() -> None:
|
|
"""Test ensures the map dicts have proper integrity."""
|
|
for capability, maps in sensor.CAPABILITY_TO_SENSORS.items():
|
|
assert capability in CAPABILITIES, capability
|
|
for sensor_map in maps:
|
|
assert sensor_map.attribute in ATTRIBUTES, sensor_map.attribute
|
|
if sensor_map.device_class:
|
|
assert (
|
|
sensor_map.device_class in DEVICE_CLASSES
|
|
), sensor_map.device_class
|
|
if sensor_map.state_class:
|
|
assert sensor_map.state_class in STATE_CLASSES, sensor_map.state_class
|
|
|
|
|
|
async def test_entity_state(hass: HomeAssistant, device_factory) -> None:
|
|
"""Tests the state attributes properly match the sensor types."""
|
|
device = device_factory("Sensor 1", [Capability.battery], {Attribute.battery: 100})
|
|
await setup_platform(hass, SENSOR_DOMAIN, devices=[device])
|
|
state = hass.states.get("sensor.sensor_1_battery")
|
|
assert state.state == "100"
|
|
assert state.attributes[ATTR_UNIT_OF_MEASUREMENT] == PERCENTAGE
|
|
assert state.attributes[ATTR_FRIENDLY_NAME] == f"{device.label} Battery"
|
|
|
|
|
|
async def test_entity_three_axis_state(hass: HomeAssistant, device_factory) -> None:
|
|
"""Tests the state attributes properly match the three axis types."""
|
|
device = device_factory(
|
|
"Three Axis", [Capability.three_axis], {Attribute.three_axis: [100, 75, 25]}
|
|
)
|
|
await setup_platform(hass, SENSOR_DOMAIN, devices=[device])
|
|
state = hass.states.get("sensor.three_axis_x_coordinate")
|
|
assert state.state == "100"
|
|
assert state.attributes[ATTR_FRIENDLY_NAME] == f"{device.label} X Coordinate"
|
|
state = hass.states.get("sensor.three_axis_y_coordinate")
|
|
assert state.state == "75"
|
|
assert state.attributes[ATTR_FRIENDLY_NAME] == f"{device.label} Y Coordinate"
|
|
state = hass.states.get("sensor.three_axis_z_coordinate")
|
|
assert state.state == "25"
|
|
assert state.attributes[ATTR_FRIENDLY_NAME] == f"{device.label} Z Coordinate"
|
|
|
|
|
|
async def test_entity_three_axis_invalid_state(
|
|
hass: HomeAssistant, device_factory
|
|
) -> None:
|
|
"""Tests the state attributes properly match the three axis types."""
|
|
device = device_factory(
|
|
"Three Axis", [Capability.three_axis], {Attribute.three_axis: []}
|
|
)
|
|
await setup_platform(hass, SENSOR_DOMAIN, devices=[device])
|
|
state = hass.states.get("sensor.three_axis_x_coordinate")
|
|
assert state.state == STATE_UNKNOWN
|
|
state = hass.states.get("sensor.three_axis_y_coordinate")
|
|
assert state.state == STATE_UNKNOWN
|
|
state = hass.states.get("sensor.three_axis_z_coordinate")
|
|
assert state.state == STATE_UNKNOWN
|
|
|
|
|
|
async def test_entity_and_device_attributes(
|
|
hass: HomeAssistant,
|
|
device_registry: dr.DeviceRegistry,
|
|
entity_registry: er.EntityRegistry,
|
|
device_factory,
|
|
) -> None:
|
|
"""Test the attributes of the entity are correct."""
|
|
# Arrange
|
|
device = device_factory(
|
|
"Sensor 1",
|
|
[Capability.battery],
|
|
{
|
|
Attribute.battery: 100,
|
|
Attribute.mnmo: "123",
|
|
Attribute.mnmn: "Generic manufacturer",
|
|
Attribute.mnhw: "v4.56",
|
|
Attribute.mnfv: "v7.89",
|
|
},
|
|
)
|
|
# Act
|
|
await setup_platform(hass, SENSOR_DOMAIN, devices=[device])
|
|
# Assert
|
|
entry = entity_registry.async_get("sensor.sensor_1_battery")
|
|
assert entry
|
|
assert entry.unique_id == f"{device.device_id}.{Attribute.battery}"
|
|
assert entry.entity_category is EntityCategory.DIAGNOSTIC
|
|
entry = device_registry.async_get_device(identifiers={(DOMAIN, device.device_id)})
|
|
assert entry
|
|
assert entry.configuration_url == "https://account.smartthings.com"
|
|
assert entry.identifiers == {(DOMAIN, device.device_id)}
|
|
assert entry.name == device.label
|
|
assert entry.model == "123"
|
|
assert entry.manufacturer == "Generic manufacturer"
|
|
assert entry.hw_version == "v4.56"
|
|
assert entry.sw_version == "v7.89"
|
|
|
|
|
|
async def test_energy_sensors_for_switch_device(
|
|
hass: HomeAssistant,
|
|
device_registry: dr.DeviceRegistry,
|
|
entity_registry: er.EntityRegistry,
|
|
device_factory,
|
|
) -> None:
|
|
"""Test the attributes of the entity are correct."""
|
|
# Arrange
|
|
device = device_factory(
|
|
"Switch_1",
|
|
[Capability.switch, Capability.power_meter, Capability.energy_meter],
|
|
{
|
|
Attribute.switch: "off",
|
|
Attribute.power: 355,
|
|
Attribute.energy: 11.422,
|
|
Attribute.mnmo: "123",
|
|
Attribute.mnmn: "Generic manufacturer",
|
|
Attribute.mnhw: "v4.56",
|
|
Attribute.mnfv: "v7.89",
|
|
},
|
|
)
|
|
# Act
|
|
await setup_platform(hass, SENSOR_DOMAIN, devices=[device])
|
|
# Assert
|
|
state = hass.states.get("sensor.switch_1_energy_meter")
|
|
assert state
|
|
assert state.state == "11.422"
|
|
entry = entity_registry.async_get("sensor.switch_1_energy_meter")
|
|
assert entry
|
|
assert entry.unique_id == f"{device.device_id}.{Attribute.energy}"
|
|
assert entry.entity_category is None
|
|
entry = device_registry.async_get_device(identifiers={(DOMAIN, device.device_id)})
|
|
assert entry
|
|
assert entry.configuration_url == "https://account.smartthings.com"
|
|
assert entry.identifiers == {(DOMAIN, device.device_id)}
|
|
assert entry.name == device.label
|
|
assert entry.model == "123"
|
|
assert entry.manufacturer == "Generic manufacturer"
|
|
assert entry.hw_version == "v4.56"
|
|
assert entry.sw_version == "v7.89"
|
|
|
|
state = hass.states.get("sensor.switch_1_power_meter")
|
|
assert state
|
|
assert state.state == "355"
|
|
entry = entity_registry.async_get("sensor.switch_1_power_meter")
|
|
assert entry
|
|
assert entry.unique_id == f"{device.device_id}.{Attribute.power}"
|
|
assert entry.entity_category is None
|
|
entry = device_registry.async_get_device(identifiers={(DOMAIN, device.device_id)})
|
|
assert entry
|
|
assert entry.configuration_url == "https://account.smartthings.com"
|
|
assert entry.identifiers == {(DOMAIN, device.device_id)}
|
|
assert entry.name == device.label
|
|
assert entry.model == "123"
|
|
assert entry.manufacturer == "Generic manufacturer"
|
|
assert entry.hw_version == "v4.56"
|
|
assert entry.sw_version == "v7.89"
|
|
|
|
|
|
async def test_power_consumption_sensor(
|
|
hass: HomeAssistant,
|
|
device_registry: dr.DeviceRegistry,
|
|
entity_registry: er.EntityRegistry,
|
|
device_factory,
|
|
) -> None:
|
|
"""Test the attributes of the entity are correct."""
|
|
# Arrange
|
|
device = device_factory(
|
|
"refrigerator",
|
|
[Capability.power_consumption_report],
|
|
{
|
|
Attribute.power_consumption: {
|
|
"energy": 1412002,
|
|
"deltaEnergy": 25,
|
|
"power": 109,
|
|
"powerEnergy": 24.304498331745464,
|
|
"persistedEnergy": 0,
|
|
"energySaved": 0,
|
|
"start": "2021-07-30T16:45:25Z",
|
|
"end": "2021-07-30T16:58:33Z",
|
|
},
|
|
Attribute.mnmo: "123",
|
|
Attribute.mnmn: "Generic manufacturer",
|
|
Attribute.mnhw: "v4.56",
|
|
Attribute.mnfv: "v7.89",
|
|
},
|
|
)
|
|
# Act
|
|
await setup_platform(hass, SENSOR_DOMAIN, devices=[device])
|
|
# Assert
|
|
state = hass.states.get("sensor.refrigerator_energy")
|
|
assert state
|
|
assert state.state == "1412.002"
|
|
entry = entity_registry.async_get("sensor.refrigerator_energy")
|
|
assert entry
|
|
assert entry.unique_id == f"{device.device_id}.energy_meter"
|
|
entry = device_registry.async_get_device(identifiers={(DOMAIN, device.device_id)})
|
|
assert entry
|
|
assert entry.configuration_url == "https://account.smartthings.com"
|
|
assert entry.identifiers == {(DOMAIN, device.device_id)}
|
|
assert entry.name == device.label
|
|
assert entry.model == "123"
|
|
assert entry.manufacturer == "Generic manufacturer"
|
|
assert entry.hw_version == "v4.56"
|
|
assert entry.sw_version == "v7.89"
|
|
|
|
state = hass.states.get("sensor.refrigerator_power")
|
|
assert state
|
|
assert state.state == "109"
|
|
assert state.attributes["power_consumption_start"] == "2021-07-30T16:45:25Z"
|
|
assert state.attributes["power_consumption_end"] == "2021-07-30T16:58:33Z"
|
|
entry = entity_registry.async_get("sensor.refrigerator_power")
|
|
assert entry
|
|
assert entry.unique_id == f"{device.device_id}.power_meter"
|
|
entry = device_registry.async_get_device(identifiers={(DOMAIN, device.device_id)})
|
|
assert entry
|
|
assert entry.configuration_url == "https://account.smartthings.com"
|
|
assert entry.identifiers == {(DOMAIN, device.device_id)}
|
|
assert entry.name == device.label
|
|
assert entry.model == "123"
|
|
assert entry.manufacturer == "Generic manufacturer"
|
|
assert entry.hw_version == "v4.56"
|
|
assert entry.sw_version == "v7.89"
|
|
|
|
device = device_factory(
|
|
"vacuum",
|
|
[Capability.power_consumption_report],
|
|
{
|
|
Attribute.power_consumption: {},
|
|
Attribute.mnmo: "123",
|
|
Attribute.mnmn: "Generic manufacturer",
|
|
Attribute.mnhw: "v4.56",
|
|
Attribute.mnfv: "v7.89",
|
|
},
|
|
)
|
|
# Act
|
|
await setup_platform(hass, SENSOR_DOMAIN, devices=[device])
|
|
# Assert
|
|
state = hass.states.get("sensor.vacuum_energy")
|
|
assert state
|
|
assert state.state == "unknown"
|
|
entry = entity_registry.async_get("sensor.vacuum_energy")
|
|
assert entry
|
|
assert entry.unique_id == f"{device.device_id}.energy_meter"
|
|
entry = device_registry.async_get_device(identifiers={(DOMAIN, device.device_id)})
|
|
assert entry
|
|
assert entry.configuration_url == "https://account.smartthings.com"
|
|
assert entry.identifiers == {(DOMAIN, device.device_id)}
|
|
assert entry.name == device.label
|
|
assert entry.model == "123"
|
|
assert entry.manufacturer == "Generic manufacturer"
|
|
assert entry.hw_version == "v4.56"
|
|
assert entry.sw_version == "v7.89"
|
|
|
|
|
|
async def test_update_from_signal(hass: HomeAssistant, device_factory) -> None:
|
|
"""Test the binary_sensor updates when receiving a signal."""
|
|
# Arrange
|
|
device = device_factory("Sensor 1", [Capability.battery], {Attribute.battery: 100})
|
|
await setup_platform(hass, SENSOR_DOMAIN, devices=[device])
|
|
device.status.apply_attribute_update(
|
|
"main", Capability.battery, Attribute.battery, 75
|
|
)
|
|
# Act
|
|
async_dispatcher_send(hass, SIGNAL_SMARTTHINGS_UPDATE, [device.device_id])
|
|
# Assert
|
|
await hass.async_block_till_done()
|
|
state = hass.states.get("sensor.sensor_1_battery")
|
|
assert state is not None
|
|
assert state.state == "75"
|
|
|
|
|
|
async def test_unload_config_entry(hass: HomeAssistant, device_factory) -> None:
|
|
"""Test the binary_sensor is removed when the config entry is unloaded."""
|
|
# Arrange
|
|
device = device_factory("Sensor 1", [Capability.battery], {Attribute.battery: 100})
|
|
config_entry = await setup_platform(hass, SENSOR_DOMAIN, devices=[device])
|
|
config_entry.mock_state(hass, ConfigEntryState.LOADED)
|
|
# Act
|
|
await hass.config_entries.async_forward_entry_unload(config_entry, "sensor")
|
|
# Assert
|
|
assert hass.states.get("sensor.sensor_1_battery").state == STATE_UNAVAILABLE
|