MELCloud Home add reauth flow (#173502)

This commit is contained in:
Erwin Douna
2026-06-18 16:59:41 +02:00
committed by GitHub
parent f8ce98ed39
commit ffd08265bd
6 changed files with 176 additions and 9 deletions
@@ -1,5 +1,6 @@
"""Config flow for MELCloud Home."""
from collections.abc import Mapping
import logging
from typing import Any
@@ -94,3 +95,36 @@ class MelCloudHomeConfigFlow(ConfigFlow, domain=DOMAIN):
data_schema=STEP_USER_DATA_SCHEMA,
errors=errors,
)
async def async_step_reauth(
self, entry_data: Mapping[str, Any]
) -> ConfigFlowResult:
"""Perform reauth when MELCloud Home API authentication fails."""
return await self.async_step_reauth_confirm()
async def async_step_reauth_confirm(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle reauth: ask for new API token and validate."""
errors: dict[str, str] = {}
reauth_entry = self._get_reauth_entry()
if user_input is not None:
errors, user_id = await self._async_validate_credentials(
user_input[CONF_EMAIL], user_input[CONF_PASSWORD]
)
if not errors:
await self.async_set_unique_id(user_id)
self._abort_if_unique_id_mismatch()
return self.async_update_reload_and_abort(
reauth_entry,
data_updates={
CONF_EMAIL: user_input[CONF_EMAIL],
CONF_PASSWORD: user_input[CONF_PASSWORD],
},
)
return self.async_show_form(
step_id="reauth_confirm",
data_schema=STEP_USER_DATA_SCHEMA,
errors=errors,
)
@@ -13,6 +13,7 @@ from aiomelcloudhome.exceptions import (
from homeassistant.config_entries import ConfigEntry
from homeassistant.core import HomeAssistant, callback
from homeassistant.exceptions import ConfigEntryAuthFailed
from homeassistant.helpers.update_coordinator import DataUpdateCoordinator, UpdateFailed
from .const import DOMAIN
@@ -87,7 +88,7 @@ class MelCloudHomeCoordinator(DataUpdateCoordinator[UserContext]):
try:
data = await self.client.get_context()
except MelCloudHomeAuthenticationError as err:
raise UpdateFailed(
raise ConfigEntryAuthFailed(
translation_domain=DOMAIN,
translation_key="invalid_auth",
) from err
@@ -1,7 +1,9 @@
{
"config": {
"abort": {
"already_configured": "[%key:common::config_flow::abort::already_configured_account%]"
"already_configured": "[%key:common::config_flow::abort::already_configured_account%]",
"reauth_successful": "[%key:common::config_flow::abort::reauth_successful%]",
"unique_id_mismatch": "The login details correspond to a different account. Please re-authenticate to the previously configured account."
},
"error": {
"cannot_connect": "[%key:common::config_flow::error::cannot_connect%]",
@@ -10,6 +12,18 @@
"unknown": "[%key:common::config_flow::error::unknown%]"
},
"step": {
"reauth_confirm": {
"data": {
"email": "[%key:common::config_flow::data::email%]",
"password": "[%key:common::config_flow::data::password%]"
},
"data_description": {
"email": "[%key:component::melcloud_home::config::step::user::data_description::email%]",
"password": "[%key:component::melcloud_home::config::step::user::data_description::password%]"
},
"description": "The credentials for your MELCloud Home account are no longer valid. Enter your current credentials to reauthenticate.",
"title": "[%key:common::config_flow::title::reauth%]"
},
"user": {
"data": {
"email": "[%key:common::config_flow::data::email%]",
@@ -16,6 +16,20 @@ MOCK_USER_INPUT = {
CONF_PASSWORD: "thatyouevenlookedheretoseethepassword",
}
MOCK_REAUTH_INPUT = {
CONF_EMAIL: "new_user@example.com",
CONF_PASSWORD: "newpassword",
}
@pytest.fixture
def mock_setup_entry() -> Generator[AsyncMock]:
"""Override async_setup_entry."""
with patch(
"homeassistant.components.melcloud_home.async_setup_entry", return_value=True
) as mock_setup_entry:
yield mock_setup_entry
@pytest.fixture
def mock_melcloud_client() -> Generator[AsyncMock]:
@@ -1,6 +1,6 @@
"""Test the MELCloud Home config flow."""
from unittest.mock import AsyncMock
from unittest.mock import AsyncMock, MagicMock
from aiomelcloudhome.exceptions import (
MelCloudHomeAuthenticationError,
@@ -15,7 +15,7 @@ from homeassistant.const import CONF_EMAIL
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
from .conftest import MOCK_USER_INPUT
from .conftest import MOCK_REAUTH_INPUT, MOCK_USER_INPUT
from tests.common import MockConfigEntry
@@ -106,3 +106,106 @@ async def test_duplicate_entry(
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
async def test_full_flow_reauth(
hass: HomeAssistant,
mock_melcloud_client: AsyncMock,
mock_setup_entry: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the full reauth flow."""
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"] == "reauth_confirm"
result = await hass.config_entries.flow.async_configure(result["flow_id"])
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=MOCK_REAUTH_INPUT,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert mock_config_entry.data == MOCK_REAUTH_INPUT
async def test_reauth_flow_wrong_account(
hass: HomeAssistant,
mock_melcloud_client: AsyncMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test the reauth flow aborts when a different account is used."""
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"] == "reauth_confirm"
mock_melcloud_client.get_context.return_value = (
mock_melcloud_client.get_context.return_value.model_copy(
update={"id": "user-uuid-2"}
)
)
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=MOCK_REAUTH_INPUT,
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "unique_id_mismatch"
assert mock_config_entry.data == MOCK_USER_INPUT
assert mock_config_entry.unique_id == "user-uuid-1"
@pytest.mark.parametrize(
("exception", "reason"),
[
pytest.param(MelCloudHomeAuthenticationError("bad creds"), "invalid_auth"),
pytest.param(MelCloudHomeConnectionError("offline"), "cannot_connect"),
pytest.param(MelCloudHomeTimeoutError("timed out"), "timeout_connect"),
pytest.param(Exception("unexpected"), "unknown"),
],
)
async def test_reauth_flow_exceptions(
hass: HomeAssistant,
mock_melcloud_client: AsyncMock,
mock_setup_entry: MagicMock,
mock_config_entry: MockConfigEntry,
exception: Exception,
reason: str,
) -> None:
"""Test we handle all exceptions in the reauth flow."""
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"] == "reauth_confirm"
mock_melcloud_client.get_context.side_effect = exception
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=MOCK_REAUTH_INPUT,
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": reason}
mock_melcloud_client.get_context.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
user_input=MOCK_REAUTH_INPUT,
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert mock_config_entry.data == MOCK_REAUTH_INPUT
+6 -5
View File
@@ -35,11 +35,11 @@ async def test_entry_setup_unload(
@pytest.mark.parametrize(
"exception",
("exception", "setup_state"),
[
MelCloudHomeAuthenticationError("bad creds"),
MelCloudHomeConnectionError("cannot connect"),
MelCloudHomeTimeoutError("timeout"),
(MelCloudHomeAuthenticationError("bad creds"), ConfigEntryState.SETUP_ERROR),
(MelCloudHomeConnectionError("cannot connect"), ConfigEntryState.SETUP_RETRY),
(MelCloudHomeTimeoutError("timeout"), ConfigEntryState.SETUP_RETRY),
],
)
async def test_entry_setup_retry_on_update_failure(
@@ -47,6 +47,7 @@ async def test_entry_setup_retry_on_update_failure(
mock_config_entry: MockConfigEntry,
mock_melcloud_client: AsyncMock,
exception: Exception,
setup_state: ConfigEntryState,
) -> None:
"""Test setup retries when initial coordinator refresh fails."""
mock_melcloud_client.get_context.side_effect = exception
@@ -55,7 +56,7 @@ async def test_entry_setup_retry_on_update_failure(
await hass.config_entries.async_setup(mock_config_entry.entry_id)
await hass.async_block_till_done()
assert mock_config_entry.state is ConfigEntryState.SETUP_RETRY
assert mock_config_entry.state is setup_state
async def test_new_ata_unit_callback(