Skip to content

Commit 6820cc8

Browse files
committed
fix(core): handle json from_dict correctly for optinal types
1 parent da206b9 commit 6820cc8

File tree

2 files changed

+28
-1
lines changed

2 files changed

+28
-1
lines changed

packages/core/src/robotcode/core/utils/dataclasses.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -419,6 +419,9 @@ def from_dict(
419419
match_type_hints: Optional[Dict[str, Any]] = None
420420

421421
for t in types:
422+
if t is type(None):
423+
continue
424+
422425
origin = _get_origin_cached(t)
423426

424427
if origin is Literal:
@@ -455,7 +458,7 @@ def from_dict(
455458
match_type_hints = type_hints
456459
elif match_same_keys is not None and len(match_same_keys) == len(same_keys):
457460
raise TypeError(
458-
f"Value {value!r} matches to more then one types of "
461+
f"Value {value!r} of type {type(value)!r} matches to more then one types of "
459462
f"{repr(types[0].__name__) if len(types) == 1 else ' | '.join(repr(e.__name__) for e in types)}."
460463
)
461464

tests/robotcode/core/test_dataclasses.py

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -594,6 +594,30 @@ def test_literal_with_invalid_args_should_raise_typerror(expr: Any, type: Any) -
594594
from_json(expr, type)
595595

596596

597+
@dataclass
598+
class SimpleData:
599+
a: Optional[int] = None
600+
b: Optional[str] = None
601+
602+
603+
@dataclass
604+
class ComplexData:
605+
data: Optional[SimpleData] = None
606+
more_data: Optional[str] = None
607+
608+
609+
@pytest.mark.parametrize(
610+
("expr", "type", "expected"),
611+
[
612+
('{"a":1, "b":"2"}', Optional[SimpleData], SimpleData(1, "2")),
613+
("{}", Optional[SimpleData], SimpleData()),
614+
("{}", Optional[ComplexData], ComplexData()),
615+
],
616+
)
617+
def test_empty_dict_should_not_match_none_type(expr: Any, type: Any, expected: str) -> None:
618+
assert from_json(expr, type, strict=True) == expected
619+
620+
597621
@dataclass
598622
class SimpleItemWithAlias:
599623
a: int = field(metadata={"alias": "a_test"})

0 commit comments

Comments
 (0)