diff --git a/redash/handlers/destinations.py b/redash/handlers/destinations.py index 2e51dc65fa..2112e98c89 100644 --- a/redash/handlers/destinations.py +++ b/redash/handlers/destinations.py @@ -1,5 +1,6 @@ from flask import make_response, request from flask_restful import abort +from sqlalchemy.exc import IntegrityError from redash import models from redash.destinations import (destinations, @@ -45,6 +46,10 @@ def post(self, destination_id): models.db.session.commit() except ValidationError: abort(400) + except IntegrityError as e: + if 'name' in e.message: + abort(400, message=u"Alert Destination with the name {} already exists.".format(req['name'])) + abort(500) return destination.to_dict(all=True) @@ -102,6 +107,12 @@ def post(self): options=config, user=self.current_user) - models.db.session.add(destination) - models.db.session.commit() + try: + models.db.session.add(destination) + models.db.session.commit() + except IntegrityError as e: + if 'name' in e.message: + abort(400, message=u"Alert Destination with the name {} already exists.".format(req['name'])) + abort(500) + return destination.to_dict(all=True) diff --git a/tests/handlers/test_destinations.py b/tests/handlers/test_destinations.py index 2e1533b7cb..e3a31d0bfd 100644 --- a/tests/handlers/test_destinations.py +++ b/tests/handlers/test_destinations.py @@ -38,6 +38,17 @@ def test_post_requires_admin(self): rv = self.make_request('post', '/api/destinations', user=self.factory.user, data=data) self.assertEqual(rv.status_code, 403) + def test_returns_400_when_name_already_exists(self): + d1 = self.factory.create_destination() + data = { + 'options': {'addresses': 'test@example.com'}, + 'name': d1.name, + 'type': 'email' + } + + rv = self.make_request('post', '/api/destinations', user=self.factory.create_admin(), data=data) + self.assertEqual(rv.status_code, 400) + class TestDestinationResource(BaseTestCase): def test_get(self):