Compare commits

..

6 Commits

Author SHA1 Message Date
J. Nick Koston
77bf5871cb move tests 2025-10-13 12:55:55 -10:00
J. Nick Koston
4a032e5831 cleanup 2025-10-13 12:49:49 -10:00
J. Nick Koston
b2ed6895f7 cleanup 2025-10-13 12:48:53 -10:00
J. Nick Koston
efc1df4945 Update homeassistant/data_entry_flow.py
Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-10-13 12:36:37 -10:00
J. Nick Koston
b69ed592bb move it to bottom level 2025-10-13 12:00:51 -10:00
J. Nick Koston
5a168662b2 Allow passing next_flow for aborted flows 2025-10-13 11:50:16 -10:00
15 changed files with 251 additions and 103 deletions

View File

@@ -125,8 +125,9 @@ class IcloudAccount:
return
try:
api_devices = self.api.devices
# Gets device owners infos
user_info = self.api.devices.user_info
user_info = api_devices.response["userInfo"]
except (
PyiCloudServiceNotActivatedException,
PyiCloudNoDevicesException,

View File

@@ -6,5 +6,5 @@
"documentation": "https://www.home-assistant.io/integrations/icloud",
"iot_class": "cloud_polling",
"loggers": ["keyrings.alt", "pyicloud"],
"requirements": ["pyicloud==2.1.0"]
"requirements": ["pyicloud==2.0.3"]
}

View File

@@ -84,11 +84,11 @@ class _KnxBinarySensor(BinarySensorEntity, RestoreEntity):
async def async_added_to_hass(self) -> None:
"""Restore last state."""
await super().async_added_to_hass()
if (
last_state := await self.async_get_last_state()
) and last_state.state not in (STATE_UNKNOWN, STATE_UNAVAILABLE):
self._device.remote_value.update_value(last_state.state == STATE_ON)
await super().async_added_to_hass()
@property
def is_on(self) -> bool:

View File

@@ -6,15 +6,15 @@ from collections.abc import Callable
from dataclasses import dataclass
from datetime import datetime, timedelta
from functools import partial
from typing import Any
from xknx import XKNX
from xknx.core.connection_state import XknxConnectionState, XknxConnectionType
from xknx.devices import Device as XknxDevice, Sensor as XknxSensor
from xknx.devices import Sensor as XknxSensor
from homeassistant import config_entries
from homeassistant.components.sensor import (
CONF_STATE_CLASS,
RestoreSensor,
SensorDeviceClass,
SensorEntity,
SensorEntityDescription,
@@ -25,8 +25,6 @@ from homeassistant.const import (
CONF_ENTITY_CATEGORY,
CONF_NAME,
CONF_TYPE,
STATE_UNAVAILABLE,
STATE_UNKNOWN,
EntityCategory,
Platform,
)
@@ -143,7 +141,7 @@ def _create_sensor(xknx: XKNX, config: ConfigType) -> XknxSensor:
)
class KNXSensor(KnxYamlEntity, RestoreSensor):
class KNXSensor(KnxYamlEntity, SensorEntity):
"""Representation of a KNX sensor."""
_device: XknxSensor
@@ -166,30 +164,20 @@ class KNXSensor(KnxYamlEntity, RestoreSensor):
self._attr_unique_id = str(self._device.sensor_value.group_address_state)
self._attr_native_unit_of_measurement = self._device.unit_of_measurement()
self._attr_state_class = config.get(CONF_STATE_CLASS)
self._attr_extra_state_attributes = {}
async def async_added_to_hass(self) -> None:
"""Restore last state."""
if (
(last_state := await self.async_get_last_state())
and last_state.state not in (STATE_UNKNOWN, STATE_UNAVAILABLE)
and (
(last_sensor_data := await self.async_get_last_sensor_data())
is not None
)
):
self._attr_native_value = last_sensor_data.native_value
self._attr_extra_state_attributes.update(last_state.attributes)
await super().async_added_to_hass()
@property
def native_value(self) -> StateType:
"""Return the state of the sensor."""
return self._device.resolve_state()
def after_update_callback(self, device: XknxDevice) -> None:
"""Call after device was updated."""
self._attr_native_value = self._device.resolve_state()
if telegram := self._device.last_telegram:
self._attr_extra_state_attributes[ATTR_SOURCE] = str(
telegram.source_address
)
super().after_update_callback(device)
@property
def extra_state_attributes(self) -> dict[str, Any] | None:
"""Return device specific state attributes."""
attr: dict[str, Any] = {}
if self._device.last_telegram is not None:
attr[ATTR_SOURCE] = str(self._device.last_telegram.source_address)
return attr
class KNXSystemSensor(SensorEntity):

View File

@@ -5,7 +5,6 @@
"config_flow": true,
"dependencies": ["application_credentials"],
"documentation": "https://www.home-assistant.io/integrations/miele",
"integration_type": "hub",
"iot_class": "cloud_push",
"loggers": ["pymiele"],
"quality_scale": "platinum",

View File

@@ -65,7 +65,7 @@ def register_services() -> None:
"""Register snapcast services."""
platform = entity_platform.async_get_current_platform()
platform.async_register_entity_service(SERVICE_SNAPSHOT, None, "async_snapshot")
platform.async_register_entity_service(SERVICE_SNAPSHOT, None, "snapshot")
platform.async_register_entity_service(SERVICE_RESTORE, None, "async_restore")
platform.async_register_entity_service(
SERVICE_JOIN, {vol.Required(ATTR_MASTER): cv.entity_id}, "async_join"
@@ -250,7 +250,7 @@ class SnapcastBaseDevice(SnapcastCoordinatorEntity, MediaPlayerEntity):
await self._device.set_volume(round(volume * 100))
self.async_write_ha_state()
async def async_snapshot(self) -> None:
def snapshot(self) -> None:
"""Snapshot the group state."""
self._device.snapshot()
@@ -428,12 +428,12 @@ class SnapcastGroupDevice(SnapcastBaseDevice):
await super().async_set_volume_level(volume)
async def async_snapshot(self) -> None:
def snapshot(self) -> None:
"""Snapshot the group state."""
# Groups are deprecated, create an issue when used
self._async_create_group_deprecation_issue()
await super().async_snapshot()
super().snapshot()
async def async_restore(self) -> None:
"""Restore the group state."""

View File

@@ -5,7 +5,6 @@
"config_flow": true,
"dependencies": ["assist_pipeline", "assist_satellite", "intent", "network"],
"documentation": "https://www.home-assistant.io/integrations/voip",
"integration_type": "hub",
"iot_class": "local_push",
"loggers": ["voip_utils"],
"quality_scale": "internal",

View File

@@ -3168,6 +3168,37 @@ class ConfigFlow(ConfigEntryBaseFlow):
"""Handle a flow initialized by Zeroconf discovery."""
return await self._async_step_discovery_without_unique_id()
def _async_set_next_flow_if_valid(
self,
result: ConfigFlowResult,
next_flow: tuple[FlowType, str] | None,
) -> None:
"""Validate and set next_flow in result if provided."""
if next_flow is None:
return
flow_type, flow_id = next_flow
if flow_type != FlowType.CONFIG_FLOW:
raise HomeAssistantError("Invalid next_flow type")
# Raises UnknownFlow if the flow does not exist.
self.hass.config_entries.flow.async_get(flow_id)
result["next_flow"] = next_flow
@callback
def async_abort(
self,
*,
reason: str,
description_placeholders: Mapping[str, str] | None = None,
next_flow: tuple[FlowType, str] | None = None,
) -> ConfigFlowResult:
"""Abort the config flow."""
result = super().async_abort(
reason=reason,
description_placeholders=description_placeholders,
)
self._async_set_next_flow_if_valid(result, next_flow)
return result
@callback
def async_create_entry( # type: ignore[override]
self,
@@ -3197,13 +3228,7 @@ class ConfigFlow(ConfigEntryBaseFlow):
)
result["minor_version"] = self.MINOR_VERSION
if next_flow is not None:
flow_type, flow_id = next_flow
if flow_type != FlowType.CONFIG_FLOW:
raise HomeAssistantError("Invalid next_flow type")
# Raises UnknownFlow if the flow does not exist.
self.hass.config_entries.flow.async_get(flow_id)
result["next_flow"] = next_flow
self._async_set_next_flow_if_valid(result, next_flow)
result["options"] = options or {}
result["subentries"] = subentries or ()
result["version"] = self.VERSION

2
requirements_all.txt generated
View File

@@ -2072,7 +2072,7 @@ pyhomeworks==1.1.2
pyialarm==2.2.0
# homeassistant.components.icloud
pyicloud==2.1.0
pyicloud==2.0.3
# homeassistant.components.insteon
pyinsteon==1.6.3

View File

@@ -1735,7 +1735,7 @@ pyhomeworks==1.1.2
pyialarm==2.2.0
# homeassistant.components.icloud
pyicloud==2.1.0
pyicloud==2.0.3
# homeassistant.components.insteon
pyinsteon==1.6.3

View File

@@ -30,7 +30,7 @@ async def test_full_flow(
) -> None:
"""Check full flow."""
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
"google_assistant_sdk", context={"source": config_entries.SOURCE_USER}
)
state = config_entry_oauth2_flow._encode_jwt(
hass,
@@ -88,14 +88,25 @@ async def test_reauth(
hass_client_no_auth: ClientSessionGenerator,
aioclient_mock: AiohttpClientMocker,
setup_credentials: None,
config_entry: MockConfigEntry,
) -> None:
"""Test the reauthentication case updates the existing config entry."""
config_entry = MockConfigEntry(
domain=DOMAIN,
data={
"token": {
"access_token": "mock-access-token",
},
},
)
config_entry.add_to_hass(hass)
result = await config_entry.start_reauth_flow(hass)
config_entry.async_start_reauth(hass)
await hass.async_block_till_done()
assert result["type"] is FlowResultType.FORM
flows = hass.config_entries.flow.async_progress()
assert len(flows) == 1
result = flows[0]
assert result["step_id"] == "reauth_confirm"
result = await hass.config_entries.flow.async_configure(result["flow_id"], {})
@@ -208,13 +219,20 @@ async def test_single_instance_allowed(
hass_client_no_auth: ClientSessionGenerator,
aioclient_mock: AiohttpClientMocker,
setup_credentials: None,
config_entry: MockConfigEntry,
) -> None:
"""Test case where config flow allows a single test."""
config_entry = MockConfigEntry(
domain=DOMAIN,
data={
"token": {
"access_token": "mock-access-token",
},
},
)
config_entry.add_to_hass(hass)
result = await hass.config_entries.flow.async_init(
DOMAIN, context={"source": config_entries.SOURCE_USER}
"google_assistant_sdk", context={"source": config_entries.SOURCE_USER}
)
assert result.get("type") is FlowResultType.ABORT

View File

@@ -284,8 +284,8 @@ async def test_binary_sensor_reset(
assert state.state is STATE_OFF
async def test_binary_sensor_restore(hass: HomeAssistant, knx: KNXTestKit) -> None:
"""Test restoring KNX binary sensor state."""
async def test_binary_sensor_restore_and_respond(hass: HomeAssistant, knx) -> None:
"""Test restoring KNX binary sensor state and respond to read."""
_ADDRESS = "2/2/2"
fake_state = State("binary_sensor.test", STATE_ON)
mock_restore_cache(hass, (fake_state,))
@@ -312,9 +312,7 @@ async def test_binary_sensor_restore(hass: HomeAssistant, knx: KNXTestKit) -> No
assert state.state is STATE_OFF
async def test_binary_sensor_restore_invert(
hass: HomeAssistant, knx: KNXTestKit
) -> None:
async def test_binary_sensor_restore_invert(hass: HomeAssistant, knx) -> None:
"""Test restoring KNX binary sensor state with invert."""
_ADDRESS = "2/2/2"
fake_state = State("binary_sensor.test", STATE_ON)

View File

@@ -2,22 +2,14 @@
from freezegun.api import FrozenDateTimeFactory
from homeassistant.components.knx.const import (
ATTR_SOURCE,
CONF_STATE_ADDRESS,
CONF_SYNC_STATE,
)
from homeassistant.components.knx.const import CONF_STATE_ADDRESS, CONF_SYNC_STATE
from homeassistant.components.knx.schema import SensorSchema
from homeassistant.const import CONF_NAME, CONF_TYPE, STATE_UNKNOWN
from homeassistant.core import HomeAssistant, State
from homeassistant.core import HomeAssistant
from .conftest import KNXTestKit
from tests.common import (
async_capture_events,
async_fire_time_changed,
mock_restore_cache_with_extra_data,
)
from tests.common import async_capture_events, async_fire_time_changed
async def test_sensor(hass: HomeAssistant, knx: KNXTestKit) -> None:
@@ -51,41 +43,6 @@ async def test_sensor(hass: HomeAssistant, knx: KNXTestKit) -> None:
await knx.assert_no_telegram()
async def test_sensor_restore(hass: HomeAssistant, knx: KNXTestKit) -> None:
"""Test restoring KNX sensor state."""
ADDRESS = "2/2/2"
RAW_FLOAT_21_0 = (0x0C, 0x1A)
RESTORED_STATE = "21.0"
RESTORED_STATE_ATTRIBUTES = {ATTR_SOURCE: knx.INDIVIDUAL_ADDRESS}
fake_state = State(
"sensor.test", "ignored in favour of native_value", RESTORED_STATE_ATTRIBUTES
)
extra_data = {"native_value": RESTORED_STATE, "native_unit_of_measurement": "°C"}
mock_restore_cache_with_extra_data(hass, [(fake_state, extra_data)])
await knx.setup_integration(
{
SensorSchema.PLATFORM: [
{
CONF_NAME: "test",
CONF_STATE_ADDRESS: ADDRESS,
CONF_TYPE: "temperature", # 2 byte float
CONF_SYNC_STATE: False,
},
]
}
)
# restored state - no read-response due to sync_state False
knx.assert_state("sensor.test", RESTORED_STATE, **RESTORED_STATE_ATTRIBUTES)
await knx.assert_telegram_count(0)
# receiving the restored value from restored source does not trigger state_changed event
events = async_capture_events(hass, "state_changed")
await knx.receive_write(ADDRESS, RAW_FLOAT_21_0)
assert not events
async def test_last_reported(
hass: HomeAssistant,
knx: KNXTestKit,

View File

@@ -111,7 +111,7 @@ async def test_switch_state(hass: HomeAssistant, knx: KNXTestKit) -> None:
await knx.assert_telegram_count(0)
async def test_switch_restore_and_respond(hass: HomeAssistant, knx: KNXTestKit) -> None:
async def test_switch_restore_and_respond(hass: HomeAssistant, knx) -> None:
"""Test restoring KNX switch state and respond to read."""
_ADDRESS = "1/1/1"
fake_state = State("switch.test", "on")

View File

@@ -9582,3 +9582,166 @@ async def test_async_update_title_placeholders(hass: HomeAssistant) -> None:
# Verify frontend was notified again
assert len(events) == 2
async def test_config_flow_abort_with_next_flow(hass: HomeAssistant) -> None:
"""Test that ConfigFlow.async_abort() can include next_flow parameter."""
class TargetFlow(config_entries.ConfigFlow):
VERSION = 1
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> config_entries.ConfigFlowResult:
return self.async_show_form(step_id="user")
class TestFlow(config_entries.ConfigFlow):
VERSION = 1
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> config_entries.ConfigFlowResult:
# Create target flow first
target_result = await hass.config_entries.flow.async_init(
"test2", context={"source": config_entries.SOURCE_USER}
)
# Abort with next_flow
return self.async_abort(
reason="provision_successful",
next_flow=(
config_entries.FlowType.CONFIG_FLOW,
target_result["flow_id"],
),
)
mock_integration(hass, MockModule("test"))
mock_platform(hass, "test.config_flow", None)
mock_integration(hass, MockModule("test2"))
mock_platform(hass, "test2.config_flow", None)
with (
mock_config_flow("test", TestFlow),
mock_config_flow("test2", TargetFlow),
):
result = await hass.config_entries.flow.async_init(
"test", context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == data_entry_flow.FlowResultType.ABORT
assert result["reason"] == "provision_successful"
assert "next_flow" in result
assert result["next_flow"][0] == config_entries.FlowType.CONFIG_FLOW
# Verify the target flow exists
hass.config_entries.flow.async_get(result["next_flow"][1])
async def test_config_flow_abort_with_invalid_next_flow_type(
hass: HomeAssistant,
) -> None:
"""Test that ConfigFlow.async_abort() raises error for invalid flow type."""
class TestFlow(config_entries.ConfigFlow):
VERSION = 1
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> config_entries.ConfigFlowResult:
# Try to abort with invalid flow type
return self.async_abort(
reason="test",
next_flow=("invalid_type", "some_flow_id"), # type: ignore[arg-type]
)
mock_integration(hass, MockModule("test"))
mock_platform(hass, "test.config_flow", None)
with (
mock_config_flow("test", TestFlow),
pytest.raises(HomeAssistantError, match="Invalid next_flow type"),
):
await hass.config_entries.flow.async_init(
"test", context={"source": config_entries.SOURCE_USER}
)
async def test_config_flow_abort_with_nonexistent_next_flow(
hass: HomeAssistant,
) -> None:
"""Test that ConfigFlow.async_abort() raises error for nonexistent flow."""
class TestFlow(config_entries.ConfigFlow):
VERSION = 1
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> config_entries.ConfigFlowResult:
# Try to abort with nonexistent flow
return self.async_abort(
reason="test",
next_flow=(config_entries.FlowType.CONFIG_FLOW, "nonexistent_flow_id"),
)
mock_integration(hass, MockModule("test"))
mock_platform(hass, "test.config_flow", None)
with (
mock_config_flow("test", TestFlow),
pytest.raises(data_entry_flow.UnknownFlow),
):
await hass.config_entries.flow.async_init(
"test", context={"source": config_entries.SOURCE_USER}
)
async def test_config_flow_create_entry_with_next_flow(hass: HomeAssistant) -> None:
"""Test that ConfigFlow.async_create_entry() can include next_flow parameter."""
class TargetFlow(config_entries.ConfigFlow):
VERSION = 1
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> config_entries.ConfigFlowResult:
return self.async_show_form(step_id="user")
class TestFlow(config_entries.ConfigFlow):
VERSION = 1
async def async_step_user(
self, user_input: dict[str, Any] | None = None
) -> config_entries.ConfigFlowResult:
# Create target flow first
target_result = await hass.config_entries.flow.async_init(
"test2", context={"source": config_entries.SOURCE_USER}
)
# Create entry with next_flow
return self.async_create_entry(
title="Test Entry",
data={},
next_flow=(
config_entries.FlowType.CONFIG_FLOW,
target_result["flow_id"],
),
)
mock_integration(
hass, MockModule("test", async_setup_entry=AsyncMock(return_value=True))
)
mock_platform(hass, "test.config_flow", None)
mock_integration(hass, MockModule("test2"))
mock_platform(hass, "test2.config_flow", None)
with (
mock_config_flow("test", TestFlow),
mock_config_flow("test2", TargetFlow),
):
result = await hass.config_entries.flow.async_init(
"test", context={"source": config_entries.SOURCE_USER}
)
assert result["type"] == data_entry_flow.FlowResultType.CREATE_ENTRY
assert result["title"] == "Test Entry"
assert "next_flow" in result
assert result["next_flow"][0] == config_entries.FlowType.CONFIG_FLOW
# Verify the target flow exists
hass.config_entries.flow.async_get(result["next_flow"][1])