Throw better error for invalid child component (#655)

This commit is contained in:
Xiaojing Chen 2023-03-11 05:02:17 +08:00 committed by GitHub
parent ea5ef8ecb9
commit 3bf7d1f722
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 26 additions and 1 deletions

View File

@ -57,6 +57,9 @@ class Var(ABC):
Returns:
The var.
Raises:
TypeError: If the value is JSON-unserializable.
"""
# Check for none values.
if value is None:
@ -73,7 +76,12 @@ class Var(ABC):
value = json.loads(to_json(value))["data"] # type: ignore
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)

View File

@ -138,6 +138,23 @@ def test_create(value, expected):
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:
val = Var.create(value)
assert val is not None