From 1e39bf5a90b2cbe46a6adf5af929b5d5412de9b4 Mon Sep 17 00:00:00 2001 From: Sean Stoube <31805425+HoneyBearTech@users.noreply.github.com> Date: Sat, 21 Nov 2026 21:43:44 +0000 Subject: [PATCH 1/2] let trigger expressions start and end with blanks (#617) A trigger expression with a leading space or new line, such as @state_trigger(""" pyscript.a == 'x'"""), failed with IndentationError and the trigger was never created. Surrounding spaces, tabs and new lines are now stripped from a trigger expression before it is parsed, for @state_trigger, @state_active and the filters of @event_trigger, @mqtt_trigger and @webhook_trigger, for both the current and the legacy decorators, and for task.wait_until. Bare state names are stripped before they are recognised, so " pyscript.a" still means any change. Syntax errors show the stripped expression. The time triggers, eval() and script code are unchanged. Signed-off-by: Sean Stoube <31805425+HoneyBearTech@users.noreply.github.com> --- custom_components/pyscript/decorators/base.py | 3 +- .../pyscript/decorators/state.py | 10 +- custom_components/pyscript/trigger.py | 35 ++- docs/reference.rst | 6 + tests/test_decorator_errors.py | 233 ++++++++++++++++++ tests/test_unit_eval.py | 18 ++ tests/test_unit_trigger.py | 38 ++- 7 files changed, 330 insertions(+), 13 deletions(-) diff --git a/custom_components/pyscript/decorators/base.py b/custom_components/pyscript/decorators/base.py index 3babc243..2bd6f1f8 100644 --- a/custom_components/pyscript/decorators/base.py +++ b/custom_components/pyscript/decorators/base.py @@ -9,6 +9,7 @@ from ..decorator import FunctionDecoratorManager from ..decorator_abc import Decorator from ..eval import AstEval, Function +from ..trigger import strip_trigger_expr _LOGGER = logging.getLogger(__name__) @@ -54,7 +55,7 @@ def create_expression(self, expression: str) -> None: self.dm.name + " " + dec_name, self.dm.ast_ctx.global_ctx, self.dm.name ) Function.install_ast_funcs(self._ast_expression) - self._ast_expression.parse(expression, mode="eval") + self._ast_expression.parse(strip_trigger_expr(expression), mode="eval") def has_expression(self) -> bool: """Return True if expression was created.""" diff --git a/custom_components/pyscript/decorators/state.py b/custom_components/pyscript/decorators/state.py index 889d296d..e7d3035b 100644 --- a/custom_components/pyscript/decorators/state.py +++ b/custom_components/pyscript/decorators/state.py @@ -12,7 +12,12 @@ from ..decorator import WaitUntilDecoratorManager from ..decorator_abc import DecoratorManagerStatus, DispatchData, TriggerDecorator, TriggerHandlerDecorator from ..state import State -from ..trigger import ident_any_values_changed, ident_values_changed +from ..trigger import ( + any_trigger_exprs, + ident_any_values_changed, + ident_values_changed, + strip_trigger_expr, +) from .base import AutoKwargsDecorator, ExpressionDecorator STATE_RE = re.compile(r"\w+\.\w+(\.((\w+)|\*))?$") @@ -116,6 +121,7 @@ async def validate(self) -> None: state_trig = [] for trig in self.args: + trig = strip_trigger_expr(trig) if STATE_RE.match(trig): self.state_trig_ident_any.add(trig) else: @@ -125,7 +131,7 @@ async def validate(self) -> None: if len(state_trig) == 1: state_trig_expr = state_trig[0] else: - state_trig_expr = f"any([{', '.join(state_trig)}])" + state_trig_expr = any_trigger_exprs(state_trig) self.create_expression(state_trig_expr) diff --git a/custom_components/pyscript/trigger.py b/custom_components/pyscript/trigger.py index 2a16e3e5..420da913 100644 --- a/custom_components/pyscript/trigger.py +++ b/custom_components/pyscript/trigger.py @@ -32,6 +32,21 @@ STATE_RE = re.compile(r"\w+\.\w+(\.((\w+)|\*))?$") +def strip_trigger_expr(expr): + """Strip surrounding whitespace from a trigger expression (non-strings are returned as is).""" + return expr.strip(" \t\r\n") if isinstance(expr, str) else expr + + +def any_trigger_exprs(exprs): + """ + Join trigger expressions into one any([...]) expression. + + Each expression goes on its own lines, so a trailing # comment can't swallow the separator + or the closing bracket that follow it. + """ + return "any([" + "\n,\n".join(exprs) + "\n])" + + def dt_now(): """Return current time.""" return dt.datetime.now() @@ -274,6 +289,7 @@ async def wait_until( # on any change (no expr) # for trig in state_trigger: + trig = strip_trigger_expr(trig) if STATE_RE.match(trig): state_trig_ident_any.add(trig) else: @@ -283,7 +299,7 @@ async def wait_until( if len(state_trig) == 1: state_trig_expr = state_trig[0] else: - state_trig_expr = f"any([{', '.join(state_trig)}])" + state_trig_expr = any_trigger_exprs(state_trig) state_trig_eval = AstEval( f"{ast_ctx.name} state_trigger", ast_ctx.get_global_ctx(), @@ -336,7 +352,7 @@ async def wait_until( ) Function.install_ast_funcs(event_trig_expr) try: - event_trig_expr.parse(event_trigger[1], mode="eval") + event_trig_expr.parse(strip_trigger_expr(event_trigger[1]), mode="eval") except: if len(state_trig_ident) > 0: State.notify_del(state_trig_ident, notify_q) @@ -353,7 +369,7 @@ async def wait_until( ) Function.install_ast_funcs(mqtt_trig_expr) try: - mqtt_trig_expr.parse(mqtt_trigger[1], mode="eval") + mqtt_trig_expr.parse(strip_trigger_expr(mqtt_trigger[1]), mode="eval") except: if len(state_trig_ident) > 0: State.notify_del(state_trig_ident, notify_q) @@ -370,7 +386,7 @@ async def wait_until( ) Function.install_ast_funcs(webhook_trig_expr) try: - webhook_trig_expr.parse(webhook_trigger[1], mode="eval") + webhook_trig_expr.parse(strip_trigger_expr(webhook_trigger[1]), mode="eval") except: if len(state_trig_ident) > 0: State.notify_del(state_trig_ident, notify_q) @@ -916,7 +932,7 @@ def __init__( f"{self.name} @state_active()", self.global_ctx, logger_name=self.name ) Function.install_ast_funcs(self.active_expr) - self.active_expr.parse(self.state_active, mode="eval") + self.active_expr.parse(strip_trigger_expr(self.state_active), mode="eval") if "time_trigger" in trig_cfg and self.time_trigger is None: self.run_on_startup = True @@ -942,6 +958,7 @@ def __init__( # on any change (no expr) # for trig in triggers: + trig = strip_trigger_expr(trig) if STATE_RE.match(trig): self.state_trig_ident_any.add(trig) else: @@ -951,7 +968,7 @@ def __init__( if len(state_trig) == 1: self.state_trig_expr = state_trig[0] else: - self.state_trig_expr = f"any([{', '.join(state_trig)}])" + self.state_trig_expr = any_trigger_exprs(state_trig) self.state_trig_eval = AstEval( f"{self.name} @state_trigger()", self.global_ctx, logger_name=self.name ) @@ -972,7 +989,7 @@ def __init__( ) Function.install_ast_funcs(self.event_trig_expr) try: - self.event_trig_expr.parse(self.event_trigger[1], mode="eval") + self.event_trig_expr.parse(strip_trigger_expr(self.event_trigger[1]), mode="eval") except Exception as exc: self.event_trig_expr.log_exception(exc) return @@ -987,7 +1004,7 @@ def __init__( ) Function.install_ast_funcs(self.mqtt_trig_expr) try: - self.mqtt_trig_expr.parse(self.mqtt_trigger[1], mode="eval") + self.mqtt_trig_expr.parse(strip_trigger_expr(self.mqtt_trigger[1]), mode="eval") except Exception as exc: self.mqtt_trig_expr.log_exception(exc) return @@ -1002,7 +1019,7 @@ def __init__( ) Function.install_ast_funcs(self.webhook_trig_expr) try: - self.webhook_trig_expr.parse(self.webhook_trigger[1], mode="eval") + self.webhook_trig_expr.parse(strip_trigger_expr(self.webhook_trigger[1]), mode="eval") except Exception as exc: self.webhook_trig_expr.log_exception(exc) return diff --git a/docs/reference.rst b/docs/reference.rst index 8226ea61..27fc400a 100644 --- a/docs/reference.rst +++ b/docs/reference.rst @@ -546,6 +546,12 @@ The trigger can include arguments with any mixture of string expressions (that a when any of the underlying state variables change) and string state variable or attribute names (that trigger whenever that variable or attribute changes). +A trigger expression may start or end with spaces, tabs or new lines, which are ignored, so it can +be written over several lines in a triple-quoted string. Inside the expression Python's usual +rules still apply, so a multi-line expression needs brackets around it. The same goes for +``@state_active``, ``task.wait_until`` and the expressions of ``@event_trigger``, +``@mqtt_trigger`` and ``@webhook_trigger``. + Note that if a state variable and attributes are set to the same value, HASS doesn't generate a state change event, so the ``@state_trigger`` condition will not be checked. It is only evaluated each time a state variable or any of its attributes change to a new value. diff --git a/tests/test_decorator_errors.py b/tests/test_decorator_errors.py index dbb38da1..6312699a 100644 --- a/tests/test_decorator_errors.py +++ b/tests/test_decorator_errors.py @@ -522,3 +522,236 @@ def func7(): "TypeError: function 'func7' defined in file.hello: decorator @state_trigger keyword 'watch' should be type list or set" in caplog.text ) + + +TRIGGER_WHITESPACE_SOURCE = r""" +seq_num = 0 + +@time_trigger("startup") +def func_startup(): + pyscript.done = "startup" + +@state_trigger(" pyscript.a == '1'") +def func_space(value=None): + pyscript.done = "space" + +@state_trigger("\npyscript.b == '1'\n") +def func_newline(value=None): + pyscript.done = "newline" + +@state_trigger("\t pyscript.c == '1'\t") +def func_tab(value=None): + pyscript.done = "tab" + +@state_trigger(''' + (pyscript.d == '1' and + pyscript.e == '1') +''') +def func_multiline(value=None): + pyscript.done = "multiline" + +@state_trigger(" pyscript.f ", "\n pyscript.g == '1'") +def func_any(var_name=None): + pyscript.done = var_name + +@state_trigger(" pyscript.h == '1'") +@state_active("\n pyscript.active == '1'\n") +def func_active(): + pyscript.done = "active" + +@event_trigger("test_event", "\n arg1 == 1 \n") +def func_event(arg1=None): + pyscript.done = "event" + +@state_trigger("pyscript.w1 == '1'") +def func_wait(): + task.wait_until(state_trigger=" pyscript.w2 == 'go'\n", state_check_now=False) + pyscript.done = "waited state" + +@state_trigger("pyscript.w3 == '1'") +def func_wait_event(): + task.wait_until(event_trigger=["test_wait", "\t arg1 == 2 "]) + pyscript.done = "waited event" + +@state_trigger("pyscript.s == '1'") +def func_syntax(): + try: + task.wait_until(state_trigger="\n a b \n") + except SyntaxError as exc: + pyscript.done = f"syntax: {exc.msg} {exc.text} {exc.offset}" +""" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("legacy", [False, True], ids=["decorators", "legacy_decorators"]) +async def test_trigger_expression_whitespace(hass, caplog, monkeypatch, legacy): + """Trigger expressions may start and end with spaces, tabs and new lines.""" + if legacy: + monkeypatch.setenv("NODM", "1") + notify_q = asyncio.Queue(0) + await setup_script(hass, notify_q, [dt(2020, 7, 1, 10, 59, 59, 999999)], TRIGGER_WHITESPACE_SOURCE) + assert ("Using legacy decorators" in caplog.text) == legacy + + hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED) + assert await wait_until_done(notify_q) == "startup" + + async def check(expected): + assert await wait_until_done(notify_q) == expected + + hass.states.async_set("pyscript.a", "1") + await check("space") + hass.states.async_set("pyscript.b", "1") + await check("newline") + hass.states.async_set("pyscript.c", "1") + await check("tab") + hass.states.async_set("pyscript.d", "1") + hass.states.async_set("pyscript.e", "1") + await check("multiline") + + # the entity name is trimmed too, so it still means "any change" and the name is exact + hass.states.async_set("pyscript.f", "x") + await check("pyscript.f") + hass.states.async_set("pyscript.g", "1") + await check("pyscript.g") + + hass.states.async_set("pyscript.h", "1") + await hass.async_block_till_done() + assert notify_q.empty() + hass.states.async_set("pyscript.active", "1") + hass.states.async_set("pyscript.h", "0") + hass.states.async_set("pyscript.h", "1") + await check("active") + + hass.bus.async_fire("test_event", {"arg1": 0}) + await hass.async_block_till_done() + assert notify_q.empty() + hass.bus.async_fire("test_event", {"arg1": 1}) + await check("event") + + # task.wait_until: keep poking the state until the function is waiting + hass.states.async_set("pyscript.w1", "1") + for i in range(100): + if not notify_q.empty(): + break + hass.states.async_set("pyscript.w2", f"stop{i}") + hass.states.async_set("pyscript.w2", "go") + await asyncio.sleep(0.02) + await check("waited state") + + hass.states.async_set("pyscript.w3", "1") + for _ in range(100): + if not notify_q.empty(): + break + hass.bus.async_fire("test_wait", {"arg1": 1}) + hass.bus.async_fire("test_wait", {"arg1": 2}) + await asyncio.sleep(0.02) + await check("waited event") + + # a real syntax error reports the stripped expression, caret under the right place + hass.states.async_set("pyscript.s", "1") + # same message, text and offset as CPython gives for the stripped expression + with pytest.raises(SyntaxError) as exc_info: + compile("a b", "", "eval") + exc = exc_info.value + await check(f"syntax: {exc.msg} {exc.text} {exc.offset}") + + assert "IndentationError" not in caplog.text + + +@pytest.mark.asyncio +@pytest.mark.parametrize("legacy", [False, True], ids=["decorators", "legacy_decorators"]) +async def test_trigger_expression_whitespace_syntax_error(hass, caplog, monkeypatch, legacy): + """A broken trigger expression is shown stripped, with the marker under the problem.""" + if legacy: + monkeypatch.setenv("NODM", "1") + await setup_script( + hass, + None, + [dt(2020, 7, 1, 10, 59, 59, 999999)], + r""" +@state_trigger("\n \t(1 +\n * 2) \n") +def func1(): + pass + +@event_trigger("some_event", " \n a b ") +def func2(): + pass +""", + ) + assert ( + """File "/hello.py", line 2, in file.hello.func1 @state_trigger() + * 2) + ^ +SyntaxError: invalid syntax""" + in caplog.text + ) + assert ( + """File "/hello.py", line 1, in file.hello.func2 @event_trigger() + a b + ^ +SyntaxError: invalid syntax""" + in caplog.text + ) + assert "IndentationError" not in caplog.text + + +TRIGGER_COMMENT_SOURCE = r""" +@time_trigger("startup") +def func_startup(): + pyscript.done = "startup" + +@state_trigger("pyscript.c1 == '1' # first condition\n", "pyscript.c2 == '1'\t# last condition") +def func_comments(var_name=None): + pyscript.done = var_name + +@state_trigger(" pyscript.c3 == '1' # only condition\n") +def func_single_comment(): + pyscript.done = "single" + +@state_trigger("pyscript.w1 == '1'") +def func_wait_first(): + task.wait_until(state_trigger=["pyscript.w2 == 'go' # first\n", "pyscript.w3 == 'go' # last"], state_check_now=False) + pyscript.done = "waited first" + +@state_trigger("pyscript.w4 == '1'") +def func_wait_last(): + task.wait_until(state_trigger=["pyscript.w2 == 'go' # first\n", "pyscript.w3 == 'go' # last"], state_check_now=False) + pyscript.done = "waited last" +""" + + +@pytest.mark.asyncio +@pytest.mark.parametrize("legacy", [False, True], ids=["decorators", "legacy_decorators"]) +async def test_trigger_expression_comments(hass, caplog, monkeypatch, legacy): + """A # comment ending a trigger expression never swallows what follows it.""" + if legacy: + monkeypatch.setenv("NODM", "1") + notify_q = asyncio.Queue(0) + await setup_script(hass, notify_q, [dt(2020, 7, 1, 10, 59, 59, 999999)], TRIGGER_COMMENT_SOURCE) + assert ("Using legacy decorators" in caplog.text) == legacy + + hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED) + assert await wait_until_done(notify_q) == "startup" + + hass.states.async_set("pyscript.c1", "1") + assert await wait_until_done(notify_q) == "pyscript.c1" + hass.states.async_set("pyscript.c2", "1") + assert await wait_until_done(notify_q) == "pyscript.c2" + hass.states.async_set("pyscript.c3", "1") + assert await wait_until_done(notify_q) == "single" + + # task.wait_until with a list: the first entry ends in a comment, the last entry is a comment + for trig, entity, expected in ( + ("pyscript.w1", "pyscript.w2", "waited first"), + ("pyscript.w4", "pyscript.w3", "waited last"), + ): + hass.states.async_set(trig, "1") + for i in range(100): + if not notify_q.empty(): + break + hass.states.async_set(entity, f"stop{i}") + hass.states.async_set(entity, "go") + await asyncio.sleep(0.02) + assert await wait_until_done(notify_q) == expected + + assert "SyntaxError" not in caplog.text diff --git a/tests/test_unit_eval.py b/tests/test_unit_eval.py index 067bb8d4..63796744 100644 --- a/tests/test_unit_eval.py +++ b/tests/test_unit_eval.py @@ -4885,7 +4885,25 @@ async def test_class_init_super_match_python(hass, caplog): Function.install_ast_funcs(ast) ast.parse(source + "result\n") assert await ast.eval() == expected_ns["result"], source + await Function.waiter_sync() + await Function.waiter_stop() + await Function.reaper_stop() + +@pytest.mark.asyncio +@pytest.mark.parametrize("source", [" x = 1", "\n x = 1\n", "if True:\nx = 1"]) +async def test_script_indentation_stays_strict(hass, source): + """Only trigger expressions are stripped: script code keeps Python's indentation rules.""" + hass.data[DOMAIN] = {CONFIG_ENTRY: MockConfigEntry(domain=DOMAIN, data={CONF_ALLOW_ALL_IMPORTS: False})} + Function.init(hass) + with pytest.raises(IndentationError) as cpython_exc: + ast_module.parse(source) + ast = AstEval("test", global_ctx=GlobalContext("test", global_sym_table={}, manager=GlobalContextMgr)) + with pytest.raises(IndentationError) as exc: + ast.parse(source) + assert exc.value.msg == cpython_exc.value.msg + with pytest.raises(IndentationError): + ast.parse(" 1 + 1", mode="eval") await Function.waiter_sync() await Function.waiter_stop() await Function.reaper_stop() diff --git a/tests/test_unit_trigger.py b/tests/test_unit_trigger.py index 32281be9..692826c6 100644 --- a/tests/test_unit_trigger.py +++ b/tests/test_unit_trigger.py @@ -1,12 +1,13 @@ """Unit tests for time trigger functions.""" +import ast as ast_module from datetime import datetime as dt, timedelta from unittest.mock import patch import pytest from custom_components.pyscript.function import Function -from custom_components.pyscript.trigger import TrigTime +from custom_components.pyscript.trigger import TrigTime, strip_trigger_expr parseDateTimeTests = [ ["2019/9/12 13:45", 0, dt(2019, 9, 12, 13, 45, 0, 0)], @@ -717,3 +718,38 @@ async def test_timer_trigger_dst_next(hass): await Function.waiter_sync() await Function.waiter_stop() await Function.reaper_stop() + + +TRIGGER_EXPR_STRIP_TESTS = [ + ("x == 1", "x == 1"), + (" x == 1", "x == 1"), + ("x == 1 ", "x == 1"), + ("\nx == 1\n", "x == 1"), + ("\t x == 1 \t\r\n", "x == 1"), + ("\n (x == 1 and\n y == 2)\n", "(x == 1 and\n y == 2)"), + ("", ""), + (" \n ", ""), +] + + +@pytest.mark.parametrize("expr, expected", TRIGGER_EXPR_STRIP_TESTS) +def test_strip_trigger_expr(expr, expected): + """Surrounding blanks go; the inside of the expression is untouched.""" + assert strip_trigger_expr(expr) == expected + + +def test_strip_trigger_expr_not_str(): + """Values that aren't strings are left for the argument validation.""" + assert strip_trigger_expr(None) is None + assert strip_trigger_expr(3) == 3 + + +@pytest.mark.parametrize("expr, expected", TRIGGER_EXPR_STRIP_TESTS[1:6]) +def test_strip_trigger_expr_matches_cpython(expr, expected): + """Python rejects the unstripped text; the stripped text parses the same as the plain expression.""" + if expr[0] in " \t": + with pytest.raises(IndentationError): + ast_module.parse(expr, mode="eval") + assert ast_module.dump(ast_module.parse(strip_trigger_expr(expr), mode="eval")) == ast_module.dump( + ast_module.parse(expected, mode="eval") + ) From a2e13b72567f17b962ef2cc81d5b6c26adbd2baf Mon Sep 17 00:00:00 2001 From: Sean Stoube <31805425+HoneyBearTech@users.noreply.github.com> Date: Sun, 22 Nov 2026 22:15:48 +0000 Subject: [PATCH 2/2] let multi-line trigger expressions span lines without brackets (#617) Stripping the blanks wasn't enough for #617's own example: its lines end in "and" with no brackets around the whole expression. As one of several @state_trigger entries it already worked, inside the any([...]). A trigger expression that still has a line break after stripping is now parsed unstripped as "(" + expr + "\n)", by AstEval.parse_trigger_expr(). Its line numbers stay as written, and positions on its first line move back by one, in the logged error and in a caught SyntaxError. A one-line expression is stripped and parsed exactly as before. Nothing becomes valid only because of the added brackets: over several lines, a bare generator expression, a bare tuple, an empty expression, "a) or (b", and a bare := or yield give a SyntaxError. Inside the user's own brackets they work as before, and anything that parsed before still parses as before, such as a tuple followed by a comment line. Signed-off-by: Sean Stoube <31805425+HoneyBearTech@users.noreply.github.com> --- custom_components/pyscript/decorators/base.py | 3 +- .../pyscript/decorators/state.py | 6 +- custom_components/pyscript/eval.py | 87 ++++- custom_components/pyscript/trigger.py | 36 +- docs/reference.rst | 22 +- tests/decorators/test_webhook.py | 59 ++++ tests/test_decorator_errors.py | 324 ++++++++++++++---- tests/test_decorator_manager.py | 10 +- tests/test_unit_trigger.py | 240 +++++++++++++ 9 files changed, 685 insertions(+), 102 deletions(-) diff --git a/custom_components/pyscript/decorators/base.py b/custom_components/pyscript/decorators/base.py index 2bd6f1f8..bd3245c7 100644 --- a/custom_components/pyscript/decorators/base.py +++ b/custom_components/pyscript/decorators/base.py @@ -9,7 +9,6 @@ from ..decorator import FunctionDecoratorManager from ..decorator_abc import Decorator from ..eval import AstEval, Function -from ..trigger import strip_trigger_expr _LOGGER = logging.getLogger(__name__) @@ -55,7 +54,7 @@ def create_expression(self, expression: str) -> None: self.dm.name + " " + dec_name, self.dm.ast_ctx.global_ctx, self.dm.name ) Function.install_ast_funcs(self._ast_expression) - self._ast_expression.parse(strip_trigger_expr(expression), mode="eval") + self._ast_expression.parse_trigger_expr(expression) def has_expression(self) -> bool: """Return True if expression was created.""" diff --git a/custom_components/pyscript/decorators/state.py b/custom_components/pyscript/decorators/state.py index e7d3035b..616ad379 100644 --- a/custom_components/pyscript/decorators/state.py +++ b/custom_components/pyscript/decorators/state.py @@ -121,9 +121,9 @@ async def validate(self) -> None: state_trig = [] for trig in self.args: - trig = strip_trigger_expr(trig) - if STATE_RE.match(trig): - self.state_trig_ident_any.add(trig) + name = strip_trigger_expr(trig) + if STATE_RE.match(name): + self.state_trig_ident_any.add(name) else: state_trig.append(trig) diff --git a/custom_components/pyscript/eval.py b/custom_components/pyscript/eval.py index 5cbde344..735d8377 100644 --- a/custom_components/pyscript/eval.py +++ b/custom_components/pyscript/eval.py @@ -2415,6 +2415,88 @@ def parse(self, code_str: str | list[str], filename: str | None = None, mode: st self.code_list = [] self.ast = ast.parse(self.code_str, filename=self.filename, mode=mode) + def parse_trigger_expr(self, expr: str) -> None: + r""" + Parse a trigger expression. + + Blanks around it are stripped. If it still has a line break, it is parsed unstripped as + "(" + expr + "\n)", so it needs no brackets of its own and keeps its line numbers; positions + on its first line move back by the added "(". Nothing that is valid only because of the + added brackets is accepted; what parsed before (stripped) still parses as before. + """ + stripped = expr.strip(" \t\r\n") if isinstance(expr, str) else expr + if not isinstance(stripped, str) or ("\n" not in stripped and "\r" not in stripped): + self.parse(stripped, mode="eval") + return + self.ast = None + self.code_str = expr + # Python reads "\r\n" and "\r" as "\n"; joining with "\n" keeps the added ")" on a line of its own + self.code_list = expr.replace("\r\n", "\n").replace("\r", "\n").split("\n") + source = "\n".join(self.code_list) + try: + tree = ast.parse("(" + source + "\n)", filename=self.filename, mode="eval") + except SyntaxError as exc: + raise self._trigger_syntax_error( + exc.msg, exc.lineno, exc.offset, exc.end_lineno, exc.end_offset + ) from None + top, msg = tree.body, None + if (top.lineno, top.col_offset) == (1, 0): + # Python's parser says it starts at the added "(", so it needs that bracket + if isinstance(top, ast.Tuple): + msg = "tuple must be inside brackets" if top.elts else "expression is empty" + elif isinstance(top, ast.GeneratorExp): + msg = "generator expression must be inside brackets" + else: + msg = "unmatched ')'" + elif isinstance(top, (ast.NamedExpr, ast.Yield, ast.YieldFrom)): + # a bare ":=" or yield is an error as a keyword value, a bracketed one isn't + try: + ast.parse("f(value=" + source + "\n)", mode="eval") + except SyntaxError: + msg = ("':='" if isinstance(top, ast.NamedExpr) else "'yield'") + " must be inside brackets" + if msg: + try: + ast.parse(stripped, mode="eval") + except SyntaxError: + # point at the first part of it that the user wrote + starts = [ + (node.lineno, node.col_offset) for node in ast.walk(top) if hasattr(node, "lineno") + ] + lineno, col = min((start for start in starts if start != (1, 0)), default=(1, 1)) + raise self._trigger_syntax_error(msg, lineno, col + 1) from None + # valid without the added brackets, like "a, b" then a "# comment" line: parse it as before + self.parse(stripped, mode="eval") + return + for node in ast.walk(tree): + if getattr(node, "lineno", None) == 1: + node.col_offset -= 1 + if getattr(node, "end_lineno", None) == 1: + node.end_col_offset -= 1 + self.ast = tree + + def _trigger_syntax_error( + self, + msg: str, + lineno: int | None, + offset: int | None, + end_lineno: int | None = None, + end_offset: int | None = None, + ) -> SyntaxError: + r"""Return a SyntaxError, its position in "(" + expr + "\n)" moved onto the expression as written.""" + + def move(lineno: int, offset: int) -> tuple[int, int]: + if lineno > len(self.code_list): + # on the added ")": point at the end of the last line that isn't blank + lineno = max((idx for idx, line in enumerate(self.code_list, 1) if line.strip()), default=1) + return lineno, len(self.code_list[lineno - 1].rstrip()) + return lineno, max(offset - (lineno == 1), 1) + + start = move(lineno or 1, offset or 1) + end = move(end_lineno, end_offset or 1) if end_lineno else start + if end <= start: + end = (start[0], start[1] + 1) + return SyntaxError(msg, (self.filename, start[0], start[1], self.code_list[start[0] - 1], *end)) + def log_exception(self, exc: Exception) -> None: """Log eval exception.""" try: @@ -2586,7 +2668,10 @@ def _build_stack(self) -> None: self.current_filename = eval_func.global_ctx.get_file_path() elif code.co_qualname == AstEval.call_func.__qualname__ and self.current_func is None: self.current_func = frame.f_locals.get("func_name", None) - elif code.co_qualname == AstEval.parse.__qualname__ and isinstance(self.exc, SyntaxError): + elif code.co_qualname in ( + AstEval.parse.__qualname__, + AstEval.parse_trigger_expr.__qualname__, + ) and isinstance(self.exc, SyntaxError): ctx = frame.f_locals.get("self") self.current_code_list = ctx.code_list self.current_filename = ctx.global_ctx.get_file_path() or ctx.filename diff --git a/custom_components/pyscript/trigger.py b/custom_components/pyscript/trigger.py index 420da913..bd83fedd 100644 --- a/custom_components/pyscript/trigger.py +++ b/custom_components/pyscript/trigger.py @@ -41,10 +41,10 @@ def any_trigger_exprs(exprs): """ Join trigger expressions into one any([...]) expression. - Each expression goes on its own lines, so a trailing # comment can't swallow the separator - or the closing bracket that follow it. + Each expression is stripped and goes on its own lines, so a trailing # comment can't swallow + the separator or the closing bracket that follow it. """ - return "any([" + "\n,\n".join(exprs) + "\n])" + return "any([" + "\n,\n".join(strip_trigger_expr(expr) for expr in exprs) + "\n])" def dt_now(): @@ -289,9 +289,9 @@ async def wait_until( # on any change (no expr) # for trig in state_trigger: - trig = strip_trigger_expr(trig) - if STATE_RE.match(trig): - state_trig_ident_any.add(trig) + name = strip_trigger_expr(trig) + if STATE_RE.match(name): + state_trig_ident_any.add(name) else: state_trig.append(trig) @@ -306,7 +306,7 @@ async def wait_until( logger_name=ast_ctx.get_logger_name(), ) Function.install_ast_funcs(state_trig_eval) - state_trig_eval.parse(state_trig_expr, mode="eval") + state_trig_eval.parse_trigger_expr(state_trig_expr) state_trig_ident = await state_trig_eval.get_names() state_trig_ident.update(state_trig_ident_any) @@ -352,7 +352,7 @@ async def wait_until( ) Function.install_ast_funcs(event_trig_expr) try: - event_trig_expr.parse(strip_trigger_expr(event_trigger[1]), mode="eval") + event_trig_expr.parse_trigger_expr(event_trigger[1]) except: if len(state_trig_ident) > 0: State.notify_del(state_trig_ident, notify_q) @@ -369,7 +369,7 @@ async def wait_until( ) Function.install_ast_funcs(mqtt_trig_expr) try: - mqtt_trig_expr.parse(strip_trigger_expr(mqtt_trigger[1]), mode="eval") + mqtt_trig_expr.parse_trigger_expr(mqtt_trigger[1]) except: if len(state_trig_ident) > 0: State.notify_del(state_trig_ident, notify_q) @@ -386,7 +386,7 @@ async def wait_until( ) Function.install_ast_funcs(webhook_trig_expr) try: - webhook_trig_expr.parse(strip_trigger_expr(webhook_trigger[1]), mode="eval") + webhook_trig_expr.parse_trigger_expr(webhook_trigger[1]) except: if len(state_trig_ident) > 0: State.notify_del(state_trig_ident, notify_q) @@ -932,7 +932,7 @@ def __init__( f"{self.name} @state_active()", self.global_ctx, logger_name=self.name ) Function.install_ast_funcs(self.active_expr) - self.active_expr.parse(strip_trigger_expr(self.state_active), mode="eval") + self.active_expr.parse_trigger_expr(self.state_active) if "time_trigger" in trig_cfg and self.time_trigger is None: self.run_on_startup = True @@ -958,9 +958,9 @@ def __init__( # on any change (no expr) # for trig in triggers: - trig = strip_trigger_expr(trig) - if STATE_RE.match(trig): - self.state_trig_ident_any.add(trig) + name = strip_trigger_expr(trig) + if STATE_RE.match(name): + self.state_trig_ident_any.add(name) else: state_trig.append(trig) @@ -974,7 +974,7 @@ def __init__( ) Function.install_ast_funcs(self.state_trig_eval) try: - self.state_trig_eval.parse(self.state_trig_expr, mode="eval") + self.state_trig_eval.parse_trigger_expr(self.state_trig_expr) except Exception as exc: self.state_trig_eval.log_exception(exc) return @@ -989,7 +989,7 @@ def __init__( ) Function.install_ast_funcs(self.event_trig_expr) try: - self.event_trig_expr.parse(strip_trigger_expr(self.event_trigger[1]), mode="eval") + self.event_trig_expr.parse_trigger_expr(self.event_trigger[1]) except Exception as exc: self.event_trig_expr.log_exception(exc) return @@ -1004,7 +1004,7 @@ def __init__( ) Function.install_ast_funcs(self.mqtt_trig_expr) try: - self.mqtt_trig_expr.parse(strip_trigger_expr(self.mqtt_trigger[1]), mode="eval") + self.mqtt_trig_expr.parse_trigger_expr(self.mqtt_trigger[1]) except Exception as exc: self.mqtt_trig_expr.log_exception(exc) return @@ -1019,7 +1019,7 @@ def __init__( ) Function.install_ast_funcs(self.webhook_trig_expr) try: - self.webhook_trig_expr.parse(strip_trigger_expr(self.webhook_trigger[1]), mode="eval") + self.webhook_trig_expr.parse_trigger_expr(self.webhook_trigger[1]) except Exception as exc: self.webhook_trig_expr.log_exception(exc) return diff --git a/docs/reference.rst b/docs/reference.rst index 27fc400a..e249162a 100644 --- a/docs/reference.rst +++ b/docs/reference.rst @@ -546,11 +546,23 @@ The trigger can include arguments with any mixture of string expressions (that a when any of the underlying state variables change) and string state variable or attribute names (that trigger whenever that variable or attribute changes). -A trigger expression may start or end with spaces, tabs or new lines, which are ignored, so it can -be written over several lines in a triple-quoted string. Inside the expression Python's usual -rules still apply, so a multi-line expression needs brackets around it. The same goes for -``@state_active``, ``task.wait_until`` and the expressions of ``@event_trigger``, -``@mqtt_trigger`` and ``@webhook_trigger``. +A trigger expression may start or end with spaces, tabs or new lines, which are ignored. An +expression written over several lines, for example in a triple-quoted string, is read as if it were +inside brackets, so it needs no brackets of its own, and any of its lines can end with a +``# comment``: + +.. code:: python + + @state_trigger(""" + binary_sensor.motion == 'off' and # nobody there + light.porch == 'on' + """) + +An expression over several lines can't rely on those brackets for anything else: a bare generator +expression (forgetting the ``any()`` around ``x == 1 for x in ...``), a bare tuple that needs them +for its line break, an empty expression, or a bare ``:=`` or ``yield`` gives a ``SyntaxError``. +Inside brackets of your own they work as they do in Python. The same goes for ``@state_active``, ``task.wait_until`` and the +expressions of ``@event_trigger``, ``@mqtt_trigger``, ``@webhook_trigger`` and ``@webhook_handler``. Note that if a state variable and attributes are set to the same value, HASS doesn't generate a state change event, so the ``@state_trigger`` condition will not be checked. It is only evaluated diff --git a/tests/decorators/test_webhook.py b/tests/decorators/test_webhook.py index 4f6d67ec..2618640b 100644 --- a/tests/decorators/test_webhook.py +++ b/tests/decorators/test_webhook.py @@ -397,3 +397,62 @@ def webhook_dup_b(**_): pass """) await pyscript.wait_exception(ValueError, match="Handler is already defined") + + +@pytest.mark.asyncio +@pytest.mark.parametrize("legacy", [False, True]) +async def test_webhook_trigger_expression_over_several_lines(pyscript, hass, legacy): + """A webhook trigger expression can start with blanks and run over several lines without brackets.""" + pyscript.config = {DOMAIN: {CONF_LEGACY_DECORATORS: legacy}} + await pyscript.start(""" +@webhook_trigger("lines_hook", ''' + payload.get('a') == 1 and # first + payload.get('b') == 2 +''') +def webhook_lines(payload): + pyscript.done = payload + +@webhook_trigger("start_wait_hook") +def webhook_wait(payload): + task.wait_until(webhook_trigger=["wait_hook", "\\n payload.get('c') == 3 or\\n payload.get('c') == 4\\n"]) + pyscript.done = "waited" +""") + + def json_request(body: bytes) -> MockRequest: + return _request(body=body, headers={"Content-Type": "application/json"}) + + await webhook.async_handle_webhook(hass, "lines_hook", json_request(b'{"a": 1, "b": 0}')) + await hass.async_block_till_done() + assert pyscript.done.empty() + await webhook.async_handle_webhook(hass, "lines_hook", json_request(b'{"a": 1, "b": 2}')) + await pyscript.wait_done({"a": 1, "b": 2}) + + await webhook.async_handle_webhook(hass, "start_wait_hook", json_request(b"{}")) + for _ in range(100): + if not pyscript.done.empty(): + break + await webhook.async_handle_webhook(hass, "wait_hook", json_request(b'{"c": 4}')) + await asyncio.sleep(0.02) + await pyscript.wait_done("waited") + + +@pytest.mark.asyncio +async def test_webhook_handler_expression_over_several_lines(pyscript, hass): + """A @webhook_handler expression can start with blanks and run over several lines without brackets.""" + await pyscript.start(""" +@webhook_handler("lines_handler", ''' + payload.get('token') == 'secret' and + payload.get('user') == 'me' # both +''') +def webhook_lines_handler(payload, **_): + return {"ok": True} +""") + + for body, status in ( + (b'{"token": "secret", "user": "you"}', 403), + (b'{"token": "secret", "user": "me"}', 200), + ): + response = await webhook.async_handle_webhook( + hass, "lines_handler", _request(body=body, headers={"Content-Type": "application/json"}) + ) + assert response.status == status diff --git a/tests/test_decorator_errors.py b/tests/test_decorator_errors.py index 6312699a..3a9dad65 100644 --- a/tests/test_decorator_errors.py +++ b/tests/test_decorator_errors.py @@ -1,8 +1,11 @@ """Test pyscript decorator syntax error and eval-time exception reporting.""" +import ast from ast import literal_eval import asyncio from datetime import datetime as dt +import traceback +from types import SimpleNamespace from unittest.mock import mock_open, patch import pytest @@ -524,6 +527,27 @@ def func7(): ) +# the example in #617, as written there (its lines end in "and "), as a single trigger and as one of several +ISSUE_617_SOURCE = ( + "_state_sensor = 'sensor.office_state'\n" + "\n" + '@state_trigger(f"""\n' + "{_state_sensor} in ['recently occupied', 'unoccupied', 'dormant', 'unavailable'] and \n" + "(sensor.octoprint_actual_tool0_temp == 'unavailable' or float(sensor.octoprint_actual_tool0_temp) <= 110) and \n" + "(sensor.octoprint_actual_bed_temp == 'unavailable' or float(sensor.octoprint_actual_bed_temp) <= 110)\n" + '""", state_hold_false=0)\n' + "def should_turn_off():\n" + " pyscript.done = '617 single'\n" + "\n" + '@state_trigger("pyscript.never == \'1\'", f"""\n' + "{_state_sensor}2 in ['recently occupied', 'unoccupied', 'dormant', 'unavailable'] and \n" + "(sensor.printer2_tool0_temp == 'unavailable' or float(sensor.printer2_tool0_temp) <= 110) and \n" + "(sensor.printer2_bed_temp == 'unavailable' or float(sensor.printer2_bed_temp) <= 110)\n" + '""", state_hold_false=0)\n' + "def should_turn_off_2():\n" + " pyscript.done = '617 several'\n" +) + TRIGGER_WHITESPACE_SOURCE = r""" seq_num = 0 @@ -550,46 +574,100 @@ def func_tab(value=None): def func_multiline(value=None): pyscript.done = "multiline" +@state_trigger(''' + pyscript.m1 == '1' and # first condition + pyscript.m2 == '1' # last condition +''') +def func_no_brackets(): + pyscript.done = "no brackets" + +# a bare name and one expression: the expression is parsed on its own +@state_trigger("pyscript.crn ", "pyscript.cr1 == '1' and\r\n pyscript.cr2 == '1'") +def func_crlf(): + pyscript.done = "crlf" + +@state_trigger("pyscript.cr3 == '1' and\r pyscript.cr4 == '1'") +def func_cr(): + pyscript.done = "cr" + @state_trigger(" pyscript.f ", "\n pyscript.g == '1'") def func_any(var_name=None): pyscript.done = var_name +@state_trigger("pyscript.n1 ", "\n pyscript.n2 == '1' and # both\n pyscript.n3 == '1'\n", " pyscript.n4 == '1' # or this") +def func_mixed(var_name=None): + pyscript.done = f"mixed {var_name}" + +# one line: a tuple is always true, and a walrus in brackets works, as before +@state_trigger(" pyscript.t1 == 'no', pyscript.t2 == 'no' ") +def func_tuple(var_name=None): + pyscript.done = f"tuple {var_name}" + +@state_trigger("(k := pyscript.walrus) == '1' ") +def func_walrus(): + pyscript.done = "walrus" + @state_trigger(" pyscript.h == '1'") -@state_active("\n pyscript.active == '1'\n") +@state_active(''' + pyscript.active == '1' and + pyscript.active2 == '1' +''') def func_active(): pyscript.done = "active" -@event_trigger("test_event", "\n arg1 == 1 \n") -def func_event(arg1=None): +@event_trigger("test_event", "\n arg1 == 1 and\n arg2 == 2 \n") +def func_event(arg1=None, arg2=None): pyscript.done = "event" +@mqtt_trigger("test/topic", "\n payload == 'on' and # the payload\n topic == 'test/topic'\n") +def func_mqtt(): + pyscript.done = "mqtt" + @state_trigger("pyscript.w1 == '1'") def func_wait(): - task.wait_until(state_trigger=" pyscript.w2 == 'go'\n", state_check_now=False) + task.wait_until(state_trigger=" pyscript.w2 == 'go' and\n pyscript.w2b == 'go' # both\n", state_check_now=False) pyscript.done = "waited state" @state_trigger("pyscript.w3 == '1'") def func_wait_event(): - task.wait_until(event_trigger=["test_wait", "\t arg1 == 2 "]) + task.wait_until(event_trigger=["test_wait", "\t arg1 == 2 and\n arg2 == 3 "]) pyscript.done = "waited event" +@state_trigger("pyscript.w4 == '1'") +def func_wait_mqtt(): + task.wait_until(mqtt_trigger=["test/wait", "\n payload == 'go' or\n payload == 'went'\n"]) + pyscript.done = "waited mqtt" + @state_trigger("pyscript.s == '1'") def func_syntax(): - try: - task.wait_until(state_trigger="\n a b \n") - except SyntaxError as exc: - pyscript.done = f"syntax: {exc.msg} {exc.text} {exc.offset}" + for expr in ["\n a b \n", "\n a and\n b c\n"]: + try: + task.wait_until(state_trigger=expr) + except SyntaxError as exc: + pyscript.done = [exc.lineno, exc.offset, exc.text] """ @pytest.mark.asyncio @pytest.mark.parametrize("legacy", [False, True], ids=["decorators", "legacy_decorators"]) async def test_trigger_expression_whitespace(hass, caplog, monkeypatch, legacy): - """Trigger expressions may start and end with spaces, tabs and new lines.""" + """Trigger expressions may start and end with blanks, and run over several lines without brackets.""" if legacy: monkeypatch.setenv("NODM", "1") + mqtt_handlers = {} + + async def mqtt_subscribe(_hass, topic, handler, **_kwargs): + mqtt_handlers[topic] = handler + return lambda: None + + async def mqtt_message(topic, payload): + await mqtt_handlers[topic](SimpleNamespace(topic=topic, payload=payload, qos=0, retain=False)) + + monkeypatch.setattr("homeassistant.components.mqtt.async_subscribe", mqtt_subscribe) notify_q = asyncio.Queue(0) - await setup_script(hass, notify_q, [dt(2020, 7, 1, 10, 59, 59, 999999)], TRIGGER_WHITESPACE_SOURCE) + await setup_script( + hass, notify_q, [dt(2020, 7, 1, 10, 59, 59, 999999)], ISSUE_617_SOURCE + TRIGGER_WHITESPACE_SOURCE + ) assert ("Using legacy decorators" in caplog.text) == legacy hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED) @@ -598,6 +676,10 @@ async def test_trigger_expression_whitespace(hass, caplog, monkeypatch, legacy): async def check(expected): assert await wait_until_done(notify_q) == expected + async def check_none(): + await hass.async_block_till_done() + assert notify_q.empty() + hass.states.async_set("pyscript.a", "1") await check("space") hass.states.async_set("pyscript.b", "1") @@ -607,91 +689,197 @@ async def check(expected): hass.states.async_set("pyscript.d", "1") hass.states.async_set("pyscript.e", "1") await check("multiline") + for first, second, expected in ( + ("pyscript.m1", "pyscript.m2", "no brackets"), + ("pyscript.cr1", "pyscript.cr2", "crlf"), + ("pyscript.cr3", "pyscript.cr4", "cr"), + ): + hass.states.async_set(first, "1") + await check_none() + hass.states.async_set(second, "1") + await check(expected) + + # #617: false first (state_hold_false=0), then true when the last state changes + for suffix, temps, expected in ( + ("", "octoprint_actual", "617 single"), + ("2", "printer2", "617 several"), + ): + hass.states.async_set(f"sensor.office_state{suffix}", "occupied") + hass.states.async_set(f"sensor.{temps}_tool0_temp", "100") + hass.states.async_set(f"sensor.{temps}_bed_temp", "120") + await check_none() + hass.states.async_set(f"sensor.office_state{suffix}", "unoccupied") + await check_none() + hass.states.async_set(f"sensor.{temps}_bed_temp", "100") + await check(expected) # the entity name is trimmed too, so it still means "any change" and the name is exact hass.states.async_set("pyscript.f", "x") await check("pyscript.f") hass.states.async_set("pyscript.g", "1") await check("pyscript.g") + hass.states.async_set("pyscript.n1", "x") + await check("mixed pyscript.n1") + hass.states.async_set("pyscript.n2", "1") + await check_none() + hass.states.async_set("pyscript.n3", "1") + await check("mixed pyscript.n3") + hass.states.async_set("pyscript.n4", "1") + await check("mixed pyscript.n4") + + hass.states.async_set("pyscript.t1", "x") + await check("tuple pyscript.t1") + hass.states.async_set("pyscript.walrus", "0") + await check_none() + hass.states.async_set("pyscript.walrus", "1") + await check("walrus") hass.states.async_set("pyscript.h", "1") - await hass.async_block_till_done() - assert notify_q.empty() + await check_none() hass.states.async_set("pyscript.active", "1") + hass.states.async_set("pyscript.active2", "1") hass.states.async_set("pyscript.h", "0") hass.states.async_set("pyscript.h", "1") await check("active") - hass.bus.async_fire("test_event", {"arg1": 0}) - await hass.async_block_till_done() - assert notify_q.empty() - hass.bus.async_fire("test_event", {"arg1": 1}) + hass.bus.async_fire("test_event", {"arg1": 1, "arg2": 0}) + await check_none() + hass.bus.async_fire("test_event", {"arg1": 1, "arg2": 2}) await check("event") - # task.wait_until: keep poking the state until the function is waiting - hass.states.async_set("pyscript.w1", "1") - for i in range(100): - if not notify_q.empty(): - break + await mqtt_message("test/topic", "off") + await check_none() + await mqtt_message("test/topic", "on") + await check("mqtt") + + # task.wait_until: keep poking until the function is waiting + async def poke_until_done(start, poke, expected): + hass.states.async_set(start, "1") + for i in range(100): + if not notify_q.empty(): + break + await poke(i) + await asyncio.sleep(0.02) + await check(expected) + + async def poke_state(i): + hass.states.async_set("pyscript.w2b", "go") hass.states.async_set("pyscript.w2", f"stop{i}") hass.states.async_set("pyscript.w2", "go") - await asyncio.sleep(0.02) - await check("waited state") - - hass.states.async_set("pyscript.w3", "1") - for _ in range(100): - if not notify_q.empty(): - break - hass.bus.async_fire("test_wait", {"arg1": 1}) - hass.bus.async_fire("test_wait", {"arg1": 2}) - await asyncio.sleep(0.02) - await check("waited event") - - # a real syntax error reports the stripped expression, caret under the right place + + async def poke_event(_i): + hass.bus.async_fire("test_wait", {"arg1": 2, "arg2": 0}) + hass.bus.async_fire("test_wait", {"arg1": 2, "arg2": 3}) + + async def poke_mqtt(_i): + if "test/wait" in mqtt_handlers: + await mqtt_message("test/wait", "went") + + await poke_until_done("pyscript.w1", poke_state, "waited state") + await poke_until_done("pyscript.w3", poke_event, "waited event") + await poke_until_done("pyscript.w4", poke_mqtt, "waited mqtt") + + # a script catching the SyntaxError reads the line, place and text of the expression as written: + # one line is stripped, several lines keep their numbers hass.states.async_set("pyscript.s", "1") - # same message, text and offset as CPython gives for the stripped expression + for source, lines in (("a b", ["a b"]), ("\n a and\n b c\n", ["", " a and", " b c", ""])): + with pytest.raises(SyntaxError) as exc_info: + compile("(" + source + "\n)" if "\n" in source else source, "", "eval") + exc = exc_info.value + expected = [exc.lineno, exc.offset - (exc.lineno == 1 and "\n" in source), lines[exc.lineno - 1]] + assert literal_eval(await wait_until_done(notify_q)) == expected + + assert "IndentationError" not in caplog.text + + +# function name: (decorator and its leading arguments, expression) +TRIGGER_EXPR_ERRORS = { + "func1": ("state_trigger(", "\n \t(1 +\n * 2)\n"), + "func2": ('event_trigger("some_event", ', " \n a b "), + "func3": ("state_trigger(", "a b and\n c"), + "func4": ("state_trigger(", "\n pyscript.x == '1' and\n pyscript.y ==\n\n"), + "func5": ("state_trigger(", "\n pyscript.x == '1' and (\n pyscript.y == '1'"), + "func6": ("state_trigger(", "\n pyscript.x == '1'\n for x in [1]\n"), + "func7": ("state_trigger(", "1 / int(pyscript.r1) > 0 and\n True"), + "func8": ("state_trigger(", "\n pyscript.r2 == '1' and\n 1 / int(pyscript.r3) > 0\n"), +} + + +def trigger_expr_frame(name, lineno, line, col, end_col): + """Return the traceback text for one frame of a trigger expression, as Python's traceback shows it.""" + frame = traceback.FrameSummary( + "/hello.py", + lineno, + f"file.hello.{name} @{TRIGGER_EXPR_ERRORS[name][0].split('(')[0]}()", + lookup_line=False, + line=line, + end_lineno=lineno, + colno=col, + end_colno=end_col, + ) + return "".join(traceback.StackSummary.from_list([frame]).format()) + + +def python_syntax_error_frame(name): + """Return the frame for Python's own syntax error: on the stripped line, or in brackets for several lines.""" + expr = TRIGGER_EXPR_ERRORS[name][1] + stripped = expr.strip(" \t\r\n") + several = "\n" in stripped with pytest.raises(SyntaxError) as exc_info: - compile("a b", "", "eval") + compile("(" + expr + "\n)" if several else stripped, "", "eval") exc = exc_info.value - await check(f"syntax: {exc.msg} {exc.text} {exc.offset}") + lines = (expr if several else stripped).split("\n") + # the added "(" is gone from the first line + col, end_col = ( + exc.offset - 1 - (several and exc.lineno == 1), + exc.end_offset - 1 - (several and exc.end_lineno == 1), + ) + return trigger_expr_frame(name, exc.lineno, lines[exc.lineno - 1], col, end_col) - assert "IndentationError" not in caplog.text + +def python_runtime_error_frame(name): + """Return the frame for the division that fails, at its place in Python's tree for the text in brackets.""" + expr = TRIGGER_EXPR_ERRORS[name][1] + tree = ast.parse("(" + expr + "\n)", mode="eval") + node = next(node for node in ast.walk(tree) if isinstance(node, ast.BinOp)) + col, end_col = node.col_offset - (node.lineno == 1), node.end_col_offset - (node.end_lineno == 1) + return trigger_expr_frame(name, node.lineno, expr.split("\n")[node.lineno - 1], col, end_col) @pytest.mark.asyncio @pytest.mark.parametrize("legacy", [False, True], ids=["decorators", "legacy_decorators"]) -async def test_trigger_expression_whitespace_syntax_error(hass, caplog, monkeypatch, legacy): - """A broken trigger expression is shown stripped, with the marker under the problem.""" +async def test_trigger_expression_error_messages(hass, caplog, monkeypatch, legacy): + """An error in a trigger expression shows its line as written, with the marker under the problem.""" if legacy: monkeypatch.setenv("NODM", "1") - await setup_script( - hass, - None, - [dt(2020, 7, 1, 10, 59, 59, 999999)], - r""" -@state_trigger("\n \t(1 +\n * 2) \n") -def func1(): - pass - -@event_trigger("some_event", " \n a b ") -def func2(): - pass -""", - ) - assert ( - """File "/hello.py", line 2, in file.hello.func1 @state_trigger() - * 2) - ^ -SyntaxError: invalid syntax""" - in caplog.text - ) - assert ( - """File "/hello.py", line 1, in file.hello.func2 @event_trigger() - a b - ^ -SyntaxError: invalid syntax""" - in caplog.text + source = "".join( + f"@{dec}{expr!r})\ndef {name}():\n pass\n\n" for name, (dec, expr) in TRIGGER_EXPR_ERRORS.items() ) + await setup_script(hass, None, [dt(2020, 7, 1, 10, 59, 59, 999999)], source) + hass.bus.async_fire(EVENT_HOMEASSISTANT_STARTED) + await hass.async_block_till_done() + hass.states.async_set("pyscript.r1", "0") + hass.states.async_set("pyscript.r3", "0") + hass.states.async_set("pyscript.r2", "1") + await hass.async_block_till_done() + + for expected in [ + # where Python chooses the place: several lines keep their numbers, one line is stripped, + # and on the first line the marker is where it is in the text as written + python_syntax_error_frame("func1") + "SyntaxError: ", + python_syntax_error_frame("func2") + "SyntaxError: ", + python_syntax_error_frame("func3") + "SyntaxError: ", + # where this code chooses it: stopped short, at the end of the last line that isn't blank + trigger_expr_frame("func4", 3, " pyscript.y ==", 14, 15) + "SyntaxError: ", + # a bracket left open: Python blames the added one, at the start of the first line (blank here) + ' File "/hello.py", line 1, in file.hello.func5 @state_trigger()\nSyntaxError: ', + # needs the added brackets: at the first part the user wrote + trigger_expr_frame("func6", 2, " pyscript.x == '1'", 2, 3) + "SyntaxError: ", + # errors while it runs + python_runtime_error_frame("func7") + "ZeroDivisionError: ", + python_runtime_error_frame("func8") + "ZeroDivisionError: ", + ]: + assert expected in caplog.text assert "IndentationError" not in caplog.text diff --git a/tests/test_decorator_manager.py b/tests/test_decorator_manager.py index a4d17f5b..87fea5bf 100644 --- a/tests/test_decorator_manager.py +++ b/tests/test_decorator_manager.py @@ -293,12 +293,12 @@ def __init__(self, name: str, global_ctx: object, local_name: str) -> None: self.name = name self.global_ctx = global_ctx self.local_name = local_name - self.parse_calls: list[tuple[str, str]] = [] + self.parse_calls: list[str] = [] self.__class__.instances.append(self) - def parse(self, expression: str, mode: str) -> None: + def parse_trigger_expr(self, expression: str) -> None: """Record parse invocations.""" - self.parse_calls.append((expression, mode)) + self.parse_calls.append(expression) class DummyEvalFunc: @@ -561,7 +561,7 @@ def test_expression_decorator_create_expression_uses_manager_context(): assert ast_eval.name == "file.hello.func expression_test" assert ast_eval.global_ctx is dm.ast_ctx.global_ctx assert ast_eval.local_name == dm.name - assert ast_eval.parse_calls == [("value > 1", "eval")] + assert ast_eval.parse_calls == ["value > 1"] install_ast_funcs.assert_called_once_with(ast_eval) @@ -583,7 +583,7 @@ def test_expression_decorator_create_expression_formats_function_manager_name(): assert ast_eval.name == "file.hello.func @expression_test()" assert ast_eval.global_ctx is manager.ast_ctx.global_ctx assert ast_eval.local_name == manager.name - assert ast_eval.parse_calls == [("value > 1", "eval")] + assert ast_eval.parse_calls == ["value > 1"] install_ast_funcs.assert_called_once_with(ast_eval) diff --git a/tests/test_unit_trigger.py b/tests/test_unit_trigger.py index 692826c6..2dd42ad7 100644 --- a/tests/test_unit_trigger.py +++ b/tests/test_unit_trigger.py @@ -2,11 +2,17 @@ import ast as ast_module from datetime import datetime as dt, timedelta +import random from unittest.mock import patch +import warnings import pytest +from pytest_homeassistant.common import MockConfigEntry +from custom_components.pyscript.const import CONF_ALLOW_ALL_IMPORTS, CONFIG_ENTRY, DOMAIN +from custom_components.pyscript.eval import AstEval from custom_components.pyscript.function import Function +from custom_components.pyscript.global_ctx import GlobalContext, GlobalContextMgr from custom_components.pyscript.trigger import TrigTime, strip_trigger_expr parseDateTimeTests = [ @@ -753,3 +759,237 @@ def test_strip_trigger_expr_matches_cpython(expr, expected): assert ast_module.dump(ast_module.parse(strip_trigger_expr(expr), mode="eval")) == ast_module.dump( ast_module.parse(expected, mode="eval") ) + + +@pytest.fixture +async def trigger_ctx(hass): + """Return an AstEval for parsing trigger expressions.""" + hass.data[DOMAIN] = {CONFIG_ENTRY: MockConfigEntry(domain=DOMAIN, data={CONF_ALLOW_ALL_IMPORTS: False})} + Function.init(hass) + yield AstEval("test", global_ctx=GlobalContext("test", global_sym_table={}, manager=GlobalContextMgr)) + await Function.waiter_sync() + await Function.waiter_stop() + await Function.reaper_stop() + + +# one line after the blanks around it are stripped: parsed exactly as before, accepted or not +TRIGGER_EXPR_ONE_LINE = [ + " x == 1", + "\n x == 1 \t\r\n", + "x == 1 # comment\n", + "a, b", + "\na, b\n", + "(x := 1)", + "x := 1", + "\n x := 1\n", + "x == 1 for x in y", + "a) or (b", + "a b", + " a + \n", + "a\\\n", + " # comment\n", + " \n ", + "é == 1 b", +] + + +@pytest.mark.parametrize("expr", TRIGGER_EXPR_ONE_LINE) +async def test_parse_trigger_expr_one_line(trigger_ctx, expr): + """A one-line trigger expression is stripped and parsed as before, with Python's exact errors.""" + stripped = expr.strip(" \t\r\n") + try: + expected = ast_module.dump(ast_module.parse(stripped, mode="eval"), include_attributes=True) + except SyntaxError as exc: + with pytest.raises(SyntaxError) as ours: + trigger_ctx.parse_trigger_expr(expr) + assert (ours.value.msg, ours.value.lineno, ours.value.offset, ours.value.text) == ( + exc.msg, + exc.lineno, + exc.offset, + exc.text, + ) + return + trigger_ctx.parse_trigger_expr(expr) + assert ast_module.dump(trigger_ctx.ast, include_attributes=True) == expected + assert trigger_ctx.code_str == stripped + + +# several lines: read as if inside brackets; the user's own brackets work as in Python +TRIGGER_EXPR_SEVERAL_LINES = [ + "\n{_s} in ['a', 'b'] and \n(sensor.t0 == 'unavailable' or float(sensor.t0) <= 110) and \n(sensor.t1 <= 110)\n", + "a and # first\n b # last\n", + "# before\na and\nb", + "\n a and\n b\n\n", + "a and \\\n b", + "a and\r\n b", + "a and\r b", + "é == 'à' and\n f(b) > 1", + "f'{a})' == 'x)' and\n b", + "lambda x:\n x", + "(x := 1) and\n b", +] +TRIGGER_EXPR_BRACKETED = [ + "(x == 1 for x in y)", + "any(x == 1\n for x in y)", + "(a,\n b)", + "()", + "(x := 1)", + "(yield 1)", + "(yield from a)", +] + + +def trigger_expr_variants(exprs): + """Each expression after a comment line, and indented before a comment line.""" + return [ + variant + for expr in exprs + for variant in ("# comment\n" + expr, "\n " + expr.replace("\n", "\n ") + "\n # comment\n") + ] + + +@pytest.mark.parametrize("expr", TRIGGER_EXPR_SEVERAL_LINES + trigger_expr_variants(TRIGGER_EXPR_BRACKETED)) +async def test_parse_trigger_expr_several_lines(trigger_ctx, expr): + """A trigger expression over several lines parses as inside brackets, and each part keeps its place.""" + trigger_ctx.parse_trigger_expr(expr) + wrapped = ast_module.parse("(" + expr + "\n)", mode="eval") + assert ast_module.dump(trigger_ctx.ast) == ast_module.dump(wrapped) + assert trigger_ctx.code_str == expr + for ours, theirs in zip( + ast_module.walk(trigger_ctx.ast.body), ast_module.walk(wrapped.body), strict=True + ): + if hasattr(ours, "lineno"): + assert ours.lineno == theirs.lineno + # the same text, read from the expression as written + assert ast_module.get_source_segment(expr, ours) == ast_module.get_source_segment( + "(" + expr + "\n)", theirs + ) + + +# several lines, valid only because of the added brackets: each is an error +TRIGGER_EXPR_NEEDS_BRACKETS = [ + ("x == 1\n for x in y", "x == 1"), + ("a,\n b", "a,"), + ("*a,\n b", "*a,"), + ("a and\n b) or (c", "a and"), + ("x :=\n 1", "x :="), + ("yield\n 1", "yield"), + ("yield from\n a", "yield from"), +] + + +@pytest.mark.parametrize( + "expr, text", + [ + (variant, text) + for expr, text in TRIGGER_EXPR_NEEDS_BRACKETS + for variant in trigger_expr_variants([expr]) + ], +) +async def test_parse_trigger_expr_needs_brackets(trigger_ctx, expr, text): + """Over several lines, what would need the added brackets is a SyntaxError at its start.""" + with pytest.raises(SyntaxError) as exc: + trigger_ctx.parse_trigger_expr(expr) + assert trigger_ctx.ast is None + lines = expr.split("\n") + lineno = 2 if lines[0] in ("# comment", "") else 1 + assert (exc.value.lineno, exc.value.text.strip()) == (lineno, text) + assert exc.value.offset == len(lines[lineno - 1]) - len(lines[lineno - 1].lstrip()) + 1 + assert exc.value.args[1][1:] == ( + exc.value.lineno, + exc.value.offset, + exc.value.text, + exc.value.end_lineno, + exc.value.end_offset, + ) + + +@pytest.mark.parametrize("expr", ["# only a comment\n# and another", "\n # nothing\n\n"]) +async def test_parse_trigger_expr_empty(trigger_ctx, expr): + """An expression of only comments over several lines is a SyntaxError, as it is on one line.""" + with pytest.raises(SyntaxError): + trigger_ctx.parse_trigger_expr(expr) + + +@pytest.mark.parametrize( + "expr", + [ + "a b and\n c", + "é b and\n c", + "\n a and\n b c\n", + "\n a ==\n b = 1", + "a and\n b +\n\n", + "\n a + (b and\n c", + "a and\r b +\r", + "a and\r\n b +\r\n", + ], +) +async def test_parse_trigger_expr_syntax_error(trigger_ctx, expr): + """A syntax error over several lines is at the same place as in brackets, on the text as written.""" + with pytest.raises(SyntaxError) as cpython_exc: + ast_module.parse("(" + expr + "\n)", mode="eval") + with pytest.raises(SyntaxError) as exc: + trigger_ctx.parse_trigger_expr(expr) + lines = expr.replace("\r\n", "\n").replace("\r", "\n").split("\n") + lineno, offset = cpython_exc.value.lineno, cpython_exc.value.offset + # Python's line with the added ")" (a lone "\r" at the end joins its "\n") + closer = len(("(" + expr + "\n)").replace("\r\n", "\n").replace("\r", "\n").split("\n")) + if lineno == closer: + # stopped short: at the last character of the last line that isn't blank + lineno = max(idx for idx, line in enumerate(lines, 1) if line.strip()) + offset = len(lines[lineno - 1].rstrip()) + elif lineno == 1: + # the added "(" is gone; a bracket left open is blamed on it, at the start of the first line + offset = max(offset - 1, 1) + assert (exc.value.lineno, exc.value.offset, exc.value.text) == (lineno, offset, lines[lineno - 1]) + assert (exc.value.end_lineno, exc.value.end_offset) > (exc.value.lineno, exc.value.offset) + assert exc.value.args[1][1:4] == (exc.value.lineno, exc.value.offset, exc.value.text) + + +# valid once stripped, as before this change, although they only look like tuples needing brackets +TRIGGER_EXPR_STILL_VALID = [ + "a, b\n# trailing comment", + "a, (\n b\n)", + "a, \\\n b", + "a, '''x\ny'''", + "\n a, b\n # comment\n", + "a, (b,\n c) # c\n# d", + "(a\n), b", +] + + +@pytest.mark.parametrize("expr", TRIGGER_EXPR_STILL_VALID) +async def test_parse_trigger_expr_still_valid(trigger_ctx, expr): + """What parsed before (stripped) still parses, to the same tree with the same positions.""" + stripped = expr.strip(" \t\r\n") + trigger_ctx.parse_trigger_expr(expr) + assert ast_module.dump(trigger_ctx.ast, include_attributes=True) == ast_module.dump( + ast_module.parse(stripped, mode="eval"), include_attributes=True + ) + assert trigger_ctx.code_str == stripped + + +TRIGGER_EXPR_PIECES = [ + "a", "b", "1", ", ", " ", "\n", "\r", "\r\n", "\t", "(", ")", "[", "]", " and ", " or ", " == ", "*", + " for a in b", " if a else b", " := ", "yield ", "# c\n", "\\\n", "\'\'\'x\ny\'\'\'", "not ", "lambda: ", +] # fmt: skip + + +async def test_parse_trigger_expr_fuzz(trigger_ctx): + """For random text, anything that parsed before (stripped) still parses, to the same tree.""" + rand = random.Random(617) # noqa: S311 - a repeatable sample, not a secret + valid = several_lines = 0 + with warnings.catch_warnings(): + warnings.simplefilter("ignore", SyntaxWarning) # like "1not" + for _ in range(20000): + expr = "".join(rand.choice(TRIGGER_EXPR_PIECES) for _ in range(rand.randint(1, 8))) + stripped = expr.strip(" \t\r\n") + try: + expected = ast_module.dump(ast_module.parse(stripped, mode="eval")) + except SyntaxError: + continue + valid += 1 + several_lines += "\n" in stripped or "\r" in stripped + trigger_ctx.parse_trigger_expr(expr) + assert ast_module.dump(trigger_ctx.ast) == expected, repr(expr) + assert valid > 1000 and several_lines > 100