From fa65a07a0c17b8a13e434202b03d33ef3ab1fd01 Mon Sep 17 00:00:00 2001 From: Denis Kataev Date: Thu, 28 Mar 2019 20:26:06 +0500 Subject: [PATCH] Correct path in nested models (#437) * Correct path in nested models * History * Fix code review --- HISTORY.rst | 1 + pydantic/error_wrappers.py | 6 +++++- tests/test_error_wrappers.py | 18 ++++++++++++++++++ 3 files changed, 24 insertions(+), 1 deletion(-) diff --git a/HISTORY.rst b/HISTORY.rst index 03c5954..f76d53f 100644 --- a/HISTORY.rst +++ b/HISTORY.rst @@ -8,6 +8,7 @@ v0.21.1 (unreleased) * add ``IPv{4,6,Any}Network`` and ``IPv{4,6,Any}Interface`` types from ``ipaddress`` stdlib, #333 by @pilosus * add docs for ``datetime`` types, #386 by @pilosus * fix to schema generation in dataclass-based models, #408 by @pilosus +* fix path in nested models #437, by @kataev v0.21.0 (2019-03-15) diff --git a/pydantic/error_wrappers.py b/pydantic/error_wrappers.py index a1ae583..c30db5e 100644 --- a/pydantic/error_wrappers.py +++ b/pydantic/error_wrappers.py @@ -93,7 +93,11 @@ def flatten_errors( for error in errors: if isinstance(error, ErrorWrapper): if isinstance(error.exc, ValidationError): - yield from flatten_errors(error.exc.raw_errors, loc=error.loc) + if loc is not None: + error_loc = loc + error.loc + else: + error_loc = error.loc + yield from flatten_errors(error.exc.raw_errors, loc=error_loc) else: yield error.dict(loc_prefix=loc) elif isinstance(error, list): diff --git a/tests/test_error_wrappers.py b/tests/test_error_wrappers.py index e299a0b..f019cf4 100644 --- a/tests/test_error_wrappers.py +++ b/tests/test_error_wrappers.py @@ -243,3 +243,21 @@ x x field required (type=value_error.missing)""" ) + + +def test_nested_error(): + class NestedModel3(BaseModel): + x: str + + class NestedModel2(BaseModel): + data2: List[NestedModel3] + + class NestedModel1(BaseModel): + data1: List[NestedModel2] + + with pytest.raises(ValidationError) as exc_info: + NestedModel1(data1=[{'data2': [{'y': 1}]}]) + + expected = [{'loc': ('data1', 0, 'data2', 0, 'x'), 'msg': 'field required', 'type': 'value_error.missing'}] + + assert exc_info.value.errors() == expected