Fix event handler string args (#928)

This commit is contained in:
Nikhil Rao 2023-05-01 17:06:42 -07:00 committed by GitHub
parent d5977ffce4
commit 34d77db541
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 24 additions and 3 deletions

View File

@ -65,7 +65,7 @@ class EventHandler(Base):
# Otherwise, convert to JSON.
try:
values.append(Var.create(arg))
values.append(Var.create(arg, is_string=type(arg) is str))
except TypeError as e:
raise TypeError(
f"Arguments to event handlers must be Vars or JSON-serializable. Got {arg} of type {type(arg)}."

View File

@ -223,8 +223,8 @@ def format_cond(
# Format prop conds.
if is_prop:
prop1 = Var.create(true_value, is_string=type(true_value) == str)
prop2 = Var.create(false_value, is_string=type(false_value) == str)
prop1 = Var.create(true_value, is_string=type(true_value) is str)
prop2 = Var.create(false_value, is_string=type(false_value) is str)
assert prop1 is not None and prop2 is not None, "Invalid prop values"
return f"{cond} ? {prop1} : {prop2}".replace("{", "").replace("}", "")

View File

@ -34,26 +34,47 @@ def test_call_event_handler():
def test_fn():
pass
test_fn.__qualname__ = "test_fn"
def test_fn_with_args(_, arg1, arg2):
pass
test_fn_with_args.__qualname__ = "test_fn_with_args"
handler = EventHandler(fn=test_fn)
event_spec = handler()
assert event_spec.handler == handler
assert event_spec.local_args == ()
assert event_spec.args == ()
assert format.format_event(event_spec) == 'E("test_fn", {})'
handler = EventHandler(fn=test_fn_with_args)
event_spec = handler(make_var("first"), make_var("second"))
# Test passing vars as args.
assert event_spec.handler == handler
assert event_spec.local_args == ()
assert event_spec.args == (("arg1", "first"), ("arg2", "second"))
assert (
format.format_event(event_spec)
== 'E("test_fn_with_args", {arg1:first,arg2:second})'
)
# Passing args as strings should format differently.
event_spec = handler("first", "second") # type: ignore
assert (
format.format_event(event_spec)
== 'E("test_fn_with_args", {arg1:"first",arg2:"second"})'
)
first, second = 123, "456"
handler = EventHandler(fn=test_fn_with_args)
event_spec = handler(first, second) # type: ignore
assert (
format.format_event(event_spec)
== 'E("test_fn_with_args", {arg1:123,arg2:"456"})'
)
assert event_spec.handler == handler
assert event_spec.local_args == ()