浏览代码

Fix event handler string args (#928)

Nikhil Rao 2 年之前
父节点
当前提交
34d77db541
共有 3 个文件被更改,包括 24 次插入3 次删除
  1. 1 1
      pynecone/event.py
  2. 2 2
      pynecone/utils/format.py
  3. 21 0
      tests/test_event.py

+ 1 - 1
pynecone/event.py

@@ -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)}."

+ 2 - 2
pynecone/utils/format.py

@@ -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("}", "")
 

+ 21 - 0
tests/test_event.py

@@ -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 == ()