From 41ed66ae2310fa5b502960f12ce51f5b67247baf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Sampaio?= Date: Tue, 12 Nov 2019 09:16:55 -0300 Subject: [PATCH] Allow required lists to be empty --- cleancat/base.py | 10 +++++----- tests/test_base.py | 18 ++++++++++++------ 2 files changed, 17 insertions(+), 11 deletions(-) diff --git a/cleancat/base.py b/cleancat/base.py index 05f69aa..4ffdfca 100644 --- a/cleancat/base.py +++ b/cleancat/base.py @@ -368,19 +368,19 @@ class List(Field): base_type = list blank_value = [] - def __init__(self, field_instance, max_length=None, **kwargs): + def __init__( + self, field_instance, max_length=None, allow_empty=False, **kwargs + ): self.max_length = max_length + self.allow_empty = allow_empty super(List, self).__init__(**kwargs) self.field_instance = field_instance - def has_value(self, value): - return bool(value) - def clean(self, value): value = super(List, self).clean(value) item_cnt = len(value) - if self.required and not item_cnt: + if not self.allow_empty and not item_cnt: raise ValidationError('List must not be empty.') if self.max_length and item_cnt > self.max_length: diff --git a/tests/test_base.py b/tests/test_base.py index ab40ffa..982a4e2 100644 --- a/tests/test_base.py +++ b/tests/test_base.py @@ -470,18 +470,24 @@ def test_it_enforces_max_length(self, value, valid): with pytest.raises(ValidationError, match=expected_err_msg): field.clean(value) - @pytest.mark.parametrize('value', [None, []]) - def test_it_enforces_required_flag(self, value): + def test_it_enforces_required_flag(self): expected_err_msg = 'This field is required.' with pytest.raises(ValidationError, match=expected_err_msg): - List(String()).clean(value) + List(String()).clean(None) - @pytest.mark.parametrize('value', [None, []]) - def test_it_can_be_optional(self, value): + def test_it_enforces_allow_empty_flag(self): + expected_err_msg = 'List must not be empty.' + with pytest.raises(ValidationError, match=expected_err_msg): + List(String()).clean([]) + + def test_it_can_be_optional(self): with pytest.raises(StopValidation) as e: - List(String(), required=False).clean(value) + List(String(), required=False).clean(None) assert e.value.args[0] == [] + def test_it_can_be_empty(self): + assert List(String(), allow_empty=True).clean([]) == [] + class TestSortedSetField: def test_it_dedupes_valid_values(self):