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
airtouch5
airvisual
airvisual_pro
airzone
airzone_cloud
aladdin_connect
alarm_control_panel
alarmdecoder
alert
alexa
amberelectric
ambiclimate
ambient_network
ambient_station
analytics
analytics_insights
android_ip_webcam
androidtv
androidtv_remote
anova
anthemav
aosmith
apache_kafka
apcupsd
api
api_streams
apple_tv
application_credentials
apprise
aprilaire
aprs
aranet
arcam_fmj
arve
aseko_pool_live
assist_pipeline
asterisk_mbox
asuswrt
atag
august
aurora
aurora_abb_powerone
aussie_broadband
auth
automation
awair
aws
axis
azure_devops
azure_event_hub
backup
baf
balboa
bang_olufsen
bayesian
binary_sensor
blackbird
blebox
blink
blue_current
bluemaestro
blueprint
bluetooth
bluetooth_adapters
bluetooth_le_tracker
bmw_connected_drive
bond
bosch_shc
braviatv
bring
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
downloader
dremel_3d_printer
drop_connect
dsmr
dsmr_reader
dte_energy_bridge
duckdns
dunehd
duotecno
dwd_weather_warnings
dynalite
eafm
easyenergy
ecobee
ecoforest
econet
ecovacs
ecowitt
edl21
efergy
eight_sleep
electrasmart
electric_kiwi
elgato
elkm1
elmax
elvia
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
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
fully_kiosk
fyta
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
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
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
isal
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
lamarzocco
lametric
landisgyr_heat_meter
lastfm
launch_library
laundrify
lawn_mower
lcn
ld2410_ble
leaone
led_ble
lg_netcast
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
lupusec
lutron
lutron_caseta
lyric
mailbox
mailgun
manual
manual_mqtt
map
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
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
monoprice
moon
mopeka
motion_blinds
motionblinds_ble
motioneye
motionmount
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
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
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
romy
roomba
roon
rova
rpi_power
rss_feed_template
rtsp_to_webrtc
ruckus_unleashed
ruuvi_gateway
ruuvitag_ble
rympro
sabnzbd
samsungtv
sanix
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
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_wall_connector
teslemetry
tessie
text
thermobeacon
thermopro
thread
threshold
tibber
tile
tilt_ble
time
time_date
timer
tod
todo
todoist
tolo
tomato
tomorrowio
toon
__init__.py
test_config_flow.py
totalconnect
tplink
tplink_omada
traccar
traccar_server
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
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
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
non_packaged_scripts
pylint
resources
script
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_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
.coveragerc
.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
358 lines
12 KiB
Python
358 lines
12 KiB
Python
"""Tests for the Toon config flow."""
|
|
|
|
from http import HTTPStatus
|
|
from unittest.mock import patch
|
|
|
|
from toonapi import Agreement, ToonError
|
|
|
|
from homeassistant.components.toon.const import CONF_AGREEMENT, CONF_MIGRATE, DOMAIN
|
|
from homeassistant.config import async_process_ha_core_config
|
|
from homeassistant.config_entries import SOURCE_IMPORT, SOURCE_USER
|
|
from homeassistant.const import CONF_CLIENT_ID, CONF_CLIENT_SECRET
|
|
from homeassistant.core import HomeAssistant
|
|
from homeassistant.data_entry_flow import FlowResultType
|
|
from homeassistant.helpers import config_entry_oauth2_flow
|
|
from homeassistant.setup import async_setup_component
|
|
|
|
from tests.common import MockConfigEntry
|
|
from tests.test_util.aiohttp import AiohttpClientMocker
|
|
from tests.typing import ClientSessionGenerator
|
|
|
|
|
|
async def setup_component(hass):
|
|
"""Set up Toon component."""
|
|
await async_process_ha_core_config(
|
|
hass,
|
|
{"external_url": "https://example.com"},
|
|
)
|
|
|
|
with patch("os.path.isfile", return_value=False):
|
|
assert await async_setup_component(
|
|
hass,
|
|
DOMAIN,
|
|
{DOMAIN: {CONF_CLIENT_ID: "client", CONF_CLIENT_SECRET: "secret"}},
|
|
)
|
|
await hass.async_block_till_done()
|
|
|
|
|
|
async def test_abort_if_no_configuration(hass: HomeAssistant) -> None:
|
|
"""Test abort if no app is configured."""
|
|
result = await hass.config_entries.flow.async_init(
|
|
DOMAIN, context={"source": SOURCE_USER}
|
|
)
|
|
|
|
assert result["type"] is FlowResultType.ABORT
|
|
assert result["reason"] == "missing_configuration"
|
|
|
|
|
|
async def test_full_flow_implementation(
|
|
hass: HomeAssistant,
|
|
hass_client_no_auth: ClientSessionGenerator,
|
|
aioclient_mock: AiohttpClientMocker,
|
|
current_request_with_host: None,
|
|
) -> None:
|
|
"""Test registering an integration and finishing flow works."""
|
|
await setup_component(hass)
|
|
|
|
result = await hass.config_entries.flow.async_init(
|
|
DOMAIN, context={"source": SOURCE_USER}
|
|
)
|
|
|
|
assert result["type"] is FlowResultType.FORM
|
|
assert result["step_id"] == "pick_implementation"
|
|
|
|
state = config_entry_oauth2_flow._encode_jwt(
|
|
hass,
|
|
{
|
|
"flow_id": result["flow_id"],
|
|
"redirect_uri": "https://example.com/auth/external/callback",
|
|
},
|
|
)
|
|
|
|
result2 = await hass.config_entries.flow.async_configure(
|
|
result["flow_id"], {"implementation": "eneco"}
|
|
)
|
|
|
|
assert result2["type"] is FlowResultType.EXTERNAL_STEP
|
|
assert result2["url"] == (
|
|
"https://api.toon.eu/authorize"
|
|
"?response_type=code&client_id=client"
|
|
"&redirect_uri=https://example.com/auth/external/callback"
|
|
f"&state={state}"
|
|
"&tenant_id=eneco&issuer=identity.toon.eu"
|
|
)
|
|
|
|
client = await hass_client_no_auth()
|
|
resp = await client.get(f"/auth/external/callback?code=abcd&state={state}")
|
|
assert resp.status == HTTPStatus.OK
|
|
assert resp.headers["content-type"] == "text/html; charset=utf-8"
|
|
|
|
aioclient_mock.post(
|
|
"https://api.toon.eu/token",
|
|
json={
|
|
"refresh_token": "mock-refresh-token",
|
|
"access_token": "mock-access-token",
|
|
"type": "Bearer",
|
|
"expires_in": 60,
|
|
},
|
|
)
|
|
|
|
with patch("toonapi.Toon.agreements", return_value=[Agreement(agreement_id=123)]):
|
|
result3 = await hass.config_entries.flow.async_configure(result["flow_id"])
|
|
|
|
assert result3["data"]["auth_implementation"] == "eneco"
|
|
assert result3["data"]["agreement_id"] == 123
|
|
result3["data"]["token"].pop("expires_at")
|
|
assert result3["data"]["token"] == {
|
|
"refresh_token": "mock-refresh-token",
|
|
"access_token": "mock-access-token",
|
|
"type": "Bearer",
|
|
"expires_in": 60,
|
|
}
|
|
|
|
|
|
async def test_no_agreements(
|
|
hass: HomeAssistant,
|
|
hass_client_no_auth: ClientSessionGenerator,
|
|
aioclient_mock: AiohttpClientMocker,
|
|
current_request_with_host: None,
|
|
) -> None:
|
|
"""Test abort when there are no displays."""
|
|
await setup_component(hass)
|
|
result = await hass.config_entries.flow.async_init(
|
|
DOMAIN, context={"source": SOURCE_USER}
|
|
)
|
|
|
|
state = config_entry_oauth2_flow._encode_jwt(
|
|
hass,
|
|
{
|
|
"flow_id": result["flow_id"],
|
|
"redirect_uri": "https://example.com/auth/external/callback",
|
|
},
|
|
)
|
|
await hass.config_entries.flow.async_configure(
|
|
result["flow_id"], {"implementation": "eneco"}
|
|
)
|
|
|
|
client = await hass_client_no_auth()
|
|
await client.get(f"/auth/external/callback?code=abcd&state={state}")
|
|
aioclient_mock.post(
|
|
"https://api.toon.eu/token",
|
|
json={
|
|
"refresh_token": "mock-refresh-token",
|
|
"access_token": "mock-access-token",
|
|
"type": "Bearer",
|
|
"expires_in": 60,
|
|
},
|
|
)
|
|
|
|
with patch("toonapi.Toon.agreements", return_value=[]):
|
|
result3 = await hass.config_entries.flow.async_configure(result["flow_id"])
|
|
|
|
assert result3["type"] is FlowResultType.ABORT
|
|
assert result3["reason"] == "no_agreements"
|
|
|
|
|
|
async def test_multiple_agreements(
|
|
hass: HomeAssistant,
|
|
hass_client_no_auth: ClientSessionGenerator,
|
|
aioclient_mock: AiohttpClientMocker,
|
|
current_request_with_host: None,
|
|
) -> None:
|
|
"""Test abort when there are no displays."""
|
|
await setup_component(hass)
|
|
result = await hass.config_entries.flow.async_init(
|
|
DOMAIN, context={"source": SOURCE_USER}
|
|
)
|
|
|
|
state = config_entry_oauth2_flow._encode_jwt(
|
|
hass,
|
|
{
|
|
"flow_id": result["flow_id"],
|
|
"redirect_uri": "https://example.com/auth/external/callback",
|
|
},
|
|
)
|
|
await hass.config_entries.flow.async_configure(
|
|
result["flow_id"], {"implementation": "eneco"}
|
|
)
|
|
|
|
client = await hass_client_no_auth()
|
|
await client.get(f"/auth/external/callback?code=abcd&state={state}")
|
|
|
|
aioclient_mock.post(
|
|
"https://api.toon.eu/token",
|
|
json={
|
|
"refresh_token": "mock-refresh-token",
|
|
"access_token": "mock-access-token",
|
|
"type": "Bearer",
|
|
"expires_in": 60,
|
|
},
|
|
)
|
|
|
|
with patch(
|
|
"toonapi.Toon.agreements",
|
|
return_value=[Agreement(agreement_id=1), Agreement(agreement_id=2)],
|
|
):
|
|
result3 = await hass.config_entries.flow.async_configure(result["flow_id"])
|
|
|
|
assert result3["type"] is FlowResultType.FORM
|
|
assert result3["step_id"] == "agreement"
|
|
|
|
result4 = await hass.config_entries.flow.async_configure(
|
|
result["flow_id"], {CONF_AGREEMENT: "None None, None"}
|
|
)
|
|
assert result4["data"]["auth_implementation"] == "eneco"
|
|
assert result4["data"]["agreement_id"] == 1
|
|
|
|
|
|
async def test_agreement_already_set_up(
|
|
hass: HomeAssistant,
|
|
hass_client_no_auth: ClientSessionGenerator,
|
|
aioclient_mock: AiohttpClientMocker,
|
|
current_request_with_host: None,
|
|
) -> None:
|
|
"""Test showing display form again if display already exists."""
|
|
await setup_component(hass)
|
|
MockConfigEntry(domain=DOMAIN, unique_id=123).add_to_hass(hass)
|
|
result = await hass.config_entries.flow.async_init(
|
|
DOMAIN, context={"source": SOURCE_USER}
|
|
)
|
|
|
|
state = config_entry_oauth2_flow._encode_jwt(
|
|
hass,
|
|
{
|
|
"flow_id": result["flow_id"],
|
|
"redirect_uri": "https://example.com/auth/external/callback",
|
|
},
|
|
)
|
|
await hass.config_entries.flow.async_configure(
|
|
result["flow_id"], {"implementation": "eneco"}
|
|
)
|
|
|
|
client = await hass_client_no_auth()
|
|
await client.get(f"/auth/external/callback?code=abcd&state={state}")
|
|
aioclient_mock.post(
|
|
"https://api.toon.eu/token",
|
|
json={
|
|
"refresh_token": "mock-refresh-token",
|
|
"access_token": "mock-access-token",
|
|
"type": "Bearer",
|
|
"expires_in": 60,
|
|
},
|
|
)
|
|
|
|
with patch("toonapi.Toon.agreements", return_value=[Agreement(agreement_id=123)]):
|
|
result3 = await hass.config_entries.flow.async_configure(result["flow_id"])
|
|
|
|
assert result3["type"] is FlowResultType.ABORT
|
|
assert result3["reason"] == "already_configured"
|
|
|
|
|
|
async def test_toon_abort(
|
|
hass: HomeAssistant,
|
|
hass_client_no_auth: ClientSessionGenerator,
|
|
aioclient_mock: AiohttpClientMocker,
|
|
current_request_with_host: None,
|
|
) -> None:
|
|
"""Test we abort on Toon error."""
|
|
await setup_component(hass)
|
|
result = await hass.config_entries.flow.async_init(
|
|
DOMAIN, context={"source": SOURCE_USER}
|
|
)
|
|
|
|
state = config_entry_oauth2_flow._encode_jwt(
|
|
hass,
|
|
{
|
|
"flow_id": result["flow_id"],
|
|
"redirect_uri": "https://example.com/auth/external/callback",
|
|
},
|
|
)
|
|
await hass.config_entries.flow.async_configure(
|
|
result["flow_id"], {"implementation": "eneco"}
|
|
)
|
|
|
|
client = await hass_client_no_auth()
|
|
await client.get(f"/auth/external/callback?code=abcd&state={state}")
|
|
aioclient_mock.post(
|
|
"https://api.toon.eu/token",
|
|
json={
|
|
"refresh_token": "mock-refresh-token",
|
|
"access_token": "mock-access-token",
|
|
"type": "Bearer",
|
|
"expires_in": 60,
|
|
},
|
|
)
|
|
|
|
with patch("toonapi.Toon.agreements", side_effect=ToonError):
|
|
result2 = await hass.config_entries.flow.async_configure(result["flow_id"])
|
|
|
|
assert result2["type"] is FlowResultType.ABORT
|
|
assert result2["reason"] == "connection_error"
|
|
|
|
|
|
async def test_import(hass: HomeAssistant, current_request_with_host: None) -> None:
|
|
"""Test if importing step works."""
|
|
await setup_component(hass)
|
|
|
|
# Setting up the component without entries, should already have triggered
|
|
# it. Hence, expect this to throw an already_in_progress.
|
|
result = await hass.config_entries.flow.async_init(
|
|
DOMAIN, context={"source": SOURCE_IMPORT}
|
|
)
|
|
|
|
assert result["type"] is FlowResultType.ABORT
|
|
assert result["reason"] == "already_in_progress"
|
|
|
|
|
|
async def test_import_migration(
|
|
hass: HomeAssistant,
|
|
hass_client_no_auth: ClientSessionGenerator,
|
|
aioclient_mock: AiohttpClientMocker,
|
|
current_request_with_host: None,
|
|
) -> None:
|
|
"""Test if importing step with migration works."""
|
|
old_entry = MockConfigEntry(domain=DOMAIN, unique_id=123, version=1)
|
|
old_entry.add_to_hass(hass)
|
|
|
|
await setup_component(hass)
|
|
|
|
entries = hass.config_entries.async_entries(DOMAIN)
|
|
assert len(entries) == 1
|
|
assert entries[0].version == 1
|
|
|
|
flows = hass.config_entries.flow.async_progress()
|
|
assert len(flows) == 1
|
|
assert flows[0]["context"][CONF_MIGRATE] == old_entry.entry_id
|
|
|
|
state = config_entry_oauth2_flow._encode_jwt(
|
|
hass,
|
|
{
|
|
"flow_id": flows[0]["flow_id"],
|
|
"redirect_uri": "https://example.com/auth/external/callback",
|
|
},
|
|
)
|
|
await hass.config_entries.flow.async_configure(
|
|
flows[0]["flow_id"], {"implementation": "eneco"}
|
|
)
|
|
|
|
client = await hass_client_no_auth()
|
|
await client.get(f"/auth/external/callback?code=abcd&state={state}")
|
|
aioclient_mock.post(
|
|
"https://api.toon.eu/token",
|
|
json={
|
|
"refresh_token": "mock-refresh-token",
|
|
"access_token": "mock-access-token",
|
|
"type": "Bearer",
|
|
"expires_in": 60,
|
|
},
|
|
)
|
|
|
|
with patch("toonapi.Toon.agreements", return_value=[Agreement(agreement_id=123)]):
|
|
result = await hass.config_entries.flow.async_configure(flows[0]["flow_id"])
|
|
|
|
assert result["type"] is FlowResultType.CREATE_ENTRY
|
|
|
|
entries = hass.config_entries.async_entries(DOMAIN)
|
|
assert len(entries) == 1
|
|
assert entries[0].version == 2
|