浏览代码

Throw better error for invalid child component (#655)

Xiaojing Chen 2 年之前
父节点
当前提交
3bf7d1f722
共有 2 个文件被更改,包括 26 次插入1 次删除
  1. 9 1
      pynecone/var.py
  2. 17 0
      tests/test_var.py

+ 9 - 1
pynecone/var.py

@@ -57,6 +57,9 @@ class Var(ABC):
 
 
         Returns:
         Returns:
             The var.
             The var.
+
+        Raises:
+            TypeError: If the value is JSON-unserializable.
         """
         """
         # Check for none values.
         # Check for none values.
         if value is None:
         if value is None:
@@ -73,7 +76,12 @@ class Var(ABC):
             value = json.loads(to_json(value))["data"]  # type: ignore
             value = json.loads(to_json(value))["data"]  # type: ignore
             type_ = Figure
             type_ = Figure
 
 
-        name = value if isinstance(value, str) else json.dumps(value)
+        try:
+            name = value if isinstance(value, str) else json.dumps(value)
+        except TypeError as e:
+            raise TypeError(
+                f"To create a Var must be Var or JSON-serializable. Got {value} of type {type(value)}."
+            ) from e
 
 
         return BaseVar(name=name, type_=type_, is_local=is_local, is_string=is_string)
         return BaseVar(name=name, type_=type_, is_local=is_local, is_string=is_string)
 
 

+ 17 - 0
tests/test_var.py

@@ -138,6 +138,23 @@ def test_create(value, expected):
         assert prop.equals(expected)  # type: ignore
         assert prop.equals(expected)  # type: ignore
 
 
 
 
+def test_create_type_error():
+    """Test the var create function when inputs type error."""
+
+    class ErrorType:
+        pass
+
+    value = ErrorType()
+
+    with pytest.raises(TypeError) as exception:
+        Var.create(value)
+
+    assert (
+        exception.value.args[0]
+        == f"To create a Var must be Var or JSON-serializable. Got {value} of type {type(value)}."
+    )
+
+
 def v(value) -> Var:
 def v(value) -> Var:
     val = Var.create(value)
     val = Var.create(value)
     assert val is not None
     assert val is not None