diff --git a/packages/pylint-home-assistant/README.md b/packages/pylint-home-assistant/README.md index d027ccbb3aaa..7af9d2d1037c 100644 --- a/packages/pylint-home-assistant/README.md +++ b/packages/pylint-home-assistant/README.md @@ -173,6 +173,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` | +| `W7454` | [`home-assistant-sequential-add-entities`](#w7454-home-assistant-sequential-add-entities) | Sequential `async_add_entities` calls should be grouped | | `W7457` | [`home-assistant-flow-call-in-try`](#w7457-home-assistant-flow-call-in-try) | Flow creates an entry, shows a form, handles the unique ID or moves on to another step inside a `try` block | ## `home_assistant_logger` checker @@ -1297,6 +1298,24 @@ avoiding unnecessary context switches back to the event loop between blocking calls. The rule applies to integration modules only. +## `home_assistant_sequential_add_entities` checker + +Detects consecutive `async_add_entities` calls in integration modules that +could be grouped into a single call. + +### `W7454`: `home-assistant-sequential-add-entities` + +Two or more `async_add_entities` (or `add_entities`) calls appearing as +consecutive statements (uninterrupted by control flow such as +`if`/`try`/`with`/`for`) should be combined into a single call that adds all +entities at once. Calls with different arguments besides the entities, such +as a different `config_subentry_id` when adding entities for multiple +subentries or a different `update_before_add`, cannot be combined and are not +flagged. Only calls to the callback passed to the platform setup function +(`async_setup_entry`, `async_setup_platform` or `setup_platform`) are checked. +The rule applies to integration modules only. + + ## `home_assistant_has_entity_name` checker Quality-scale-gated checker for the diff --git a/packages/pylint-home-assistant/pylint_home_assistant/checkers/sequential_add_entities.py b/packages/pylint-home-assistant/pylint_home_assistant/checkers/sequential_add_entities.py new file mode 100644 index 000000000000..9fcd1fdbb9c2 --- /dev/null +++ b/packages/pylint-home-assistant/pylint_home_assistant/checkers/sequential_add_entities.py @@ -0,0 +1,139 @@ +"""Checker for sequential async_add_entities calls. + +Multiple sequential ``async_add_entities()`` calls should be grouped into a +single call, so all entities are added to the platform in one go. + +Calls with different arguments besides the entities (for example a different +``config_subentry_id`` or ``update_before_add``) cannot be grouped and are not +flagged. +""" + +from astroid import nodes +from pylint.checkers import BaseChecker +from pylint.lint import PyLinter + +from pylint_home_assistant.helpers.module_info import is_integration_module + +ADD_ENTITIES_CALLBACK_NAMES = {"async_add_entities", "add_entities"} +PLATFORM_SETUP_FUNCTIONS = { + "async_setup_entry", + "async_setup_platform", + "setup_platform", +} + + +def _get_add_entities_call(node: nodes.NodeNG) -> nodes.Call | None: + """Return the call if *node* is an ``async_add_entities(...)`` statement.""" + if not isinstance(node, nodes.Expr) or not isinstance(node.value, nodes.Call): + return None + + call = node.value + if ( + not isinstance(call.func, nodes.Name) + or call.func.name not in ADD_ENTITIES_CALLBACK_NAMES + ): + return None + + # Only the callback passed to the platform setup function, not a local helper + # or a parameter of a nested function shadowing it + _, assignments = call.func.lookup(call.func.name) + if not assignments or not all( + isinstance(assignment.parent, nodes.Arguments) + and isinstance(setup := assignment.parent.parent, nodes.FunctionDef) + and setup.name in PLATFORM_SETUP_FUNCTIONS + and isinstance(setup.parent, nodes.Module) + for assignment in assignments + ): + return None + + return call + + +def _extra_arguments(call: nodes.Call) -> list[str] | None: + """Return the arguments of *call* besides the entities, or None if unknown.""" + if any(isinstance(arg, nodes.Starred) for arg in call.args) or any( + keyword.arg is None for keyword in call.keywords + ): + return None + keywords = [keyword for keyword in call.keywords if keyword.arg != "new_entities"] + # Calls can return a different value each time, despite identical source + if any( + next(node.nodes_of_class(nodes.Call), None) is not None + for node in (*call.args[1:2], *keywords) + ): + return None + # update_before_add can also be passed positionally + arguments = [f"update_before_add={arg.as_string()}" for arg in call.args[1:2]] + arguments.extend(keyword.as_string() for keyword in keywords) + return sorted(arguments) + + +class SequentialAddEntitiesChecker(BaseChecker): + """Checker for sequential async_add_entities calls.""" + + name = "home_assistant_sequential_add_entities" + priority = -1 + msgs = { + "W7454": ( + "Sequential `%s` calls should be grouped into a single call", + "home-assistant-sequential-add-entities", + "Used when multiple async_add_entities() calls with the same " + "arguments besides the entities appear in sequence. Collect the entities and " + "call async_add_entities once.", + ), + } + options = () + + _in_integration: bool + + def visit_module(self, node: nodes.Module) -> None: + """Track whether we are in an integration module.""" + self._in_integration = is_integration_module(node.name) + + def visit_functiondef(self, node: nodes.FunctionDef) -> None: + """Check for sequential async_add_entities calls.""" + if not self._in_integration: + return + + self._check_body(node.body) + + visit_asyncfunctiondef = visit_functiondef + + def _check_body(self, body: list[nodes.NodeNG]) -> None: + """Check a list of statements for sequential async_add_entities calls.""" + prev_arguments: list[str] | None = None + + for stmt in body: + if (call := _get_add_entities_call(stmt)) is not None: + arguments = _extra_arguments(call) + if arguments is not None and arguments == prev_arguments: + self.add_message( + "home-assistant-sequential-add-entities", + node=stmt, + args=(call.func.name,), + ) + prev_arguments = arguments + continue + + prev_arguments = None + + # Recurse into control flow blocks (but not nested functions) + if isinstance(stmt, nodes.If): + self._check_body(stmt.body) + self._check_body(stmt.orelse) + elif isinstance(stmt, nodes.Try): + self._check_body(stmt.body) + for handler in stmt.handlers: + self._check_body(handler.body) + self._check_body(stmt.orelse) + self._check_body(stmt.finalbody) + elif isinstance(stmt, (nodes.With, nodes.AsyncWith)): + self._check_body(stmt.body) + elif isinstance(stmt, (nodes.For, nodes.AsyncFor, nodes.While)): + self._check_body(stmt.body) + self._check_body(stmt.orelse) + + +def register(linter: PyLinter) -> None: + """Register the checker.""" + linter.register_checker(SequentialAddEntitiesChecker(linter)) diff --git a/tests/pylint/test_sequential_add_entities.py b/tests/pylint/test_sequential_add_entities.py new file mode 100644 index 000000000000..469262e44cd5 --- /dev/null +++ b/tests/pylint/test_sequential_add_entities.py @@ -0,0 +1,305 @@ +"""Tests for the sequential add entities checker.""" + +import astroid +from pylint.testutils import UnittestLinter +from pylint_home_assistant.checkers.sequential_add_entities import ( + SequentialAddEntitiesChecker, +) +import pytest + +from . import assert_no_messages, walk_checker + +INTEGRATION_MODULE = "homeassistant.components.test_integration.sensor" + + +@pytest.fixture(name="add_entities_checker") +def add_entities_checker_fixture( + linter: UnittestLinter, +) -> SequentialAddEntitiesChecker: + """Fixture to provide a sequential add entities checker.""" + return SequentialAddEntitiesChecker(linter) + + +@pytest.mark.parametrize( + ("code", "module_name"), + [ + pytest.param( + """ +async def async_setup_entry(hass, entry, async_add_entities): + async_add_entities([SensorA(), SensorB()]) +""", + INTEGRATION_MODULE, + id="single_call", + ), + pytest.param( + """ +async def async_setup_entry(hass, entry, async_add_entities): + async_add_entities([SensorA()]) + coordinator = entry.runtime_data + async_add_entities([SensorB(coordinator)]) +""", + INTEGRATION_MODULE, + id="separated_by_other_statement", + ), + pytest.param( + """ +async def async_setup_entry(hass, entry, async_add_entities): + async_add_entities([SensorA()]) + if entry.data["extra"]: + async_add_entities([SensorB()]) +""", + INTEGRATION_MODULE, + id="separated_by_control_flow", + ), + pytest.param( + """ +async def async_setup_entry(hass, entry, async_add_entities): + for subentry_id, subentry in entry.subentries.items(): + async_add_entities([SensorA(subentry)], config_subentry_id=subentry_id) +""", + INTEGRATION_MODULE, + id="subentry_loop", + ), + pytest.param( + """ +async def async_setup_entry(hass, entry, async_add_entities): + async_add_entities([SensorA()], config_subentry_id="subentry_1") + async_add_entities([SensorB()], config_subentry_id="subentry_2") +""", + INTEGRATION_MODULE, + id="different_subentries", + ), + pytest.param( + """ +async def async_setup_entry(hass, entry, async_add_entities): + async_add_entities([SensorA()]) + async_add_entities([SensorB()], config_subentry_id="subentry_1") +""", + INTEGRATION_MODULE, + id="entry_and_subentry", + ), + pytest.param( + """ +async def async_setup_entry(hass, entry, async_add_entities): + async_add_entities([SensorA()]) + async_add_entities([SensorB()], update_before_add=True) +""", + INTEGRATION_MODULE, + id="different_update_before_add", + ), + pytest.param( + """ +async def async_setup_entry(hass, entry, async_add_entities): + async_add_entities([SensorA()], True) + async_add_entities([SensorB()], False) +""", + INTEGRATION_MODULE, + id="different_positional_update_before_add", + ), + pytest.param( + """ +async def async_setup_entry(hass, entry, async_add_entities): + async_add_entities([SensorA()], True) + async_add_entities([SensorB()]) +""", + INTEGRATION_MODULE, + id="positional_update_before_add_and_omitted", + ), + pytest.param( + """ +async def async_setup_entry(hass, entry, async_add_entities): + async_add_entities(*args) + async_add_entities(*args) +""", + INTEGRATION_MODULE, + id="unpacked_arguments", + ), + pytest.param( + """ +async def async_setup_entry(hass, entry, async_add_entities): + async_add_entities([SensorA()], config_subentry_id=next(subentry_ids)) + async_add_entities([SensorB()], config_subentry_id=next(subentry_ids)) +""", + INTEGRATION_MODULE, + id="keyword_argument_with_call", + ), + pytest.param( + """ +async def async_setup_entry(hass, entry, async_add_entities): + async_add_entities([SensorA()], should_update()) + async_add_entities([SensorB()], should_update()) +""", + INTEGRATION_MODULE, + id="positional_argument_with_call", + ), + pytest.param( + """ +async def async_setup_entry(hass, entry, async_add_entities): + async_add_entities([SensorA()], **kwargs) + async_add_entities([SensorB()], **kwargs) +""", + INTEGRATION_MODULE, + id="unpacked_keywords", + ), + pytest.param( + """ +async def async_setup_entry(hass, entry, async_add_entities): + def add_entities(): + async_add_entities([SensorA()]) + + add_entities() + add_entities() +""", + INTEGRATION_MODULE, + id="local_helper_function", + ), + pytest.param( + """ +async def async_setup_entry(hass, entry, async_add_entities): + def helper(add_entities): + add_entities([SensorA()]) + add_entities([SensorB()]) +""", + INTEGRATION_MODULE, + id="nested_function_shadowing_parameter", + ), + pytest.param( + """ +def _add_sensors(async_add_entities): + async_add_entities([SensorA()]) + async_add_entities([SensorB()]) +""", + INTEGRATION_MODULE, + id="not_platform_setup_function", + ), + pytest.param( + """ +async def async_setup_entry(hass, entry, async_add_entities): + async_add_entities([SensorA()]) + async_add_entities([SensorB()]) +""", + "tests.components.test_integration.test_sensor", + id="not_integration_module", + ), + ], +) +def test_no_warning( + linter: UnittestLinter, + add_entities_checker: SequentialAddEntitiesChecker, + code: str, + module_name: str, +) -> None: + """Test cases that should not trigger a warning.""" + root_node = astroid.parse(code, module_name) + + with assert_no_messages(linter): + walk_checker(linter, add_entities_checker, root_node) + + +@pytest.mark.parametrize( + ("code", "expected_lines", "callback_name"), + [ + pytest.param( + """ +async def async_setup_entry(hass, entry, async_add_entities): + async_add_entities([SensorA()]) + async_add_entities([SensorB()]) +""", + [4], + "async_add_entities", + id="two_sequential", + ), + pytest.param( + """ +async def async_setup_entry(hass, entry, async_add_entities): + async_add_entities([SensorA()]) + async_add_entities([SensorB()]) + async_add_entities([SensorC()]) +""", + [4, 5], + "async_add_entities", + id="three_sequential", + ), + pytest.param( + """ +async def async_setup_entry(hass, entry, async_add_entities): + async_add_entities([SensorA()], config_subentry_id="subentry_1") + async_add_entities([SensorB()], config_subentry_id="subentry_1") +""", + [4], + "async_add_entities", + id="same_subentry", + ), + pytest.param( + """ +async def async_setup_entry(hass, entry, async_add_entities): + async_add_entities([SensorA()], True) + async_add_entities([SensorB()], update_before_add=True) +""", + [4], + "async_add_entities", + id="same_update_before_add_positional_and_keyword", + ), + pytest.param( + """ +async def async_setup_entry(hass, entry, async_add_entities): + for subentry_id, subentry in entry.subentries.items(): + async_add_entities([SensorA(subentry)], config_subentry_id=subentry_id) + async_add_entities([SensorB(subentry)], config_subentry_id=subentry_id) +""", + [5], + "async_add_entities", + id="same_subentry_in_loop", + ), + pytest.param( + """ +async def async_setup_entry(hass, entry, async_add_entities): + if entry.data["extra"]: + async_add_entities([SensorA()]) + async_add_entities([SensorB()]) +""", + [5], + "async_add_entities", + id="inside_if_block", + ), + pytest.param( + """ +async def async_setup_entry(hass, entry, async_add_entities): + @callback + def _async_add_new_devices(devices): + async_add_entities([SensorA(device) for device in devices]) + async_add_entities([SensorB(device) for device in devices]) +""", + [6], + "async_add_entities", + id="nested_callback", + ), + pytest.param( + """ +def setup_platform(hass, config, add_entities, discovery_info=None): + add_entities([SensorA()]) + add_entities([SensorB()]) +""", + [4], + "add_entities", + id="setup_platform", + ), + ], +) +def test_sequential_flagged( + linter: UnittestLinter, + add_entities_checker: SequentialAddEntitiesChecker, + code: str, + expected_lines: list[int], + callback_name: str, +) -> None: + """Test that sequential async_add_entities calls are flagged.""" + root_node = astroid.parse(code, INTEGRATION_MODULE) + walk_checker(linter, add_entities_checker, root_node) + + messages = linter.release_messages() + assert [message.line for message in messages] == expected_lines + assert {message.msg_id for message in messages} == { + "home-assistant-sequential-add-entities" + } + assert {message.args for message in messages} == {(callback_name,)}