From 041dbf7d5b4f2280be96cb397b5ebf787a08ad9b Mon Sep 17 00:00:00 2001 From: Franck Nijhof Date: Sun, 11 Oct 2026 21:14:58 +0200 Subject: [PATCH] Add setting up LaMetric with a press on its button (#184197) --- .../components/lametric/config_flow.py | 191 ++++++- .../components/lametric/strings.json | 23 +- tests/components/lametric/conftest.py | 28 +- tests/components/lametric/test_config_flow.py | 466 +++++++++++++++++- tests/components/lametric/test_init.py | 4 +- 5 files changed, 696 insertions(+), 16 deletions(-) diff --git a/homeassistant/components/lametric/config_flow.py b/homeassistant/components/lametric/config_flow.py index fd45306c84ce..3e1a823f5e1c 100644 --- a/homeassistant/components/lametric/config_flow.py +++ b/homeassistant/components/lametric/config_flow.py @@ -1,16 +1,21 @@ """Config flow to configure the LaMetric integration.""" +import asyncio from collections.abc import Mapping from ipaddress import ip_address import logging -from typing import Any, override +from typing import TYPE_CHECKING, Any, override from demetriek import ( + AuthChallenge, CloudDevice, LaMetricAuthenticationError, LaMetricCloud, LaMetricConnectionError, LaMetricDevice, + LaMetricError, + LaMetricLocalAuth, + LaMetricUnsupportedError, Model, Notification, NotificationIconType, @@ -24,6 +29,7 @@ from yarl import URL from homeassistant.config_entries import SOURCE_REAUTH, ConfigFlowResult from homeassistant.const import CONF_API_KEY, CONF_DEVICE, CONF_HOST, CONF_MAC +from homeassistant.core import callback from homeassistant.data_entry_flow import AbortFlow from homeassistant.helpers.aiohttp_client import async_get_clientsession from homeassistant.helpers.config_entry_oauth2_flow import AbstractOAuth2FlowHandler @@ -49,6 +55,13 @@ from .const import DOMAIN, LOGGER DEVICES_URL = "https://developer.lametric.com/user/devices" +# How often to check whether the button on the device has been pressed. +BUTTON_POLL_INTERVAL = 1 + + +class ButtonNotPressed(Exception): + """The button on the device was not pressed in time.""" + class LaMetricFlowHandler(AbstractOAuth2FlowHandler, domain=DOMAIN): """Handle a LaMetric config flow.""" @@ -57,6 +70,11 @@ class LaMetricFlowHandler(AbstractOAuth2FlowHandler, domain=DOMAIN): VERSION = 1 devices: dict[str, CloudDevice] + button_challenge: AuthChallenge + button_error: str | None = None + button_host: str + button_task: asyncio.Task[str] | None = None + removed: bool = False discovered_host: str discovered_serial: str discovered: bool = False @@ -67,6 +85,12 @@ class LaMetricFlowHandler(AbstractOAuth2FlowHandler, domain=DOMAIN): """Return logger.""" return LOGGER + @callback + @override + def async_remove(self) -> None: + """Handle the flow being removed, for example closed by the user.""" + self.removed = True + @property @override def extra_authorize_data(self) -> dict[str, Any]: @@ -175,13 +199,41 @@ class LaMetricFlowHandler(AbstractOAuth2FlowHandler, domain=DOMAIN): ) -> ConfigFlowResult: """Handle the user's choice. - Either enter the manual credentials or fetch the cloud credentials. + Either press the button on the device, enter the manual credentials, + or fetch the cloud credentials. """ + menu_options = ["press_button", "pick_implementation", "manual_entry"] + + # With the host known, ask the device whether it supports the button + # press. Nothing shows on its screen for that. A device that does goes + # straight to it, one that does not (like an LM 37X8) is not offered it. + if host := self._known_host(): + auth = LaMetricLocalAuth( + host=host, session=async_get_clientsession(self.hass) + ) + try: + supported = await auth.supported() + except LaMetricConnectionError as ex: + # No telling, so offer every way to set it up. + LOGGER.debug("Could not check for the button press: %s", ex) + else: + if supported: + return await self.async_step_press_button() + menu_options.remove("press_button") + return self.async_show_menu( step_id="choice_enter_manual_or_fetch_cloud", - menu_options=["pick_implementation", "manual_entry"], + menu_options=menu_options, ) + def _known_host(self) -> str | None: + """Return the host of the device, when it is known already.""" + if self.discovered: + return self.discovered_host + if self.source == SOURCE_REAUTH: + return str(self._get_reauth_entry().data[CONF_HOST]) + return None + async def async_step_manual_entry( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: @@ -228,6 +280,125 @@ class LaMetricFlowHandler(AbstractOAuth2FlowHandler, domain=DOMAIN): errors=errors, ) + async def async_step_press_button( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Handle getting the API key from the device, with a press on its button. + + Devices from 2022 onward hand out their API key locally, after someone + presses the button on top of the device. No LaMetric account needed. + """ + errors: dict[str, str] = {} + if self.button_error: + errors["base"] = self.button_error + self.button_error = None + + if user_input is not None: + self.button_host = user_input[CONF_HOST] + auth = LaMetricLocalAuth( + host=self.button_host, session=async_get_clientsession(self.hass) + ) + try: + self.button_challenge = await auth.request_challenge() + except LaMetricUnsupportedError: + # A device without this flow, like an LM 37X8, ends up here. + errors["base"] = "button_not_supported" + except LaMetricConnectionError as ex: + LOGGER.error("Error connecting to LaMetric: %s", ex) + errors["base"] = "cannot_connect" + except LaMetricError as ex: + LOGGER.error("Error asking LaMetric for a button press: %s", ex) + errors["base"] = "unknown" + except Exception: # noqa: BLE001 + LOGGER.exception("Unexpected error occurred") + errors["base"] = "unknown" + else: + # Closed while the device answered, so no one waits for a press. + if self.removed: + return self.async_abort(reason="unknown") + self.button_task = self.hass.async_create_task( + self._async_wait_for_button(auth) + ) + return await self.async_step_press_button_wait() + + return self.async_show_form( + step_id="press_button", + data_schema=self.add_suggested_values_to_schema( + probatio.Schema({probatio.Required(CONF_HOST): TextSelector()}), + {CONF_HOST: self._known_host()}, + ), + errors=errors, + ) + + async def _async_wait_for_button(self, auth: LaMetricLocalAuth) -> str: + """Wait for the button on the device to be pressed, and get the API key.""" + challenge = self.button_challenge + while challenge.state == "in-progress": + await asyncio.sleep(BUTTON_POLL_INTERVAL) + challenge = await auth.challenge(challenge_id=challenge.challenge_id) + + if not challenge.resolved: + raise ButtonNotPressed + return await auth.api_key(challenge_id=challenge.challenge_id) + + async def async_step_press_button_wait( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Wait for the button on the device to be pressed.""" + if TYPE_CHECKING: + assert self.button_task is not None + + if not self.button_task.done(): + return self.async_show_progress( + step_id="press_button_wait", + progress_action="press_button", + description_placeholders={ + "duration": str(self.button_challenge.duration) + }, + progress_task=self.button_task, + ) + + if isinstance(exception := self.button_task.exception(), ButtonNotPressed): + return self.async_show_progress_done(next_step_id="press_button_timeout") + if exception is not None: + LOGGER.error("Error getting the API key from LaMetric: %s", exception) + self.button_error = ( + "cannot_connect" + if isinstance(exception, LaMetricConnectionError) + else "unknown" + ) + return self.async_show_progress_done(next_step_id="press_button") + return self.async_show_progress_done(next_step_id="press_button_finish") + + async def async_step_press_button_timeout( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Handle the button not being pressed in time.""" + if user_input is None: + return self.async_show_form(step_id="press_button_timeout") + return await self.async_step_press_button({CONF_HOST: self.button_host}) + + async def async_step_press_button_finish( + self, user_input: dict[str, Any] | None = None + ) -> ConfigFlowResult: + """Set up the device with the API key it handed out.""" + if TYPE_CHECKING: + assert self.button_task is not None + + try: + return await self._async_step_create_entry( + self.button_host, self.button_task.result() + ) + except AbortFlow: + raise + except LaMetricConnectionError as ex: + LOGGER.error("Error connecting to LaMetric: %s", ex) + self.button_error = "cannot_connect" + except Exception: # noqa: BLE001 + LOGGER.exception("Unexpected error occurred") + self.button_error = "unknown" + return await self.async_step_press_button() + async def async_step_cloud_fetch_devices( self, data: dict[str, Any] ) -> ConfigFlowResult: @@ -311,11 +482,15 @@ class LaMetricFlowHandler(AbstractOAuth2FlowHandler, domain=DOMAIN): device = await lametric.device() - if self.source != SOURCE_REAUTH: - await self.async_set_unique_id( - device.serial_number, - raise_on_progress=False, - ) + await self.async_set_unique_id( + device.serial_number, + raise_on_progress=False, + ) + if self.source == SOURCE_REAUTH: + # The host can differ from the one set up, so make sure it is + # still the same device before touching its entry. + self._abort_if_unique_id_mismatch() + else: self._abort_if_unique_id_configured( updates={CONF_HOST: lametric.host, CONF_API_KEY: lametric.api_key} ) diff --git a/homeassistant/components/lametric/strings.json b/homeassistant/components/lametric/strings.json index d07d5232b9d5..bca7c0a5a4fa 100644 --- a/homeassistant/components/lametric/strings.json +++ b/homeassistant/components/lametric/strings.json @@ -7,20 +7,25 @@ "missing_configuration": "The LaMetric integration is not configured. Please follow the documentation.", "no_devices": "The authorized user has no LaMetric devices", "reauth_device_not_found": "The device you are trying to re-authenticate is not found in this LaMetric account", - "unique_id_mismatch": "The device at this address is not the LaMetric device you are reconfiguring.", + "unique_id_mismatch": "The device at this address is a different LaMetric device than the one set up.", "unknown": "[%key:common::config_flow::error::unknown%]" }, "error": { + "button_not_supported": "This device cannot hand out its API key with a button press, for example an older LaMetric TIME. Enter the API key manually, or import it from LaMetric.com.", "cannot_connect": "[%key:common::config_flow::error::cannot_connect%]", "invalid_auth": "[%key:common::config_flow::error::invalid_auth%]", "unknown": "[%key:common::config_flow::error::unknown%]" }, + "progress": { + "press_button": "Press the button on top of your LaMetric device now. You have {duration} seconds." + }, "step": { "choice_enter_manual_or_fetch_cloud": { - "description": "A LaMetric device can be set up in Home Assistant in two different ways.\n\nYou can enter all device information and API tokens yourself, or Home Assistant can import them from your LaMetric.com account.", + "description": "A LaMetric device from 2022 onward can hand out its API key after you press its button, no account needed.\n\nHome Assistant can also import the device information and API tokens from your LaMetric.com account, or you can enter them yourself.", "menu_options": { "manual_entry": "Enter manually", - "pick_implementation": "Import from LaMetric.com (recommended)" + "pick_implementation": "Import from LaMetric.com", + "press_button": "Press the button on the device (no account needed)" } }, "cloud_select_device": { @@ -50,6 +55,18 @@ }, "title": "[%key:common::config_flow::title::oauth2_pick_implementation%]" }, + "press_button": { + "data": { + "host": "[%key:common::config_flow::data::host%]" + }, + "data_description": { + "host": "[%key:component::lametric::config::step::manual_entry::data_description::host%]" + }, + "description": "Your LaMetric device will ask for its button to be pressed, to hand out its API key. This works on devices from 2022 onward." + }, + "press_button_timeout": { + "description": "The button on the LaMetric device was not pressed in time. Submit to try again." + }, "reconfigure": { "data": { "api_key": "[%key:common::config_flow::data::api_key%]", diff --git a/tests/components/lametric/conftest.py b/tests/components/lametric/conftest.py index 73b0b2362dc6..22b6cf40ac81 100644 --- a/tests/components/lametric/conftest.py +++ b/tests/components/lametric/conftest.py @@ -4,7 +4,7 @@ from collections.abc import Generator from contextlib import nullcontext from unittest.mock import AsyncMock, MagicMock, patch -from demetriek import CloudDevice, Device +from demetriek import AuthChallenge, CloudDevice, Device import pytest from homeassistant.components.application_credentials import ( @@ -67,6 +67,32 @@ def mock_lametric_cloud() -> Generator[MagicMock]: yield lametric +@pytest.fixture +def mock_lametric_local_auth() -> Generator[MagicMock]: + """Return a mocked LaMetric local auth client. + + It answers like a real device: the challenge is in progress at first, + and resolved once the button on the device is pressed. + """ + with ( + patch( + "homeassistant.components.lametric.config_flow.LaMetricLocalAuth", + autospec=True, + ) as local_auth_mock, + patch("homeassistant.components.lametric.config_flow.BUTTON_POLL_INTERVAL", 0), + ): + local_auth = local_auth_mock.return_value + local_auth.supported.return_value = True + local_auth.request_challenge.return_value = AuthChallenge( + challenge_id="mock-challenge", duration=60, state="in-progress" + ) + local_auth.challenge.return_value = AuthChallenge( + challenge_id="mock-challenge", duration=60, state="resolved" + ) + local_auth.api_key.return_value = "mock-local-api-key" + yield local_auth + + @pytest.fixture def device_fixture() -> str: """Return the device fixture for a specific device.""" diff --git a/tests/components/lametric/test_config_flow.py b/tests/components/lametric/test_config_flow.py index 192429ca1d12..e1ff19c1ca7d 100644 --- a/tests/components/lametric/test_config_flow.py +++ b/tests/components/lametric/test_config_flow.py @@ -1,19 +1,23 @@ """Tests for the LaMetric config flow.""" from http import HTTPStatus +from typing import Any from unittest.mock import MagicMock from demetriek import ( + AuthChallenge, LaMetricAuthenticationError, LaMetricConnectionError, LaMetricConnectionTimeoutError, LaMetricError, + LaMetricUnsupportedError, Notification, NotificationSound, Sound, ) import pytest +from homeassistant.components.lametric import config_flow from homeassistant.components.lametric.const import DOMAIN from homeassistant.config_entries import SOURCE_DHCP, SOURCE_SSDP, SOURCE_USER from homeassistant.const import CONF_API_KEY, CONF_DEVICE, CONF_HOST, CONF_MAC @@ -57,7 +61,11 @@ async def test_full_cloud_import_flow_multiple_devices( assert result["type"] is FlowResultType.MENU assert result["step_id"] == "choice_enter_manual_or_fetch_cloud" - assert result["menu_options"] == ["pick_implementation", "manual_entry"] + assert result["menu_options"] == [ + "press_button", + "pick_implementation", + "manual_entry", + ] result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={"next_step_id": "pick_implementation"} @@ -136,7 +144,11 @@ async def test_full_cloud_import_flow_single_device( assert result["type"] is FlowResultType.MENU assert result["step_id"] == "choice_enter_manual_or_fetch_cloud" - assert result["menu_options"] == ["pick_implementation", "manual_entry"] + assert result["menu_options"] == [ + "press_button", + "pick_implementation", + "manual_entry", + ] result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={"next_step_id": "pick_implementation"} @@ -210,7 +222,11 @@ async def test_full_manual( assert result["type"] is FlowResultType.MENU assert result["step_id"] == "choice_enter_manual_or_fetch_cloud" - assert result["menu_options"] == ["pick_implementation", "manual_entry"] + assert result["menu_options"] == [ + "press_button", + "pick_implementation", + "manual_entry", + ] result = await hass.config_entries.flow.async_configure( result["flow_id"], user_input={"next_step_id": "manual_entry"} @@ -251,8 +267,11 @@ async def test_full_ssdp_with_cloud_import( aioclient_mock: AiohttpClientMocker, mock_lametric_cloud: MagicMock, mock_lametric: MagicMock, + mock_lametric_local_auth: MagicMock, ) -> None: """Check a full flow triggered by SSDP, importing from cloud.""" + # A device without the button press, like an LM 37X8, gets the menu. + mock_lametric_local_auth.supported.return_value = False result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_SSDP}, data=SSDP_DISCOVERY_INFO ) @@ -319,8 +338,11 @@ async def test_full_ssdp_with_cloud_import( async def test_full_ssdp_manual_entry( hass: HomeAssistant, mock_lametric: MagicMock, + mock_lametric_local_auth: MagicMock, ) -> None: """Check a full flow triggered by SSDP, with manual API key entry.""" + # A device without the button press, like an LM 37X8, gets the menu. + mock_lametric_local_auth.supported.return_value = False result = await hass.config_entries.flow.async_init( DOMAIN, context={"source": SOURCE_SSDP}, data=SSDP_DISCOVERY_INFO ) @@ -772,8 +794,11 @@ async def test_reauth_cloud_import( mock_lametric_cloud: MagicMock, mock_lametric: MagicMock, mock_config_entry: MockConfigEntry, + mock_lametric_local_auth: MagicMock, ) -> None: """Test reauth flow importing api keys from the cloud.""" + # A device without the button press, like an LM 37X8, gets the menu. + mock_lametric_local_auth.supported.return_value = False mock_config_entry.add_to_hass(hass) result = await mock_config_entry.start_reauth_flow(hass) @@ -825,8 +850,11 @@ async def test_reauth_cloud_abort_device_not_found( mock_lametric_cloud: MagicMock, mock_lametric: MagicMock, mock_config_entry: MockConfigEntry, + mock_lametric_local_auth: MagicMock, ) -> None: """Test reauth flow importing api keys from the cloud.""" + # A device without the button press, like an LM 37X8, gets the menu. + mock_lametric_local_auth.supported.return_value = False mock_config_entry.add_to_hass(hass) hass.config_entries.async_update_entry(mock_config_entry, unique_id="UKNOWN_DEVICE") @@ -871,8 +899,11 @@ async def test_reauth_manual( hass: HomeAssistant, mock_lametric: MagicMock, mock_config_entry: MockConfigEntry, + mock_lametric_local_auth: MagicMock, ) -> None: """Test reauth flow with manual entry.""" + # A device without the button press, like an LM 37X8, gets the menu. + mock_lametric_local_auth.supported.return_value = False mock_config_entry.add_to_hass(hass) result = await mock_config_entry.start_reauth_flow(hass) @@ -903,9 +934,16 @@ async def test_reauth_manual_sky( hass: HomeAssistant, mock_lametric: MagicMock, mock_config_entry: MockConfigEntry, + mock_lametric_local_auth: MagicMock, ) -> None: """Test reauth flow with manual entry for LaMetric Sky.""" + # A device without the button press, like an LM 37X8, gets the menu. + mock_lametric_local_auth.supported.return_value = False mock_config_entry.add_to_hass(hass) + # The entry belongs to the SKY the reauthentication talks to. + hass.config_entries.async_update_entry( + mock_config_entry, unique_id="SA52100000123TBNC" + ) result = await mock_config_entry.start_reauth_flow(hass) @@ -1024,3 +1062,425 @@ async def test_reconfigure_errors( assert result["type"] is FlowResultType.ABORT assert result["reason"] == "reconfigure_successful" + + +@pytest.mark.usefixtures("mock_setup_entry") +async def test_full_press_button( + hass: HomeAssistant, + mock_lametric: MagicMock, + mock_lametric_local_auth: MagicMock, +) -> None: + """Check a full flow getting the API key with a press on the button.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={"next_step_id": "press_button"} + ) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "press_button" + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_HOST: "127.0.0.1"} + ) + + assert result["type"] is FlowResultType.SHOW_PROGRESS + assert result["step_id"] == "press_button_wait" + assert result["description_placeholders"] == {"duration": "60"} + + await hass.async_block_till_done() + result = await hass.config_entries.flow.async_configure(result["flow_id"]) + + assert result["type"] is FlowResultType.CREATE_ENTRY + + assert result["result"].unique_id == "SA110405124500W00BS9" + + # The device is set up with the API key it handed out. + assert config_flow.LaMetricDevice.call_args.kwargs["api_key"] == ( + "mock-local-api-key" + ) + mock_lametric_local_auth.challenge.assert_called_once_with( + challenge_id="mock-challenge" + ) + mock_lametric_local_auth.api_key.assert_called_once_with( + challenge_id="mock-challenge" + ) + assert len(mock_lametric.notify.mock_calls) == 1 + + +@pytest.mark.parametrize( + ("side_effect", "error"), + [ + (LaMetricUnsupportedError, "button_not_supported"), + (LaMetricConnectionError, "cannot_connect"), + (LaMetricError, "unknown"), + # Like a URL entered as the host, which demetriek refuses. + (ValueError, "unknown"), + ], +) +@pytest.mark.usefixtures("mock_setup_entry", "mock_lametric") +async def test_press_button_request_errors( + hass: HomeAssistant, + mock_lametric_local_auth: MagicMock, + side_effect: type[Exception], + error: str, +) -> None: + """Test a device that cannot be asked for a button press says why.""" + mock_lametric_local_auth.request_challenge.side_effect = side_effect + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={"next_step_id": "press_button"} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_HOST: "127.0.0.1"} + ) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "press_button" + assert result["errors"] == {"base": error} + + # Once the problem is gone, the same flow still finishes the setup. + mock_lametric_local_auth.request_challenge.side_effect = None + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_HOST: "127.0.0.1"} + ) + await hass.async_block_till_done() + result = await hass.config_entries.flow.async_configure(result["flow_id"]) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["result"].unique_id == "SA110405124500W00BS9" + assert config_flow.LaMetricDevice.call_args.kwargs["api_key"] == ( + "mock-local-api-key" + ) + + +@pytest.mark.usefixtures("mock_setup_entry", "mock_lametric") +async def test_press_button_closed_while_requesting( + hass: HomeAssistant, + mock_lametric_local_auth: MagicMock, +) -> None: + """Test closing the flow while the device answers does not wait for a press.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={"next_step_id": "press_button"} + ) + flow_id = result["flow_id"] + challenge = mock_lametric_local_auth.request_challenge.return_value + + async def close_flow_while_answering() -> AuthChallenge: + hass.config_entries.flow.async_abort(flow_id) + return challenge + + mock_lametric_local_auth.request_challenge.side_effect = close_flow_while_answering + + result = await hass.config_entries.flow.async_configure( + flow_id, user_input={CONF_HOST: "127.0.0.1"} + ) + await hass.async_block_till_done() + + assert result["type"] is FlowResultType.ABORT + + mock_lametric_local_auth.challenge.assert_not_called() + mock_lametric_local_auth.api_key.assert_not_called() + + +@pytest.mark.usefixtures("mock_setup_entry", "mock_lametric") +async def test_press_button_not_in_time( + hass: HomeAssistant, + mock_lametric_local_auth: MagicMock, +) -> None: + """Test the button not pressed in time offers to try again.""" + mock_lametric_local_auth.challenge.return_value = AuthChallenge( + challenge_id="mock-challenge", duration=60, state="expired" + ) + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={"next_step_id": "press_button"} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_HOST: "127.0.0.1"} + ) + await hass.async_block_till_done() + result = await hass.config_entries.flow.async_configure(result["flow_id"]) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "press_button_timeout" + mock_lametric_local_auth.api_key.assert_not_called() + + # Trying again asks the same device for a button press right away. + mock_lametric_local_auth.challenge.return_value = AuthChallenge( + challenge_id="mock-challenge", duration=60, state="resolved" + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={} + ) + + assert result["type"] is FlowResultType.SHOW_PROGRESS + assert result["step_id"] == "press_button_wait" + assert mock_lametric_local_auth.request_challenge.call_count == 2 + + await hass.async_block_till_done() + result = await hass.config_entries.flow.async_configure(result["flow_id"]) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["result"].unique_id == "SA110405124500W00BS9" + assert config_flow.LaMetricDevice.call_args.kwargs["api_key"] == ( + "mock-local-api-key" + ) + + +@pytest.mark.parametrize( + ("side_effect", "error"), + [ + (LaMetricConnectionError, "cannot_connect"), + (LaMetricError, "unknown"), + ], +) +@pytest.mark.usefixtures("mock_setup_entry", "mock_lametric") +async def test_press_button_api_key_errors( + hass: HomeAssistant, + mock_lametric_local_auth: MagicMock, + side_effect: type[Exception], + error: str, +) -> None: + """Test an error getting the API key after the press returns to the form.""" + mock_lametric_local_auth.api_key.side_effect = side_effect + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={"next_step_id": "press_button"} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_HOST: "127.0.0.1"} + ) + await hass.async_block_till_done() + result = await hass.config_entries.flow.async_configure(result["flow_id"]) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "press_button" + assert result["errors"] == {"base": error} + + # Once the problem is gone, the same flow still finishes the setup. + mock_lametric_local_auth.api_key.side_effect = None + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_HOST: "127.0.0.1"} + ) + await hass.async_block_till_done() + result = await hass.config_entries.flow.async_configure(result["flow_id"]) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["result"].unique_id == "SA110405124500W00BS9" + assert config_flow.LaMetricDevice.call_args.kwargs["api_key"] == ( + "mock-local-api-key" + ) + + +@pytest.mark.parametrize( + ("side_effect", "error"), + [ + (LaMetricConnectionError, "cannot_connect"), + (RuntimeError, "unknown"), + ], +) +@pytest.mark.usefixtures("mock_setup_entry") +async def test_press_button_setup_errors( + hass: HomeAssistant, + mock_lametric: MagicMock, + mock_lametric_local_auth: MagicMock, + side_effect: type[Exception], + error: str, +) -> None: + """Test an error setting up the device with its key returns to the form.""" + mock_lametric.device.side_effect = side_effect + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={"next_step_id": "press_button"} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_HOST: "127.0.0.1"} + ) + await hass.async_block_till_done() + result = await hass.config_entries.flow.async_configure(result["flow_id"]) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "press_button" + assert result["errors"] == {"base": error} + + # Once the problem is gone, the same flow still finishes the setup. + mock_lametric.device.side_effect = None + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_HOST: "127.0.0.1"} + ) + await hass.async_block_till_done() + result = await hass.config_entries.flow.async_configure(result["flow_id"]) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["result"].unique_id == "SA110405124500W00BS9" + assert config_flow.LaMetricDevice.call_args.kwargs["api_key"] == ( + "mock-local-api-key" + ) + + +@pytest.mark.usefixtures("mock_setup_entry", "mock_lametric") +async def test_press_button_discovered( + hass: HomeAssistant, + mock_lametric_local_auth: MagicMock, +) -> None: + """Test a discovered device with the button press goes straight to it.""" + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_SSDP}, data=SSDP_DISCOVERY_INFO + ) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "press_button" + schema = result["data_schema"].schema + host_key = next(key for key in schema if key == CONF_HOST) + assert host_key.description == {"suggested_value": "127.0.0.1"} + + # Checking for the button press is no reason to ask for one. + mock_lametric_local_auth.request_challenge.assert_not_called() + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_HOST: "127.0.0.1"} + ) + await hass.async_block_till_done() + result = await hass.config_entries.flow.async_configure(result["flow_id"]) + + assert result["type"] is FlowResultType.CREATE_ENTRY + assert result["result"].unique_id == "SA110405124500W00BS9" + assert config_flow.LaMetricDevice.call_args.kwargs["api_key"] == ( + "mock-local-api-key" + ) + + +@pytest.mark.parametrize( + ("supported", "menu_options"), + [ + ({"return_value": False}, ["pick_implementation", "manual_entry"]), + ( + {"side_effect": LaMetricConnectionError}, + ["press_button", "pick_implementation", "manual_entry"], + ), + ], + ids=["not_supported", "cannot_tell"], +) +@pytest.mark.usefixtures("mock_setup_entry", "mock_lametric") +async def test_press_button_discovered_menu( + hass: HomeAssistant, + mock_lametric_local_auth: MagicMock, + supported: dict[str, Any], + menu_options: list[str], +) -> None: + """Test a discovered device only offers the button press when it can.""" + mock_lametric_local_auth.supported.configure_mock(**supported) + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_SSDP}, data=SSDP_DISCOVERY_INFO + ) + + assert result["type"] is FlowResultType.MENU + assert result["step_id"] == "choice_enter_manual_or_fetch_cloud" + assert result["menu_options"] == menu_options + + +@pytest.mark.usefixtures("mock_setup_entry") +async def test_reauth_press_button( + hass: HomeAssistant, + mock_lametric: MagicMock, + mock_lametric_local_auth: MagicMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test reauthenticating with a press on the button.""" + mock_config_entry.add_to_hass(hass) + + result = await mock_config_entry.start_reauth_flow(hass) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "press_button" + + schema = result["data_schema"].schema + host_key = next(key for key in schema if key == CONF_HOST) + assert host_key.description == {"suggested_value": "127.0.0.2"} + + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_HOST: "127.0.0.2"} + ) + await hass.async_block_till_done() + result = await hass.config_entries.flow.async_configure(result["flow_id"]) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "reauth_successful" + assert config_flow.LaMetricDevice.call_args.kwargs["api_key"] == ( + "mock-local-api-key" + ) + + +@pytest.mark.usefixtures( + "mock_setup_entry", "mock_lametric", "mock_lametric_local_auth" +) +async def test_press_button_existing_device( + hass: HomeAssistant, + mock_config_entry: MockConfigEntry, +) -> None: + """Test pressing the button for a device that is set up already.""" + mock_config_entry.add_to_hass(hass) + + result = await hass.config_entries.flow.async_init( + DOMAIN, context={"source": SOURCE_USER} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={"next_step_id": "press_button"} + ) + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_HOST: "127.0.0.1"} + ) + await hass.async_block_till_done() + result = await hass.config_entries.flow.async_configure(result["flow_id"]) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "already_configured" + + +@pytest.mark.usefixtures("mock_setup_entry", "mock_lametric_local_auth") +async def test_reauth_press_button_other_device( + hass: HomeAssistant, + mock_lametric: MagicMock, + mock_config_entry: MockConfigEntry, +) -> None: + """Test reauthenticating against another device is refused. + + The host can be changed when pressing the button, so it could point at + another LaMetric device than the one set up. + """ + mock_config_entry.add_to_hass(hass) + mock_lametric.device.return_value.serial_number = "SA000000000000000000" + + result = await mock_config_entry.start_reauth_flow(hass) + + assert result["type"] is FlowResultType.FORM + assert result["step_id"] == "press_button" + result = await hass.config_entries.flow.async_configure( + result["flow_id"], user_input={CONF_HOST: "127.0.0.42"} + ) + await hass.async_block_till_done() + result = await hass.config_entries.flow.async_configure(result["flow_id"]) + + assert result["type"] is FlowResultType.ABORT + assert result["reason"] == "unique_id_mismatch" + assert mock_config_entry.data[CONF_HOST] == "127.0.0.2" + assert mock_config_entry.data[CONF_API_KEY] == "mock-from-fixture" + mock_lametric.notify.assert_not_called() diff --git a/tests/components/lametric/test_init.py b/tests/components/lametric/test_init.py index 9113eb45575f..7acbe47ef036 100644 --- a/tests/components/lametric/test_init.py +++ b/tests/components/lametric/test_init.py @@ -85,6 +85,7 @@ async def test_config_entry_authentication_failed( hass: HomeAssistant, mock_config_entry: MockConfigEntry, mock_lametric: MagicMock, + mock_lametric_local_auth: MagicMock, ) -> None: """Test trigger reauthentication flow.""" mock_config_entry.add_to_hass(hass) @@ -100,7 +101,8 @@ async def test_config_entry_authentication_failed( assert len(flows) == 1 flow = flows[0] - assert flow["step_id"] == "choice_enter_manual_or_fetch_cloud" + # The device supports the button press, so the flow starts right there. + assert flow["step_id"] == "press_button" assert flow.get("handler") == DOMAIN assert "context" in flow