mirror of
https://github.com/home-assistant/core.git
synced 2026-12-02 19:57:03 -04:00
Close the temporary webOS TV connection in the config flow (#194823)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
330461bb9a
commit
80d2544fe0
@@ -1,6 +1,7 @@
|
||||
"""Config flow for LG webOS TV integration."""
|
||||
|
||||
from collections.abc import Mapping
|
||||
from collections.abc import AsyncIterator, Mapping
|
||||
from contextlib import asynccontextmanager
|
||||
from typing import Any, Self, override
|
||||
from urllib.parse import urlparse
|
||||
|
||||
@@ -8,6 +9,7 @@ from aiowebostv import WebOsClient, WebOsTvPairError
|
||||
import probatio
|
||||
|
||||
from homeassistant.config_entries import (
|
||||
ConfigEntryState,
|
||||
ConfigFlow,
|
||||
ConfigFlowResult,
|
||||
OptionsFlowWithReload,
|
||||
@@ -34,10 +36,11 @@ DATA_SCHEMA = probatio.Schema(
|
||||
)
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def async_control_connect(
|
||||
hass: HomeAssistant, host: str, key: str | None
|
||||
) -> WebOsClient:
|
||||
"""Create LG webOS client and connect to the TV."""
|
||||
) -> AsyncIterator[WebOsClient]:
|
||||
"""Connect to the TV and disconnect when done."""
|
||||
client = WebOsClient(
|
||||
host,
|
||||
key,
|
||||
@@ -45,8 +48,10 @@ async def async_control_connect(
|
||||
)
|
||||
|
||||
await client.connect()
|
||||
|
||||
return client
|
||||
try:
|
||||
yield client
|
||||
finally:
|
||||
await client.disconnect()
|
||||
|
||||
|
||||
class FlowHandler(ConfigFlow, domain=DOMAIN):
|
||||
@@ -65,7 +70,7 @@ class FlowHandler(ConfigFlow, domain=DOMAIN):
|
||||
@override
|
||||
def async_get_options_flow(config_entry: WebOsTvConfigEntry) -> OptionsFlowHandler:
|
||||
"""Get the options flow for this handler."""
|
||||
return OptionsFlowHandler(config_entry)
|
||||
return OptionsFlowHandler()
|
||||
|
||||
@override
|
||||
async def async_step_user(
|
||||
@@ -89,20 +94,21 @@ class FlowHandler(ConfigFlow, domain=DOMAIN):
|
||||
|
||||
if user_input is not None:
|
||||
try:
|
||||
client = await async_control_connect(self.hass, self._host, None)
|
||||
async with async_control_connect(self.hass, self._host, None) as client:
|
||||
uuid = client.tv_info.hello["deviceUUID"]
|
||||
client_key = client.client_key
|
||||
model_name = client.tv_info.system.get("modelName")
|
||||
except WebOsTvPairError:
|
||||
errors["base"] = "error_pairing"
|
||||
except WEBOSTV_EXCEPTIONS:
|
||||
errors["base"] = "cannot_connect"
|
||||
else:
|
||||
await self.async_set_unique_id(
|
||||
client.tv_info.hello["deviceUUID"], raise_on_progress=False
|
||||
)
|
||||
await self.async_set_unique_id(uuid, raise_on_progress=False)
|
||||
self._abort_if_unique_id_configured({CONF_HOST: self._host})
|
||||
data = {CONF_HOST: self._host, CONF_CLIENT_SECRET: client.client_key}
|
||||
data = {CONF_HOST: self._host, CONF_CLIENT_SECRET: client_key}
|
||||
|
||||
if not self._name:
|
||||
if model_name := client.tv_info.system.get("modelName"):
|
||||
if model_name:
|
||||
self._name = f"{DEFAULT_NAME} {model_name}"
|
||||
else:
|
||||
self._name = DEFAULT_NAME
|
||||
@@ -155,14 +161,15 @@ class FlowHandler(ConfigFlow, domain=DOMAIN):
|
||||
|
||||
if user_input is not None:
|
||||
try:
|
||||
client = await async_control_connect(self.hass, self._host, None)
|
||||
async with async_control_connect(self.hass, self._host, None) as client:
|
||||
client_key = client.client_key
|
||||
except WebOsTvPairError:
|
||||
errors["base"] = "error_pairing"
|
||||
except WEBOSTV_EXCEPTIONS:
|
||||
errors["base"] = "cannot_connect"
|
||||
else:
|
||||
reauth_entry = self._get_reauth_entry()
|
||||
data = {CONF_HOST: self._host, CONF_CLIENT_SECRET: client.client_key}
|
||||
data = {CONF_HOST: self._host, CONF_CLIENT_SECRET: client_key}
|
||||
return self.async_update_reload_and_abort(reauth_entry, data=data)
|
||||
|
||||
return self.async_show_form(step_id="reauth_confirm", errors=errors)
|
||||
@@ -179,15 +186,17 @@ class FlowHandler(ConfigFlow, domain=DOMAIN):
|
||||
client_key = reconfigure_entry.data.get(CONF_CLIENT_SECRET)
|
||||
|
||||
try:
|
||||
client = await async_control_connect(self.hass, host, client_key)
|
||||
async with async_control_connect(self.hass, host, client_key) as client:
|
||||
uuid = client.tv_info.hello["deviceUUID"]
|
||||
client_key = client.client_key
|
||||
except WebOsTvPairError:
|
||||
errors["base"] = "error_pairing"
|
||||
except WEBOSTV_EXCEPTIONS:
|
||||
errors["base"] = "cannot_connect"
|
||||
else:
|
||||
await self.async_set_unique_id(client.tv_info.hello["deviceUUID"])
|
||||
await self.async_set_unique_id(uuid)
|
||||
self._abort_if_unique_id_mismatch(reason="wrong_device")
|
||||
data = {CONF_HOST: host, CONF_CLIENT_SECRET: client.client_key}
|
||||
data = {CONF_HOST: host, CONF_CLIENT_SECRET: client_key}
|
||||
return self.async_update_reload_and_abort(reconfigure_entry, data=data)
|
||||
|
||||
return self.async_show_form(
|
||||
@@ -206,10 +215,7 @@ class FlowHandler(ConfigFlow, domain=DOMAIN):
|
||||
class OptionsFlowHandler(OptionsFlowWithReload):
|
||||
"""Handle options."""
|
||||
|
||||
def __init__(self, config_entry: WebOsTvConfigEntry) -> None:
|
||||
"""Initialize options flow."""
|
||||
self.host = config_entry.data[CONF_HOST]
|
||||
self.key = config_entry.data[CONF_CLIENT_SECRET]
|
||||
config_entry: WebOsTvConfigEntry
|
||||
|
||||
async def async_step_init(
|
||||
self, user_input: dict[str, Any] | None = None
|
||||
@@ -219,14 +225,14 @@ class OptionsFlowHandler(OptionsFlowWithReload):
|
||||
if user_input is not None:
|
||||
options_input = {CONF_SOURCES: user_input[CONF_SOURCES]}
|
||||
return self.async_create_entry(title="", data=options_input)
|
||||
# Get sources
|
||||
sources_list = []
|
||||
try:
|
||||
client = await async_control_connect(self.hass, self.host, self.key)
|
||||
entry = self.config_entry
|
||||
if (
|
||||
entry.state is ConfigEntryState.LOADED
|
||||
and (client := entry.runtime_data.client).is_connected()
|
||||
):
|
||||
sources_list = get_sources(client.tv_state)
|
||||
except WebOsTvPairError:
|
||||
errors["base"] = "error_pairing"
|
||||
except WEBOSTV_EXCEPTIONS:
|
||||
else:
|
||||
errors["base"] = "cannot_connect"
|
||||
|
||||
option_sources = self.config_entry.options.get(CONF_SOURCES, [])
|
||||
|
||||
@@ -93,8 +93,7 @@
|
||||
},
|
||||
"options": {
|
||||
"error": {
|
||||
"cannot_connect": "[%key:component::webostv::config::error::cannot_connect%]",
|
||||
"error_pairing": "[%key:component::webostv::config::error::error_pairing%]"
|
||||
"cannot_connect": "[%key:component::webostv::config::error::cannot_connect%]"
|
||||
},
|
||||
"step": {
|
||||
"init": {
|
||||
|
||||
@@ -4,12 +4,7 @@ from aiowebostv import WebOsTvPairError
|
||||
import pytest
|
||||
|
||||
from homeassistant import config_entries
|
||||
from homeassistant.components.webostv.const import (
|
||||
CONF_SOURCES,
|
||||
DEFAULT_NAME,
|
||||
DOMAIN,
|
||||
LIVE_TV_APP_ID,
|
||||
)
|
||||
from homeassistant.components.webostv.const import DEFAULT_NAME, DOMAIN
|
||||
from homeassistant.config_entries import SOURCE_SSDP
|
||||
from homeassistant.const import CONF_CLIENT_SECRET, CONF_HOST, CONF_SOURCE
|
||||
from homeassistant.core import HomeAssistant
|
||||
@@ -21,15 +16,7 @@ from homeassistant.helpers.service_info.ssdp import (
|
||||
)
|
||||
|
||||
from . import setup_webostv
|
||||
from .const import (
|
||||
CLIENT_KEY,
|
||||
FAKE_UUID,
|
||||
HOST,
|
||||
MOCK_APPS,
|
||||
MOCK_INPUTS,
|
||||
TV_MODEL,
|
||||
TV_NAME,
|
||||
)
|
||||
from .const import CLIENT_KEY, FAKE_UUID, HOST, TV_MODEL, TV_NAME
|
||||
|
||||
pytestmark = pytest.mark.usefixtures("mock_setup_entry")
|
||||
|
||||
@@ -66,6 +53,7 @@ async def test_form(hass: HomeAssistant, client) -> None:
|
||||
assert result["title"] == TV_NAME
|
||||
config_entry = result["result"]
|
||||
assert config_entry.unique_id == FAKE_UUID
|
||||
client.disconnect.assert_awaited_once()
|
||||
|
||||
|
||||
async def test_form_no_model_name(hass: HomeAssistant, client) -> None:
|
||||
@@ -91,85 +79,6 @@ async def test_form_no_model_name(hass: HomeAssistant, client) -> None:
|
||||
assert config_entry.unique_id == FAKE_UUID
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("apps", "inputs"),
|
||||
[
|
||||
# Live TV in apps (default)
|
||||
(MOCK_APPS, MOCK_INPUTS),
|
||||
# Live TV in inputs
|
||||
(
|
||||
{},
|
||||
{
|
||||
**MOCK_INPUTS,
|
||||
"livetv": {"label": "Live TV", "id": "livetv", "appId": LIVE_TV_APP_ID},
|
||||
},
|
||||
),
|
||||
# Live TV not found
|
||||
({}, MOCK_INPUTS),
|
||||
],
|
||||
)
|
||||
async def test_options_flow_live_tv_in_apps(
|
||||
hass: HomeAssistant, client, apps, inputs
|
||||
) -> None:
|
||||
"""Test options config flow Live TV found in apps."""
|
||||
client.tv_state.apps = apps
|
||||
client.tv_state.inputs = inputs
|
||||
entry = await setup_webostv(hass)
|
||||
|
||||
result = await hass.config_entries.options.async_init(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "init"
|
||||
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={CONF_SOURCES: ["Live TV", "Input01", "Input02"]},
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["data"][CONF_SOURCES] == ["Live TV", "Input01", "Input02"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("side_effect", "error"),
|
||||
[
|
||||
(WebOsTvPairError, "error_pairing"),
|
||||
(ConnectionResetError, "cannot_connect"),
|
||||
],
|
||||
)
|
||||
async def test_options_flow_errors(
|
||||
hass: HomeAssistant, client, side_effect, error
|
||||
) -> None:
|
||||
"""Test options config flow errors."""
|
||||
entry = await setup_webostv(hass)
|
||||
|
||||
client.connect.side_effect = side_effect
|
||||
result = await hass.config_entries.options.async_init(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["errors"] == {"base": error}
|
||||
|
||||
# recover
|
||||
client.connect.side_effect = None
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"],
|
||||
user_input=None,
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "init"
|
||||
|
||||
result3 = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={CONF_SOURCES: ["Input01", "Input02"]},
|
||||
)
|
||||
|
||||
assert result3["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result3["data"][CONF_SOURCES] == ["Input01", "Input02"]
|
||||
|
||||
|
||||
async def test_form_cannot_connect(hass: HomeAssistant, client) -> None:
|
||||
"""Test we handle cannot connect error."""
|
||||
result = await hass.config_entries.flow.async_init(
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
"""Test the LG webOS TV options flow."""
|
||||
|
||||
import pytest
|
||||
from pytest_homeassistant.common import MockConfigEntry
|
||||
|
||||
from homeassistant.components.webostv.const import CONF_SOURCES, DOMAIN, LIVE_TV_APP_ID
|
||||
from homeassistant.const import CONF_CLIENT_SECRET, CONF_HOST
|
||||
from homeassistant.core import HomeAssistant
|
||||
from homeassistant.data_entry_flow import FlowResultType
|
||||
|
||||
from . import setup_webostv
|
||||
from .const import CLIENT_KEY, FAKE_UUID, HOST, MOCK_APPS, MOCK_INPUTS
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
("apps", "inputs"),
|
||||
[
|
||||
# Live TV in apps (default)
|
||||
(MOCK_APPS, MOCK_INPUTS),
|
||||
# Live TV in inputs
|
||||
(
|
||||
{},
|
||||
{
|
||||
**MOCK_INPUTS,
|
||||
"livetv": {"label": "Live TV", "id": "livetv", "appId": LIVE_TV_APP_ID},
|
||||
},
|
||||
),
|
||||
# Live TV not found
|
||||
({}, MOCK_INPUTS),
|
||||
],
|
||||
)
|
||||
async def test_options_flow_live_tv_in_apps(
|
||||
hass: HomeAssistant, client, apps, inputs
|
||||
) -> None:
|
||||
"""Test options config flow Live TV found in apps."""
|
||||
client.tv_state.apps = apps
|
||||
client.tv_state.inputs = inputs
|
||||
entry = await setup_webostv(hass)
|
||||
|
||||
result = await hass.config_entries.options.async_init(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "init"
|
||||
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={CONF_SOURCES: ["Live TV", "Input01", "Input02"]},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result["data"][CONF_SOURCES] == ["Live TV", "Input01", "Input02"]
|
||||
|
||||
|
||||
async def test_options_flow_not_connected(hass: HomeAssistant, client) -> None:
|
||||
"""Test options flow when the TV is not connected."""
|
||||
entry = await setup_webostv(hass)
|
||||
|
||||
client.is_connected.return_value = False
|
||||
result = await hass.config_entries.options.async_init(entry.entry_id)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["errors"] == {"base": "cannot_connect"}
|
||||
|
||||
# recover
|
||||
client.is_connected.return_value = True
|
||||
result = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"],
|
||||
user_input=None,
|
||||
)
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["step_id"] == "init"
|
||||
|
||||
result3 = await hass.config_entries.options.async_configure(
|
||||
result["flow_id"],
|
||||
user_input={CONF_SOURCES: ["Input01", "Input02"]},
|
||||
)
|
||||
await hass.async_block_till_done()
|
||||
|
||||
assert result3["type"] is FlowResultType.CREATE_ENTRY
|
||||
assert result3["data"][CONF_SOURCES] == ["Input01", "Input02"]
|
||||
|
||||
|
||||
@pytest.mark.usefixtures("client")
|
||||
async def test_options_flow_entry_not_loaded(hass: HomeAssistant) -> None:
|
||||
"""Test options flow when the config entry is not loaded."""
|
||||
entry = MockConfigEntry(
|
||||
domain=DOMAIN,
|
||||
data={CONF_HOST: HOST, CONF_CLIENT_SECRET: CLIENT_KEY},
|
||||
unique_id=FAKE_UUID,
|
||||
)
|
||||
entry.add_to_hass(hass)
|
||||
|
||||
result = await hass.config_entries.options.async_init(entry.entry_id)
|
||||
|
||||
assert result["type"] is FlowResultType.FORM
|
||||
assert result["errors"] == {"base": "cannot_connect"}
|
||||
Reference in New Issue
Block a user