Add pylint checker for action registration outside services module (#185967)

This commit is contained in:
epenet
2026-10-14 16:34:34 +02:00
committed by GitHub
parent ffc459df18
commit 08979080ea
25 changed files with 602 additions and 0 deletions
@@ -198,6 +198,8 @@ class Configurator:
self._requests: dict[
str, tuple[str, list[dict[str, str]], ConfiguratorCallback | None]
] = {}
# Deprecated integration, to be removed in 2027.10
# pylint: disable-next=home-assistant-action-registered-outside-services-module
async_register_admin_service(
hass,
DOMAIN,
@@ -46,6 +46,8 @@ def setup_scanner(
battery=53,
)
# Should be adjusted to register actions in setup_services in services.py
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.register(DOMAIN, SERVICE_RANDOMIZE_DEVICE_TRACKER_DATA, observe)
return True
@@ -255,6 +255,8 @@ async def async_setup_integration(
data.pop("battery_status", None)
await tracker.async_see(**data)
# Cannot be moved: actions are registered per legacy platform
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.async_register(
DOMAIN, SERVICE_SEE, async_see_service, SERVICE_SEE_PAYLOAD_SCHEMA
)
@@ -1578,6 +1578,8 @@ def _async_register_service(
esphome_supports_response = service.supports_response or SupportsResponseType.NONE
ha_supports_response = _RESPONSE_TYPE_MAPPER.from_esphome(esphome_supports_response)
# Cannot be moved: action names come from the device
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.async_register(
DOMAIN,
service_name,
+2
View File
@@ -175,6 +175,8 @@ async def async_setup_platform(
await flux.async_flux_update()
service_name = slugify(f"{name} update")
# Cannot be moved: action names come from the configuration
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.async_register(SWITCH_DOMAIN, service_name, async_update)
@@ -607,6 +607,8 @@ async def _async_setup_themes(
hass.data[DATA_DEFAULT_DARK_THEME] = None
async_update_theme_and_fire_event(hass)
# Should be adjusted to register actions in async_setup_services in services.py
# pylint: disable-next=home-assistant-action-registered-outside-services-module
service.async_register_admin_service(
hass,
DOMAIN,
@@ -626,6 +628,7 @@ async def _async_setup_themes(
),
)
# pylint: disable-next=home-assistant-action-registered-outside-services-module
service.async_register_admin_service(
hass, DOMAIN, SERVICE_RELOAD_THEMES, reload_themes
)
@@ -317,20 +317,27 @@ def setup(hass: HomeAssistant, base_config: ConfigType) -> bool: # noqa: C901
def _start_cec(callback_event):
"""Register services and start HDMI network to watch for devices."""
# Should be adjusted to register actions in setup_services in services.py
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.register(
DOMAIN, SERVICE_SEND_COMMAND, _tx, SERVICE_SEND_COMMAND_SCHEMA
)
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.register(
DOMAIN, SERVICE_VOLUME, _volume, schema=SERVICE_VOLUME_SCHEMA
)
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.register(
DOMAIN,
SERVICE_UPDATE_DEVICES,
_update,
schema=SERVICE_UPDATE_DEVICES_SCHEMA,
)
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.register(DOMAIN, SERVICE_POWER_ON, _power_on)
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.register(DOMAIN, SERVICE_STANDBY, _standby)
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.register(DOMAIN, SERVICE_SELECT_DEVICE, _select_device)
hdmi_network.set_new_device_callback(_new_device)
@@ -210,6 +210,8 @@ async def async_setup_platform(
hass.bus.async_fire(EVENT_SCENE_RELOADED, context=call.context)
# Cannot be moved: scene actions are registered by the scene platform
# pylint: disable-next=home-assistant-action-registered-outside-services-module
async_register_admin_service(hass, SCENE_DOMAIN, SERVICE_RELOAD, reload_config)
async def apply_service(call: ServiceCall) -> None:
@@ -226,6 +228,7 @@ async def async_setup_platform(
reproduce_options=reproduce_options,
)
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.async_register(
SCENE_DOMAIN,
SERVICE_APPLY,
@@ -267,6 +270,7 @@ async def async_setup_platform(
await platform.async_remove_entity(entity_id)
async_add_entities([HomeAssistantScene(hass, scene_config, from_service=True)])
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.async_register(
SCENE_DOMAIN, SERVICE_CREATE, create_service, CREATE_SCENE_SCHEMA
)
@@ -297,6 +301,7 @@ async def async_setup_platform(
await platform.async_remove_entity(entity_id)
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.async_register(
SCENE_DOMAIN,
SERVICE_DELETE,
@@ -299,6 +299,8 @@ def setup(hass: HomeAssistant, config: ConfigType) -> bool:
# Call parameter
hmdevice.actionNodeData(param, True, channel)
# Should be adjusted to register actions in setup_services in services.py
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.register(
DOMAIN,
SERVICE_VIRTUALKEY,
@@ -326,6 +328,7 @@ def setup(hass: HomeAssistant, config: ConfigType) -> bool:
for hub in entities:
hub.hm_set_variable(name, value)
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.register(
DOMAIN,
SERVICE_SET_VARIABLE_VALUE,
@@ -337,6 +340,7 @@ def setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Service to reconnect all HomeMatic hubs."""
homematic.reconnect()
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.register(
DOMAIN,
SERVICE_RECONNECT,
@@ -375,6 +379,7 @@ def setup(hass: HomeAssistant, config: ConfigType) -> bool:
hmdevice.setValue(param, value, channel)
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.register(
DOMAIN,
SERVICE_SET_DEVICE_VALUE,
@@ -422,6 +427,7 @@ def setup(hass: HomeAssistant, config: ConfigType) -> bool:
)
homematic.putParamset(interface, address, paramset_key, paramset, rx_mode)
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.register(
DOMAIN,
SERVICE_PUT_PARAMSET,
@@ -107,11 +107,18 @@ def register_device(hass, api_key, name, device_id, device_ids, device_names):
api_key=api_key,
)
# Cannot be moved: action names come from the configuration
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.register(DOMAIN, f"{name}ring", ring_service)
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.register(DOMAIN, f"{name}set_wallpaper", set_wallpaper_service)
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.register(DOMAIN, f"{name}send_sms", send_sms_service)
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.register(DOMAIN, f"{name}send_file", send_file_service)
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.register(DOMAIN, f"{name}send_url", send_url_service)
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.register(DOMAIN, f"{name}send_tasker", send_tasker_service)
@@ -156,8 +156,12 @@ def setup(hass: HomeAssistant, config: ConfigType) -> bool:
minio_client.remove_object(bucket, key)
# Should be adjusted to register actions in setup_services in services.py
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.register(DOMAIN, "put", put_file, schema=BUCKET_KEY_FILE_SCHEMA)
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.register(DOMAIN, "get", get_file, schema=BUCKET_KEY_FILE_SCHEMA)
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.register(DOMAIN, "remove", remove_file, schema=BUCKET_KEY_SCHEMA)
return True
@@ -285,6 +285,8 @@ class BaseNotificationService:
):
continue
self.registered_targets[target_name] = target
# Cannot be moved: actions are registered per legacy platform
# pylint: disable-next=home-assistant-action-registered-outside-services-module
self.hass.services.async_register(
DOMAIN,
target_name,
@@ -312,6 +314,7 @@ class BaseNotificationService:
if self.hass.services.has_service(DOMAIN, self._service_name):
return
# pylint: disable-next=home-assistant-action-registered-outside-services-module
self.hass.services.async_register(
DOMAIN,
self._service_name,
@@ -107,6 +107,8 @@ def setup(hass: HomeAssistant, config: ConfigType) -> bool:
_LOGGER.error("Pilight send failed for %s", str(message_data))
def _register_service() -> None:
# Cannot be moved: the integration is disabled
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.async_register(
DOMAIN,
SERVICE_NAME,
@@ -44,6 +44,8 @@ def setup(hass: HomeAssistant, config: ConfigType) -> bool:
"""Handle reload service calls."""
discover_scripts(hass)
# Should be adjusted to register actions in setup_services in services.py
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.register(DOMAIN, SERVICE_RELOAD, reload_scripts_handler)
return True
@@ -76,6 +78,8 @@ def discover_scripts(hass: HomeAssistant) -> None:
for fil in glob.iglob(os.path.join(path, "*.py")):
name = os.path.splitext(os.path.basename(fil))[0]
# Cannot be moved: action names come from the script files
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.register(
DOMAIN,
name,
@@ -185,12 +185,15 @@ async def async_setup_entry(
# The services are registered here for now because they need the account name.
# The services are deprecated in favor of the todo platform.
# pylint: disable=home-assistant-service-registered-in-setup-entry
# Deprecated actions, to be removed in 2027.5
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.async_register(
DOMAIN,
f"{account_name}_create_task",
entity.create_task,
schema=SERVICE_SCHEMA_CREATE_TASK,
)
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.async_register(
DOMAIN,
f"{account_name}_complete_task",
@@ -274,6 +274,8 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
) from err
# register services
# Cannot be moved: action names come from the configuration
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.async_register(
DOMAIN,
name,
@@ -284,6 +286,8 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
for name, command_config in config[DOMAIN].items():
async_register_rest_command(name, command_config)
# Should be adjusted to register actions in async_setup_services in services.py
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.async_register(
DOMAIN, SERVICE_RELOAD, reload_service_handler, schema=probatio.Schema({})
)
@@ -67,6 +67,8 @@ def setup(hass: HomeAssistant, config: ConfigType) -> bool:
track_time_interval(hass, update_records_interval, INTERVAL)
# Should be adjusted to register actions in setup_services in services.py
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.register(DOMAIN, "update_records", update_records_service)
return True
@@ -220,15 +220,20 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
for script_entity in script_entities:
await script_entity.async_toggle(context=service.context, wait=False)
# Should be adjusted to register actions in async_setup_services in services.py
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.async_register(
DOMAIN, SERVICE_RELOAD, reload_service, schema=RELOAD_SERVICE_SCHEMA
)
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.async_register(
DOMAIN, SERVICE_TURN_ON, turn_on_service, schema=SCRIPT_TURN_ONOFF_SCHEMA
)
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.async_register(
DOMAIN, SERVICE_TURN_OFF, turn_off_service, schema=SCRIPT_TURN_ONOFF_SCHEMA
)
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.async_register(
DOMAIN, SERVICE_TOGGLE, toggle_service, schema=SCRIPT_TURN_ONOFF_SCHEMA
)
@@ -429,6 +429,8 @@ class ScriptEntity(BaseScriptEntity, RestoreEntity):
unique_id = self.unique_id
hass = self.hass
# Cannot be moved: each script is also registered as its own action
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.async_register(
DOMAIN,
unique_id,
@@ -172,6 +172,8 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
)
_LOGGER.warning("Skipping shell_command entry '%s': name is reserved", name)
continue
# Cannot be moved: action names come from the configuration
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.async_register(
DOMAIN,
name,
@@ -214,6 +216,8 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
"Skipping shell_command entry '%s': name is reserved", name
)
continue
# Cannot be moved: action names come from the configuration
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.async_register(
DOMAIN,
name,
@@ -221,6 +225,8 @@ async def async_setup(hass: HomeAssistant, config: ConfigType) -> bool:
supports_response=SupportsResponse.OPTIONAL,
)
# Should be adjusted to register actions in async_setup_services in services.py
# pylint: disable-next=home-assistant-action-registered-outside-services-module
service_helper.async_register_admin_service(
hass,
DOMAIN,
+2
View File
@@ -171,6 +171,8 @@ async def async_setup_legacy(
)
service_name = p_config.get(CONF_SERVICE_NAME, f"{p_type}_{SERVICE_SAY}")
# Cannot be moved: actions are registered per legacy platform
# pylint: disable-next=home-assistant-action-registered-outside-services-module
hass.services.async_register(
DOMAIN, service_name, async_say_handle, schema=SCHEMA_SERVICE_SAY
)
@@ -425,6 +425,8 @@ class ZWaveServices:
return val
# Should be adjusted to register actions outside the ZWaveServices class
# pylint: disable-next=home-assistant-action-registered-outside-services-module
self._hass.services.async_register(
const.DOMAIN,
const.SERVICE_SET_CONFIG_PARAMETER,
@@ -465,6 +467,7 @@ class ZWaveServices:
),
)
# pylint: disable-next=home-assistant-action-registered-outside-services-module
self._hass.services.async_register(
const.DOMAIN,
const.SERVICE_BULK_SET_PARTIAL_CONFIG_PARAMETERS,
@@ -497,6 +500,7 @@ class ZWaveServices:
),
)
# pylint: disable-next=home-assistant-action-registered-outside-services-module
self._hass.services.async_register(
const.DOMAIN,
const.SERVICE_REFRESH_VALUE,
@@ -514,6 +518,7 @@ class ZWaveServices:
),
)
# pylint: disable-next=home-assistant-action-registered-outside-services-module
self._hass.services.async_register(
const.DOMAIN,
const.SERVICE_SET_VALUE,
@@ -545,6 +550,7 @@ class ZWaveServices:
),
)
# pylint: disable-next=home-assistant-action-registered-outside-services-module
self._hass.services.async_register(
const.DOMAIN,
const.SERVICE_MULTICAST_SET_VALUE,
@@ -583,6 +589,7 @@ class ZWaveServices:
),
)
# pylint: disable-next=home-assistant-action-registered-outside-services-module
self._hass.services.async_register(
const.DOMAIN,
const.SERVICE_PING,
@@ -597,6 +604,7 @@ class ZWaveServices:
),
)
# pylint: disable-next=home-assistant-action-registered-outside-services-module
self._hass.services.async_register(
const.DOMAIN,
const.SERVICE_INVOKE_CC_API,
@@ -622,6 +630,7 @@ class ZWaveServices:
},
)
# pylint: disable-next=home-assistant-action-registered-outside-services-module
self._hass.services.async_register(
const.DOMAIN,
const.SERVICE_REFRESH_NOTIFICATIONS,
@@ -644,6 +653,7 @@ class ZWaveServices:
),
)
# pylint: disable-next=home-assistant-action-registered-outside-services-module
async_register_platform_entity_service(
self._hass,
const.DOMAIN,
@@ -657,6 +667,7 @@ class ZWaveServices:
supports_response=SupportsResponse.ONLY,
)
# pylint: disable-next=home-assistant-action-registered-outside-services-module
async_register_platform_entity_service(
self._hass,
const.DOMAIN,
@@ -670,6 +681,7 @@ class ZWaveServices:
func="async_set_lock_usercode",
)
# pylint: disable-next=home-assistant-action-registered-outside-services-module
async_register_platform_entity_service(
self._hass,
const.DOMAIN,
@@ -682,6 +694,7 @@ class ZWaveServices:
func="async_clear_lock_usercode",
)
# pylint: disable-next=home-assistant-action-registered-outside-services-module
async_register_platform_entity_service(
self._hass,
const.DOMAIN,
+20
View File
@@ -151,6 +151,8 @@ Every check has a code following the
| `W7448` | [`home-assistant-coordinator-redundant-config-entry`](#w7448-home-assistant-coordinator-redundant-config-entry) | Coordinator assigns `self.config_entry` that `DataUpdateCoordinator.__init__` already sets |
| `W7449` | [`home-assistant-coordinator-entity-available`](#w7449-home-assistant-coordinator-entity-available) | `CoordinatorEntity` overrides `available` with only `coordinator.data` and without `super().available` |
| `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` |
## `home_assistant_logger` checker
@@ -944,6 +946,24 @@ from `services.py`.
See the [action-setup quality scale rule](https://developers.home-assistant.io/docs/core/integration-quality-scale/rules/action-setup).
## `home_assistant_actions_services_module` checker
Detects actions registered outside the integration's `services.py`.
### `W7452`: `home-assistant-action-registered-outside-services-module`
Actions should be registered in `services.py`, from `async_setup_services`
(called from `async_setup`) or `setup_services` (called from a synchronous
`setup`). Module-level functions in `services.py` that are called from these
functions may register actions too.
### `W7453`: `home-assistant-invalid-setup-services`
`async_setup_services` should be a synchronous function decorated with
`@callback`, and `setup_services` a synchronous function that is not, since
it runs in the executor. Both should only take `hass`.
## `home_assistant_exception_translations` checker
Ensures `HomeAssistantError` and its subclasses use the translation system
@@ -0,0 +1,186 @@
"""Checker for action registration outside ``services.py``.
Actions must be registered in the integration's ``services.py``, from
``async_setup_services`` (a synchronous ``@callback`` function called from
``async_setup``) or ``setup_services`` (a synchronous function, not a
``@callback``, called from ``setup``). Both only take ``hass``.
Module-level functions in ``services.py`` called from these functions may
register actions too.
This checker flags:
- action registrations anywhere else in an integration
- an ``async_setup_services`` or ``setup_services`` with a different signature
https://developers.home-assistant.io/docs/core/integration-quality-scale/rules/action-setup/
"""
from astroid import nodes
from pylint.checkers import BaseChecker
from pylint.lint import PyLinter
from pylint_home_assistant.helpers.module_info import parse_module
# Setup function name and whether it must be a ``@callback``
_SETUP_FUNCTIONS = {
"async_setup_services": True,
"setup_services": False,
}
_REGISTRATION_FUNCTIONS = {
"async_register_admin_service",
"async_register_batched_entity_service",
"async_register_batched_platform_entity_service",
"async_register_entity_service",
"async_register_platform_entity_service",
}
def _is_action_registration(node: nodes.Call) -> bool:
"""Return True if *node* registers an action."""
match node.func:
# hass.services.async_register(...) / hass.services.register(...)
case nodes.Attribute(
attrname="async_register" | "register",
expr=nodes.Attribute(attrname="services"),
):
return True
case nodes.Name(name=name) | nodes.Attribute(attrname=name):
return name in _REGISTRATION_FUNCTIONS
return False
def _is_callback(node: nodes.FunctionDef) -> bool:
"""Return True if *node* is decorated with ``@callback``."""
if node.decorators is None:
return False
return any(
isinstance(decorator, (nodes.Name, nodes.Attribute))
and (getattr(decorator, "name", None) or getattr(decorator, "attrname", None))
== "callback"
for decorator in node.decorators.nodes
)
def _has_valid_signature(node: nodes.FunctionDef, callback: bool) -> bool:
"""Return True if *node* is a sync function taking only hass.
*callback* tells whether it must or must not be a ``@callback``.
"""
args = node.args
return (
not isinstance(node, nodes.AsyncFunctionDef)
and _is_callback(node) is callback
and [arg.name for arg in args.args] == ["hass"]
and not args.posonlyargs
and not args.kwonlyargs
and args.vararg is None
and args.kwarg is None
)
def _allowed_functions(module: nodes.Module) -> set[str]:
"""Return the module-level functions allowed to register actions.
These are the setup functions and the module-level functions they call,
directly or indirectly.
"""
functions = {
child.name: child
for child in module.body
if isinstance(child, nodes.FunctionDef)
}
allowed: set[str] = set()
pending = [name for name in _SETUP_FUNCTIONS if name in functions]
while pending:
name = pending.pop()
if name in allowed:
continue
allowed.add(name)
pending.extend(
call.func.name
for call in functions[name].nodes_of_class(nodes.Call)
if isinstance(call.func, nodes.Name)
and call.func.name in functions
# Async helpers run later, e.g. when scheduled as a task
and not isinstance(functions[call.func.name], nodes.AsyncFunctionDef)
)
return allowed
def _top_level_function(node: nodes.NodeNG) -> nodes.FunctionDef | None:
"""Return the module-level function containing *node*, if any."""
scope: nodes.NodeNG = node
while not isinstance(scope.parent, nodes.Module):
if scope.parent is None:
return None
scope = scope.parent
return scope if isinstance(scope, nodes.FunctionDef) else None
class ServicesModuleChecker(BaseChecker):
"""Checker for action registration outside ``services.py``."""
name = "home_assistant_actions_services_module"
priority = -1
msgs = {
"W7452": (
"Action registered outside `async_setup_services` or "
"`setup_services` in `services.py`",
"home-assistant-action-registered-outside-services-module",
"Used when an action is registered outside `async_setup_services` "
"or `setup_services` in the integration's `services.py`, or the "
"module-level functions they call.",
),
"W7453": (
"`%s` should be a synchronous function%s that only takes `hass`",
"home-assistant-invalid-setup-services",
"Used when `async_setup_services` or `setup_services` in "
"`services.py` is a coroutine, takes other arguments than `hass`, "
"or is (`setup_services`) or is not (`async_setup_services`) "
"decorated with `@callback`.",
),
}
options = ()
_in_integration: bool
_allowed: set[str]
def visit_module(self, node: nodes.Module) -> None:
"""Collect the functions allowed to register actions."""
module = parse_module(node.name)
self._in_integration = module is not None
self._allowed = set()
if module is None or module.module != "services":
return
self._allowed = _allowed_functions(node)
for child in node.body:
if (
isinstance(child, nodes.FunctionDef)
and (callback := _SETUP_FUNCTIONS.get(child.name)) is not None
and not _has_valid_signature(child, callback)
):
self.add_message(
"home-assistant-invalid-setup-services",
node=child,
args=(
child.name,
(" decorated" if callback else " not decorated")
+ " with `@callback`",
),
)
def visit_call(self, node: nodes.Call) -> None:
"""Check that actions are registered from async_setup_services."""
if not self._in_integration or not _is_action_registration(node):
return
function = _top_level_function(node)
if function is not None and function.name in self._allowed:
return
self.add_message(
"home-assistant-action-registered-outside-services-module", node=node
)
def register(linter: PyLinter) -> None:
"""Register the checker."""
linter.register_checker(ServicesModuleChecker(linter))
@@ -0,0 +1,308 @@
"""Tests for the services module checker."""
import astroid
from astroid import nodes
from pylint.testutils import MessageTest, UnittestLinter
from pylint_home_assistant.checkers.actions.services_module import ServicesModuleChecker
import pytest
from tests.pylint import assert_adds_messages, assert_no_messages, walk_checker
SERVICES_MODULE = "homeassistant.components.test_integration.services"
@pytest.fixture(name="services_module_checker")
def services_module_checker_fixture(
linter: UnittestLinter,
) -> ServicesModuleChecker:
"""Fixture to provide a services module checker."""
return ServicesModuleChecker(linter)
@pytest.mark.parametrize(
("code", "module_name"),
[
pytest.param(
"""
@callback
def async_setup_services(hass):
hass.services.async_register(DOMAIN, "my_action", _handler)
async_register_admin_service(hass, DOMAIN, "admin_action", _handler)
service.async_register_platform_entity_service(
hass, DOMAIN, "entity_action", entity_domain=LIGHT_DOMAIN, func="method"
)
""",
SERVICES_MODULE,
id="async_setup_services",
),
pytest.param(
"""
def setup_services(hass):
hass.services.register(DOMAIN, "my_action", _handler)
""",
SERVICES_MODULE,
id="setup_services",
),
pytest.param(
"""
@callback
def async_setup_services(hass):
_register_more(hass)
def _register_more(hass):
_register_even_more(hass)
def _register_even_more(hass):
hass.services.async_register(DOMAIN, "my_action", _handler)
""",
SERVICES_MODULE,
id="helper_called_from_async_setup_services",
),
pytest.param(
"""
def setup_services(hass):
_register_more(hass)
def _register_more(hass):
hass.services.register(DOMAIN, "my_action", _handler)
""",
SERVICES_MODULE,
id="helper_called_from_setup_services",
),
pytest.param(
"""
@core.callback
def async_setup_services(hass):
def _register() -> None:
hass.services.async_register(DOMAIN, "my_action", _handler)
_register()
""",
SERVICES_MODULE,
id="nested_function_in_async_setup_services",
),
pytest.param(
"""
async def async_setup_entry(hass, entry):
hass.services.async_register(DOMAIN, "my_action", handler)
""",
"tests.components.test_integration",
id="not_integration_module",
),
],
)
def test_no_warning(
linter: UnittestLinter,
services_module_checker: ServicesModuleChecker,
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, services_module_checker, root_node)
@pytest.mark.parametrize(
("code", "module_name", "line"),
[
pytest.param(
"""
async def async_setup(hass, config):
hass.services.async_register(DOMAIN, "my_action", handler)
""",
"homeassistant.components.test_integration",
3,
id="in_init",
),
pytest.param(
"""
def setup(hass, config):
hass.services.register(DOMAIN, "my_action", handler)
""",
"homeassistant.components.test_integration",
3,
id="sync_register_in_init",
),
pytest.param(
"""
async def async_setup(hass, config):
service.async_register_batched_platform_entity_service(
hass, DOMAIN, "my_action", entity_domain=MP_DOMAIN, func=handler
)
""",
"homeassistant.components.test_integration",
3,
id="batched_platform_entity_service_in_init",
),
pytest.param(
"""
async def async_setup_entry(hass, entry, async_add_entities):
platform = entity_platform.async_get_current_platform()
platform.async_register_entity_service("my_action", {}, "async_method")
""",
"homeassistant.components.test_integration.light",
4,
id="entity_service_in_platform",
),
pytest.param(
"""
@callback
def async_setup_services(hass):
hass.services.async_register(DOMAIN, "my_action", handler)
""",
"homeassistant.components.test_integration.helpers",
4,
id="async_setup_services_outside_services_module",
),
pytest.param(
"""
@callback
def register_actions(hass):
hass.services.async_register(DOMAIN, "my_action", handler)
""",
SERVICES_MODULE,
4,
id="other_function_in_services_module",
),
pytest.param(
"""
@callback
def async_setup_services(hass):
pass
def _register_more(hass):
hass.services.async_register(DOMAIN, "my_action", handler)
""",
SERVICES_MODULE,
7,
id="helper_not_called_from_setup",
),
pytest.param(
"""
class Actions:
def async_register(self):
self.hass.services.async_register(DOMAIN, "my_action", self.handler)
@callback
def async_setup_services(hass):
Actions(hass).async_register()
""",
SERVICES_MODULE,
4,
id="class_method",
),
pytest.param(
"""
@callback
def async_setup_services(hass):
hass.async_create_task(_async_register(hass))
async def _async_register(hass):
hass.services.async_register(DOMAIN, "my_action", handler)
""",
SERVICES_MODULE,
7,
id="async_helper_called_from_setup",
),
],
)
def test_registration_outside_services_module(
linter: UnittestLinter,
services_module_checker: ServicesModuleChecker,
code: str,
module_name: str,
line: int,
) -> None:
"""Test that registrations outside the setup functions are flagged."""
root_node = astroid.parse(code, module_name)
call = next(
node for node in root_node.nodes_of_class(nodes.Call) if node.lineno == line
)
with assert_adds_messages(
linter,
MessageTest(
msg_id="home-assistant-action-registered-outside-services-module",
node=call,
line=call.lineno,
col_offset=call.col_offset,
end_line=call.end_lineno,
end_col_offset=call.end_col_offset,
),
):
walk_checker(linter, services_module_checker, root_node)
@pytest.mark.parametrize(
("code", "args"),
[
pytest.param(
"""
def async_setup_services(hass):
pass
""",
("async_setup_services", " decorated with `@callback`"),
id="async_setup_services_not_callback",
),
pytest.param(
"""
@callback
async def async_setup_services(hass):
pass
""",
("async_setup_services", " decorated with `@callback`"),
id="async_setup_services_coroutine",
),
pytest.param(
"""
@callback
def async_setup_services(hass, config):
pass
""",
("async_setup_services", " decorated with `@callback`"),
id="async_setup_services_extra_argument",
),
pytest.param(
"""
@callback
def setup_services(hass):
pass
""",
("setup_services", " not decorated with `@callback`"),
id="setup_services_callback",
),
pytest.param(
"""
def setup_services(hass, *, config):
pass
""",
("setup_services", " not decorated with `@callback`"),
id="setup_services_extra_argument",
),
],
)
def test_invalid_setup_services(
linter: UnittestLinter,
services_module_checker: ServicesModuleChecker,
code: str,
args: tuple[str, str],
) -> None:
"""Test that setup functions with a wrong signature are flagged."""
root_node = astroid.parse(code, SERVICES_MODULE)
function = root_node.body[0]
with assert_adds_messages(
linter,
MessageTest(
msg_id="home-assistant-invalid-setup-services",
node=function,
args=args,
line=function.position.lineno,
col_offset=function.position.col_offset,
end_line=function.position.end_lineno,
end_col_offset=function.position.end_col_offset,
),
):
walk_checker(linter, services_module_checker, root_node)