diff --git a/custom_components/pyscript/decorator.py b/custom_components/pyscript/decorator.py index 0e801e64..be88e058 100644 --- a/custom_components/pyscript/decorator.py +++ b/custom_components/pyscript/decorator.py @@ -284,6 +284,12 @@ async def _call(self, data: DispatchData) -> None: accepted = {a.arg for a in func_args.args + func_args.kwonlyargs} call_kwargs = {k: v for k, v in data.func_args.items() if k in accepted} result = await data.call_ast_ctx.call_func(self.eval_func, None, **call_kwargs) + except asyncio.CancelledError: + # the call was killed while running; let result handlers answer their callers + self.logger.debug("Call cancelled for %s", self.name) + for result_handler_dec in result_handlers: + await self.safe_await(result_handler_dec.handle_call_canceled(data)) + raise except Exception as e: for result_handler_dec in result_handlers: await self.safe_await(result_handler_dec.handle_call_exception(data, e)) @@ -325,4 +331,5 @@ async def dispatch(self, data: DispatchData) -> None: ) task = Function.create_task(self._call(data), ast_ctx=action_ast_ctx) + data.call_task = task Function.task_done_callback_ctx(task, action_ast_ctx) diff --git a/custom_components/pyscript/decorator_abc.py b/custom_components/pyscript/decorator_abc.py index d0ac74e4..e608b164 100644 --- a/custom_components/pyscript/decorator_abc.py +++ b/custom_components/pyscript/decorator_abc.py @@ -3,6 +3,7 @@ from __future__ import annotations from abc import ABC, abstractmethod +import asyncio from collections.abc import Awaitable from dataclasses import dataclass, field from enum import StrEnum @@ -46,6 +47,8 @@ class DispatchData: call_ast_ctx: AstEval | None = field(default=None, kw_only=True) hass_context: Context | None = field(default=None, kw_only=True) + # the task running the function, set by the manager once the call is started + call_task: asyncio.Task | None = field(default=None, kw_only=True) class Decorator(ABC): diff --git a/custom_components/pyscript/decorators/service.py b/custom_components/pyscript/decorators/service.py index b9b97935..e035eaea 100644 --- a/custom_components/pyscript/decorators/service.py +++ b/custom_components/pyscript/decorators/service.py @@ -3,24 +3,29 @@ from __future__ import annotations import ast +import asyncio from collections import OrderedDict import io import logging import typing +from typing import Any import voluptuous as vol import yaml from homeassistant.const import SERVICE_RELOAD -from homeassistant.core import ServiceCall, SupportsResponse +from homeassistant.core import ServiceCall, ServiceResponse, SupportsResponse +from homeassistant.exceptions import HomeAssistantError from homeassistant.helpers.service import async_set_service_schema -from .. import DOMAIN, SERVICE_JUPYTER_KERNEL_START, AstEval, Function, State +from .. import DOMAIN, SERVICE_JUPYTER_KERNEL_START, Function, State from ..decorator import FunctionDecoratorManager -from ..decorator_abc import Decorator +from ..decorator_abc import CallResultHandlerDecorator, DispatchData, TriggerDecorator _LOGGER = logging.getLogger(__name__) +_SERVICE_RESULT_FUTURE = "service_result_future" + def service_validator(args: list[str]) -> list[str]: """Validate and normalize service name.""" @@ -37,7 +42,7 @@ def service_validator(args: list[str]) -> list[str]: return [domain, name] -class ServiceDecorator(Decorator): +class ServiceDecorator(TriggerDecorator, CallResultHandlerDecorator): """Implementation for @service.""" name = "service" @@ -89,31 +94,56 @@ async def validate(self) -> None: fields[arg.arg] = OrderedDict(description=f"argument {arg.arg}") self.description = {"description": desc, "fields": fields} - async def _service_callback(self, call: ServiceCall) -> None: + async def _service_callback(self, call: ServiceCall) -> ServiceResponse: _LOGGER.info("Service callback: %s", call.service) - # use a new AstEval context so it can run fully independently - # of other instances (except for global_ctx which is common) - global_ctx = self.dm.eval_func.global_ctx - ast_ctx = AstEval(self.dm.name, global_ctx) - Function.install_ast_funcs(ast_ctx) func_args = { "trigger_type": "service", "context": call.context, } func_args.update(call.data) - async def do_service_call(func, ast_ctx, data): - try: - _LOGGER.debug("Service call start: %s", func.name) - return await func.call(ast_ctx, **data) - except Exception as exc: - await self.dm.handle_exception(exc) - return None - - task = Function.create_task(do_service_call(self.dm.eval_func, ast_ctx, func_args)) - await task - return task.result() + future = self.dm.hass.loop.create_future() + data = DispatchData(func_args, trigger_context={_SERVICE_RESULT_FUTURE: future}) + await self.dispatch(data) + try: + result = await future + except asyncio.CancelledError: + # the caller was cancelled (e.g. a restarted script): stop the function too + if data.call_task is not None: + data.call_task.cancel() + raise + if call.return_response and result is None: + # like HA scripts: a call that was skipped or returned nothing gives an empty response + return {} + return result + + async def handle_call_result(self, data: DispatchData, result: Any) -> None: + """ + Return the function result as the service response. + + A call that was skipped or cancelled (@state_active, @time_active, @task_unique) + gets None via the default handle_call_canceled. + """ + if data.trigger is not self: + return + future = data.trigger_context.get(_SERVICE_RESULT_FUTURE) + if future is not None and not future.done(): + future.set_result(result) + + async def handle_call_exception(self, data: DispatchData, exc: Exception) -> None: + """Fail the service call when the function raised; the manager still logs the exception.""" + if data.trigger is not self: + return + future = data.trigger_context.get(_SERVICE_RESULT_FUTURE) + if future is None or future.done(): + return + if isinstance(exc, HomeAssistantError): + future.set_exception(exc) + return + error = HomeAssistantError(f"{self.dm.name}() raised {type(exc).__name__}: {exc}") + error.__cause__ = exc + future.set_exception(error) async def start(self) -> None: """Register the service.""" diff --git a/docs/reference.rst b/docs/reference.rst index d2045e6c..a44a01c9 100644 --- a/docs/reference.rst +++ b/docs/reference.rst @@ -1183,13 +1183,25 @@ default), ``"only"``, or ``"optional"``, depending on whether the service provid provides a response, or sometimes provides a response. Services responses were added in HASS 2023.7. The service response is a dictionary returned by the function. -Other trigger decorators like ``@state_active`` and ``@time_active`` don't affect the service. -Those still allow state, time or other triggers to be specified in addition. +A service call is handled like any other trigger, so ``@state_active``, ``@time_active`` and +``@task_unique`` apply to it, and other triggers like ``@state_trigger`` or ``@time_trigger`` can be +added to the same function. If ``@state_active`` or ``@time_active`` evaluates to ``False``, or +``@task_unique(kill_me=True)`` finds the task already running, the function is not called. A call +that is cancelled by a newer call with the same ``@task_unique`` name doesn't complete either. In +these cases, and whenever the function returns ``None``, a caller that requested a response gets an +empty dictionary, as with Home Assistant scripts. If the function raises an exception, the service +call fails with a ``HomeAssistantError`` (shown in the UI and stopping a calling automation or +script), and the exception is also logged by pyscript. Like other triggers, each service call fires a +``pyscript_running`` event, which is shown in the logbook. + +With ``@time_active(hold_off_send_last=True)``, a service call that arrives during the hold-off +window is answered right away like a skipped call, but the function still runs with its parameters +when the window ends. The function is called with keyword parameters set to the service call parameters, plus -``trigger_type`` is set to ``"service"``. The function definition should specify all the -expected keyword arguments to match the service call parameters, or use the ``**kwargs`` -argument declaration to capture all the keyword arguments. +``trigger_type`` is set to ``"service"``. The function receives only the service call parameters +it declares; others are ignored unless the function uses the ``**kwargs`` argument declaration to +capture all of them. The ``doc_string`` (the string immediately after the function declaration) is used as the service description that appears is in the Services tab of the Developer Tools page. The function argument diff --git a/tests/decorators/test_service.py b/tests/decorators/test_service.py new file mode 100644 index 00000000..a07f03db --- /dev/null +++ b/tests/decorators/test_service.py @@ -0,0 +1,338 @@ +"""Test pyscript @service decorator.""" + +import asyncio +import pathlib +from unittest.mock import patch + +import pytest + +from custom_components.pyscript.const import DOMAIN +from homeassistant import loader +from homeassistant.core import Context +from homeassistant.exceptions import HomeAssistantError +from homeassistant.helpers.service import async_get_all_descriptions + + +@pytest.mark.asyncio +async def test_service_exists(pyscript, hass): + """Test discover, compile script and install a service.""" + await pyscript.start(""" +@service +def func1(): + pass + +# make sure a double definition still keeps the service registered +@service +@service("other.func1_renamed") +def func1(): + pass + +def func2(): + pass +""") + + assert hass.services.has_service("pyscript", "func1") + assert hass.services.has_service("other", "func1_renamed") + assert hass.services.has_service("pyscript", "reload") + assert not hass.services.has_service("pyscript", "func2") + + +@pytest.mark.asyncio +async def test_service_description(pyscript, hass): + """Test service description defined in doc_string.""" + await pyscript.start(""" +@service +def func_no_doc_string(param1=None): + pass + +@service +def func_simple_doc_string(param2=None, param3=None): + \"\"\"This is func2_simple_doc_string.\"\"\" + pass + +@service +def func_yaml_doc_string(param2=None, param3=None): + \"\"\"yaml +description: This is func_yaml_doc_string. +fields: + param1: + description: first argument + example: 12 + param2: + description: second argument + example: 34 +\"\"\" + pass +""") + + integration = loader.Integration( + hass, + "custom_components.pyscript", + pathlib.Path("custom_components/pyscript"), + {"name": "pyscript", "dependencies": [], "requirements": [], "domain": "automation"}, + ) + + with patch( + "homeassistant.loader.async_get_custom_components", + return_value={"pyscript": integration}, + ): + descriptions = (await async_get_all_descriptions(hass))[DOMAIN] + + assert descriptions["func_no_doc_string"]["description"] == "pyscript function func_no_doc_string()" + assert descriptions["func_no_doc_string"]["fields"] == {"param1": {"description": "argument param1"}} + + assert descriptions["func_simple_doc_string"]["description"] == "This is func2_simple_doc_string." + assert descriptions["func_simple_doc_string"]["fields"] == { + "param2": {"description": "argument param2"}, + "param3": {"description": "argument param3"}, + } + + assert descriptions["func_yaml_doc_string"]["description"] == "This is func_yaml_doc_string." + assert descriptions["func_yaml_doc_string"]["fields"] == { + "param1": {"description": "first argument", "example": 12}, + "param2": {"description": "second argument", "example": 34}, + } + + +@pytest.mark.asyncio +async def test_service_run(pyscript, hass, caplog): + """Test running a service with keyword arguments.""" + await pyscript.start(""" + +@service +def func1(arg1=1, arg2=2, context=None): + x = 1 + x = 2 * x + 3 + log.info(f"this is func1 x = {x}, arg1 = {arg1}, arg2 = {arg2}") + pyscript.done = [x, arg1, arg2, str(context)] + +# registering twice will cause it to be called twice +@service("other.func2") +@service("other.func2") +@service +def func2(**kwargs): + x = 1 + x = 2 * x + 3 + log.info(f"this is func1 x = {x}, kwargs = {kwargs}") + has2 = service.has_service("pyscript", "func2") + has3 = service.has_service("pyscript", "func3") + del kwargs["context"] + pyscript.done = [x, kwargs, has2, has3] + +@service +def call_service(domain=None, name=None, **kwargs): + if domain == "pyscript" and name == "func1": + task.sleep(0) + pyscript.func1(**kwargs) + else: + service.call(domain, name, **kwargs) + +""") + + context = Context(user_id="1234", parent_id="5678", id="8901") + await hass.services.async_call("pyscript", "func1", {}, context=context) + await pyscript.wait_done([5, 1, 2, str(context)]) + assert "this is func1 x = 5" in caplog.text + + await hass.services.async_call("pyscript", "func1", {"arg1": 10}, context=context) + await pyscript.wait_done([5, 10, 2, str(context)]) + + await hass.services.async_call( + "pyscript", + "call_service", + {"domain": "pyscript", "name": "func1", "arg1": "string1"}, + context=context, + ) + await pyscript.wait_done([5, "string1", 2, str(context)]) + + await hass.services.async_call("pyscript", "func1", {"arg1": "string1", "arg2": 123}, context=context) + await pyscript.wait_done([5, "string1", 123, str(context)]) + + await hass.services.async_call("pyscript", "call_service", {"domain": "pyscript", "name": "func2"}) + await pyscript.wait_done([5, {"trigger_type": "service"}, 1, 0]) + + await hass.services.async_call( + "pyscript", + "call_service", + {"domain": "pyscript", "name": "func2", "arg1": "string1"}, + ) + await pyscript.wait_done([5, {"trigger_type": "service", "arg1": "string1"}, 1, 0]) + + await hass.services.async_call("pyscript", "func2", {"arg1": "string1", "arg2": 456}) + await pyscript.wait_done([5, {"trigger_type": "service", "arg1": "string1", "arg2": 456}, 1, 0]) + + await hass.services.async_call("other", "func2", {"arg1": "string1", "arg2": 123}) + await pyscript.wait_done([5, {"trigger_type": "service", "arg1": "string1", "arg2": 123}, 1, 0]) + + +@pytest.mark.asyncio +async def test_service_reload_error(pyscript): + """Test using a reserved name generates an error.""" + await pyscript.start(""" +@service +def reload(): + pass +""") + + await pyscript.wait_exception( + SyntaxError, match="function 'reload' defined in file.hello: @service conflicts with builtin service" + ) + + +@pytest.mark.asyncio +async def test_service_wrong_arg_type(pyscript): + """Test a non-string service name generates an error.""" + await pyscript.start(""" +@service(1) +def func5(): + pass +""") + + await pyscript.wait_exception( + TypeError, + match="function 'func5' defined in file.hello: decorator @service argument 1 should be a string", + ) + + +@pytest.mark.asyncio +async def test_service_state_active_blocks_call(pyscript, hass): + """@state_active skips the service call and the caller gets no response.""" + hass.states.async_set("pyscript.enabled", "off") + await pyscript.start(""" +@service(supports_response="optional") +@state_active("pyscript.enabled == 'on'") +def guarded(x=None): + pyscript.done = ["ran", x] + return {"x": x} +""") + + assert await hass.services.async_call("pyscript", "guarded", {"x": 1}, blocking=True) is None + # like HA scripts, a skipped call gives an empty response when one is requested + response = await hass.services.async_call( + "pyscript", "guarded", {"x": 2}, blocking=True, return_response=True + ) + assert response == {} + assert pyscript.done.empty() + + hass.states.async_set("pyscript.enabled", "on") + response = await hass.services.async_call( + "pyscript", "guarded", {"x": 3}, blocking=True, return_response=True + ) + assert response == {"x": 3} + await pyscript.wait_done(["ran", 3]) + + +@pytest.mark.asyncio +async def test_service_time_active_blocks_call(pyscript, hass): + """@time_active applies to service calls.""" + await pyscript.start(""" +@service +@time_active("range(13:00, 14:00)") +def inactive(): + pyscript.done = "inactive ran" + +@service +@time_active("range(11:00, 13:00)") +def active(): + pyscript.done = "active ran" +""") + + await hass.services.async_call("pyscript", "inactive", {}, blocking=True) + await hass.services.async_call("pyscript", "active", {}, blocking=True) + await pyscript.wait_done("active ran") + + +@pytest.mark.asyncio +async def test_service_task_unique_kill_me(pyscript, hass): + """@task_unique(kill_me=True) skips a service call while the previous one is running.""" + hass.states.async_set("pyscript.release", "wait") + await pyscript.start(""" +@service +@task_unique("svc_kill_me", kill_me=True) +def slow(n=None): + pyscript.done = ["started", n] + task.wait_until(state_trigger="pyscript.release == 'go'") + pyscript.done = ["finished", n] +""") + + await hass.services.async_call("pyscript", "slow", {"n": 1}) + await pyscript.wait_done(["started", 1]) + # the second call is skipped and returns right away; the fixture fails on an extra ["started", 2] + await asyncio.wait_for(hass.services.async_call("pyscript", "slow", {"n": 2}, blocking=True), timeout=1) + hass.states.async_set("pyscript.release", "go") + await pyscript.wait_done(["finished", 1]) + + +@pytest.mark.asyncio +async def test_service_task_unique_cancelled_call_returns(pyscript, hass): + """A service call cancelled by a newer @task_unique call returns instead of hanging.""" + await pyscript.start(""" +@service +@task_unique("svc_restart") +def restart(n=None): + pyscript.done = ["started", n] + if n == 1: + task.sleep(10) # still running when the second call cancels it + pyscript.done = ["finished", n] +""") + + first = hass.async_create_task(hass.services.async_call("pyscript", "restart", {"n": 1}, blocking=True)) + await pyscript.wait_done(["started", 1]) + await hass.services.async_call("pyscript", "restart", {"n": 2}, blocking=True) + await pyscript.wait_done(["started", 2]) + await pyscript.wait_done(["finished", 2]) + assert await asyncio.wait_for(first, timeout=1) is None + + +@pytest.mark.asyncio +async def test_service_call_cancelled_by_caller_cancels_function(pyscript, hass): + """Cancelling a blocking service call (e.g. a restarted script) also cancels the running function.""" + await pyscript.start(""" +@service +def slow(): + pyscript.done = "started" + try: + task.sleep(10) + finally: + pyscript.done = "stopped" +""") + + call = hass.async_create_task(hass.services.async_call("pyscript", "slow", {}, blocking=True)) + await pyscript.wait_done("started") + call.cancel() + with pytest.raises(asyncio.CancelledError): + await call + + # the function is cancelled inside task.sleep() and reports it from its finally block + await pyscript.wait_done("stopped", timeout=1) + + +@pytest.mark.asyncio +async def test_service_no_result_gives_empty_response(pyscript, hass): + """A function returning nothing gives an empty response when one is requested, like HA scripts.""" + await pyscript.start(""" +@service(supports_response="optional") +def no_result(): + pass +""") + + assert await hass.services.async_call("pyscript", "no_result", {}, blocking=True) is None + response = await hass.services.async_call( + "pyscript", "no_result", {}, blocking=True, return_response=True + ) + assert response == {} + + +@pytest.mark.asyncio +async def test_service_exception_fails_call(pyscript, hass): + """An exception in the function fails the service call and is still logged by pyscript.""" + await pyscript.start(""" +@service +def broken(): + return 1 / 0 +""") + + with pytest.raises(HomeAssistantError, match=r"broken\(\) raised ZeroDivisionError") as excinfo: + await hass.services.async_call("pyscript", "broken", {}, blocking=True) + assert isinstance(excinfo.value.__cause__, ZeroDivisionError) + await pyscript.wait_exception(ZeroDivisionError) diff --git a/tests/decorators/test_webhook.py b/tests/decorators/test_webhook.py index cab7f79d..2ab5f338 100644 --- a/tests/decorators/test_webhook.py +++ b/tests/decorators/test_webhook.py @@ -351,3 +351,31 @@ def webhook_dup_b(**_): pass """) await pyscript.wait_exception(ValueError, match="Handler is already defined") + + +@pytest.mark.asyncio +async def test_webhook_handler_cancelled_by_task_unique(pyscript, hass): + """A request whose call is cancelled by a newer @task_unique call gets 503 right away, not a timeout.""" + await pyscript.start(""" +@webhook_handler("restart_hook", timeout=5) +@task_unique("restart_hook") +def handler(payload): + pyscript.done = ["started", payload["n"]] + if payload["n"] == 1: + task.sleep(10) # still running when the second request cancels it + return {"n": payload["n"]} +""") + + def request(n: int) -> MockRequest: + return _request(body=json.dumps({"n": n}).encode(), headers={"Content-Type": "application/json"}) + + first = hass.async_create_task(webhook.async_handle_webhook(hass, "restart_hook", request(1))) + await pyscript.wait_done(["started", 1]) + + second = await webhook.async_handle_webhook(hass, "restart_hook", request(2)) + await pyscript.wait_done(["started", 2]) + assert second.status == 200 + assert json.loads(second.text) == {"n": 2} + + first_response = await asyncio.wait_for(first, timeout=1) + assert first_response.status == 503 diff --git a/tests/test_decorator_errors.py b/tests/test_decorator_errors.py index dbb38da1..622c705c 100644 --- a/tests/test_decorator_errors.py +++ b/tests/test_decorator_errors.py @@ -364,26 +364,6 @@ def func11(): ) -@pytest.mark.asyncio -async def test_service_reload_error(hass, caplog): - """Test using a reserved name generates an error.""" - - await setup_script( - hass, - None, - dt(2020, 7, 1, 11, 59, 59, 999999), - """ -@service -def reload(): - pass -""", - ) - assert ( - "SyntaxError: function 'reload' defined in file.hello: @service conflicts with builtin service" - in caplog.text - ) - - @pytest.mark.asyncio async def test_service_state_active_extra_args(hass, caplog): """Test using extra args to state_active generates an error.""" @@ -404,26 +384,6 @@ def func4(): ) -@pytest.mark.asyncio -async def test_service_wrong_arg_type(hass, caplog): - """Test using too many args with service an error.""" - - await setup_script( - hass, - None, - dt(2020, 7, 1, 11, 59, 59, 999999), - """ -@service(1) -def func5(): - pass -""", - ) - assert ( - "TypeError: function 'func5' defined in file.hello: decorator @service argument 1 should be a string" - in caplog.text - ) - - @pytest.mark.asyncio async def test_time_trigger_wrong_arg_type(hass, caplog): """Test using wrong argument type generates an error.""" diff --git a/tests/test_decorator_manager.py b/tests/test_decorator_manager.py index fd8e28e6..52ced674 100644 --- a/tests/test_decorator_manager.py +++ b/tests/test_decorator_manager.py @@ -3,6 +3,7 @@ from __future__ import annotations import ast +import asyncio from collections.abc import Awaitable import logging from typing import Any, ClassVar @@ -325,7 +326,7 @@ def get_name(self) -> str: class DummyCallAstCtx: """Minimal action AstEval stub for manager call tests.""" - def __init__(self, result: object = None, exc: Exception | None = None) -> None: + def __init__(self, result: object = None, exc: BaseException | None = None) -> None: """Initialize the dummy action context.""" self.result = result self.exc = exc @@ -773,6 +774,30 @@ async def test_function_decorator_manager_exception_calls_handle_call_exception( assert ast_ctx.logged_exceptions == [exc] +@pytest.mark.asyncio +async def test_function_decorator_manager_task_cancelled(hass): + """A call cancelled while running (e.g. by @task_unique) resolves result handlers and stays cancelled.""" + DecoratorManager.hass = hass + ast_ctx = DummyAstCtx() + manager = FunctionDecoratorManager(ast_ctx, DummyEvalFuncVar()) + result_handler = make_full_recording_result_handler() + manager.add(result_handler) + call_ast_ctx = DummyCallAstCtx(exc=asyncio.CancelledError()) + + with pytest.raises(asyncio.CancelledError): + await call_function_manager( + manager, + make_dispatch_data( + {"arg1": 1}, call_ast_ctx=call_ast_ctx, hass_context=Context(id="call-parent") + ), + ) + + assert result_handler.canceled_calls == 1 + assert not result_handler.results + assert not result_handler.exceptions + assert not ast_ctx.logged_exceptions + + @pytest.mark.asyncio async def test_function_decorator_manager_cancel_calls_handle_call_canceled(hass): """On CallHandler veto, result handlers should receive handle_call_canceled (not handle_call_result).""" diff --git a/tests/test_init.py b/tests/test_init.py index ba88b577..e6c4f9bc 100644 --- a/tests/test_init.py +++ b/tests/test_init.py @@ -5,7 +5,6 @@ from datetime import datetime as dt import ntpath import os -import pathlib from types import SimpleNamespace from unittest.mock import mock_open, patch @@ -19,11 +18,9 @@ from custom_components.pyscript.function import Function from custom_components.pyscript.global_ctx import GlobalContextMgr from custom_components.pyscript.state import State -from homeassistant import loader from homeassistant.const import EVENT_STATE_CHANGED -from homeassistant.core import Context, State as HassState +from homeassistant.core import State as HassState from homeassistant.helpers.restore_state import DATA_RESTORE_STATE -from homeassistant.helpers.service import async_get_all_descriptions from homeassistant.setup import async_setup_component @@ -170,35 +167,6 @@ async def test_restore_state_unexpected_internals(hass, monkeypatch, caplog): assert "Unable to restore persisted pyscript state variables" in caplog.text -@pytest.mark.asyncio -async def test_service_exists(hass, caplog): - """Test discover, compile script and install a service.""" - - await setup_script( - hass, - None, - dt(2020, 7, 1, 11, 59, 59, 999999), - """ -@service -def func1(): - pass - -# make sure a double definition still keeps the service registered -@service -@service("other.func1_renamed") -def func1(): - pass - -def func2(): - pass -""", - ) - assert hass.services.has_service("pyscript", "func1") - assert hass.services.has_service("other", "func1_renamed") - assert hass.services.has_service("pyscript", "reload") - assert not hass.services.has_service("pyscript", "func2") - - @pytest.mark.asyncio async def test_syntax_error(hass, caplog): """Test syntax error in pyscript file.""" @@ -285,154 +253,6 @@ def div_zero_service(): assert "got exception division by zero" in caplog.text -@pytest.mark.asyncio -async def test_service_description(hass): - """Test service description defined in doc_string.""" - - await setup_script( - hass, - None, - dt(2020, 7, 1, 11, 59, 59, 999999), - """ -@service -def func_no_doc_string(param1=None): - pass - -@service -def func_simple_doc_string(param2=None, param3=None): - \"\"\"This is func2_simple_doc_string.\"\"\" - pass - -@service -def func_yaml_doc_string(param2=None, param3=None): - \"\"\"yaml -description: This is func_yaml_doc_string. -fields: - param1: - description: first argument - example: 12 - param2: - description: second argument - example: 34 -\"\"\" - pass -""", - ) - - integration = loader.Integration( - hass, - "custom_components.pyscript", - pathlib.Path("custom_components/pyscript"), - {"name": "pyscript", "dependencies": [], "requirements": [], "domain": "automation"}, - ) - - with patch( - "homeassistant.loader.async_get_custom_components", - return_value={"pyscript": integration}, - ): - descriptions = (await async_get_all_descriptions(hass))[DOMAIN] - - assert descriptions["func_no_doc_string"]["description"] == "pyscript function func_no_doc_string()" - assert descriptions["func_no_doc_string"]["fields"] == {"param1": {"description": "argument param1"}} - - assert descriptions["func_simple_doc_string"]["description"] == "This is func2_simple_doc_string." - assert descriptions["func_simple_doc_string"]["fields"] == { - "param2": {"description": "argument param2"}, - "param3": {"description": "argument param3"}, - } - - assert descriptions["func_yaml_doc_string"]["description"] == "This is func_yaml_doc_string." - assert descriptions["func_yaml_doc_string"]["fields"] == { - "param1": {"description": "first argument", "example": 12}, - "param2": {"description": "second argument", "example": 34}, - } - - -@pytest.mark.asyncio -async def test_service_run(hass, caplog): - """Test running a service with keyword arguments.""" - notify_q = asyncio.Queue(0) - await setup_script( - hass, - notify_q, - dt(2020, 7, 1, 11, 59, 59, 999999), - """ - -@service -def func1(arg1=1, arg2=2, context=None): - x = 1 - x = 2 * x + 3 - log.info(f"this is func1 x = {x}, arg1 = {arg1}, arg2 = {arg2}") - pyscript.done = [x, arg1, arg2, str(context)] - -# registering twice will cause it to be called twice -@service("other.func2") -@service("other.func2") -@service -def func2(**kwargs): - x = 1 - x = 2 * x + 3 - log.info(f"this is func1 x = {x}, kwargs = {kwargs}") - has2 = service.has_service("pyscript", "func2") - has3 = service.has_service("pyscript", "func3") - del kwargs["context"] - pyscript.done = [x, kwargs, has2, has3] - -@service -def call_service(domain=None, name=None, **kwargs): - if domain == "pyscript" and name == "func1": - task.sleep(0) - pyscript.func1(**kwargs) - else: - service.call(domain, name, **kwargs) - -""", - ) - context = Context(user_id="1234", parent_id="5678", id="8901") - await hass.services.async_call("pyscript", "func1", {}, context=context) - ret = await wait_until_done(notify_q) - assert literal_eval(ret) == [5, 1, 2, str(context)] - assert "this is func1 x = 5" in caplog.text - - await hass.services.async_call("pyscript", "func1", {"arg1": 10}, context=context) - ret = await wait_until_done(notify_q) - assert literal_eval(ret) == [5, 10, 2, str(context)] - - await hass.services.async_call( - "pyscript", - "call_service", - {"domain": "pyscript", "name": "func1", "arg1": "string1"}, - context=context, - ) - ret = await wait_until_done(notify_q) - assert literal_eval(ret) == [5, "string1", 2, str(context)] - - await hass.services.async_call("pyscript", "func1", {"arg1": "string1", "arg2": 123}, context=context) - ret = await wait_until_done(notify_q) - assert literal_eval(ret) == [5, "string1", 123, str(context)] - - await hass.services.async_call("pyscript", "call_service", {"domain": "pyscript", "name": "func2"}) - ret = await wait_until_done(notify_q) - assert literal_eval(ret) == [5, {"trigger_type": "service"}, 1, 0] - - await hass.services.async_call( - "pyscript", - "call_service", - {"domain": "pyscript", "name": "func2", "arg1": "string1"}, - ) - ret = await wait_until_done(notify_q) - assert literal_eval(ret) == [5, {"trigger_type": "service", "arg1": "string1"}, 1, 0] - - await hass.services.async_call("pyscript", "func2", {"arg1": "string1", "arg2": 456}) - ret = await wait_until_done(notify_q) - assert literal_eval(ret) == [5, {"trigger_type": "service", "arg1": "string1", "arg2": 456}, 1, 0] - - await hass.services.async_call("other", "func2", {"arg1": "string1", "arg2": 123}) - ret = await wait_until_done(notify_q) - assert literal_eval(ret) == [5, {"trigger_type": "service", "arg1": "string1", "arg2": 123}, 1, 0] - assert literal_eval(ret) == [5, {"trigger_type": "service", "arg1": "string1", "arg2": 123}, 1, 0] - - @pytest.mark.asyncio async def test_reload(hass, caplog): """Test reload."""