Skip to content

Commit

Permalink
better handling of integrity error (#501)
Browse files Browse the repository at this point in the history
  • Loading branch information
ciur authored Oct 26, 2024
1 parent bef6559 commit 7c70e5a
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
9 changes: 3 additions & 6 deletions papermerge/core/routers/custom_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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

Expand Down
21 changes: 21 additions & 0 deletions tests/core/routes/test_custom_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down

0 comments on commit 7c70e5a

Please sign in to comment.