Skip to content

Commit bc34a46

Browse files
Sort extra keys when formatting ForbiddenExtraKeysError (#776)
`ForbiddenExtraKeysError.extra_fields` is a `set`, and `format_exception` in src/cattrs/v.py joined it directly, so `transform_error` put the extra keys in whatever order that set happened to iterate in. String hashing is randomized per process, so the message text changed from run to run once more than one extra key was present, which breaks anything that compares or snapshots the output of `transform_error`. `ForbiddenExtraKeysError.__str__` in src/cattrs/errors.py already sorts the same set, so the two renderings of one error disagreed as well. Sort the keys in `format_exception` too, and add a regression test with five extra keys, since the existing test only used one and could not observe the ordering.
1 parent df4e4bb commit bc34a46

3 files changed

Lines changed: 27 additions & 1 deletion

File tree

‎HISTORY.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,11 @@ The third number is for emergencies when we need to start branches for older rel
1111

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

14+
## NEXT (UNRELEASED)
15+
16+
- Fix {func}`transform_error <cattrs.transform_error>` listing the extra keys of a `ForbiddenExtraKeysError` in set iteration order, which made the message differ between runs; the keys are now sorted, like the error's own `__str__` already sorts them.
17+
([#776](https://github.com/python-attrs/cattrs/pull/776))
18+
1419
## 26.2.0 (2026-09-08)
1520

1621
- Fix the `msgpack` and `cbor2` converters unstructuring naive datetimes as local time, which made the serialized value depend on the timezone of the machine doing the unstructuring; naive datetimes are now assumed to be UTC, matching what the structure hooks already read back.

‎src/cattrs/v.py‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -41,7 +41,7 @@ def format_exception(exc: BaseException, type: Union[type, None]) -> str:
4141
tn = type.__name__ if hasattr(type, "__name__") else repr(type)
4242
res = f"invalid value for type, expected {tn}"
4343
elif isinstance(exc, ForbiddenExtraKeysError):
44-
res = f"extra fields found ({', '.join(exc.extra_fields)})"
44+
res = f"extra fields found ({', '.join(sorted(exc.extra_fields))})"
4545
elif isinstance(exc, AttributeError) and exc.args[0].endswith(
4646
"object has no attribute 'items'"
4747
):

‎tests/test_v.py‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,27 @@ class C:
106106
]
107107

108108

109+
def test_extra_keys_are_sorted(c: Converter) -> None:
110+
"""Extra keys are reported in a stable order.
111+
112+
`ForbiddenExtraKeysError.extra_fields` is a set, so the message used to
113+
depend on the iteration order of that set, which differs between processes.
114+
"""
115+
116+
@define
117+
class C:
118+
a: int
119+
120+
c.register_structure_hook(
121+
C, make_dict_structure_fn(C, c, _cattrs_forbid_extra_keys=True)
122+
)
123+
124+
with raises(Exception) as exc_info:
125+
c.structure({"a": 1, "e": 2, "c": 3, "b": 4, "d": 5}, C)
126+
127+
assert transform_error(exc_info.value) == ["extra fields found (b, c, d, e) @ $"]
128+
129+
109130
def test_untyped_class_errors(c: Converter) -> None:
110131
"""Errors on untyped attrs classes transform correctly."""
111132

0 commit comments

Comments
 (0)