diff --git a/homeassistant/components/hassio/repairs.py b/homeassistant/components/hassio/repairs.py index 12cbfe634847..0c57be5f7c83 100644 --- a/homeassistant/components/hassio/repairs.py +++ b/homeassistant/components/hassio/repairs.py @@ -8,6 +8,7 @@ from aiohasupervisor import SupervisorError from aiohasupervisor.models import ContextType import probatio +from homeassistant import data_entry_flow from homeassistant.components.repairs import ( ConfirmRepairFlow, RepairsFlow, @@ -88,12 +89,12 @@ class SupervisorIssueRepairFlow(RepairsFlow): def _async_form_for_suggestion(self, suggestion: Suggestion) -> RepairsFlowResult: """Return form for suggestion.""" - return self.async_show_form( - step_id=suggestion.key, - data_schema=probatio.Schema({}), - description_placeholders=self.description_placeholders, - last_step=True, - ) + with self._as_step(suggestion.key): + return self.async_show_form( + data_schema=probatio.Schema({}), + description_placeholders=self.description_placeholders, + last_step=True, + ) async def async_step_init(self, _: None = None) -> RepairsFlowResult: """Handle the first step of a fix flow.""" @@ -122,12 +123,12 @@ class SupervisorIssueRepairFlow(RepairsFlow): # Always show a form for one suggestion to explain to user what's happening return self._async_form_for_suggestion(self._suggestions[0]) + @data_entry_flow.flow_step async def async_step_fix_menu(self, _: None = None) -> RepairsFlowResult: """Show the fix menu.""" assert self._suggestions return self.async_show_menu( - step_id="fix_menu", menu_options=[suggestion.key for suggestion in self._suggestions], description_placeholders=self.description_placeholders, ) diff --git a/homeassistant/config_entries.py b/homeassistant/config_entries.py index a71d3c6868bd..1af13a6ecea4 100644 --- a/homeassistant/config_entries.py +++ b/homeassistant/config_entries.py @@ -3488,6 +3488,7 @@ class ConfigFlow(ConfigEntryBaseFlow): if flw["flow_id"] != self.flow_id ] + @data_entry_flow.flow_step async def async_step_ignore(self, user_input: dict[str, Any]) -> ConfigFlowResult: """Ignore this config flow. @@ -3507,6 +3508,7 @@ class ConfigFlow(ConfigEntryBaseFlow): await self.async_set_unique_id(user_input["unique_id"], raise_on_progress=False) return self.async_create_entry(title=user_input["title"], data={}) + @data_entry_flow.flow_step async def async_step_user( self, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: @@ -3548,58 +3550,68 @@ class ConfigFlow(ConfigEntryBaseFlow): await self._async_handle_discovery_without_unique_id() return await self.async_step_user() + @data_entry_flow.flow_step async def async_step_discovery( self, discovery_info: DiscoveryInfoType ) -> ConfigFlowResult: """Handle a flow initialized by discovery.""" return await self._async_step_discovery_without_unique_id() + @data_entry_flow.flow_step async def async_step_bluetooth( self, discovery_info: BluetoothServiceInfoBleak ) -> ConfigFlowResult: """Handle a flow initialized by Bluetooth discovery.""" return await self._async_step_discovery_without_unique_id() + @data_entry_flow.flow_step async def async_step_dhcp( self, discovery_info: DhcpServiceInfo ) -> ConfigFlowResult: """Handle a flow initialized by DHCP discovery.""" return await self._async_step_discovery_without_unique_id() + @data_entry_flow.flow_step async def async_step_hassio( self, discovery_info: HassioServiceInfo ) -> ConfigFlowResult: """Handle a flow initialized by HASS IO discovery.""" return await self._async_step_discovery_without_unique_id() + @data_entry_flow.flow_step async def async_step_integration_discovery( self, discovery_info: DiscoveryInfoType ) -> ConfigFlowResult: """Handle a flow initialized by integration specific discovery.""" return await self._async_step_discovery_without_unique_id() + @data_entry_flow.flow_step async def async_step_homekit( self, discovery_info: ZeroconfServiceInfo ) -> ConfigFlowResult: """Handle a flow initialized by Homekit discovery.""" return await self._async_step_discovery_without_unique_id() + @data_entry_flow.flow_step async def async_step_mqtt( self, discovery_info: MqttServiceInfo ) -> ConfigFlowResult: """Handle a flow initialized by MQTT discovery.""" return await self._async_step_discovery_without_unique_id() + @data_entry_flow.flow_step async def async_step_ssdp( self, discovery_info: SsdpServiceInfo ) -> ConfigFlowResult: """Handle a flow initialized by SSDP discovery.""" return await self._async_step_discovery_without_unique_id() + @data_entry_flow.flow_step async def async_step_usb(self, discovery_info: UsbServiceInfo) -> ConfigFlowResult: """Handle a flow initialized by USB discovery.""" return await self._async_step_discovery_without_unique_id() + @data_entry_flow.flow_step async def async_step_zeroconf( self, discovery_info: ZeroconfServiceInfo ) -> ConfigFlowResult: diff --git a/homeassistant/data_entry_flow.py b/homeassistant/data_entry_flow.py index adcc791fb071..edf48b11f143 100644 --- a/homeassistant/data_entry_flow.py +++ b/homeassistant/data_entry_flow.py @@ -3,14 +3,24 @@ import abc import asyncio from collections import defaultdict -from collections.abc import Callable, Container, Hashable, Iterable, Mapping -from contextlib import suppress +from collections.abc import ( + Callable, + Container, + Coroutine, + Generator, + Hashable, + Iterable, + Mapping, +) +from contextlib import contextmanager, suppress +from contextvars import ContextVar import copy from dataclasses import dataclass from enum import StrEnum +from functools import wraps import logging from types import MappingProxyType -from typing import Any, Generic, Required, TypedDict, TypeVar, cast +from typing import Any, Concatenate, Generic, Required, TypedDict, TypeVar, cast import probatio @@ -23,6 +33,10 @@ from .util import uuid as uuid_util _LOGGER = logging.getLogger(__name__) +_current_step: ContextVar[tuple[FlowHandler[Any, Any, Any], str] | None] = ContextVar( + "current_step", default=None +) + class FlowResultType(StrEnum): """Result type for a data entry flow.""" @@ -617,6 +631,22 @@ class FlowManager(abc.ABC, Generic[_FlowContextT, _FlowResultT, _HandlerT]): ] +def flow_step[_FlowHandlerT: FlowHandler[Any, Any, Any], **_P, _R]( + func: Callable[Concatenate[_FlowHandlerT, _P], Coroutine[Any, Any, _R]], / +) -> Callable[Concatenate[_FlowHandlerT, _P], Coroutine[Any, Any, _R]]: + """Mark a step method so results built inside it default to its step id.""" + if not func.__name__.startswith("async_step_"): + raise TypeError(f"{func.__qualname__} is not an async_step_ method") + step_id = func.__name__.removeprefix("async_step_") + + @wraps(func) + async def wrapper(self: _FlowHandlerT, *args: _P.args, **kwargs: _P.kwargs) -> _R: + with self._as_step(step_id): + return await func(self, *args, **kwargs) + + return wrapper + + class FlowHandler(Generic[_FlowContextT, _FlowResultT, _HandlerT]): """Handle a data entry flow.""" @@ -702,6 +732,22 @@ class FlowHandler(Generic[_FlowContextT, _FlowResultT, _HandlerT]): schema[new_key] = val return probatio.Schema(schema) + @contextmanager + def _as_step(self, step_id: str) -> Generator[None]: + """Default the step id of results built inside the block.""" + token = _current_step.set((self, step_id)) + try: + yield + finally: + _current_step.reset(token) + + def _inferred_step_id(self) -> str | None: + """Return the id of the step running on this handler, if any.""" + current = _current_step.get() + if current is None or current[0] is not self: + return None + return current[1] + @callback def async_show_form( self, @@ -724,6 +770,8 @@ class FlowHandler(Generic[_FlowContextT, _FlowResultT, _HandlerT]): last_step=last_step, # Display next or submit button in frontend preview=preview, # Display preview component in frontend ) + if step_id is None: + step_id = self._inferred_step_id() if step_id is not None: flow_result["step_id"] = step_id return flow_result @@ -791,6 +839,8 @@ class FlowHandler(Generic[_FlowContextT, _FlowResultT, _HandlerT]): url=url, description_placeholders=description_placeholders, ) + if step_id is None: + step_id = self._inferred_step_id() if step_id is not None: flow_result["step_id"] = step_id return flow_result @@ -841,6 +891,8 @@ class FlowHandler(Generic[_FlowContextT, _FlowResultT, _HandlerT]): description_placeholders=description_placeholders, progress_task=progress_task, ) + if step_id is None: + step_id = self._inferred_step_id() if step_id is not None: flow_result["step_id"] = step_id return flow_result @@ -897,6 +949,8 @@ class FlowHandler(Generic[_FlowContextT, _FlowResultT, _HandlerT]): ) if sort: flow_result["sort"] = sort + if step_id is None: + step_id = self._inferred_step_id() if step_id is not None: flow_result["step_id"] = step_id return flow_result diff --git a/homeassistant/helpers/schema_config_entry_flow.py b/homeassistant/helpers/schema_config_entry_flow.py index c4de641e873e..e2bc7f55f57d 100644 --- a/homeassistant/helpers/schema_config_entry_flow.py +++ b/homeassistant/helpers/schema_config_entry_flow.py @@ -248,11 +248,11 @@ class SchemaCommonFlowHandler: """Show form for next step.""" if isinstance(self._flow[next_step_id], SchemaFlowMenuStep): menu_step = cast(SchemaFlowMenuStep, self._flow[next_step_id]) - return self._handler.async_show_menu( - step_id=next_step_id, - menu_options=await self._get_options(menu_step), - sort=menu_step.sort, - ) + menu_options = await self._get_options(menu_step) + with self._handler._as_step(next_step_id): # noqa: SLF001 + return self._handler.async_show_menu( + menu_options=menu_options, sort=menu_step.sort + ) form_step = cast(SchemaFlowFormStep, self._flow[next_step_id]) @@ -288,25 +288,25 @@ class SchemaCommonFlowHandler: last_step = None if not callable(form_step.next_step): last_step = form_step.next_step is None - return self._handler.async_show_form( - step_id=next_step_id, - data_schema=data_schema, - description_placeholders=description_placeholders, - errors=errors, - last_step=last_step, - preview=form_step.preview, - ) + with self._handler._as_step(next_step_id): # noqa: SLF001 + return self._handler.async_show_form( + data_schema=data_schema, + description_placeholders=description_placeholders, + errors=errors, + last_step=last_step, + preview=form_step.preview, + ) async def _async_menu_step( self, step_id: str, user_input: dict[str, Any] | None = None ) -> ConfigFlowResult: """Handle a menu step.""" menu_step: SchemaFlowMenuStep = cast(SchemaFlowMenuStep, self._flow[step_id]) - return self._handler.async_show_menu( - step_id=step_id, - menu_options=await self._get_options(menu_step), - sort=menu_step.sort, - ) + menu_options = await self._get_options(menu_step) + with self._handler._as_step(step_id): # noqa: SLF001 + return self._handler.async_show_menu( + menu_options=menu_options, sort=menu_step.sort + ) class SchemaConfigFlowHandler(ConfigFlow, ABC): diff --git a/tests/test_data_entry_flow.py b/tests/test_data_entry_flow.py index bbb3ec49c2ed..c26075cd0fc5 100644 --- a/tests/test_data_entry_flow.py +++ b/tests/test_data_entry_flow.py @@ -3,6 +3,7 @@ import asyncio import dataclasses import logging +from typing import Any from unittest.mock import Mock, patch import probatio @@ -118,6 +119,196 @@ async def test_configure_two_steps(manager: MockFlowManager) -> None: assert result["data"] == ["INIT-DATA", "SECOND-DATA"] +async def test_flow_step_nested_step_id(manager: MockFlowManager) -> None: + """Test a decorated step that hands off to another step reports the inner id.""" + + @manager.mock_reg_handler("test") + class TestFlow(data_entry_flow.FlowHandler): + VERSION = 1 + data: list[str] | None = None + + @data_entry_flow.flow_step + async def async_step_first(self, user_input=None): + if user_input is not None: + self.data = user_input + return await self.async_step_second() + return self.async_show_form(data_schema=probatio.Schema([str])) + + @data_entry_flow.flow_step + async def async_step_second(self, user_input=None): + return await self.async_step_third() + + @data_entry_flow.flow_step + async def async_step_third(self, user_input=None): + if user_input is not None: + return self.async_create_entry( + title="Test Entry", data=self.data + user_input + ) + return self.async_show_form(data_schema=probatio.Schema([str])) + + form = await manager.async_init("test", context={"init_step": "first"}) + assert form["step_id"] == "first" + form = await manager.async_configure(form["flow_id"], ["FIRST-DATA"]) + assert form["step_id"] == "third" + form = await manager.async_configure(form["flow_id"], ["THIRD-DATA"]) + assert form["type"] is data_entry_flow.FlowResultType.CREATE_ENTRY + assert form["data"] == ["FIRST-DATA", "THIRD-DATA"] + + +@pytest.mark.parametrize( + ("method", "params"), + [ + pytest.param("async_show_form", {}, id="form"), + pytest.param("async_show_menu", {"menu_options": ["first"]}, id="menu"), + pytest.param( + "async_show_progress", + {"progress_action": "task", "progress_task": Mock()}, + id="progress", + ), + pytest.param("async_external_step", {"url": "https://example.com"}, id="ext"), + ], +) +async def test_flow_step_all_result_types( + manager: MockFlowManager, method: str, params: dict[str, Any] +) -> None: + """Test every result builder picks up the id of the decorated step.""" + + @manager.mock_reg_handler("test") + class TestFlow(data_entry_flow.FlowHandler): + @data_entry_flow.flow_step + async def async_step_first(self, user_input=None): + return await self.async_step_second() + + @data_entry_flow.flow_step + async def async_step_second(self, user_input=None): + return getattr(self, method)(**params) + + result = await manager.async_init("test", context={"init_step": "first"}) + assert result["step_id"] == "second" + + +async def test_flow_step_restores_outer_step_id(manager: MockFlowManager) -> None: + """Test a step that resumes after awaiting another step keeps its own id.""" + + @manager.mock_reg_handler("test") + class TestFlow(data_entry_flow.FlowHandler): + @data_entry_flow.flow_step + async def async_step_init(self, user_input=None): + await self.async_step_helper() + return self.async_show_form(data_schema=probatio.Schema([str])) + + @data_entry_flow.flow_step + async def async_step_helper(self, user_input=None): + return self.async_abort(reason="unused") + + form = await manager.async_init("test") + assert form["step_id"] == "init" + assert form["flow_id"] in [flow["flow_id"] for flow in manager.async_progress()] + + +async def test_flow_step_concurrent_configure( + hass: HomeAssistant, manager: MockFlowManager +) -> None: + """Test overlapping configure calls on one flow keep their own step ids.""" + confirm_entered = asyncio.Event() + release = asyncio.Event() + + @manager.mock_reg_handler("test") + class TestFlow(data_entry_flow.FlowHandler): + @data_entry_flow.flow_step + async def async_step_user(self, user_input=None): + if user_input is None: + return self.async_show_form(data_schema=probatio.Schema([str])) + if user_input == ["confirm"]: + return await self.async_step_confirm() + # Suspend here so the other call reaches the confirm step meanwhile + await confirm_entered.wait() + return self.async_show_form(errors={"base": "invalid"}) + + @data_entry_flow.flow_step + async def async_step_confirm(self, user_input=None): + confirm_entered.set() + await release.wait() + return self.async_show_form() + + form = await manager.async_init("test", context={"init_step": "user"}) + erroring = hass.async_create_task( + manager.async_configure(form["flow_id"], ["error"]) + ) + confirming = hass.async_create_task( + manager.async_configure(form["flow_id"], ["confirm"]) + ) + assert (await erroring)["step_id"] == "user" + release.set() + assert (await confirming)["step_id"] == "confirm" + + +async def test_flow_step_does_not_leak_into_nested_flow( + manager: MockFlowManager, +) -> None: + """Test a step that starts another flow does not leak its id into it.""" + inner_results: list[data_entry_flow.FlowResult] = [] + + @manager.mock_reg_handler("inner") + class InnerFlow(data_entry_flow.FlowHandler): + async def async_step_init(self, user_input=None): + return self.async_show_form(data_schema=probatio.Schema([str])) + + @manager.mock_reg_handler("outer") + class OuterFlow(data_entry_flow.FlowHandler): + @data_entry_flow.flow_step + async def async_step_start(self, user_input=None): + inner_results.append(await manager.async_init("inner")) + return self.async_show_form(data_schema=probatio.Schema([str])) + + outer = await manager.async_init("outer", context={"init_step": "start"}) + assert outer["step_id"] == "start" + assert inner_results[0]["step_id"] == "init" + + +async def test_flow_step_explicit_step_id_wins(manager: MockFlowManager) -> None: + """Test an explicit step_id overrides the decorated step's id.""" + + @manager.mock_reg_handler("test") + class TestFlow(data_entry_flow.FlowHandler): + @data_entry_flow.flow_step + async def async_step_init(self, user_input=None): + return self.async_show_form(step_id="other") + + async def async_step_other(self, user_input=None): + return self.async_create_entry(title="done", data={}) + + form = await manager.async_init("test") + assert form["step_id"] == "other" + + +async def test_undecorated_step_uses_dispatched_step_id( + manager: MockFlowManager, +) -> None: + """Test the manager still fills in the dispatched step for undecorated steps.""" + + @manager.mock_reg_handler("test") + class TestFlow(data_entry_flow.FlowHandler): + async def async_step_first(self, user_input=None): + return await self.async_step_second() + + async def async_step_second(self, user_input=None): + return self.async_show_form(data_schema=probatio.Schema([str])) + + form = await manager.async_init("test", context={"init_step": "first"}) + assert form["step_id"] == "first" + + +def test_flow_step_rejects_non_step_method() -> None: + """Test the decorator requires the async_step_ naming convention.""" + + with pytest.raises(TypeError, match="is not an async_step_ method"): + + @data_entry_flow.flow_step + async def async_not_a_step(self, user_input=None): + return None + + async def test_show_form(manager: MockFlowManager) -> None: """Test that we can show a form.""" schema = probatio.Schema(