Skip to content

Commit c935686

Browse files
authored
Add add-on discovery flow to pyLoad integration (home-assistant#148494)
1 parent 1753baf commit c935686

File tree

4 files changed

+275
-2
lines changed

4 files changed

+275
-2
lines changed

homeassistant/components/pyload/config_flow.py

Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -26,6 +26,7 @@
2626
TextSelectorConfig,
2727
TextSelectorType,
2828
)
29+
from homeassistant.helpers.service_info.hassio import HassioServiceInfo
2930

3031
from .const import DEFAULT_NAME, DOMAIN
3132

@@ -97,6 +98,8 @@ class PyLoadConfigFlow(ConfigFlow, domain=DOMAIN):
9798
VERSION = 1
9899
MINOR_VERSION = 1
99100

101+
_hassio_discovery: HassioServiceInfo | None = None
102+
100103
async def async_step_user(
101104
self, user_input: dict[str, Any] | None = None
102105
) -> ConfigFlowResult:
@@ -211,3 +214,58 @@ async def async_step_reconfigure(
211214
description_placeholders={CONF_NAME: reconfig_entry.data[CONF_USERNAME]},
212215
errors=errors,
213216
)
217+
218+
async def async_step_hassio(
219+
self, discovery_info: HassioServiceInfo
220+
) -> ConfigFlowResult:
221+
"""Prepare configuration for pyLoad add-on.
222+
223+
This flow is triggered by the discovery component.
224+
"""
225+
url = URL(discovery_info.config[CONF_URL]).human_repr()
226+
self._async_abort_entries_match({CONF_URL: url})
227+
await self.async_set_unique_id(discovery_info.uuid)
228+
self._abort_if_unique_id_configured(updates={CONF_URL: url})
229+
discovery_info.config[CONF_URL] = url
230+
self._hassio_discovery = discovery_info
231+
return await self.async_step_hassio_confirm()
232+
233+
async def async_step_hassio_confirm(
234+
self, user_input: dict[str, Any] | None = None
235+
) -> ConfigFlowResult:
236+
"""Confirm Supervisor discovery."""
237+
assert self._hassio_discovery
238+
errors: dict[str, str] = {}
239+
240+
data = {**self._hassio_discovery.config, CONF_VERIFY_SSL: False}
241+
242+
if user_input is not None:
243+
data.update(user_input)
244+
245+
try:
246+
await validate_input(self.hass, data)
247+
except (CannotConnect, ParserError):
248+
_LOGGER.debug("Cannot connect", exc_info=True)
249+
errors["base"] = "cannot_connect"
250+
except InvalidAuth:
251+
errors["base"] = "invalid_auth"
252+
except Exception:
253+
_LOGGER.exception("Unexpected exception")
254+
errors["base"] = "unknown"
255+
else:
256+
if user_input is None:
257+
self._set_confirm_only()
258+
return self.async_show_form(
259+
step_id="hassio_confirm",
260+
description_placeholders=self._hassio_discovery.config,
261+
)
262+
return self.async_create_entry(title=self._hassio_discovery.slug, data=data)
263+
264+
return self.async_show_form(
265+
step_id="hassio_confirm",
266+
data_schema=self.add_suggested_values_to_schema(
267+
data_schema=REAUTH_SCHEMA, suggested_values=data
268+
),
269+
description_placeholders=self._hassio_discovery.config,
270+
errors=errors if user_input is not None else None,
271+
)

homeassistant/components/pyload/strings.json

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,18 @@
3939
"username": "[%key:component::pyload::config::step::user::data_description::username%]",
4040
"password": "[%key:component::pyload::config::step::user::data_description::password%]"
4141
}
42+
},
43+
"hassio_confirm": {
44+
"title": "pyLoad via Home Assistant add-on",
45+
"description": "Do you want to configure Home Assistant to connect to the pyLoad service provided by the add-on: {addon}?",
46+
"data": {
47+
"username": "[%key:common::config_flow::data::username%]",
48+
"password": "[%key:common::config_flow::data::password%]"
49+
},
50+
"data_description": {
51+
"username": "[%key:component::pyload::config::step::user::data_description::username%]",
52+
"password": "[%key:component::pyload::config::step::user::data_description::password%]"
53+
}
4254
}
4355
},
4456
"error": {

tests/components/pyload/conftest.py

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -16,6 +16,7 @@
1616
CONF_USERNAME,
1717
CONF_VERIFY_SSL,
1818
)
19+
from homeassistant.helpers.service_info.hassio import HassioServiceInfo
1920

2021
from tests.common import MockConfigEntry
2122

@@ -39,6 +40,21 @@
3940
}
4041

4142

43+
ADDON_DISCOVERY_INFO = {
44+
"addon": "pyLoad-ng",
45+
CONF_URL: "http://539df76c-pyload-ng:8000/",
46+
CONF_USERNAME: "pyload",
47+
CONF_PASSWORD: "pyload",
48+
}
49+
50+
ADDON_SERVICE_INFO = HassioServiceInfo(
51+
config=ADDON_DISCOVERY_INFO,
52+
name="pyLoad-ng Addon",
53+
slug="p539df76c_pyload-ng",
54+
uuid="1234",
55+
)
56+
57+
4258
@pytest.fixture
4359
def mock_setup_entry() -> Generator[AsyncMock]:
4460
"""Override async_setup_entry."""

tests/components/pyload/test_config_flow.py

Lines changed: 189 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,18 @@
66
import pytest
77

88
from homeassistant.components.pyload.const import DEFAULT_NAME, DOMAIN
9-
from homeassistant.config_entries import SOURCE_USER
9+
from homeassistant.config_entries import SOURCE_HASSIO, SOURCE_IGNORE, SOURCE_USER
10+
from homeassistant.const import CONF_PASSWORD, CONF_URL, CONF_USERNAME, CONF_VERIFY_SSL
1011
from homeassistant.core import HomeAssistant
1112
from homeassistant.data_entry_flow import FlowResultType
1213

13-
from .conftest import NEW_INPUT, REAUTH_INPUT, USER_INPUT
14+
from .conftest import (
15+
ADDON_DISCOVERY_INFO,
16+
ADDON_SERVICE_INFO,
17+
NEW_INPUT,
18+
REAUTH_INPUT,
19+
USER_INPUT,
20+
)
1421

1522
from tests.common import MockConfigEntry
1623

@@ -245,3 +252,183 @@ async def test_reconfigure_errors(
245252
assert result["reason"] == "reconfigure_successful"
246253
assert config_entry.data == USER_INPUT
247254
assert len(hass.config_entries.async_entries()) == 1
255+
256+
257+
async def test_hassio_discovery(
258+
hass: HomeAssistant,
259+
mock_setup_entry: AsyncMock,
260+
mock_pyloadapi: AsyncMock,
261+
) -> None:
262+
"""Test flow started from Supervisor discovery."""
263+
264+
mock_pyloadapi.login.side_effect = InvalidAuth
265+
266+
result = await hass.config_entries.flow.async_init(
267+
DOMAIN,
268+
data=ADDON_SERVICE_INFO,
269+
context={"source": SOURCE_HASSIO},
270+
)
271+
272+
assert result["type"] is FlowResultType.FORM
273+
assert result["step_id"] == "hassio_confirm"
274+
assert result["errors"] is None
275+
276+
mock_pyloadapi.login.side_effect = None
277+
278+
result = await hass.config_entries.flow.async_configure(
279+
result["flow_id"], {CONF_USERNAME: "pyload", CONF_PASSWORD: "pyload"}
280+
)
281+
assert result["type"] is FlowResultType.CREATE_ENTRY
282+
assert result["title"] == "p539df76c_pyload-ng"
283+
assert result["data"] == {**ADDON_DISCOVERY_INFO, CONF_VERIFY_SSL: False}
284+
assert len(mock_setup_entry.mock_calls) == 1
285+
286+
287+
@pytest.mark.usefixtures("mock_pyloadapi")
288+
async def test_hassio_discovery_confirm_only(
289+
hass: HomeAssistant,
290+
mock_setup_entry: AsyncMock,
291+
) -> None:
292+
"""Test flow started from Supervisor discovery. Abort with confirm only."""
293+
294+
result = await hass.config_entries.flow.async_init(
295+
DOMAIN,
296+
data=ADDON_SERVICE_INFO,
297+
context={"source": SOURCE_HASSIO},
298+
)
299+
300+
assert result["type"] is FlowResultType.FORM
301+
assert result["step_id"] == "hassio_confirm"
302+
303+
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
304+
305+
assert result["type"] is FlowResultType.CREATE_ENTRY
306+
assert result["title"] == "p539df76c_pyload-ng"
307+
assert result["data"] == {**ADDON_DISCOVERY_INFO, CONF_VERIFY_SSL: False}
308+
assert len(mock_setup_entry.mock_calls) == 1
309+
310+
311+
@pytest.mark.parametrize(
312+
("side_effect", "error_text"),
313+
[
314+
(InvalidAuth, "invalid_auth"),
315+
(CannotConnect, "cannot_connect"),
316+
(IndexError, "unknown"),
317+
],
318+
)
319+
async def test_hassio_discovery_errors(
320+
hass: HomeAssistant,
321+
mock_setup_entry: AsyncMock,
322+
mock_pyloadapi: AsyncMock,
323+
side_effect: Exception,
324+
error_text: str,
325+
) -> None:
326+
"""Test flow started from Supervisor discovery."""
327+
328+
mock_pyloadapi.login.side_effect = side_effect
329+
330+
result = await hass.config_entries.flow.async_init(
331+
DOMAIN,
332+
data=ADDON_SERVICE_INFO,
333+
context={"source": SOURCE_HASSIO},
334+
)
335+
336+
assert result["type"] is FlowResultType.FORM
337+
assert result["step_id"] == "hassio_confirm"
338+
assert result["errors"] is None
339+
340+
result = await hass.config_entries.flow.async_configure(
341+
result["flow_id"], {CONF_USERNAME: "pyload", CONF_PASSWORD: "pyload"}
342+
)
343+
344+
assert result["type"] is FlowResultType.FORM
345+
assert result["errors"] == {"base": error_text}
346+
347+
mock_pyloadapi.login.side_effect = None
348+
349+
result = await hass.config_entries.flow.async_configure(
350+
result["flow_id"], {CONF_USERNAME: "pyload", CONF_PASSWORD: "pyload"}
351+
)
352+
353+
assert result["type"] is FlowResultType.CREATE_ENTRY
354+
assert result["title"] == "p539df76c_pyload-ng"
355+
assert result["data"] == {**ADDON_DISCOVERY_INFO, CONF_VERIFY_SSL: False}
356+
assert len(mock_setup_entry.mock_calls) == 1
357+
358+
359+
@pytest.mark.usefixtures("mock_pyloadapi")
360+
async def test_hassio_discovery_already_configured(
361+
hass: HomeAssistant,
362+
) -> None:
363+
"""Test we abort discovery flow if already configured."""
364+
365+
MockConfigEntry(
366+
domain=DOMAIN,
367+
data={
368+
CONF_URL: "http://539df76c-pyload-ng:8000/",
369+
CONF_USERNAME: "pyload",
370+
CONF_PASSWORD: "pyload",
371+
},
372+
).add_to_hass(hass)
373+
374+
result = await hass.config_entries.flow.async_init(
375+
DOMAIN,
376+
data=ADDON_SERVICE_INFO,
377+
context={"source": SOURCE_HASSIO},
378+
)
379+
380+
assert result["type"] is FlowResultType.ABORT
381+
assert result["reason"] == "already_configured"
382+
383+
384+
@pytest.mark.usefixtures("mock_pyloadapi")
385+
async def test_hassio_discovery_data_update(
386+
hass: HomeAssistant,
387+
) -> None:
388+
"""Test we abort discovery flow if already configured and we update entry from discovery data."""
389+
390+
entry = MockConfigEntry(
391+
domain=DOMAIN,
392+
data={
393+
CONF_URL: "http://localhost:8000/",
394+
CONF_USERNAME: "pyload",
395+
CONF_PASSWORD: "pyload",
396+
},
397+
unique_id="1234",
398+
)
399+
400+
entry.add_to_hass(hass)
401+
402+
result = await hass.config_entries.flow.async_init(
403+
DOMAIN,
404+
data=ADDON_SERVICE_INFO,
405+
context={"source": SOURCE_HASSIO},
406+
)
407+
408+
assert result["type"] is FlowResultType.ABORT
409+
assert result["reason"] == "already_configured"
410+
411+
assert entry.data[CONF_URL] == "http://539df76c-pyload-ng:8000/"
412+
413+
414+
@pytest.mark.usefixtures("mock_pyloadapi")
415+
async def test_hassio_discovery_ignored(
416+
hass: HomeAssistant,
417+
) -> None:
418+
"""Test we abort discovery flow if discovery was ignored."""
419+
420+
MockConfigEntry(
421+
domain=DOMAIN,
422+
source=SOURCE_IGNORE,
423+
data={},
424+
unique_id="1234",
425+
).add_to_hass(hass)
426+
427+
result = await hass.config_entries.flow.async_init(
428+
DOMAIN,
429+
data=ADDON_SERVICE_INFO,
430+
context={"source": SOURCE_HASSIO},
431+
)
432+
433+
assert result["type"] is FlowResultType.ABORT
434+
assert result["reason"] == "already_configured"

0 commit comments

Comments
 (0)