diff --git a/HISTORY.md b/HISTORY.md index 942616e3..7de81702 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -13,6 +13,9 @@ Our backwards-compatibility policy can be found [here](https://github.com/python ## NEXT +- Add an opt-in unstructure validation strategy for selected runtime classes, including enum types, without changing default unstructuring behavior. + ([#601](https://github.com/python-attrs/cattrs/issues/601)) + - Fix the msgspec converter passing typed deques directly to the encoder, which cannot serialize them. Deques are now unstructured into lists, including when nested in attrs classes or dataclasses. ([#818](https://github.com/python-attrs/cattrs/issues/818) [#819](https://github.com/python-attrs/cattrs/pull/819)) diff --git a/README.md b/README.md index 3942b414..5d010433 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,7 @@ Have a look at [*Why *cattrs*?*](https://catt.rs/en/latest/why.html) for more ex - Enumeration instances are converted to their values. - Other types are let through without conversion. This includes types such as integers, dictionaries, lists and instances of non-_attrs_ classes. - Custom converters for any type can be registered using `register_unstructure_hook`. +- Optional type validation when unstructuring selected runtime classes is available through `cattrs.strategies.validate_unstructure`. ### Recursive Structuring diff --git a/docs/strategies.md b/docs/strategies.md index 7ed68afb..d4bd921c 100644 --- a/docs/strategies.md +++ b/docs/strategies.md @@ -4,6 +4,38 @@ _cattrs_ ships with a number of _strategies_ for customizing un/structuring beha Strategies are prepackaged, high-level patterns for quickly and easily applying complex customizations to a converter. +## Opt-in Unstructure Validation + +_Found at {py:func}`cattrs.strategies.validate_unstructure`._ + +By default, unstructuring assumes the input matches the declared types. +Enable validation for selected runtime classes when additional checks are useful, for example in tests or debug configurations. +Existing hooks for the selected types continue to handle valid values. + +```{doctest} +>>> from enum import Enum +>>> from attrs import define +>>> from cattrs import Converter +>>> from cattrs.strategies import validate_unstructure +>>> class Flavor(Enum): +... SIMPLE = "simple" +>>> @define +... class Site: +... flavor: Flavor +>>> converter = Converter() +>>> validate_unstructure(converter, Flavor) +>>> converter.unstructure(Site(Flavor.SIMPLE)) +{'flavor': 'simple'} +>>> converter.unstructure(Site("simple")) +Traceback (most recent call last): +... +TypeError: Expected Flavor, got str +``` + +Register custom hooks first, then apply the strategy before generating or retaining hooks for containing classes. +The checks use `isinstance`, accept subclasses, and follow the converter's normal class-based hook dispatch rules. +This strategy does not validate arbitrary generic types or recursively validate every field of an object. + ## Tagged Unions Strategy _Found at {py:func}`cattrs.strategies.configure_tagged_union`._ diff --git a/src/cattrs/strategies/__init__.py b/src/cattrs/strategies/__init__.py index 9caf0732..b96f7658 100644 --- a/src/cattrs/strategies/__init__.py +++ b/src/cattrs/strategies/__init__.py @@ -3,10 +3,12 @@ from ._class_methods import use_class_methods from ._subclasses import include_subclasses from ._unions import configure_tagged_union, configure_union_passthrough +from ._validation import validate_unstructure __all__ = [ "configure_tagged_union", "configure_union_passthrough", "include_subclasses", "use_class_methods", + "validate_unstructure", ] diff --git a/src/cattrs/strategies/_validation.py b/src/cattrs/strategies/_validation.py new file mode 100644 index 00000000..c1e68aa9 --- /dev/null +++ b/src/cattrs/strategies/_validation.py @@ -0,0 +1,50 @@ +"""Opt-in type validation when unstructuring values.""" + +from collections.abc import Callable +from typing import Any, get_origin + +from typing_extensions import is_protocol, is_typeddict + +from ..converters import BaseConverter + + +def _checked_hook(cl: type, hook: Callable[[Any], Any]) -> Callable[[Any], Any]: + def checked(value: Any) -> Any: + if not isinstance(value, cl): + raise TypeError( + f"Expected {cl.__qualname__}, got {type(value).__qualname__}" + ) + return hook(value) + + return checked + + +def validate_unstructure(converter: BaseConverter, *types: type) -> None: + """Validate instances of selected runtime classes before unstructuring. + + Existing unstructure hooks for the selected classes are preserved for valid + inputs. Validation uses isinstance, so subclasses are accepted. Hook + registration follows the converter's usual class-based dispatch rules. + + :param converter: The converter to configure. + :param types: Concrete classes to validate (not protocols or typing forms). + + Apply the strategy after registering custom hooks and before generating or + retaining hooks for containing classes. Validation checks only the selected + type at each invocation, not every value recursively. + """ + for cl in types: + if ( + get_origin(cl) is not None + or not isinstance(cl, type) + or cl is Any + or is_protocol(cl) + or is_typeddict(cl) + ): + raise TypeError("Expected a concrete runtime class") + + # Resolve all original hooks before changing dispatch, so a registered + # base-class hook cannot replace the original hook for a selected subclass. + hooks = [(cl, converter.get_unstructure_hook(cl)) for cl in dict.fromkeys(types)] + for cl, hook in hooks: + converter.register_unstructure_hook(cl, _checked_hook(cl, hook)) diff --git a/tests/test_unstructure_validation.py b/tests/test_unstructure_validation.py new file mode 100644 index 00000000..82dc2668 --- /dev/null +++ b/tests/test_unstructure_validation.py @@ -0,0 +1,170 @@ +from dataclasses import dataclass +from enum import Enum, IntEnum +from typing import Any, Protocol, TypedDict + +import pytest +from attrs import define + +from cattrs import BaseConverter, Converter +from cattrs.strategies import validate_unstructure + + +class Flavor(Enum): + SIMPLE = "simple" + + +class Other(Enum): + SIMPLE = "simple" + + +@define +class Site: + flavor: Flavor + + +@dataclass +class DataSite: + flavor: Flavor + + +@pytest.mark.parametrize("cls", [Site, DataSite]) +@pytest.mark.parametrize("invalid", ["simple", Other.SIMPLE, None, 1]) +def test_invalid_enum(cls, invalid): + c = Converter() + validate_unstructure(c, Flavor) + with pytest.raises(TypeError, match="Expected Flavor, got"): + c.unstructure(cls(invalid)) + + +@pytest.mark.parametrize("cls", [Site, DataSite]) +def test_valid_enum(cls): + c = Converter() + validate_unstructure(c, Flavor) + assert c.unstructure(cls(Flavor.SIMPLE)) == {"flavor": "simple"} + assert c.structure({"flavor": "simple"}, cls) == cls(Flavor.SIMPLE) + + +def test_existing_hook(): + c = Converter() + c.register_unstructure_hook(Flavor, lambda e: e.name) + validate_unstructure(c, Flavor) + assert c.unstructure(Flavor.SIMPLE) == "SIMPLE" + with pytest.raises(TypeError, match="Expected Flavor, got str"): + c.unstructure("simple", unstructure_as=Flavor) + + +def test_default_unchanged(): + c = Converter() + with pytest.raises(AttributeError): + c.unstructure(Site("simple")) + + +def test_list_of_enums(): + c = Converter() + validate_unstructure(c, Flavor) + assert c.unstructure([Flavor.SIMPLE], unstructure_as=list[Flavor]) == ["simple"] + with pytest.raises(TypeError, match="Expected Flavor, got str"): + c.unstructure(["simple"], unstructure_as=list[Flavor]) + + +def test_multiple_types(): + c = Converter() + validate_unstructure(c, Flavor, int) + assert c.unstructure(1, unstructure_as=int) == 1 + with pytest.raises(TypeError, match="Expected int, got str"): + c.unstructure("1", unstructure_as=int) + + +@pytest.mark.parametrize("invalid", [list[int], int | str, 42]) +def test_only_concrete_types(invalid): + c = Converter() + with pytest.raises(TypeError, match="concrete runtime class"): + validate_unstructure(c, Flavor, invalid) + with pytest.raises(AttributeError): + c.unstructure(Site("simple")) + + +def test_related_types_preserve_original_hooks(): + class Number(IntEnum): + ONE = 1 + + c = Converter() + expected = c.get_unstructure_hook(Number)(Number.ONE) + validate_unstructure(c, int, Number) + assert c.unstructure(Number.ONE, unstructure_as=Number) == expected + with pytest.raises(TypeError, match=r"Expected .*Number, got int"): + c.unstructure(1, unstructure_as=Number) + + +def test_typing_forms_rejected(): + class P(Protocol): + pass + + class TD(TypedDict): + value: int + + c = Converter() + for invalid in (Any, P, TD): + with pytest.raises(TypeError, match="concrete runtime class"): + validate_unstructure(c, Flavor, invalid) + with pytest.raises(AttributeError): + c.unstructure(Site("simple")) + + +def test_isolated_converters(): + c = Converter() + validate_unstructure(c, Flavor) + with pytest.raises(TypeError, match="Expected Flavor, got str"): + c.unstructure(Site("simple")) + with pytest.raises(AttributeError): + Converter().unstructure(Site("simple")) + + +def test_copy(): + c = Converter() + validate_unstructure(c, Flavor) + copied = c.copy() + assert copied.unstructure(Site(Flavor.SIMPLE)) == {"flavor": "simple"} + with pytest.raises(TypeError, match="Expected Flavor, got str"): + copied.unstructure(Site("simple")) + + +def test_base_converter(): + c = BaseConverter() + validate_unstructure(c, Flavor) + assert c.unstructure(Flavor.SIMPLE) == "simple" + with pytest.raises(TypeError, match="Expected Flavor, got str"): + c.unstructure("simple", unstructure_as=Flavor) + + +def test_subclass_accepted(): + class Parent: + pass + + class Child(Parent): + pass + + c = Converter() + c.register_unstructure_hook(Parent, lambda _: "parent") + validate_unstructure(c, Parent) + assert c.unstructure(Child(), unstructure_as=Parent) == "parent" + + +def test_typed_enum_preserves_value_hook(): + class TypedNumber(Enum): + _value_: int + ONE = 1 + + c = Converter() + c.register_unstructure_hook(int, lambda value: str(value)) + validate_unstructure(c, TypedNumber) + assert c.unstructure(TypedNumber.ONE) == "1" + with pytest.raises(TypeError, match=r"Expected .*TypedNumber, got int"): + c.unstructure(1, unstructure_as=TypedNumber) + + +def test_empty_selection_leaves_hooks_unchanged(): + c = Converter() + original = c.get_unstructure_hook(Flavor) + validate_unstructure(c) + assert c.get_unstructure_hook(Flavor) is original