diff --git a/app/main/forms.py b/app/main/forms.py index 21352a7f4..300b2600f 100644 --- a/app/main/forms.py +++ b/app/main/forms.py @@ -5,7 +5,7 @@ from flask_wtf import Form from wtforms import StringField, PasswordField from wtforms.validators import DataRequired, Email, Length, Regexp -from app.main.dao import verify_codes_dao +from app.main.dao import verify_codes_dao, services_dao from app.main.encryption import check_hash from app.main.validators import Blacklist @@ -85,4 +85,11 @@ def validate_code(field, code): class AddServiceForm(Form): - service_name = StringField(validators=[DataRequired(message='Name can not be empty')]) + service_name = StringField(validators=[DataRequired(message='Please enter your service name')]) + + def validate_service_name(self, a): + if services_dao.find_service_by_service_name(self.service_name.data) is not None: + self.service_name.errors.append('Duplicate service name') + return False + else: + return True diff --git a/tests/app/main/test_add_service_form.py b/tests/app/main/test_add_service_form.py new file mode 100644 index 000000000..87f460c22 --- /dev/null +++ b/tests/app/main/test_add_service_form.py @@ -0,0 +1,18 @@ +from app.main.dao import services_dao +from app.main.forms import AddServiceForm +from tests.app.main import create_test_user + + +def test_form_should_have_errors_when_duplicate_service_is_added(notifications_admin, + notifications_admin_db, + notify_db_session): + with notifications_admin.test_request_context(method='POST', + data={'service_name': 'some service'}) as req: + user = create_test_user() + services_dao.insert_new_service('some service', user) + req.session['user_id'] = user.id + form = AddServiceForm(req.request.form) + assert form.validate() is False + assert len(form.errors) == 1 + expected = {'service_name': ['Duplicate service name']} + assert form.errors == expected diff --git a/tests/app/main/views/test_add_service.py b/tests/app/main/views/test_add_service.py index 8264a0f23..b341b6622 100644 --- a/tests/app/main/views/test_add_service.py +++ b/tests/app/main/views/test_add_service.py @@ -26,3 +26,15 @@ def test_should_add_service_and_redirect_to_next_page(notifications_admin, notif assert response.location == 'http://localhost/dashboard' saved_service = services_dao.find_service_by_service_name('testing the post') assert saved_service is not None + + +def test_should_return_form_errors_when_service_name_is_empty(notifications_admin, notifications_admin_db, notify_db_session): + with notifications_admin.test_client() as client: + with client.session_transaction() as session: + user = create_test_user() + session['user_id'] = user.id + verify_codes_dao.add_code(user_id=user.id, code='12345', code_type='sms') + client.post('/two-factor', data={'sms_code': '12345'}) + response = client.post('/add-service', data={}) + assert response.status_code == 400 + assert 'Please enter your service name' in response.get_data(as_text=True)