Ensure that project environment names are unique

This commit is contained in:
richard-dds 2018-08-24 13:49:39 -04:00
parent da5dbc5bdd
commit 66877b46bd
3 changed files with 30 additions and 3 deletions

View File

@ -1,7 +1,7 @@
from flask_wtf import Form from flask_wtf import Form
from wtforms.fields import StringField, TextAreaField, FieldList from wtforms.fields import StringField, TextAreaField, FieldList
from wtforms.validators import Required from wtforms.validators import Required
from atst.forms.validators import ListItemRequired from atst.forms.validators import ListItemRequired, ListItemsUnique
class NewProjectForm(Form): class NewProjectForm(Form):
@ -12,7 +12,10 @@ class NewProjectForm(Form):
description = TextAreaField(label="Description", validators=[Required()]) description = TextAreaField(label="Description", validators=[Required()])
environment_names = FieldList( environment_names = FieldList(
StringField(label="Environment Name"), StringField(label="Environment Name"),
validators=[ListItemRequired(message="Provide at least one environment name.")], validators=[
ListItemRequired(message="Provide at least one environment name."),
ListItemsUnique(message="Environment names must be unique."),
],
) )
@property @property

View File

@ -60,3 +60,12 @@ def ListItemRequired(message="Please provide at least one.", empty_values=("", N
raise ValidationError(message) raise ValidationError(message)
return _list_item_required return _list_item_required
def ListItemsUnique(message="Items must be unique"):
def _list_items_unique(form, field):
sorted_values = sorted(v for v in field.data)
if sorted_values != sorted(set(sorted_values)):
raise ValidationError(message)
return _list_items_unique

View File

@ -1,7 +1,7 @@
from wtforms.validators import ValidationError from wtforms.validators import ValidationError
import pytest import pytest
from atst.forms.validators import Alphabet, IsNumber, PhoneNumber from atst.forms.validators import Alphabet, IsNumber, PhoneNumber, ListItemsUnique
class TestIsNumber: class TestIsNumber:
@ -51,3 +51,18 @@ class TestAlphabet:
dummy_field.data = invalid dummy_field.data = invalid
with pytest.raises(ValidationError): with pytest.raises(ValidationError):
validator(dummy_form, dummy_field) validator(dummy_form, dummy_field)
class TestListItemsUnique:
@pytest.mark.parametrize("valid", [["a", "aa", "aaa"], ["one", "two", "three"]])
def test_ListItemsUnique_allows_unique_items(self, valid, dummy_form, dummy_field):
validator = ListItemsUnique()
dummy_field.data = valid
validator(dummy_form, dummy_field)
@pytest.mark.parametrize("invalid", [["a", "a", "a"], ["one", "two", "two", "three"]])
def test_ListItemsUnique_rejects_non_letters(self, invalid, dummy_form, dummy_field):
validator = ListItemsUnique()
dummy_field.data = invalid
with pytest.raises(ValidationError):
validator(dummy_form, dummy_field)