Feat: add response error when tribe already exists

This commit is contained in:
Bertrand Benjamin 2022-12-29 07:23:02 +01:00
parent ccf1655cf4
commit febe686688
3 changed files with 51 additions and 2 deletions

View File

@ -1,13 +1,17 @@
import sqlite3
from fastapi import FastAPI, status
from fastapi.responses import JSONResponse
from backend.adapters.sqlite import create_db
from backend.api.model import StudentModel, TribeModel
from backend.model.student import Student
from backend.model.tribe import Tribe
from backend.repository.student_sqlite_repository import StudentSQLiteRepository
from backend.repository.tribe_sqlite_repository import TribeSQLiteRepository
from backend.repository.tribe_sqlite_repository import (
TribeRepositoryError,
TribeSQLiteRepository,
)
# from sqlalchemy import create_engine
# from sqlalchemy.orm import clear_mappers, sessionmaker
@ -33,7 +37,13 @@ app = FastAPI()
async def post_tribe(item: TribeModel):
tribe = Tribe(**item.dict())
tribe_repo.add(tribe)
try:
tribe_repo.add(tribe)
except TribeRepositoryError:
return JSONResponse(
status_code=status.HTTP_409_CONFLICT,
content=f"The tribe {tribe.name} already exists",
)
conn.commit()
return tribe.to_dict()

View File

@ -2,11 +2,21 @@ from backend.model.tribe import Tribe
from backend.repository.abstract_repository import AbstractRepository
class TribeRepositoryError(Exception):
pass
class TribeSQLiteRepository(AbstractRepository):
def __init__(self, conn) -> None:
self.conn = conn
def add(self, tribe: Tribe) -> None:
tribes = self.list()
if tribe.name in map(lambda x: x.name, tribes):
raise TribeRepositoryError(
f"The tribe {tribe.name} already exists. Can't add it"
)
self.conn.execute(
"""
INSERT INTO tribes(name, level) VALUES (?, ?)

View File

@ -22,6 +22,19 @@ def test_api_post_tribe():
}
@pytest.mark.usefixtures("restart_api")
@pytest.mark.usefixtures("clean_db")
def test_api_post_tribe_already_exists():
data = {"name": "Pioupiou", "level": "2nd"}
url = config.get_api_url()
r = requests.post(f"{url}/tribes", json=data)
r = requests.post(f"{url}/tribes", json=data)
assert r.status_code == 409
assert r.json() == f"The tribe {data['name']} already exists"
@pytest.mark.usefixtures("restart_api")
@pytest.mark.usefixtures("clean_db")
def test_api_post_list_tribe():
@ -57,3 +70,19 @@ def test_api_post_student():
assert r.json()["name"] == "zart"
assert r.json()["tribe_name"] == tribe.name
assert r.json()["id"]
@pytest.mark.usefixtures("restart_api")
@pytest.mark.usefixtures("clean_db")
def test_api_post_student():
url = config.get_api_url()
tribe = build_tribes(1)[0]
requests.post(f"{url}/tribes", json=tribe.to_dict())
data = {"name": "zart", "tribe_name": tribe.name}
r = requests.post(f"{url}/students", json=data)
assert r.status_code == 201
assert r.json()["name"] == "zart"
assert r.json()["tribe_name"] == tribe.name
assert r.json()["id"]