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
7 changes: 7 additions & 0 deletions HISTORY.md
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,13 @@ The third number is for emergencies when we need to start branches for older rel

Our backwards-compatibility policy can be found [here](https://github.com/python-attrs/cattrs/blob/main/.github/SECURITY.md).

## NEXT (UNRELEASED)

- Fix unstructuring NewTypes with the {class}`BaseConverter`.
([#684](https://github.com/python-attrs/cattrs/pull/684))
- Make some Hypothesis tests more robust.
([#684](https://github.com/python-attrs/cattrs/pull/684))

## 25.2.0 (2025-08-31)

- **Potentially breaking**: Sequences are now structured into tuples.
Expand Down
4 changes: 4 additions & 0 deletions src/cattrs/converters.py
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,10 @@ def __init__(
)
self._unstructure_func.register_func_list(
[
(
lambda t: get_newtype_base(t) is not None,
lambda o: self.unstructure(o, unstructure_as=o.__class__),
),
(
is_protocol,
lambda o: self.unstructure(o, unstructure_as=o.__class__),
Expand Down
20 changes: 20 additions & 0 deletions tests/helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
"""Helpers for tests."""

from typing import Any


def assert_only_unstructured(obj: Any):
"""Assert the object is comprised of only unstructured data:

* dicts, lists, tuples
* strings, ints, floats, bools, None
"""
if isinstance(obj, dict):
for k, v in obj.items():
assert_only_unstructured(k)
assert_only_unstructured(v)
elif isinstance(obj, (list, tuple, frozenset, set)):
for e in obj:
assert_only_unstructured(e)
else:
assert isinstance(obj, (int, float, str, bool, type(None)))
7 changes: 4 additions & 3 deletions tests/test_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@
from cattrs.gen import make_dict_structure_fn, override

from ._compat import is_py310_plus
from .helpers import assert_only_unstructured
from .typed import (
nested_typed_classes,
simple_typed_attrs,
Expand All @@ -54,7 +55,7 @@ def test_simple_roundtrip(cls_and_vals, detailed_validation):
cl, vals, kwargs = cls_and_vals
inst = cl(*vals, **kwargs)
unstructured = converter.unstructure(inst)
assert "Hyp" not in repr(unstructured)
assert_only_unstructured(unstructured)
assert inst == converter.structure(unstructured, cl)


Expand All @@ -73,7 +74,7 @@ def test_simple_roundtrip_tuple(cls_and_vals, dv: bool):
cl, vals, _ = cls_and_vals
inst = cl(*vals)
unstructured = converter.unstructure(inst)
assert "Hyp" not in repr(unstructured)
assert_only_unstructured(unstructured)
assert inst == converter.structure(unstructured, cl)


Expand Down Expand Up @@ -125,7 +126,7 @@ def test_simple_roundtrip_with_extra_keys_forbidden(cls_and_vals, strat):
assume(strat is UnstructureStrategy.AS_DICT or not kwargs)
inst = cl(*vals, **kwargs)
unstructured = converter.unstructure(inst)
assert "Hyp" not in repr(unstructured)
assert_only_unstructured(unstructured)
assert inst == converter.structure(unstructured, cl)


Expand Down
6 changes: 3 additions & 3 deletions tests/test_gen_dict.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
from cattrs.errors import ClassValidationError, ForbiddenExtraKeysError
from cattrs.gen import make_dict_structure_fn, make_dict_unstructure_fn, override

from .helpers import assert_only_unstructured
from .typed import nested_typed_classes, simple_typed_classes, simple_typed_dataclasses
from .untyped import nested_classes, simple_classes

Expand Down Expand Up @@ -143,8 +144,7 @@ def test_individual_overrides(converter_cls, cl_and_vals):
inst = cl(*vals, **kwargs)

res = converter.unstructure(inst)
assert "Hyp" not in repr(res)
assert "Factory" not in repr(res)
assert_only_unstructured(res)

for attr, val in zip(fields, vals):
if attr.name == chosen_name:
Expand Down Expand Up @@ -181,7 +181,7 @@ def test_unmodified_generated_structuring(cl_and_vals, dv: bool):

unstructured = converter.unstructure(inst)

assert "Hyp" not in repr(unstructured)
assert_only_unstructured(unstructured)

converter.register_structure_hook(cl, fn)

Expand Down
52 changes: 52 additions & 0 deletions tests/test_helpers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
"""Tests for test helpers."""

import pytest
from attrs import define

from .helpers import assert_only_unstructured


def test_assert_only_unstructured_passes_for_primitives():
"""assert_only_unstructured should pass for basic Python data types."""
# Test primitives
assert_only_unstructured(42)
assert_only_unstructured("hello")
assert_only_unstructured(3.14)
assert_only_unstructured(True)
assert_only_unstructured(None)

# Test collections of primitives
assert_only_unstructured([1, 2, 3])
assert_only_unstructured({"key": "value", "number": 42})
assert_only_unstructured((1, "two", 3.0))
assert_only_unstructured({1, 2, 3})
assert_only_unstructured(frozenset([1, 2, 3]))

# Test nested structures
assert_only_unstructured(
{"list": [1, 2, {"nested": "dict"}], "tuple": (True, None), "number": 42}
)


def test_assert_only_unstructured_fails_for_attrs_classes():
"""assert_only_unstructured should fail for attrs classes."""

@define
class SimpleAttrsClass:
value: int

instance = SimpleAttrsClass(42)

# Should raise AssertionError for attrs class instance
with pytest.raises(AssertionError):
assert_only_unstructured(instance)

# Should also fail when attrs instance is nested in collections
with pytest.raises(AssertionError):
assert_only_unstructured([instance])

with pytest.raises(AssertionError):
assert_only_unstructured({"key": instance})

with pytest.raises(AssertionError):
assert_only_unstructured((1, instance, 3))