diff --git a/homeassistant/components/unifiprotect/config_flow.py b/homeassistant/components/unifiprotect/config_flow.py index 0890a962e5b..39e255bb715 100644 --- a/homeassistant/components/unifiprotect/config_flow.py +++ b/homeassistant/components/unifiprotect/config_flow.py @@ -24,6 +24,7 @@ from homeassistant.data_entry_flow import FlowResult from homeassistant.helpers.aiohttp_client import async_create_clientsession from homeassistant.helpers.typing import DiscoveryInfoType from homeassistant.loader import async_get_integration +from homeassistant.util.network import is_ip_address from .const import ( CONF_ALL_UPDATES, @@ -105,7 +106,11 @@ class ProtectFlowHandler(config_entries.ConfigFlow, domain=DOMAIN): and entry_host != direct_connect_domain ): new_host = direct_connect_domain - elif not entry_has_direct_connect and entry_host != source_ip: + elif ( + not entry_has_direct_connect + and is_ip_address(entry_host) + and entry_host != source_ip + ): new_host = source_ip if new_host: self.hass.config_entries.async_update_entry( diff --git a/tests/components/unifiprotect/test_config_flow.py b/tests/components/unifiprotect/test_config_flow.py index a1609984be3..68d90ff82eb 100644 --- a/tests/components/unifiprotect/test_config_flow.py +++ b/tests/components/unifiprotect/test_config_flow.py @@ -418,6 +418,37 @@ async def test_discovered_by_unifi_discovery_direct_connect_updated_but_not_usin assert mock_config.data[CONF_HOST] == "127.0.0.1" +async def test_discovered_host_not_updated_if_existing_is_a_hostname( + hass: HomeAssistant, mock_nvr: NVR +) -> None: + """Test we only update the host if its an ip address from discovery.""" + mock_config = MockConfigEntry( + domain=DOMAIN, + data={ + "host": "a.hostname", + "username": "test-username", + "password": "test-password", + "id": "UnifiProtect", + "port": 443, + "verify_ssl": True, + }, + unique_id=DEVICE_MAC_ADDRESS.upper().replace(":", ""), + ) + mock_config.add_to_hass(hass) + + with _patch_discovery(): + result = await hass.config_entries.flow.async_init( + DOMAIN, + context={"source": config_entries.SOURCE_DISCOVERY}, + data=UNIFI_DISCOVERY_DICT, + ) + await hass.async_block_till_done() + + assert result["type"] == RESULT_TYPE_ABORT + assert result["reason"] == "already_configured" + assert mock_config.data[CONF_HOST] == "a.hostname" + + async def test_discovered_by_unifi_discovery( hass: HomeAssistant, mock_nvr: NVR ) -> None: