Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion serde/de.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down
25 changes: 24 additions & 1 deletion tests/test_basics.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
TypeVar,
Any,
)
from collections import defaultdict
from collections import OrderedDict, defaultdict
from types import MappingProxyType

import pytest

Expand Down Expand Up @@ -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
Expand Down
Loading