mirror of
https://github.com/home-assistant/core.git
synced 2025-08-11 14:29:58 +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
bluetooth
snapshots
__init__.py
conftest.py
test_alarm_control_panel.py
test_binary_sensor.py
test_bluetooth.py
test_button.py
test_camera.py
test_climate.py
test_config_flow.py
test_cover.py
test_dashboard.py
test_diagnostics.py
test_entity.py
test_entry_data.py
test_enum_mapper.py
test_fan.py
test_init.py
test_light.py
test_lock.py
test_manager.py
test_media_player.py
test_number.py
test_select.py
test_sensor.py
test_switch.py
test_text.py
test_update.py
test_voice_assistant.py
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
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
416 lines
13 KiB
Python
416 lines
13 KiB
Python
"""esphome session fixtures."""
|
|
from __future__ import annotations
|
|
|
|
import asyncio
|
|
from asyncio import Event
|
|
from collections.abc import Awaitable, Callable
|
|
from typing import Any
|
|
from unittest.mock import AsyncMock, Mock, patch
|
|
|
|
from aioesphomeapi import (
|
|
APIClient,
|
|
APIVersion,
|
|
BluetoothProxyFeature,
|
|
DeviceInfo,
|
|
EntityInfo,
|
|
EntityState,
|
|
ReconnectLogic,
|
|
UserService,
|
|
)
|
|
import pytest
|
|
from zeroconf import Zeroconf
|
|
|
|
from homeassistant.components.esphome import dashboard
|
|
from homeassistant.components.esphome.const import (
|
|
CONF_ALLOW_SERVICE_CALLS,
|
|
CONF_DEVICE_NAME,
|
|
CONF_NOISE_PSK,
|
|
DEFAULT_NEW_CONFIG_ALLOW_ALLOW_SERVICE_CALLS,
|
|
DOMAIN,
|
|
)
|
|
from homeassistant.const import CONF_HOST, CONF_PASSWORD, CONF_PORT
|
|
from homeassistant.core import HomeAssistant
|
|
from homeassistant.setup import async_setup_component
|
|
|
|
from . import DASHBOARD_HOST, DASHBOARD_PORT, DASHBOARD_SLUG
|
|
|
|
from tests.common import MockConfigEntry
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def mock_bluetooth(enable_bluetooth):
|
|
"""Auto mock bluetooth."""
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def esphome_mock_async_zeroconf(mock_async_zeroconf):
|
|
"""Auto mock zeroconf."""
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
async def load_homeassistant(hass) -> None:
|
|
"""Load the homeassistant integration."""
|
|
assert await async_setup_component(hass, "homeassistant", {})
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def mock_tts(mock_tts_cache_dir):
|
|
"""Auto mock the tts cache."""
|
|
|
|
|
|
@pytest.fixture
|
|
def mock_config_entry(hass) -> MockConfigEntry:
|
|
"""Return the default mocked config entry."""
|
|
config_entry = MockConfigEntry(
|
|
title="ESPHome Device",
|
|
entry_id="08d821dc059cf4f645cb024d32c8e708",
|
|
domain=DOMAIN,
|
|
data={
|
|
CONF_HOST: "192.168.1.2",
|
|
CONF_PORT: 6053,
|
|
CONF_PASSWORD: "pwd",
|
|
CONF_NOISE_PSK: "12345678123456781234567812345678",
|
|
CONF_DEVICE_NAME: "test",
|
|
},
|
|
# ESPHome unique ids are lower case
|
|
unique_id="11:22:33:44:55:aa",
|
|
)
|
|
config_entry.add_to_hass(hass)
|
|
return config_entry
|
|
|
|
|
|
class BaseMockReconnectLogic(ReconnectLogic):
|
|
"""Mock ReconnectLogic."""
|
|
|
|
def stop_callback(self) -> None:
|
|
"""Stop the reconnect logic."""
|
|
# For the purposes of testing, we don't want to wait
|
|
# for the reconnect logic to finish trying to connect
|
|
self._cancel_connect("forced disconnect from test")
|
|
self._is_stopped = True
|
|
|
|
|
|
@pytest.fixture
|
|
def mock_device_info() -> DeviceInfo:
|
|
"""Return the default mocked device info."""
|
|
return DeviceInfo(
|
|
uses_password=False,
|
|
name="test",
|
|
legacy_bluetooth_proxy_version=0,
|
|
# ESPHome mac addresses are UPPER case
|
|
mac_address="11:22:33:44:55:AA",
|
|
esphome_version="1.0.0",
|
|
)
|
|
|
|
|
|
@pytest.fixture
|
|
async def init_integration(
|
|
hass: HomeAssistant, mock_config_entry: MockConfigEntry
|
|
) -> MockConfigEntry:
|
|
"""Set up the ESPHome integration for testing."""
|
|
await hass.config_entries.async_setup(mock_config_entry.entry_id)
|
|
await hass.async_block_till_done()
|
|
|
|
return mock_config_entry
|
|
|
|
|
|
@pytest.fixture
|
|
def mock_client(mock_device_info) -> APIClient:
|
|
"""Mock APIClient."""
|
|
mock_client = Mock(spec=APIClient)
|
|
|
|
def mock_constructor(
|
|
address: str,
|
|
port: int,
|
|
password: str | None,
|
|
*,
|
|
client_info: str = "aioesphomeapi",
|
|
keepalive: float = 15.0,
|
|
zeroconf_instance: Zeroconf = None,
|
|
noise_psk: str | None = None,
|
|
expected_name: str | None = None,
|
|
):
|
|
"""Fake the client constructor."""
|
|
mock_client.host = address
|
|
mock_client.port = port
|
|
mock_client.password = password
|
|
mock_client.zeroconf_instance = zeroconf_instance
|
|
mock_client.noise_psk = noise_psk
|
|
return mock_client
|
|
|
|
mock_client.side_effect = mock_constructor
|
|
mock_client.device_info = AsyncMock(return_value=mock_device_info)
|
|
mock_client.connect = AsyncMock()
|
|
mock_client.disconnect = AsyncMock()
|
|
mock_client.list_entities_services = AsyncMock(return_value=([], []))
|
|
mock_client.address = "127.0.0.1"
|
|
mock_client.api_version = APIVersion(99, 99)
|
|
|
|
with patch(
|
|
"homeassistant.components.esphome.manager.ReconnectLogic",
|
|
BaseMockReconnectLogic,
|
|
), patch("homeassistant.components.esphome.APIClient", mock_client), patch(
|
|
"homeassistant.components.esphome.config_flow.APIClient", mock_client
|
|
):
|
|
yield mock_client
|
|
|
|
|
|
@pytest.fixture
|
|
async def mock_dashboard(hass):
|
|
"""Mock dashboard."""
|
|
data = {"configured": [], "importable": []}
|
|
with patch(
|
|
"esphome_dashboard_api.ESPHomeDashboardAPI.get_devices",
|
|
return_value=data,
|
|
):
|
|
await dashboard.async_set_dashboard_info(
|
|
hass, DASHBOARD_SLUG, DASHBOARD_HOST, DASHBOARD_PORT
|
|
)
|
|
yield data
|
|
|
|
|
|
class MockESPHomeDevice:
|
|
"""Mock an esphome device."""
|
|
|
|
def __init__(self, entry: MockConfigEntry) -> None:
|
|
"""Init the mock."""
|
|
self.entry = entry
|
|
self.state_callback: Callable[[EntityState], None]
|
|
self.on_disconnect: Callable[[bool], None]
|
|
self.on_connect: Callable[[bool], None]
|
|
|
|
def set_state_callback(self, state_callback: Callable[[EntityState], None]) -> None:
|
|
"""Set the state callback."""
|
|
self.state_callback = state_callback
|
|
|
|
def set_state(self, state: EntityState) -> None:
|
|
"""Mock setting state."""
|
|
self.state_callback(state)
|
|
|
|
def set_on_disconnect(self, on_disconnect: Callable[[bool], None]) -> None:
|
|
"""Set the disconnect callback."""
|
|
self.on_disconnect = on_disconnect
|
|
|
|
async def mock_disconnect(self, expected_disconnect: bool) -> None:
|
|
"""Mock disconnecting."""
|
|
await self.on_disconnect(expected_disconnect)
|
|
|
|
def set_on_connect(self, on_connect: Callable[[], None]) -> None:
|
|
"""Set the connect callback."""
|
|
self.on_connect = on_connect
|
|
|
|
async def mock_connect(self) -> None:
|
|
"""Mock connecting."""
|
|
await self.on_connect()
|
|
|
|
|
|
async def _mock_generic_device_entry(
|
|
hass: HomeAssistant,
|
|
mock_client: APIClient,
|
|
mock_device_info: dict[str, Any],
|
|
mock_list_entities_services: tuple[list[EntityInfo], list[UserService]],
|
|
states: list[EntityState],
|
|
entry: MockConfigEntry | None = None,
|
|
) -> MockESPHomeDevice:
|
|
if not entry:
|
|
entry = MockConfigEntry(
|
|
domain=DOMAIN,
|
|
data={
|
|
CONF_HOST: "test.local",
|
|
CONF_PORT: 6053,
|
|
CONF_PASSWORD: "",
|
|
},
|
|
options={
|
|
CONF_ALLOW_SERVICE_CALLS: DEFAULT_NEW_CONFIG_ALLOW_ALLOW_SERVICE_CALLS
|
|
},
|
|
)
|
|
entry.add_to_hass(hass)
|
|
|
|
mock_device = MockESPHomeDevice(entry)
|
|
|
|
default_device_info = {
|
|
"name": "test",
|
|
"friendly_name": "Test",
|
|
"esphome_version": "1.0.0",
|
|
"mac_address": "11:22:33:44:55:AA",
|
|
}
|
|
device_info = DeviceInfo(**(default_device_info | mock_device_info))
|
|
|
|
async def _subscribe_states(callback: Callable[[EntityState], None]) -> None:
|
|
"""Subscribe to state."""
|
|
mock_device.set_state_callback(callback)
|
|
for state in states:
|
|
callback(state)
|
|
|
|
mock_client.device_info = AsyncMock(return_value=device_info)
|
|
mock_client.subscribe_voice_assistant = AsyncMock(return_value=Mock())
|
|
mock_client.list_entities_services = AsyncMock(
|
|
return_value=mock_list_entities_services
|
|
)
|
|
mock_client.subscribe_states = _subscribe_states
|
|
|
|
try_connect_done = Event()
|
|
|
|
class MockReconnectLogic(BaseMockReconnectLogic):
|
|
"""Mock ReconnectLogic."""
|
|
|
|
def __init__(self, *args, **kwargs):
|
|
"""Init the mock."""
|
|
super().__init__(*args, **kwargs)
|
|
mock_device.set_on_disconnect(kwargs["on_disconnect"])
|
|
mock_device.set_on_connect(kwargs["on_connect"])
|
|
self._try_connect = self.mock_try_connect
|
|
|
|
async def mock_try_connect(self):
|
|
"""Set an event when ReconnectLogic._try_connect has been awaited."""
|
|
result = await super()._try_connect()
|
|
try_connect_done.set()
|
|
return result
|
|
|
|
def stop_callback(self) -> None:
|
|
"""Stop the reconnect logic."""
|
|
# For the purposes of testing, we don't want to wait
|
|
# for the reconnect logic to finish trying to connect
|
|
self._cancel_connect("forced disconnect from test")
|
|
self._is_stopped = True
|
|
|
|
with patch(
|
|
"homeassistant.components.esphome.manager.ReconnectLogic", MockReconnectLogic
|
|
):
|
|
assert await hass.config_entries.async_setup(entry.entry_id)
|
|
async with asyncio.timeout(2):
|
|
await try_connect_done.wait()
|
|
|
|
await hass.async_block_till_done()
|
|
return mock_device
|
|
|
|
|
|
@pytest.fixture
|
|
async def mock_voice_assistant_entry(
|
|
hass: HomeAssistant,
|
|
mock_client: APIClient,
|
|
):
|
|
"""Set up an ESPHome entry with voice assistant."""
|
|
|
|
async def _mock_voice_assistant_entry(version: int) -> MockConfigEntry:
|
|
return (
|
|
await _mock_generic_device_entry(
|
|
hass, mock_client, {"voice_assistant_version": version}, ([], []), []
|
|
)
|
|
).entry
|
|
|
|
return _mock_voice_assistant_entry
|
|
|
|
|
|
@pytest.fixture
|
|
async def mock_voice_assistant_v1_entry(mock_voice_assistant_entry) -> MockConfigEntry:
|
|
"""Set up an ESPHome entry with voice assistant."""
|
|
return await mock_voice_assistant_entry(version=1)
|
|
|
|
|
|
@pytest.fixture
|
|
async def mock_voice_assistant_v2_entry(mock_voice_assistant_entry) -> MockConfigEntry:
|
|
"""Set up an ESPHome entry with voice assistant."""
|
|
return await mock_voice_assistant_entry(version=2)
|
|
|
|
|
|
@pytest.fixture
|
|
async def mock_bluetooth_entry(
|
|
hass: HomeAssistant,
|
|
mock_client: APIClient,
|
|
):
|
|
"""Set up an ESPHome entry with bluetooth."""
|
|
|
|
async def _mock_bluetooth_entry(
|
|
bluetooth_proxy_feature_flags: BluetoothProxyFeature,
|
|
) -> MockESPHomeDevice:
|
|
return await _mock_generic_device_entry(
|
|
hass,
|
|
mock_client,
|
|
{"bluetooth_proxy_feature_flags": bluetooth_proxy_feature_flags},
|
|
([], []),
|
|
[],
|
|
)
|
|
|
|
return _mock_bluetooth_entry
|
|
|
|
|
|
@pytest.fixture
|
|
async def mock_bluetooth_entry_with_raw_adv(mock_bluetooth_entry) -> MockESPHomeDevice:
|
|
"""Set up an ESPHome entry with bluetooth and raw advertisements."""
|
|
return await mock_bluetooth_entry(
|
|
bluetooth_proxy_feature_flags=BluetoothProxyFeature.PASSIVE_SCAN
|
|
| BluetoothProxyFeature.ACTIVE_CONNECTIONS
|
|
| BluetoothProxyFeature.REMOTE_CACHING
|
|
| BluetoothProxyFeature.PAIRING
|
|
| BluetoothProxyFeature.CACHE_CLEARING
|
|
| BluetoothProxyFeature.RAW_ADVERTISEMENTS
|
|
)
|
|
|
|
|
|
@pytest.fixture
|
|
async def mock_bluetooth_entry_with_legacy_adv(
|
|
mock_bluetooth_entry,
|
|
) -> MockESPHomeDevice:
|
|
"""Set up an ESPHome entry with bluetooth with legacy advertisements."""
|
|
return await mock_bluetooth_entry(
|
|
bluetooth_proxy_feature_flags=BluetoothProxyFeature.PASSIVE_SCAN
|
|
| BluetoothProxyFeature.ACTIVE_CONNECTIONS
|
|
| BluetoothProxyFeature.REMOTE_CACHING
|
|
| BluetoothProxyFeature.PAIRING
|
|
| BluetoothProxyFeature.CACHE_CLEARING
|
|
)
|
|
|
|
|
|
@pytest.fixture
|
|
async def mock_generic_device_entry(
|
|
hass: HomeAssistant,
|
|
) -> Callable[
|
|
[APIClient, list[EntityInfo], list[UserService], list[EntityState]],
|
|
Awaitable[MockConfigEntry],
|
|
]:
|
|
"""Set up an ESPHome entry and return the MockConfigEntry."""
|
|
|
|
async def _mock_device_entry(
|
|
mock_client: APIClient,
|
|
entity_info: list[EntityInfo],
|
|
user_service: list[UserService],
|
|
states: list[EntityState],
|
|
) -> MockConfigEntry:
|
|
return (
|
|
await _mock_generic_device_entry(
|
|
hass, mock_client, {}, (entity_info, user_service), states
|
|
)
|
|
).entry
|
|
|
|
return _mock_device_entry
|
|
|
|
|
|
@pytest.fixture
|
|
async def mock_esphome_device(
|
|
hass: HomeAssistant,
|
|
) -> Callable[
|
|
[APIClient, list[EntityInfo], list[UserService], list[EntityState]],
|
|
Awaitable[MockESPHomeDevice],
|
|
]:
|
|
"""Set up an ESPHome entry and return the MockESPHomeDevice."""
|
|
|
|
async def _mock_device(
|
|
mock_client: APIClient,
|
|
entity_info: list[EntityInfo],
|
|
user_service: list[UserService],
|
|
states: list[EntityState],
|
|
entry: MockConfigEntry | None = None,
|
|
device_info: dict[str, Any] | None = None,
|
|
) -> MockESPHomeDevice:
|
|
return await _mock_generic_device_entry(
|
|
hass,
|
|
mock_client,
|
|
device_info or {},
|
|
(entity_info, user_service),
|
|
states,
|
|
entry,
|
|
)
|
|
|
|
return _mock_device
|