From d52ee4606a2e173dd8f6fc4341c91d238796a009 Mon Sep 17 00:00:00 2001 From: Chris Hill-Scott Date: Tue, 4 Sep 2018 12:59:53 +0100 Subject: [PATCH] Add error handler for duplicate domain --- app/email_branding/rest.py | 19 ++++++++++++++++++- tests/app/email_branding/test_rest.py | 27 +++++++++++++++++++++++++++ 2 files changed, 45 insertions(+), 1 deletion(-) diff --git a/app/email_branding/rest.py b/app/email_branding/rest.py index 0991c9d0b..990f1905e 100644 --- a/app/email_branding/rest.py +++ b/app/email_branding/rest.py @@ -1,4 +1,5 @@ -from flask import Blueprint, jsonify, request +from flask import Blueprint, current_app, jsonify, request +from sqlalchemy.exc import IntegrityError from app.dao.email_branding_dao import ( dao_create_email_branding, @@ -18,6 +19,22 @@ email_branding_blueprint = Blueprint('email_branding', __name__) register_errors(email_branding_blueprint) +@email_branding_blueprint.errorhandler(IntegrityError) +def handle_integrity_error(exc): + """ + Handle integrity errors caused by the unique constraint on domain + """ + if 'domain' in str(exc): + return jsonify( + result='error', + message={'name': ["Duplicate domain '{}'".format( + exc.params.get('domain') + )]} + ), 400 + current_app.logger.exception(exc) + return jsonify(result='error', message="Internal server error"), 500 + + @email_branding_blueprint.route('', methods=['GET']) def get_email_branding_options(): email_branding_options = [o.serialize() for o in dao_get_email_branding_options()] diff --git a/tests/app/email_branding/test_rest.py b/tests/app/email_branding/test_rest.py index 03311514a..7c7954887 100644 --- a/tests/app/email_branding/test_rest.py +++ b/tests/app/email_branding/test_rest.py @@ -257,3 +257,30 @@ def test_update_email_branding_reject_invalid_brand_type(admin_request, notify_d ) assert response['errors'][0]['message'] == 'brand_type NOT A TYPE is not one of [org, both, org_banner]' + + +def test_400_for_duplicate_domain(admin_request, notify_db_session): + branding_1 = create_email_branding() + branding_2 = create_email_branding() + admin_request.post( + 'email_branding.update_email_branding', + _data={'domain': 'example.com'}, + email_branding_id=branding_1.id, + ) + + response = admin_request.post( + 'email_branding.update_email_branding', + _data={'domain': 'example.com'}, + email_branding_id=branding_2.id, + _expected_status=400, + ) + assert response['result'] == 'error' + assert response['message']['name'] == ["Duplicate domain 'example.com'"] + + response = admin_request.post( + 'email_branding.create_email_branding', + _data={'domain': 'example.com'}, + _expected_status=400, + ) + assert response['result'] == 'error' + assert response['message']['name'] == ["Duplicate domain 'example.com'"]