diff --git a/papermerge/core/routers/custom_fields.py b/papermerge/core/routers/custom_fields.py index 7838dd807..d75e80103 100644 --- a/papermerge/core/routers/custom_fields.py +++ b/papermerge/core/routers/custom_fields.py @@ -3,7 +3,7 @@ from typing import Annotated from fastapi import APIRouter, Depends, HTTPException, Security -from sqlalchemy.exc import NoResultFound +from sqlalchemy.exc import IntegrityError, NoResultFound from papermerge.core import db, schemas, utils from papermerge.core.auth import get_current_user, scopes @@ -94,11 +94,8 @@ def create_custom_field( extra_data=cfield.extra_data, user_id=user.id, ) - except Exception as e: - error_msg = str(e) - if "UNIQUE constraint failed" in error_msg: - raise HTTPException(status_code=400, detail="Custom field already exists") - raise HTTPException(status_code=400, detail=error_msg) + except IntegrityError: + raise HTTPException(status_code=400, detail="Duplicate custom field name") return custom_field diff --git a/tests/core/routes/test_custom_fields.py b/tests/core/routes/test_custom_fields.py index 23cff85bf..96dc1dffa 100644 --- a/tests/core/routes/test_custom_fields.py +++ b/tests/core/routes/test_custom_fields.py @@ -48,6 +48,27 @@ def test_create_monetary_custom_field( assert response.status_code == 200, response.json() +@pytest.mark.django_db(transaction=True) +def test_custom_field_duplicate_name( + auth_api_client: AuthTestClient, db_session: Session +): + """Make sure there is an error on custom field duplicate name""" + count_before = db_session.query(func.count(models.CustomField.id)).scalar() + assert count_before == 0 + + response = auth_api_client.post( + "/custom-fields/", json={"name": "cf1", "type": "int"} + ) + assert response.status_code == 201, response.json() + + # custom field with same name + response = auth_api_client.post( + "/custom-fields/", json={"name": "cf1", "type": "text"} + ) + assert response.status_code == 400, response.json() + assert response.json() == {"detail": "Duplicate custom field name"} + + @pytest.mark.django_db(transaction=True) def test_update_custom_field( auth_api_client: AuthTestClient,