diff --git a/homeassistant/components/knocki/config_flow.py b/homeassistant/components/knocki/config_flow.py index faa9cf2217eb..1458440cbbdf 100644 --- a/homeassistant/components/knocki/config_flow.py +++ b/homeassistant/components/knocki/config_flow.py @@ -37,7 +37,9 @@ class KnockiConfigFlow(ConfigFlow, domain=DOMAIN): token_response = await client.login( user_input[CONF_USERNAME], user_input[CONF_PASSWORD] ) + # pylint: disable-next=home-assistant-flow-call-in-try await self.async_set_unique_id(token_response.user_id) + # pylint: disable-next=home-assistant-flow-call-in-try self._abort_if_unique_id_configured() client.token = token_response.token await client.link() diff --git a/homeassistant/components/onvif/config_flow.py b/homeassistant/components/onvif/config_flow.py index 3e9049d399e7..f5e6e7dd9146 100644 --- a/homeassistant/components/onvif/config_flow.py +++ b/homeassistant/components/onvif/config_flow.py @@ -347,7 +347,9 @@ class OnvifFlowHandler(ConfigFlow, domain=DOMAIN): raise AbortFlow(reason="no_mac") if configure_unique_id: + # pylint: disable-next=home-assistant-flow-call-in-try await self.async_set_unique_id(self.device_id, raise_on_progress=False) + # pylint: disable-next=home-assistant-flow-call-in-try self._abort_if_unique_id_configured( updates={ CONF_HOST: self.onvif_config[CONF_HOST], diff --git a/homeassistant/components/smlight/config_flow.py b/homeassistant/components/smlight/config_flow.py index 97a9c96535dd..e009fc16ca57 100644 --- a/homeassistant/components/smlight/config_flow.py +++ b/homeassistant/components/smlight/config_flow.py @@ -88,6 +88,7 @@ class SmlightConfigFlow(ConfigFlow, domain=DOMAIN): self._device_name = str(info.hostname) if info.model not in Devices: + # pylint: disable-next=home-assistant-flow-call-in-try return self.async_abort(reason="unsupported_device") return await self._async_complete_entry(user_input) @@ -113,11 +114,15 @@ class SmlightConfigFlow(ConfigFlow, domain=DOMAIN): self._device_name = str(info.hostname) if info.model not in Devices: + # pylint: disable-next=home-assistant-flow-call-in-try return self.async_abort(reason="unsupported_device") if self.source == SOURCE_RECONFIGURE: + # pylint: disable-next=home-assistant-flow-call-in-try await self.async_set_unique_id(format_mac(info.MAC)) + # pylint: disable-next=home-assistant-flow-call-in-try self._abort_if_unique_id_mismatch() + # pylint: disable-next=home-assistant-flow-call-in-try return self.async_update_reload_and_abort( self._get_reconfigure_entry(), data_updates={ @@ -174,6 +179,7 @@ class SmlightConfigFlow(ConfigFlow, domain=DOMAIN): info = await self.client.get_info() if info.model not in Devices: + # pylint: disable-next=home-assistant-flow-call-in-try return self.async_abort(reason="unsupported_device") return await self._async_complete_entry(user_input) diff --git a/packages/pylint-home-assistant/README.md b/packages/pylint-home-assistant/README.md index 0be17e3f311b..810eaff5bb3f 100644 --- a/packages/pylint-home-assistant/README.md +++ b/packages/pylint-home-assistant/README.md @@ -170,6 +170,7 @@ Every check has a code following the | `W7450` | [`home-assistant-log-and-raise`](#w7450-home-assistant-log-and-raise) | Don't log an error that is raised to Home Assistant, which already reports it | | `W7452` | [`home-assistant-action-registered-outside-services-module`](#w7452-home-assistant-action-registered-outside-services-module) | Actions should be registered from `async_setup_services` or `setup_services` in `services.py` | | `W7453` | [`home-assistant-invalid-setup-services`](#w7453-home-assistant-invalid-setup-services) | `async_setup_services` / `setup_services` should be synchronous and only take `hass` | +| `W7457` | [`home-assistant-flow-call-in-try`](#w7457-home-assistant-flow-call-in-try) | Flow creates an entry, shows a form or handles the unique ID inside a `try` block | ## `home_assistant_logger` checker @@ -548,6 +549,32 @@ A `menu_options` entry does not match any `async_step_*` method defined on the flow class or its ancestors. +## `home_assistant_flow_call_in_try` checker + +Checks for flow calls inside a `try` block. + +### `W7457`: `home-assistant-flow-call-in-try` + +A `try` block in a flow step should only contain the code that can raise the +errors it catches, such as the calls to the device or service. Creating the +entry, showing a form, aborting and handling the unique ID belong after it: + +```python +try: + info = await client.get_info() +except CannotConnect: + errors["base"] = "cannot_connect" +else: + await self.async_set_unique_id(info.serial_number) + self._abort_if_unique_id_configured() + return self.async_create_entry(title=info.name, data=user_input) +``` + +The unique ID helpers raise `AbortFlow`, which a broad `except Exception` +swallows and reports as an unknown error. `try` statements that catch +`AbortFlow` themselves are not checked. + + ## `home_assistant_unused_test_fixture_args` checker **Disabled by default** while existing violations are being cleaned up. diff --git a/packages/pylint-home-assistant/pylint_home_assistant/checkers/config_flow/flow_call_in_try.py b/packages/pylint-home-assistant/pylint_home_assistant/checkers/config_flow/flow_call_in_try.py new file mode 100644 index 000000000000..4bc8ad59960d --- /dev/null +++ b/packages/pylint-home-assistant/pylint_home_assistant/checkers/config_flow/flow_call_in_try.py @@ -0,0 +1,147 @@ +"""Checker for flow results and unique ID handling inside a ``try`` block. + +A ``try`` block in a flow step should only contain the code that can raise the +errors it catches, such as the calls to the device or service. Creating the +entry, showing a form and handling the unique ID belong after it, in ``else:`` +or after the ``try`` statement. The unique ID helpers raise ``AbortFlow``, +which a broad ``except Exception`` swallows and reports as an unknown error. + +``W7457`` (``home-assistant-flow-call-in-try``) +""" + +from collections.abc import Iterator + +import astroid +from astroid import nodes +from pylint.checkers import BaseChecker +from pylint.lint import PyLinter + +from pylint_home_assistant.helpers.ast_utils import extended_ancestors +from pylint_home_assistant.helpers.module_info import is_integration_module + +_ABORT_FLOW_QNAME = "homeassistant.data_entry_flow.AbortFlow" +_FLOW_HANDLER_QNAME = "homeassistant.data_entry_flow.FlowHandler" +_FLOW_METHODS = frozenset( + { + "_abort_if_unique_id_configured", + "_abort_if_unique_id_mismatch", + "_async_abort_entries_match", + "_async_handle_discovery_without_unique_id", + "async_abort", + "async_create_entry", + "async_external_step", + "async_external_step_done", + "async_set_unique_id", + "async_show_form", + "async_show_menu", + "async_show_progress", + "async_show_progress_done", + "async_update_and_abort", + "async_update_reload_and_abort", + } +) + + +def _is_flow_handler(class_node: nodes.ClassDef) -> bool: + """Return True if the class is a flow handler.""" + return any( + ancestor.qname() == _FLOW_HANDLER_QNAME + for ancestor in extended_ancestors(class_node) + ) + + +def _catches_abort_flow(node: nodes.Try) -> bool: + """Return True if a handler of the ``try`` statement catches ``AbortFlow``.""" + for handler in node.handlers: + if handler.type is None: + continue + exception_types = ( + handler.type.elts + if isinstance(handler.type, nodes.Tuple) + else [handler.type] + ) + for exception_type in exception_types: + try: + inferred = list(exception_type.infer()) + except astroid.exceptions.InferenceError: + continue + if any( + isinstance(item, nodes.ClassDef) and item.qname() == _ABORT_FLOW_QNAME + for item in inferred + ): + return True + return False + + +def _flow_calls(node: nodes.NodeNG) -> Iterator[nodes.Call]: + """Yield the flow method calls on ``self`` in *node*. + + Calls in nested functions and classes run later, outside the ``try`` + block, so they are skipped. The body of a nested ``try`` statement with + handlers is checked when that statement is visited, unless it catches + ``AbortFlow`` itself: then its calls are still inside this ``try`` block. + """ + if isinstance(node, (nodes.FunctionDef, nodes.Lambda, nodes.ClassDef)): + return + match node: + case nodes.Call( + func=nodes.Attribute(attrname=attrname, expr=nodes.Name(name="self")) + ) if attrname in _FLOW_METHODS: + yield node + children = ( + (*node.handlers, *node.orelse, *node.finalbody) + if isinstance(node, nodes.Try) + and node.handlers + and not _catches_abort_flow(node) + else node.get_children() + ) + for child in children: + yield from _flow_calls(child) + + +class FlowCallInTryChecker(BaseChecker): + """Checker for flow calls inside a ``try`` block.""" + + name = "home_assistant_flow_call_in_try" + priority = -1 + msgs = { + "W7457": ( + ( + "Move `self.%s()` out of the `try` block, for example to " + "`else:`, only keep code that can raise the caught errors in `try`" + ), + "home-assistant-flow-call-in-try", + ( + "Used when a flow creates an entry, shows a form, aborts or " + "handles the unique ID inside a `try` block with `except` " + "handlers. Those calls don't raise the errors the handlers " + "catch, and a broad handler swallows the `AbortFlow` raised by " + "the unique ID helpers." + ), + ), + } + options = () + + def visit_try(self, node: nodes.Try) -> None: + """Check the body of ``try`` statements with ``except`` handlers.""" + if not node.handlers or not is_integration_module(node.root().name): + return + calls = [call for statement in node.body for call in _flow_calls(statement)] + if not calls or _catches_abort_flow(node): + return + class_node = node.scope().parent + if not isinstance(class_node, nodes.ClassDef) or not _is_flow_handler( + class_node + ): + return + for call in calls: + self.add_message( + "home-assistant-flow-call-in-try", + node=call, + args=(call.func.attrname,), + ) + + +def register(linter: PyLinter) -> None: + """Register the checker.""" + linter.register_checker(FlowCallInTryChecker(linter)) diff --git a/tests/pylint/config_flow/test_flow_call_in_try.py b/tests/pylint/config_flow/test_flow_call_in_try.py new file mode 100644 index 000000000000..f818a8ff22ea --- /dev/null +++ b/tests/pylint/config_flow/test_flow_call_in_try.py @@ -0,0 +1,333 @@ +"""Tests for the flow call in try checker.""" + +import astroid +from astroid import nodes +from pylint.testutils import MessageTest, UnittestLinter +from pylint_home_assistant.checkers.config_flow.flow_call_in_try import ( + FlowCallInTryChecker, +) +import pytest + +from tests.pylint import assert_adds_messages, assert_no_messages, walk_checker + +# Pre-load so astroid can resolve the flow classes in parsed snippets +astroid.MANAGER.ast_from_module_name("homeassistant.config_entries") + +_MODULE = "homeassistant.components.test_int.config_flow" + + +@pytest.fixture(name="checker") +def checker_fixture(linter: UnittestLinter) -> FlowCallInTryChecker: + """Fixture to provide a flow call in try checker.""" + return FlowCallInTryChecker(linter) + + +def _expected_messages(root: nodes.Module, *names: str) -> list[MessageTest]: + """Return the expected messages for the flow calls named *names*, in order.""" + calls = [ + next( + call + for call in root.nodes_of_class(nodes.Call) + if isinstance(call.func, nodes.Attribute) and call.func.attrname == name + ) + for name in names + ] + return [ + MessageTest( + msg_id="home-assistant-flow-call-in-try", + node=call, + args=(call.func.attrname,), + line=call.lineno, + col_offset=call.col_offset, + end_line=call.end_lineno, + end_col_offset=call.end_col_offset, + ) + for call in calls + ] + + +@pytest.mark.parametrize( + ("code", "module_name"), + [ + pytest.param( + """ +from homeassistant.config_entries import ConfigFlow + +class MyFlow(ConfigFlow, domain="test_int"): + async def async_step_user(self, user_input=None): + errors = {} + if user_input is not None: + try: + info = await validate(user_input) + except CannotConnect: + errors["base"] = "cannot_connect" + else: + await self.async_set_unique_id(info.serial_number) + self._abort_if_unique_id_configured() + return self.async_create_entry(title=info.title, data=user_input) + return self.async_show_form(step_id="user", errors=errors) +""", + _MODULE, + id="else_block", + ), + pytest.param( + """ +from homeassistant.config_entries import ConfigFlow + +class MyFlow(ConfigFlow, domain="test_int"): + async def async_step_user(self, user_input=None): + try: + await self.async_set_unique_id(user_input["serial_number"]) + return self.async_create_entry(title="Test", data=user_input) + finally: + await close() +""", + _MODULE, + id="try_finally", + ), + pytest.param( + """ +from homeassistant.config_entries import ConfigFlow +from homeassistant.data_entry_flow import AbortFlow + +class MyFlow(ConfigFlow, domain="test_int"): + async def async_step_user(self, user_input=None): + try: + await self.async_set_unique_id(user_input["serial_number"]) + self._abort_if_unique_id_configured() + except AbortFlow: + await close() + raise + return self.async_create_entry(title="Test", data=user_input) +""", + _MODULE, + id="catches_abort_flow", + ), + pytest.param( + """ +from homeassistant.config_entries import ConfigFlow +from homeassistant.data_entry_flow import AbortFlow as FlowAbort + +class MyFlow(ConfigFlow, domain="test_int"): + async def async_step_user(self, user_input=None): + try: + await self.async_set_unique_id(user_input["serial_number"]) + self._abort_if_unique_id_configured() + except FlowAbort: + await close() + raise + return self.async_create_entry(title="Test", data=user_input) +""", + _MODULE, + id="catches_aliased_abort_flow", + ), + pytest.param( + """ +from homeassistant.config_entries import ConfigFlow +from homeassistant.data_entry_flow import AbortFlow + +class MyFlow(ConfigFlow, domain="test_int"): + async def async_step_user(self, user_input=None): + try: + await self.async_set_unique_id(user_input["serial_number"]) + self._abort_if_unique_id_configured() + except (AbortFlow, CannotConnect): + await close() + raise + return self.async_create_entry(title="Test", data=user_input) +""", + _MODULE, + id="catches_abort_flow_in_tuple", + ), + pytest.param( + """ +from homeassistant.config_entries import ConfigFlow + +class MyFlow(ConfigFlow, domain="test_int"): + async def async_step_user(self, user_input=None): + try: + client.register_callback( + lambda: self.async_create_entry(title="Test", data={}) + ) + except CannotConnect: + return self.async_abort(reason="cannot_connect") + return self.async_show_form(step_id="user") +""", + _MODULE, + id="nested_lambda", + ), + pytest.param( + """ +class MyHelper: + async def async_step_user(self, user_input=None): + try: + return self.async_create_entry(title="Test", data=user_input) + except CannotConnect: + return None +""", + _MODULE, + id="not_a_flow", + ), + pytest.param( + """ +from homeassistant.config_entries import ConfigFlow + +class MyFlow(ConfigFlow, domain="test_int"): + async def async_step_user(self, user_input=None): + try: + return self.async_create_entry(title="Test", data=user_input) + except CannotConnect: + return self.async_abort(reason="cannot_connect") +""", + "homeassistant.helpers.my_helper", + id="not_an_integration", + ), + ], +) +def test_no_warning( + linter: UnittestLinter, + checker: FlowCallInTryChecker, + code: str, + module_name: str, +) -> None: + """Test cases that should not trigger a warning.""" + root = astroid.parse(code, module_name) + + with assert_no_messages(linter): + walk_checker(linter, checker, root) + + +@pytest.mark.parametrize( + ("code", "names"), + [ + pytest.param( + """ +from homeassistant.config_entries import ConfigFlow + +class MyFlow(ConfigFlow, domain="test_int"): + async def async_step_user(self, user_input=None): + errors = {} + if user_input is not None: + try: + info = await validate(user_input) + await self.async_set_unique_id(info.serial_number) + self._abort_if_unique_id_configured() + return self.async_create_entry(title=info.title, data=user_input) + except CannotConnect: + errors["base"] = "cannot_connect" + return self.async_show_form(step_id="user", errors=errors) +""", + ( + "async_set_unique_id", + "_abort_if_unique_id_configured", + "async_create_entry", + ), + id="config_flow", + ), + pytest.param( + """ +from homeassistant.config_entries import OptionsFlow + +class MyOptionsFlow(OptionsFlow): + async def async_step_init(self, user_input=None): + try: + await validate(user_input) + if user_input is not None: + return self.async_create_entry(data=user_input) + except CannotConnect: + return self.async_abort(reason="cannot_connect") + return self.async_show_form(step_id="init") +""", + ("async_create_entry",), + id="options_flow", + ), + pytest.param( + """ +from homeassistant.config_entries import ConfigFlow + +class MyFlow(ConfigFlow, domain="test_int"): + async def async_step_reconfigure(self, user_input=None): + try: + async with client: + await client.connect() + return self.async_update_reload_and_abort( + self._get_reconfigure_entry(), data_updates=user_input + ) + except Exception: + return self.async_abort(reason="unknown") +""", + ("async_update_reload_and_abort",), + id="nested_in_with_block", + ), + pytest.param( + """ +from homeassistant.config_entries import ConfigFlow + +class MyFlow(ConfigFlow, domain="test_int"): + async def async_step_user(self, user_input=None): + try: + try: + await validate(user_input) + self._async_abort_entries_match({"host": user_input["host"]}) + except InvalidAuth: + return self.async_show_form(step_id="user") + except CannotConnect: + return self.async_abort(reason="cannot_connect") + return self.async_create_entry(title="Test", data=user_input) +""", + # The outer try statement is visited first + ("async_show_form", "_async_abort_entries_match"), + id="nested_try", + ), + pytest.param( + """ +from homeassistant.config_entries import ConfigFlow + +class AbortFlow(Exception): + pass + +class MyFlow(ConfigFlow, domain="test_int"): + async def async_step_user(self, user_input=None): + try: + await self.async_set_unique_id(user_input["serial_number"]) + except AbortFlow: + return self.async_abort(reason="unknown") + return self.async_create_entry(title="Test", data=user_input) +""", + ("async_set_unique_id",), + id="other_class_named_abort_flow", + ), + pytest.param( + """ +from homeassistant.config_entries import ConfigFlow +from homeassistant.data_entry_flow import AbortFlow + +class MyFlow(ConfigFlow, domain="test_int"): + async def async_step_user(self, user_input=None): + try: + try: + await self.async_set_unique_id(user_input["serial_number"]) + self._abort_if_unique_id_configured() + except AbortFlow: + await close() + raise + except Exception: + return self.async_abort(reason="unknown") + return self.async_create_entry(title="Test", data=user_input) +""", + ("async_set_unique_id", "_abort_if_unique_id_configured"), + id="nested_try_reraises_abort_flow", + ), + ], +) +def test_flow_call_in_try( + linter: UnittestLinter, + checker: FlowCallInTryChecker, + code: str, + names: tuple[str, ...], +) -> None: + """Test flow calls inside a try block with handlers are flagged.""" + root = astroid.parse(code, _MODULE) + + with assert_adds_messages(linter, *_expected_messages(root, *names)): + walk_checker(linter, checker, root)