From f8a0b4fa5c4d782d59632ca36e04cd87a30724a4 Mon Sep 17 00:00:00 2001 From: Anna Shamray Date: Thu, 12 Oct 2023 16:14:44 +0200 Subject: [PATCH 1/2] :test_tube: test serializer with empty gegevensgroup items --- tests/test_gegevensgroepen.py | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/tests/test_gegevensgroepen.py b/tests/test_gegevensgroepen.py index a7b3bb83..166a0ca7 100644 --- a/tests/test_gegevensgroepen.py +++ b/tests/test_gegevensgroepen.py @@ -98,3 +98,16 @@ def test_nullable_gegevensgroep(): "street": "", "number": "", } + + +def test_gegevensgroep_not_required_with_all_empty_values(): + """ + check that if GegevensGroepSerializer is not required and all its items are empty + it's processed as valid + """ + serializer = PersonSerializer2( + data={"name": "Willy De Kooning", "address": {"street": "", "number": ""}}, + partial=False, + ) + + assert serializer.is_valid() From 8acc9cc8d708affaeb4866120400c84215b251cf Mon Sep 17 00:00:00 2001 From: Anna Shamray Date: Thu, 12 Oct 2023 16:19:03 +0200 Subject: [PATCH 2/2] :sparkles: allow empty data for non-required gegevensgroup --- vng_api_common/descriptors.py | 4 +++- vng_api_common/serializers.py | 11 ++++++++--- 2 files changed, 11 insertions(+), 4 deletions(-) diff --git a/vng_api_common/descriptors.py b/vng_api_common/descriptors.py index 6b929a7a..6aa426fd 100644 --- a/vng_api_common/descriptors.py +++ b/vng_api_common/descriptors.py @@ -72,7 +72,9 @@ def _value_getter(attr): def __set__(self, obj, value: Optional[dict]): # value can be empty, if that's the case, empty all model fields - if not value: + # if all nested values are empty - treat it as empty value + all_empty = all(not bool(v) for k, v in value.items()) if value else True + if not value or all_empty: if self.required: raise ValueError("A non-empty value is required") diff --git a/vng_api_common/serializers.py b/vng_api_common/serializers.py index 410dfe3d..6dfeadde 100644 --- a/vng_api_common/serializers.py +++ b/vng_api_common/serializers.py @@ -169,10 +169,15 @@ def validate_empty_values(self, data): """ (is_empty_value, data) = super().validate_empty_values(data) - if self.root.partial: - if is_empty_value: - return (is_empty_value, data) + if is_empty_value: + return (is_empty_value, data) + + # allow to have all fields empty if the gegevensgroup is not required + all_empty = all(not bool(value) for name, value in data.items()) + if not self.required and all_empty: + return (True, data) + if self.root.partial: errors = OrderedDict() for field_name, field in self.fields.items():