diff --git a/homeassistant/components/configurator/__init__.py b/homeassistant/components/configurator/__init__.py index a4d9ab7fa61a..d952313639e9 100644 --- a/homeassistant/components/configurator/__init__.py +++ b/homeassistant/components/configurator/__init__.py @@ -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, diff --git a/homeassistant/components/demo/device_tracker.py b/homeassistant/components/demo/device_tracker.py index 25e24f03a7bd..a18a882e2151 100644 --- a/homeassistant/components/demo/device_tracker.py +++ b/homeassistant/components/demo/device_tracker.py @@ -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 diff --git a/homeassistant/components/device_tracker/legacy.py b/homeassistant/components/device_tracker/legacy.py index 06ee45136fd4..2472cc91e27a 100644 --- a/homeassistant/components/device_tracker/legacy.py +++ b/homeassistant/components/device_tracker/legacy.py @@ -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 ) diff --git a/homeassistant/components/esphome/manager.py b/homeassistant/components/esphome/manager.py index 0087002dd91a..d868b6d478f2 100644 --- a/homeassistant/components/esphome/manager.py +++ b/homeassistant/components/esphome/manager.py @@ -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, diff --git a/homeassistant/components/flux/switch.py b/homeassistant/components/flux/switch.py index c9b6c92cb962..90a4fdc09a02 100644 --- a/homeassistant/components/flux/switch.py +++ b/homeassistant/components/flux/switch.py @@ -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) diff --git a/homeassistant/components/frontend/__init__.py b/homeassistant/components/frontend/__init__.py index 35d39ed343f7..b89efe3babc7 100644 --- a/homeassistant/components/frontend/__init__.py +++ b/homeassistant/components/frontend/__init__.py @@ -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 ) diff --git a/homeassistant/components/hdmi_cec/__init__.py b/homeassistant/components/hdmi_cec/__init__.py index 4f920bf40097..cd6a5b1e2640 100644 --- a/homeassistant/components/hdmi_cec/__init__.py +++ b/homeassistant/components/hdmi_cec/__init__.py @@ -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) diff --git a/homeassistant/components/homeassistant/scene.py b/homeassistant/components/homeassistant/scene.py index 56829871c005..0615a17b693d 100644 --- a/homeassistant/components/homeassistant/scene.py +++ b/homeassistant/components/homeassistant/scene.py @@ -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, diff --git a/homeassistant/components/homematic/__init__.py b/homeassistant/components/homematic/__init__.py index c67d33c4a4f9..c7ad5bb2bf17 100644 --- a/homeassistant/components/homematic/__init__.py +++ b/homeassistant/components/homematic/__init__.py @@ -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, diff --git a/homeassistant/components/joaoapps_join/__init__.py b/homeassistant/components/joaoapps_join/__init__.py index fda5dacdb1af..2b8d88a2c1f2 100644 --- a/homeassistant/components/joaoapps_join/__init__.py +++ b/homeassistant/components/joaoapps_join/__init__.py @@ -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) diff --git a/homeassistant/components/minio/__init__.py b/homeassistant/components/minio/__init__.py index 2e7bf66e2428..4255c91ea71a 100644 --- a/homeassistant/components/minio/__init__.py +++ b/homeassistant/components/minio/__init__.py @@ -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 diff --git a/homeassistant/components/notify/legacy.py b/homeassistant/components/notify/legacy.py index 90d874819cb6..0802ce9d5768 100644 --- a/homeassistant/components/notify/legacy.py +++ b/homeassistant/components/notify/legacy.py @@ -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, diff --git a/homeassistant/components/pilight/__init__.py b/homeassistant/components/pilight/__init__.py index b8e5f706879b..4124b5942899 100644 --- a/homeassistant/components/pilight/__init__.py +++ b/homeassistant/components/pilight/__init__.py @@ -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, diff --git a/homeassistant/components/python_script/__init__.py b/homeassistant/components/python_script/__init__.py index be9757445cd6..94524b4cd70c 100644 --- a/homeassistant/components/python_script/__init__.py +++ b/homeassistant/components/python_script/__init__.py @@ -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, diff --git a/homeassistant/components/remember_the_milk/__init__.py b/homeassistant/components/remember_the_milk/__init__.py index d11eaf2630fe..f45463c4c7ed 100644 --- a/homeassistant/components/remember_the_milk/__init__.py +++ b/homeassistant/components/remember_the_milk/__init__.py @@ -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", diff --git a/homeassistant/components/rest_command/__init__.py b/homeassistant/components/rest_command/__init__.py index 7a92d033e310..b7f102f73a28 100644 --- a/homeassistant/components/rest_command/__init__.py +++ b/homeassistant/components/rest_command/__init__.py @@ -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({}) ) diff --git a/homeassistant/components/route53/__init__.py b/homeassistant/components/route53/__init__.py index 7dac648e6545..dc872b20f98e 100644 --- a/homeassistant/components/route53/__init__.py +++ b/homeassistant/components/route53/__init__.py @@ -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 diff --git a/homeassistant/components/script/__init__.py b/homeassistant/components/script/__init__.py index a9afe5cd4c0e..efe8d12a50be 100644 --- a/homeassistant/components/script/__init__.py +++ b/homeassistant/components/script/__init__.py @@ -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 ) diff --git a/homeassistant/components/script/entity.py b/homeassistant/components/script/entity.py index 71a4becfa9c7..5202b70f9917 100644 --- a/homeassistant/components/script/entity.py +++ b/homeassistant/components/script/entity.py @@ -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, diff --git a/homeassistant/components/shell_command/__init__.py b/homeassistant/components/shell_command/__init__.py index 089633a8bade..9c176499b419 100644 --- a/homeassistant/components/shell_command/__init__.py +++ b/homeassistant/components/shell_command/__init__.py @@ -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, diff --git a/homeassistant/components/tts/legacy.py b/homeassistant/components/tts/legacy.py index 4f2a50171da2..93ef9fac4f6d 100644 --- a/homeassistant/components/tts/legacy.py +++ b/homeassistant/components/tts/legacy.py @@ -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 ) diff --git a/homeassistant/components/zwave_js/services.py b/homeassistant/components/zwave_js/services.py index ec620ef4a843..825d018eb2f0 100644 --- a/homeassistant/components/zwave_js/services.py +++ b/homeassistant/components/zwave_js/services.py @@ -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, diff --git a/pylint/plugins/README.md b/pylint/plugins/README.md index c0486199a340..dfb3ca0a48d0 100644 --- a/pylint/plugins/README.md +++ b/pylint/plugins/README.md @@ -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 diff --git a/pylint/plugins/pylint_home_assistant/checkers/actions/services_module.py b/pylint/plugins/pylint_home_assistant/checkers/actions/services_module.py new file mode 100644 index 000000000000..e7633107118f --- /dev/null +++ b/pylint/plugins/pylint_home_assistant/checkers/actions/services_module.py @@ -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)) diff --git a/tests/pylint/actions/test_services_module.py b/tests/pylint/actions/test_services_module.py new file mode 100644 index 000000000000..c42439b53437 --- /dev/null +++ b/tests/pylint/actions/test_services_module.py @@ -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)