Add reconfigure flow to Philips TV (#189093)

Co-authored-by: Claude <noreply@anthropic.com>
This commit is contained in:
Joost Lekkerkerker
2026-11-19 14:25:56 +01:00
committed by GitHub
co-authored by Claude
parent 07b2e29faf
commit 72f42541ae
4 changed files with 271 additions and 18 deletions
@@ -13,7 +13,12 @@ from haphilipsjs import (
)
import probatio
from homeassistant.config_entries import SOURCE_REAUTH, ConfigFlow, ConfigFlowResult
from homeassistant.config_entries import (
SOURCE_REAUTH,
SOURCE_RECONFIGURE,
ConfigFlow,
ConfigFlowResult,
)
from homeassistant.const import (
CONF_API_VERSION,
CONF_HOST,
@@ -89,11 +94,25 @@ class PhilipsJSConfigFlow(ConfigFlow, domain=DOMAIN):
if serialnumber := hub.system.get("serialnumber"):
await self.async_set_unique_id(serialnumber)
if self.source != SOURCE_REAUTH:
if self.source not in (SOURCE_REAUTH, SOURCE_RECONFIGURE):
self._abort_if_unique_id_configured(
updates=self._current, reload_on_update=True
)
async def _async_prepare_user_input(
self, user_input: dict[str, Any]
) -> dict[str, str]:
"""Connect to the TV from the user input and return any errors."""
self._current = user_input
try:
await self._async_attempt_prepare(
user_input[CONF_HOST], int(user_input[CONF_API_VERSION]), False
)
except GeneralFailure as exc:
LOGGER.error(exc)
return {"base": "cannot_connect"}
return {}
async def _async_attempt_add(self) -> ConfigFlowResult:
assert self._hub
if self._hub.pairing_type == "digest_auth_pairing":
@@ -101,12 +120,22 @@ class PhilipsJSConfigFlow(ConfigFlow, domain=DOMAIN):
return await self._async_create_current()
async def _async_create_current(self) -> ConfigFlowResult:
system = self._current[CONF_SYSTEM]
if self.source == SOURCE_RECONFIGURE:
reconfigure_entry = self._get_reconfigure_entry()
# A loaded entry is reloaded by its update listener
if reconfigure_entry.update_listeners:
return self.async_update_and_abort(
reconfigure_entry, data_updates=self._current
)
return self.async_update_reload_and_abort(
reconfigure_entry, data_updates=self._current
)
if self.source == SOURCE_REAUTH:
return self.async_update_reload_and_abort(
self._get_reauth_entry(), data_updates=self._current
)
system = self._current[CONF_SYSTEM]
return self.async_create_entry(
title=f"{system['name']} ({system['serialnumber']})",
data=self._current,
@@ -173,6 +202,32 @@ class PhilipsJSConfigFlow(ConfigFlow, domain=DOMAIN):
self._current[CONF_API_VERSION] = entry_data[CONF_API_VERSION]
return await self.async_step_user()
async def async_step_reconfigure(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle reconfiguration of the host and API version."""
reconfigure_entry = self._get_reconfigure_entry()
errors: dict[str, str] = {}
if user_input and not (
errors := await self._async_prepare_user_input(user_input)
):
self._abort_if_unique_id_mismatch()
if CONF_USERNAME in reconfigure_entry.data:
return await self._async_create_current()
return await self._async_attempt_add()
schema = self.add_suggested_values_to_schema(
USER_SCHEMA,
user_input
or {
CONF_HOST: reconfigure_entry.data[CONF_HOST],
CONF_API_VERSION: str(reconfigure_entry.data[CONF_API_VERSION]),
},
)
return self.async_show_form(
step_id="reconfigure", data_schema=schema, errors=errors
)
@override
async def async_step_zeroconf(
self, discovery_info: ZeroconfServiceInfo
@@ -218,18 +273,11 @@ class PhilipsJSConfigFlow(ConfigFlow, domain=DOMAIN):
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle the initial step."""
errors = {}
if user_input:
self._current = user_input
try:
await self._async_attempt_prepare(
user_input[CONF_HOST], int(user_input[CONF_API_VERSION]), False
)
except GeneralFailure as exc:
LOGGER.error(exc)
errors["base"] = "cannot_connect"
else:
return await self._async_attempt_add()
errors: dict[str, str] = {}
if user_input and not (
errors := await self._async_prepare_user_input(user_input)
):
return await self._async_attempt_add()
schema = self.add_suggested_values_to_schema(USER_SCHEMA, self._current)
return self.async_show_form(step_id="user", data_schema=schema, errors=errors)
@@ -2,7 +2,8 @@
"config": {
"abort": {
"already_configured": "[%key:common::config_flow::abort::already_configured_device%]",
"pairing_failure": "Unable to pair: {error_id}"
"pairing_failure": "Unable to pair: {error_id}",
"unique_id_mismatch": "The host you entered belongs to a different Philips TV."
},
"error": {
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]",
@@ -18,6 +19,12 @@
"description": "Enter the PIN displayed on your TV",
"title": "Pair"
},
"reconfigure": {
"data": {
"api_version": "[%key:component::philips_js::config::step::user::data::api_version%]",
"host": "[%key:common::config_flow::data::host%]"
}
},
"user": {
"data": {
"api_version": "API Version",
+164 -2
View File
@@ -1,14 +1,21 @@
"""Test the Philips TV config flow."""
from ipaddress import ip_address
from unittest.mock import ANY, MagicMock
from typing import Any
from unittest.mock import ANY, AsyncMock, MagicMock
from haphilipsjs import PairingFailure
from haphilipsjs import ConnectionFailure, PairingFailure
import pytest
from pytest_homeassistant.common import MockConfigEntry
from homeassistant import config_entries
from homeassistant.components.philips_js.const import CONF_ALLOW_NOTIFY, DOMAIN
from homeassistant.const import (
CONF_API_VERSION,
CONF_HOST,
CONF_PASSWORD,
CONF_USERNAME,
)
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from homeassistant.helpers.service_info.zeroconf import ZeroconfServiceInfo
@@ -324,3 +331,158 @@ async def test_zeroconf_probe_failed(
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "discovery_failure"
@pytest.mark.parametrize(
"credentials",
[
pytest.param({}, id="unpaired"),
pytest.param(
{CONF_USERNAME: MOCK_USERNAME, CONF_PASSWORD: MOCK_PASSWORD}, id="paired"
),
],
)
async def test_reconfigure(
hass: HomeAssistant,
mock_setup_entry: AsyncMock,
credentials: dict[str, str],
) -> None:
"""Test reconfiguring the host keeps the pairing credentials."""
config_entry = MockConfigEntry(
domain=DOMAIN,
data=MOCK_CONFIG | credentials,
title=MOCK_NAME,
unique_id=MOCK_SERIAL_NO,
)
config_entry.add_to_hass(hass)
result = await config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
assert result["errors"] == {}
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: "2.2.2.2", CONF_API_VERSION: "1"}
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
assert config_entry.data == MOCK_CONFIG | credentials | {CONF_HOST: "2.2.2.2"}
assert len(mock_setup_entry.mock_calls) == 1
@pytest.mark.parametrize(
("system", "get_system_side_effect"),
[
pytest.param(None, None, id="empty_system"),
pytest.param(MOCK_SYSTEM, ConnectionFailure("Timeout"), id="connection"),
],
)
async def test_reconfigure_cannot_connect(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
mock_tv: MagicMock,
system: dict[str, Any] | None,
get_system_side_effect: Exception | None,
) -> None:
"""Test reconfiguring shows an error when the TV can't be reached and recovers."""
result = await mock_config_entry.start_reconfigure_flow(hass)
mock_tv.system = system
mock_tv.getSystem.side_effect = get_system_side_effect
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: "2.2.2.2", CONF_API_VERSION: "1"}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
assert result["errors"] == {"base": "cannot_connect"}
mock_tv.system = MOCK_SYSTEM
mock_tv.getSystem.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: "2.2.2.2", CONF_API_VERSION: "1"}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
assert mock_config_entry.data[CONF_HOST] == "2.2.2.2"
async def test_reconfigure_unique_id_mismatch(
hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_tv: MagicMock
) -> None:
"""Test reconfiguring to a different TV aborts."""
result = await mock_config_entry.start_reconfigure_flow(hass)
mock_tv.system = MOCK_SYSTEM | {"serialnumber": "other_serial"}
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: "2.2.2.2", CONF_API_VERSION: "1"}
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "unique_id_mismatch"
assert mock_config_entry.data == MOCK_CONFIG
async def test_reconfigure_pairing(
hass: HomeAssistant,
mock_tv_pairable: MagicMock,
mock_setup_entry: AsyncMock,
) -> None:
"""Test reconfiguring an unpaired entry to a TV that requires pairing."""
config_entry = MockConfigEntry(
domain=DOMAIN,
data=MOCK_CONFIG,
title=MOCK_NAME,
unique_id=MOCK_SYSTEM_UNPAIRED["serialnumber"],
)
config_entry.add_to_hass(hass)
result = await config_entry.start_reconfigure_flow(hass)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: "2.2.2.2", CONF_API_VERSION: "6"}
)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "pair"
mock_tv_pairable.pairRequest.assert_called()
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {"pin": "1234"}
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
assert config_entry.data == MOCK_CONFIG_PAIRED | {CONF_HOST: "2.2.2.2"}
assert len(hass.config_entries.async_entries(DOMAIN)) == 1
async def test_reconfigure_paired_skips_pairing(
hass: HomeAssistant,
mock_tv_pairable: MagicMock,
mock_setup_entry: AsyncMock,
) -> None:
"""Test reconfiguring a paired entry keeps its credentials without pairing."""
config_entry = MockConfigEntry(
domain=DOMAIN,
data=MOCK_CONFIG_PAIRED,
title=MOCK_NAME,
unique_id=MOCK_SYSTEM_UNPAIRED["serialnumber"],
)
config_entry.add_to_hass(hass)
result = await config_entry.start_reconfigure_flow(hass)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: "2.2.2.2", CONF_API_VERSION: "6"}
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
assert config_entry.data == MOCK_CONFIG_PAIRED | {CONF_HOST: "2.2.2.2"}
mock_tv_pairable.pairRequest.assert_not_called()
+36
View File
@@ -0,0 +1,36 @@
"""Test the Philips TV integration setup."""
from unittest.mock import patch
from pytest_homeassistant.common import MockConfigEntry
from homeassistant.components.philips_js import async_setup_entry
from homeassistant.config_entries import ConfigEntryState
from homeassistant.const import CONF_API_VERSION, CONF_HOST
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
async def test_reconfigure_loaded_entry(
hass: HomeAssistant, mock_config_entry: MockConfigEntry
) -> None:
"""Test reconfiguring a loaded entry reloads it once with the new host."""
with patch(
"homeassistant.components.philips_js.async_setup_entry",
wraps=async_setup_entry,
) as mock_setup_entry:
assert await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
result = await mock_config_entry.start_reconfigure_flow(hass)
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_HOST: "2.2.2.2", CONF_API_VERSION: "1"}
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"
assert mock_config_entry.data[CONF_HOST] == "2.2.2.2"
assert mock_config_entry.state is ConfigEntryState.LOADED
# Initial setup plus a single reload by the update listener
assert mock_setup_entry.await_count == 2