Skip to content

Commit 8ffa594

Browse files
authored
fix: surface nested mapping errors (#426)
1 parent 38d8123 commit 8ffa594

File tree

3 files changed

+24
-3
lines changed

3 files changed

+24
-3
lines changed

dataclasses_json/core.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -281,10 +281,12 @@ def _decode_generic(type_, value, infer_missing):
281281

282282
# get the constructor if using corresponding generic type in `typing`
283283
# otherwise fallback on constructing using type_ itself
284+
materialize_type = type_
284285
try:
285-
res = _get_type_cons(type_)(xs)
286+
materialize_type = _get_type_cons(type_)
286287
except (TypeError, AttributeError):
287-
res = type_(xs)
288+
pass
289+
res = materialize_type(xs)
288290
else: # Optional or Union
289291
_args = _get_type_args(type_)
290292
if _args is _NO_ARGS:

tests/entities.py

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -264,6 +264,19 @@ class DataClassWithConfigHelper:
264264
id: float = field(metadata=config(encoder=str))
265265

266266

267+
@dataclass_json
268+
@dataclass
269+
class DataClassWithErroneousDecode:
270+
# Accepts no arguments, so passing in a single argument will result in a TypeError.
271+
id: float = field(metadata=config(decoder=lambda: None))
272+
273+
274+
@dataclass_json
275+
@dataclass
276+
class DataClassMappingBadDecode:
277+
map: Dict[str, DataClassWithErroneousDecode]
278+
279+
267280
@dataclass_json(letter_case=LetterCase.CAMEL)
268281
@dataclass
269282
class DataClassWithConfigDecorator:

tests/test_nested.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,6 @@
1-
from tests.entities import (DataClassWithDataClass,
1+
import pytest
2+
from tests.entities import (DataClassMappingBadDecode,
3+
DataClassWithDataClass,
24
DataClassWithList,
35
DataClassWithNestedDictWithTupleKeys,
46
DataClassX,
@@ -25,6 +27,10 @@ def test_nested_list_of_dataclasses(self):
2527
assert (DataClassXs.from_json('{"xs": [{"x": 0}, {"x": 1}]}') ==
2628
DataClassXs([DataClassX(0), DataClassX(1)]))
2729

30+
def test_nested_mapping_of_dataclasses(self):
31+
with pytest.raises(TypeError, match="positional arguments"):
32+
DataClassMappingBadDecode.from_dict(dict(map=dict(test=dict(id="irrelevant"))))
33+
2834

2935
class TestNested:
3036
def test_tuple_dict_key(self):

0 commit comments

Comments
 (0)