Retry bond setup when zeroconf discovery happens (#72687)

This commit is contained in:
J. Nick Koston 2022-05-30 06:41:07 -10:00 committed by GitHub
parent f06ceef43d
commit 3399be2dad
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 50 additions and 11 deletions

View File

@ -1,6 +1,7 @@
"""Config flow for Bond integration.""" """Config flow for Bond integration."""
from __future__ import annotations from __future__ import annotations
import contextlib
from http import HTTPStatus from http import HTTPStatus
import logging import logging
from typing import Any from typing import Any
@ -33,10 +34,9 @@ TOKEN_SCHEMA = vol.Schema({})
async def async_get_token(hass: HomeAssistant, host: str) -> str | None: async def async_get_token(hass: HomeAssistant, host: str) -> str | None:
"""Try to fetch the token from the bond device.""" """Try to fetch the token from the bond device."""
bond = Bond(host, "", session=async_get_clientsession(hass)) bond = Bond(host, "", session=async_get_clientsession(hass))
try: response: dict[str, str] = {}
response: dict[str, str] = await bond.token() with contextlib.suppress(ClientConnectionError):
except ClientConnectionError: response = await bond.token()
return None
return response.get("token") return response.get("token")
@ -101,6 +101,7 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
host: str = discovery_info.host host: str = discovery_info.host
bond_id = name.partition(".")[0] bond_id = name.partition(".")[0]
await self.async_set_unique_id(bond_id) await self.async_set_unique_id(bond_id)
hass = self.hass
for entry in self._async_current_entries(): for entry in self._async_current_entries():
if entry.unique_id != bond_id: if entry.unique_id != bond_id:
continue continue
@ -110,13 +111,12 @@ class ConfigFlow(config_entries.ConfigFlow, domain=DOMAIN):
): ):
updates[CONF_ACCESS_TOKEN] = token updates[CONF_ACCESS_TOKEN] = token
new_data = {**entry.data, **updates} new_data = {**entry.data, **updates}
if new_data != dict(entry.data): changed = new_data != dict(entry.data)
self.hass.config_entries.async_update_entry( if changed:
entry, data={**entry.data, **updates} hass.config_entries.async_update_entry(entry, data=new_data)
) if changed or entry.state is ConfigEntryState.SETUP_RETRY:
self.hass.async_create_task( entry_id = entry.entry_id
self.hass.config_entries.async_reload(entry.entry_id) hass.async_create_task(hass.config_entries.async_reload(entry_id))
)
raise AbortFlow("already_configured") raise AbortFlow("already_configured")
self._discovered = {CONF_HOST: host, CONF_NAME: bond_id} self._discovered = {CONF_HOST: host, CONF_NAME: bond_id}

View File

@ -381,6 +381,45 @@ async def test_zeroconf_already_configured(hass: core.HomeAssistant):
assert len(mock_setup_entry.mock_calls) == 1 assert len(mock_setup_entry.mock_calls) == 1
async def test_zeroconf_in_setup_retry_state(hass: core.HomeAssistant):
"""Test we retry right away on zeroconf discovery."""
entry = MockConfigEntry(
domain=DOMAIN,
unique_id="already-registered-bond-id",
data={CONF_HOST: "stored-host", CONF_ACCESS_TOKEN: "test-token"},
)
entry.add_to_hass(hass)
with patch_bond_version(side_effect=OSError):
await hass.config_entries.async_setup(entry.entry_id)
await hass.async_block_till_done()
assert entry.state is ConfigEntryState.SETUP_RETRY
with _patch_async_setup_entry() as mock_setup_entry:
result = await hass.config_entries.flow.async_init(
DOMAIN,
context={"source": config_entries.SOURCE_ZEROCONF},
data=zeroconf.ZeroconfServiceInfo(
host="updated-host",
addresses=["updated-host"],
hostname="mock_hostname",
name="already-registered-bond-id.some-other-tail-info",
port=None,
properties={},
type="mock_type",
),
)
await hass.async_block_till_done()
assert result["type"] == "abort"
assert result["reason"] == "already_configured"
assert entry.data["host"] == "updated-host"
assert len(mock_setup_entry.mock_calls) == 1
assert entry.state is ConfigEntryState.LOADED
async def test_zeroconf_already_configured_refresh_token(hass: core.HomeAssistant): async def test_zeroconf_already_configured_refresh_token(hass: core.HomeAssistant):
"""Test starting a flow from zeroconf when already configured and the token is out of date.""" """Test starting a flow from zeroconf when already configured and the token is out of date."""
entry2 = MockConfigEntry( entry2 = MockConfigEntry(