From 93d83f880a206b3d8206832bf1ff80e9c40d1072 Mon Sep 17 00:00:00 2001 From: Ben Ellis Date: Wed, 21 Jun 2023 23:53:38 +0100 Subject: [PATCH] Added format_exception to recursive calls of transform_error. [#389] (#390) --- HISTORY.md | 2 ++ src/cattrs/v.py | 4 ++-- tests/test_v.py | 19 +++++++++++++++++++ 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/HISTORY.md b/HISTORY.md index 4e9d5770..0abeb2aa 100644 --- a/HISTORY.md +++ b/HISTORY.md @@ -2,6 +2,8 @@ ## 23.2.0 (UNRELEASED) +- Fix `format_exception` parameter working for recursive calls to `transform_error` + ([#389](https://github.com/python-attrs/cattrs/issues/389) - Use [PDM](https://pdm.fming.dev/latest/) instead of Poetry. - _cattrs_ is now linted with [Ruff](https://beta.ruff.rs/docs/). - Fix TypedDicts with periods in their field names. diff --git a/src/cattrs/v.py b/src/cattrs/v.py index f3c36481..963f8536 100644 --- a/src/cattrs/v.py +++ b/src/cattrs/v.py @@ -89,7 +89,7 @@ def transform_error( for exc, note in with_notes: p = f"{path}[{note.index!r}]" if isinstance(exc, (ClassValidationError, IterableValidationError)): - errors.extend(transform_error(exc, p)) + errors.extend(transform_error(exc, p, format_exception)) else: errors.append(f"{format_exception(exc, note.type)} @ {p}") for exc in without: @@ -99,7 +99,7 @@ def transform_error( for exc, note in with_notes: p = f"{path}.{note.name}" if isinstance(exc, (ClassValidationError, IterableValidationError)): - errors.extend(transform_error(exc, p)) + errors.extend(transform_error(exc, p, format_exception)) else: errors.append(f"{format_exception(exc, note.type)} @ {p}") for exc in without: diff --git a/tests/test_v.py b/tests/test_v.py index 6bfac63a..88c063f8 100644 --- a/tests/test_v.py +++ b/tests/test_v.py @@ -227,6 +227,25 @@ class C: ] +def test_custom_error_fn_nested(c: Converter) -> None: + def my_format(exc, type): + if isinstance(exc, TypeError): + return "Must be correct type" + return format_exception(exc, type) + + @define + class C: + a: Dict[str, int] + + try: + c.structure({"a": {"a": "str", "b": 1, "c": None}}, C) + except Exception as exc: + assert transform_error(exc, format_exception=my_format) == [ + "invalid value for type, expected int @ $.a['a']", + "Must be correct type @ $.a['c']", + ] + + def test_typeddict_attribute_errors(c: Converter) -> None: """TypedDict errors are correctly generated."""