Add reauth flow to kostal_plenticore (#185841)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
G Johansson
2026-10-11 21:33:38 -04:00
committed by GitHub
co-authored by Claude Opus 5.5
parent 0861a3279a
commit 3d96173bb4
5 changed files with 182 additions and 4 deletions
@@ -6,7 +6,7 @@ from pykoplenti import ApiException
from homeassistant.const import Platform
from homeassistant.core import HomeAssistant
from homeassistant.exceptions import ConfigEntryError
from homeassistant.exceptions import ConfigEntryAuthFailed
from .const import DOMAIN
from .coordinator import Plenticore, PlenticoreConfigEntry
@@ -21,7 +21,7 @@ async def async_setup_entry(hass: HomeAssistant, entry: PlenticoreConfigEntry) -
plenticore = Plenticore(hass, entry)
if not await plenticore.async_setup():
raise ConfigEntryError(
raise ConfigEntryAuthFailed(
translation_domain=DOMAIN,
translation_key="authentication_failed",
translation_placeholders={"host": plenticore.host},
@@ -1,5 +1,6 @@
"""Config flow for Kostal Plenticore Solar Inverter integration."""
from collections.abc import Mapping
import logging
from typing import Any, override
@@ -24,6 +25,12 @@ DATA_SCHEMA = probatio.Schema(
probatio.Optional(CONF_SERVICE_CODE): str,
}
)
REAUTH_SCHEMA = probatio.Schema(
{
probatio.Required(probatio.Secret(CONF_PASSWORD)): str,
probatio.Optional(CONF_SERVICE_CODE): str,
}
)
async def test_connection(hass: HomeAssistant, data) -> str:
@@ -101,3 +108,41 @@ class KostalPlenticoreConfigFlow(ConfigFlow, domain=DOMAIN):
return self.async_show_form(
step_id="reconfigure", data_schema=DATA_SCHEMA, errors=errors
)
async def async_step_reauth(
self, entry_data: Mapping[str, Any]
) -> ConfigFlowResult:
"""Handle reauthentication."""
return await self.async_step_reauth_confirm()
async def async_step_reauth_confirm(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Confirm reauthentication with a new password."""
errors = {}
reauth_entry = self._get_reauth_entry()
if user_input is not None:
data = {CONF_HOST: reauth_entry.data[CONF_HOST], **user_input}
try:
await test_connection(self.hass, data)
except AuthenticationException as ex:
errors[CONF_PASSWORD] = "invalid_auth"
_LOGGER.error("Error response: %s", ex)
except ClientError, TimeoutError:
errors[CONF_BASE] = "cannot_connect"
except Exception:
_LOGGER.exception("Unexpected exception")
errors[CONF_BASE] = "unknown"
else:
return self.async_update_reload_and_abort(reauth_entry, data=data)
return self.async_show_form(
step_id="reauth_confirm",
data_schema=self.add_suggested_values_to_schema(
REAUTH_SCHEMA,
{CONF_SERVICE_CODE: reauth_entry.data.get(CONF_SERVICE_CODE)},
),
description_placeholders={CONF_HOST: reauth_entry.data[CONF_HOST]},
errors=errors,
)
@@ -9,6 +9,14 @@
"unknown": "[%key:common::config_flow::error::unknown%]"
},
"step": {
"reauth_confirm": {
"data": {
"password": "[%key:common::config_flow::data::password%]",
"service_code": "[%key:component::kostal_plenticore::config::step::user::data::service_code%]"
},
"description": "The credentials for the inverter at {host} are no longer valid. Please enter the new credentials.",
"title": "[%key:common::config_flow::title::reauth%]"
},
"reconfigure": {
"data": {
"host": "[%key:common::config_flow::data::host%]",
@@ -8,7 +8,7 @@ from pykoplenti import ApiClient, AuthenticationException, SettingsData
import pytest
from homeassistant import config_entries
from homeassistant.components.kostal_plenticore.const import DOMAIN
from homeassistant.components.kostal_plenticore.const import CONF_SERVICE_CODE, DOMAIN
from homeassistant.const import CONF_HOST, CONF_PASSWORD
from homeassistant.core import HomeAssistant
from homeassistant.data_entry_flow import FlowResultType
@@ -670,3 +670,123 @@ async def test_reconfigure_already_configured(
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "already_configured"
@pytest.mark.parametrize(
("user_input", "expected_data"),
[
pytest.param(
{CONF_PASSWORD: "new-password", CONF_SERVICE_CODE: "67890"},
{
CONF_HOST: "192.168.1.2",
CONF_PASSWORD: "new-password",
CONF_SERVICE_CODE: "67890",
},
id="with_service_code",
),
pytest.param(
{CONF_PASSWORD: "new-password"},
{CONF_HOST: "192.168.1.2", CONF_PASSWORD: "new-password"},
id="without_service_code",
),
],
)
async def test_reauth(
hass: HomeAssistant,
mock_apiclient_class: type[ApiClient],
mock_apiclient: ApiClient,
mock_installer_config_entry: MockConfigEntry,
user_input: dict[str, str],
expected_data: dict[str, str],
) -> None:
"""Test the reauth flow updates the credentials."""
mock_installer_config_entry.add_to_hass(hass)
result = await mock_installer_config_entry.start_reauth_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reauth_confirm"
assert result["errors"] == {}
mock_apiclient.login = AsyncMock()
mock_apiclient.get_settings = AsyncMock(
return_value={
"scb:network": [
SettingsData(
min="1",
max="63",
default=None,
access="readwrite",
unit=None,
id="Hostname",
type="string",
),
]
}
)
mock_apiclient.get_setting_values = AsyncMock(
return_value={"scb:network": {"Hostname": "scb"}}
)
with patch(
"homeassistant.components.kostal_plenticore.async_setup_entry",
return_value=True,
):
result = await hass.config_entries.flow.async_configure(
result["flow_id"], user_input
)
await hass.async_block_till_done()
mock_apiclient_class.assert_called_once_with(ANY, "192.168.1.2")
mock_apiclient.login.assert_called_once_with(
"new-password", service_code=user_input.get(CONF_SERVICE_CODE)
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert mock_installer_config_entry.data == expected_data
@pytest.mark.parametrize(
("side_effect", "errors"),
[
pytest.param(
AuthenticationException(404, "invalid user"),
{CONF_PASSWORD: "invalid_auth"},
id="invalid_auth",
),
pytest.param(TimeoutError(), {"base": "cannot_connect"}, id="cannot_connect"),
pytest.param(Exception(), {"base": "unknown"}, id="unknown"),
],
)
async def test_reauth_errors(
hass: HomeAssistant,
mock_config_entry: MockConfigEntry,
side_effect: Exception,
errors: dict[str, str],
) -> None:
"""Test we handle errors during reauth and can recover."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reauth_flow(hass)
with patch(
"homeassistant.components.kostal_plenticore.config_flow.ApiClient"
) as mock_api_class:
mock_api_ctx = MagicMock()
mock_api_ctx.login = AsyncMock(side_effect=side_effect)
mock_api_class.return_value.__aenter__.return_value = mock_api_ctx
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_PASSWORD: "wrong-password"}
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == errors
with _patch_apiclient_success():
result = await hass.config_entries.flow.async_configure(
result["flow_id"], {CONF_PASSWORD: "new-password"}
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reauth_successful"
assert mock_config_entry.data[CONF_PASSWORD] == "new-password"
@@ -4,7 +4,7 @@ from unittest.mock import MagicMock
from pykoplenti import AuthenticationException
from homeassistant.config_entries import ConfigEntryState
from homeassistant.config_entries import SOURCE_REAUTH, ConfigEntryState
from homeassistant.core import HomeAssistant
from tests.common import MockConfigEntry
@@ -26,3 +26,8 @@ async def test_setup_authentication_failed(
assert mock_config_entry.state is ConfigEntryState.SETUP_ERROR
assert mock_config_entry.reason == "Authentication failed connecting to 192.168.1.2"
flows = hass.config_entries.flow.async_progress()
assert len(flows) == 1
assert flows[0]["context"]["source"] == SOURCE_REAUTH
assert flows[0]["context"]["entry_id"] == mock_config_entry.entry_id