Skip to content

Commit

Permalink
Fix throwing ValueError when invalid value type passed to from_dict
Browse files Browse the repository at this point in the history
  • Loading branch information
Fatal1ty committed Nov 15, 2023
1 parent dbb44a9 commit a0c6dc5
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
2 changes: 1 addition & 1 deletion mashumaro/core/meta/code/builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -453,7 +453,7 @@ def _add_unpack_method_lines(self, method_name: str) -> None:
self._unpack_method_set_value(
fname, ftype, metadata, alias=alias
)
with self.indent("except TypeError:"):
with self.indent("except AttributeError:"):
with self.indent("if not isinstance(d, dict):"):
self.add_line(
f"raise ValueError('Argument for "
Expand Down
27 changes: 27 additions & 0 deletions tests/test_exceptions.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
from dataclasses import dataclass
from typing import List, Union

import pytest

from mashumaro import DataClassDictMixin
from mashumaro.codecs import Decoder
from mashumaro.core.meta.helpers import type_name
from mashumaro.exceptions import (
InvalidFieldValue,
MissingDiscriminatorError,
Expand Down Expand Up @@ -163,3 +169,24 @@ def test_suitable_variant_not_found_error():
assert exc.variants_type == Union[str, int]
assert exc.discriminator_name == "type"
assert str(exc) == "typing.Union[str, int] has no suitable subtype"


def test_deserialize_dataclass_from_wrong_value_type():
@dataclass
class MyClass(DataClassDictMixin):
x: str

with pytest.raises(ValueError) as exc_info:
MyClass.from_dict(42)
assert str(exc_info.value) == (
f"Argument for {type_name(MyClass)}."
f"__mashumaro_from_dict__ method should be a dict instance"
)

decoder = Decoder(MyClass)
with pytest.raises(ValueError) as exc_info:
decoder.decode(42)
assert str(exc_info.value) == (
f"Argument for {type_name(MyClass)}."
f"__mashumaro_from_dict__ method should be a dict instance"
)

0 comments on commit a0c6dc5

Please sign in to comment.