Skip to content

Commit

Permalink
Add reconfiguration flow in HomeWizard (home-assistant#131535)
Browse files Browse the repository at this point in the history
  • Loading branch information
DCSBL authored Nov 26, 2024
1 parent 7ba0f54 commit a252faf
Show file tree
Hide file tree
Showing 4 changed files with 183 additions and 6 deletions.
46 changes: 42 additions & 4 deletions homeassistant/components/homewizard/config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,15 @@
from homewizard_energy import HomeWizardEnergyV1
from homewizard_energy.errors import DisabledError, RequestError, UnsupportedError
from homewizard_energy.v1.models import Device
from voluptuous import Required, Schema
import voluptuous as vol

from homeassistant.components import onboarding, zeroconf
from homeassistant.components.dhcp import DhcpServiceInfo
from homeassistant.config_entries import ConfigFlow, ConfigFlowResult
from homeassistant.const import CONF_IP_ADDRESS, CONF_PATH
from homeassistant.data_entry_flow import AbortFlow
from homeassistant.exceptions import HomeAssistantError
from homeassistant.helpers.selector import TextSelector

from .const import (
CONF_API_ENABLED,
Expand Down Expand Up @@ -69,11 +70,11 @@ async def async_step_user(
user_input = user_input or {}
return self.async_show_form(
step_id="user",
data_schema=Schema(
data_schema=vol.Schema(
{
Required(
vol.Required(
CONF_IP_ADDRESS, default=user_input.get(CONF_IP_ADDRESS)
): str,
): TextSelector(),
}
),
errors=errors,
Expand Down Expand Up @@ -197,6 +198,43 @@ async def async_step_reauth_confirm(

return self.async_show_form(step_id="reauth_confirm", errors=errors)

async def async_step_reconfigure(
self, user_input: dict[str, Any] | None = None
) -> ConfigFlowResult:
"""Handle reconfiguration of the integration."""
errors: dict[str, str] = {}
if user_input:
try:
device_info = await self._async_try_connect(user_input[CONF_IP_ADDRESS])
except RecoverableError as ex:
_LOGGER.error(ex)
errors = {"base": ex.error_code}
else:
await self.async_set_unique_id(
f"{device_info.product_type}_{device_info.serial}"
)
self._abort_if_unique_id_mismatch(reason="wrong_device")
return self.async_update_reload_and_abort(
self._get_reconfigure_entry(),
data_updates=user_input,
)
reconfigure_entry = self._get_reconfigure_entry()
return self.async_show_form(
step_id="reconfigure",
data_schema=vol.Schema(
{
vol.Required(
CONF_IP_ADDRESS,
default=reconfigure_entry.data.get(CONF_IP_ADDRESS),
): TextSelector(),
}
),
description_placeholders={
"title": reconfigure_entry.title,
},
errors=errors,
)

@staticmethod
async def _async_try_connect(ip_address: str) -> Device:
"""Try to connect.
Expand Down
2 changes: 1 addition & 1 deletion homeassistant/components/homewizard/quality_scale.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,7 @@ rules:
entity-translations: done
exception-translations: done
icon-translations: done
reconfiguration-flow: todo
reconfiguration-flow: done
repair-issues:
status: exempt
comment: |
Expand Down
13 changes: 12 additions & 1 deletion homeassistant/components/homewizard/strings.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,15 @@
},
"reauth_confirm": {
"description": "The local API is disabled. Go to the HomeWizard Energy app and enable the API in the device settings."
},
"reconfigure": {
"description": "Update configuration for {title}.",
"data": {
"ip_address": "[%key:common::config_flow::data::ip%]"
},
"data_description": {
"ip_address": "[%key:component::homewizard::config::step::user::data_description::ip_address%]"
}
}
},
"error": {
Expand All @@ -29,7 +38,9 @@
"device_not_supported": "This device is not supported",
"unknown_error": "[%key:common::config_flow::error::unknown%]",
"unsupported_api_version": "Detected unsupported API version",
"reauth_successful": "Enabling API was successful"
"reauth_successful": "Enabling API was successful",
"reconfigure_successful": "[%key:common::config_flow::abort::reconfigure_successful%]",
"wrong_device": "The configured device is not the same found on this IP address."
}
},
"entity": {
Expand Down
128 changes: 128 additions & 0 deletions tests/components/homewizard/test_config_flow.py
Original file line number Diff line number Diff line change
Expand Up @@ -480,3 +480,131 @@ async def test_reauth_error(

assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": "api_not_enabled"}


async def test_reconfigure(
hass: HomeAssistant,
mock_homewizardenergy: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test reconfiguration."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
assert result["errors"] == {}

# original entry
assert mock_config_entry.data[CONF_IP_ADDRESS] == "127.0.0.1"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_IP_ADDRESS: "1.0.0.127",
},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"

# changed entry
assert mock_config_entry.data[CONF_IP_ADDRESS] == "1.0.0.127"


async def test_reconfigure_nochange(
hass: HomeAssistant,
mock_homewizardenergy: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test reconfiguration without changing values."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
assert result["errors"] == {}

# original entry
assert mock_config_entry.data[CONF_IP_ADDRESS] == "127.0.0.1"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_IP_ADDRESS: "127.0.0.1",
},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"

# changed entry
assert mock_config_entry.data[CONF_IP_ADDRESS] == "127.0.0.1"


async def test_reconfigure_wrongdevice(
hass: HomeAssistant,
mock_homewizardenergy: MagicMock,
mock_config_entry: MockConfigEntry,
) -> None:
"""Test entering ip of other device and prevent changing it based on serial."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
assert result["errors"] == {}

# simulate different serial number, as if user entered wrong IP
mock_homewizardenergy.device.return_value.serial = "not_5c2fafabcdef"
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_IP_ADDRESS: "1.0.0.127",
},
)
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "wrong_device"

# entry should still be original entry
assert mock_config_entry.data[CONF_IP_ADDRESS] == "127.0.0.1"


@pytest.mark.parametrize(
("exception", "reason"),
[(DisabledError, "api_not_enabled"), (RequestError, "network_error")],
)
async def test_reconfigure_cannot_connect(
hass: HomeAssistant,
mock_homewizardenergy: MagicMock,
mock_config_entry: MockConfigEntry,
exception: Exception,
reason: str,
) -> None:
"""Test reconfiguration fails when not able to connect."""
mock_config_entry.add_to_hass(hass)
result = await mock_config_entry.start_reconfigure_flow(hass)
assert result["type"] is FlowResultType.FORM
assert result["step_id"] == "reconfigure"
assert result["errors"] == {}

mock_homewizardenergy.device.side_effect = exception
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_IP_ADDRESS: "1.0.0.127",
},
)
assert result["type"] is FlowResultType.FORM
assert result["errors"] == {"base": reason}
assert result["data_schema"]({}) == {CONF_IP_ADDRESS: "127.0.0.1"}

# attempt with valid IP should work
mock_homewizardenergy.device.side_effect = None
result = await hass.config_entries.flow.async_configure(
result["flow_id"],
{
CONF_IP_ADDRESS: "1.0.0.127",
},
)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.ABORT
assert result["reason"] == "reconfigure_successful"

# changed entry
assert mock_config_entry.data[CONF_IP_ADDRESS] == "1.0.0.127"

0 comments on commit a252faf

Please sign in to comment.