diff --git a/swh/web/auth/mailmap.py b/swh/web/auth/mailmap.py --- a/swh/web/auth/mailmap.py +++ b/swh/web/auth/mailmap.py @@ -4,6 +4,7 @@ # See top-level LICENSE file for more information from django.conf.urls import url +from django.db import IntegrityError from django.db.models import Q from django.http.response import ( HttpResponse, @@ -40,7 +41,10 @@ if not request.user.has_perm(MAILMAP_PERMISSION): return HttpResponseForbidden() - UserMailmap.objects.create(user_id=str(request.user.id), **request.data) + try: + UserMailmap.objects.create(user_id=str(request.user.id), **request.data) + except IntegrityError: + return HttpResponseBadRequest("This 'from_email' already exists.") mm = UserMailmap.objects.get( user_id=str(request.user.id), from_email=request.data.get("from_email") ) diff --git a/swh/web/tests/auth/test_mailmap.py b/swh/web/tests/auth/test_mailmap.py --- a/swh/web/tests/auth/test_mailmap.py +++ b/swh/web/tests/auth/test_mailmap.py @@ -55,13 +55,31 @@ api_client, reverse("profile-mailmap-list"), status_code=200, - content_type="application/json" + content_type="application/json", ).data assert len(resp) == 1 assert resp[0]["from_email"] == "bar@example.org" assert resp[0]["display_name"] == "bar" +@pytest.mark.django_db(transaction=True) +def test_mailmap_add_duplicate(api_client, mailmap_user): + api_client.force_login(mailmap_user) + + check_api_post_response( + api_client, + reverse("profile-mailmap-add"), + data={"from_email": "foo@example.org", "display_name": "bar"}, + status_code=200, + ) + check_api_post_response( + api_client, + reverse("profile-mailmap-add"), + data={"from_email": "foo@example.org", "display_name": "baz"}, + status_code=400, + ) + + @pytest.mark.django_db(transaction=True) def test_mailmap_endpoints_error_response(api_client, mailmap_user): api_client.force_login(mailmap_user)