Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow required lists to be empty #51

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 5 additions & 5 deletions cleancat/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand Down
18 changes: 12 additions & 6 deletions tests/test_base.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down