diff --git a/src/cattrs/gen/typeddicts.py b/src/cattrs/gen/typeddicts.py index d5dcdab6..5fac557e 100644 --- a/src/cattrs/gen/typeddicts.py +++ b/src/cattrs/gen/typeddicts.py @@ -307,9 +307,16 @@ def make_dict_structure_fn( globs["__c_a"] = allowed_fields globs["__c_feke"] = ForbiddenExtraKeysError - lines.append(" res = o.copy()") - if _cattrs_detailed_validation: + # When running under detailed validation, be extra careful about copying + # so that the correct error is raised if the input isn't a dict. + lines.append(" try:") + lines.append(" res = o.copy()") + lines.append(" except Exception as exc:") + lines.append( + f" raise __c_cve('While structuring ' + {cl.__name__!r}, [exc], __cl)" + ) + lines.append(" errors = []") internal_arg_parts["__c_cve"] = ClassValidationError internal_arg_parts["__c_avn"] = AttributeValidationNote @@ -383,6 +390,7 @@ def make_dict_structure_fn( f" if errors: raise __c_cve('While structuring ' + {cl.__name__!r}, errors, __cl)" ) else: + lines.append(" res = o.copy()") non_required = [] # The first loop deals with required args. diff --git a/tests/test_typeddicts.py b/tests/test_typeddicts.py index da0cf109..7583d6aa 100644 --- a/tests/test_typeddicts.py +++ b/tests/test_typeddicts.py @@ -10,7 +10,7 @@ from pytest import raises from typing_extensions import NotRequired, Required -from cattrs import BaseConverter, Converter +from cattrs import BaseConverter, Converter, transform_error from cattrs._compat import ExtensionsTypedDict, get_notrequired_base, is_generic from cattrs.errors import ( ClassValidationError, @@ -509,3 +509,12 @@ class A(ExtensionsTypedDict): assert converter.unstructure({"a": 10, "b": 10}, A) == {"a": 1, "b": 2} assert converter.structure({"a": 10, "b": 10}, A) == {"a": 1, "b": 2} + + +def test_nondict_input(): + """Trying to structure typeddict from a non-dict raises the proper exception.""" + converter = Converter(detailed_validation=True) + with raises(ClassValidationError) as exc: + converter.structure(1, TypedDictA) + + assert transform_error(exc.value) == ["expected a mapping @ $"]