diff --git a/serde/de.py b/serde/de.py index 779011d7..d11fb458 100644 --- a/serde/de.py +++ b/serde/de.py @@ -11,7 +11,7 @@ import functools import typing import jinja2 -from collections.abc import Callable, Sequence, Iterable +from collections.abc import Callable, Sequence, Iterable, Mapping from beartype import beartype, BeartypeConf from beartype.door import is_bearable @@ -337,6 +337,7 @@ def wrap(cls: type[T]) -> type[T]: g["class_deserializers"] = class_deserializers g["BeartypeCallHintParamViolation"] = BeartypeCallHintParamViolation g["is_bearable"] = is_bearable + g["_Mapping"] = Mapping if deserializer: g["serde_legacy_custom_class_deserializer"] = functools.partial( serde_legacy_custom_class_deserializer, custom=deserializer @@ -1404,6 +1405,11 @@ def {{func}}(cls=cls, maybe_generic=None, maybe_generic_type_vars=None, data=Non if reuse_instances is None: reuse_instances = {{serde_scope.reuse_instances_default}} + if data.__class__ is not dict and not isinstance(data, _Mapping): + raise SerdeError( + "Can not deserialize " + typename(type(data)) + " into {{class_name}}, expected a mapping" + ) + {% if deny_unknown_fields and not has_flatten_dict %} known_fields = {{ known_fields }} unknown_fields = set((data or {}).keys()) - known_fields diff --git a/tests/test_basics.py b/tests/test_basics.py index c9d14111..346bccdf 100644 --- a/tests/test_basics.py +++ b/tests/test_basics.py @@ -13,7 +13,8 @@ TypeVar, Any, ) -from collections import defaultdict +from collections import OrderedDict, defaultdict +from types import MappingProxyType import pytest @@ -1274,6 +1275,28 @@ class Bar: assert str(exc_info.value) == "missing required field 'a' while deserializing Foo" +def test_from_dict_rejects_non_mapping() -> None: + @serde.serde + class Foo: + a: str = "none" + + @serde.serde + class Bar: + foo: Foo + + for value in ([], ["a"], "", "a", ()): + with pytest.raises(serde.SerdeError, match="expected a mapping"): + serde.from_dict(Foo, value) + with pytest.raises(serde.SerdeError, match="expected a mapping"): + serde.from_dict(Bar, {"foo": value}) + + assert serde.from_dict(Foo, {}) == Foo() + assert serde.from_dict(Foo, {"a": "b"}) == Foo("b") + assert serde.from_dict(Bar, {"foo": {}}) == Bar(Foo()) + assert serde.from_dict(Foo, OrderedDict(a="b")) == Foo("b") + assert serde.from_dict(Foo, MappingProxyType({"a": "b"})) == Foo("b") + + def test_user_error() -> None: class MyException(Exception): pass