Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

added IntegrityError handler for update operations #48

Merged
merged 3 commits into from
Mar 25, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 11 additions & 7 deletions fastapi_crudrouter/core/sqlalchemy.py
Original file line number Diff line number Diff line change
Expand Up @@ -70,16 +70,20 @@ def route(model: self.create_schema, db: Session = Depends(self.db_func)):

def _update(self) -> Callable:
def route(item_id: self._pk_type, model: self.update_schema, db: Session = Depends(self.db_func)):
db_model = self._get_one()(item_id, db)
try:
db_model = self._get_one()(item_id, db)

for key, value in model.dict(exclude={self._pk}).items():
if hasattr(db_model, key):
setattr(db_model, key, value)
for key, value in model.dict(exclude={self._pk}).items():
if hasattr(db_model, key):
setattr(db_model, key, value)

db.commit()
db.refresh(db_model)
db.commit()
db.refresh(db_model)

return db_model
return db_model
except IntegrityError as e:
db.rollback()
raise HTTPException(422, ", ".join(e.args))

return route

Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
from setuptools import setup, find_packages

VERSION = '0.5.1'
VERSION = '0.5.2'

setup(
name='fastapi-crudrouter',
Expand Down
45 changes: 37 additions & 8 deletions tests/test_sqlalchemy_router.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
import pytest

from fastapi.testclient import TestClient
from sqlalchemy import Column, String, Float, Integer
from sqlalchemy.exc import IntegrityError

from fastapi.testclient import TestClient
from fastapi_crudrouter import SQLAlchemyCRUDRouter

from tests.implementations.sqlalchemy_ import _setup_base_app
from tests import Potato, Carrot, CarrotCreate, CarrotUpdate
from tests import Potato, Carrot, CarrotUpdate
from tests import test_router
from tests.implementations.sqlalchemy_ import _setup_base_app


POTATO_URL = '/potato'


def get_app():
Expand All @@ -21,7 +19,7 @@ class PotatoModel(Base):
id = Column(Integer, primary_key=True, index=True)
thickness = Column(Float)
mass = Column(Float)
color = Column(String)
color = Column(String, unique=True)
type = Column(String)

class CarrotModel(Base):
Expand All @@ -47,7 +45,7 @@ def test_integrity_error():
type='russet'
)

args = client, '/potato', potato
args = client, POTATO_URL, potato
test_router.test_post(*args)
with pytest.raises(AssertionError):
test_router.test_post(*args)
Expand All @@ -56,3 +54,34 @@ def test_integrity_error():
args = client, '/carrot', Carrot(id=1, length=2, color='red')
test_router.test_post(*args)
test_router.test_post(*args, expected_length=2)


def test_integrity_error_update():
client = TestClient(get_app())
potato1 = Potato(
id=1,
thickness=2,
mass=5,
color='red',
type='russet'
)

potato2 = Potato(
id=2,
thickness=9,
mass=5,
color='yellow',
type='mini'
)

args = client, POTATO_URL
test_router.test_post(*args, potato1, expected_length=1)
test_router.test_post(*args, potato2, expected_length=2)

potato2.color = potato1.color
res = client.put(f'{POTATO_URL}/{potato2.id}', json=potato2.dict())
assert res.status_code == 422, res.json()

potato2.color = 'green'
res = client.put(f'{POTATO_URL}/{potato2.id}', json=potato2.dict())
assert res.status_code == 200, res.json()