diff --git a/backend/api/main.py b/backend/api/main.py index 25987de..3498813 100644 --- a/backend/api/main.py +++ b/backend/api/main.py @@ -65,8 +65,20 @@ async def get_tribe(name: str): @app.post("/students", status_code=status.HTTP_201_CREATED, response_model=StudentModel) async def post_student(item: StudentModel): + if item.id is not None: + return JSONResponse( + status_code=status.HTTP_409_CONFLICT, + content=f"You can't post a student with an id. It is already registrered. Use PUT to modify it.", + ) + tribe_name = item.tribe_name - tribe = tribe_repo.get(tribe_name) + try: + tribe = tribe_repo.get(tribe_name) + except TribeRepositoryError: + return JSONResponse( + status_code=status.HTTP_409_CONFLICT, + content=f"The tribe {tribe_name} does not exists. You can't add a student in it.", + ) student = Student(item.name, tribe) diff --git a/backend/repository/tribe_sqlite_repository.py b/backend/repository/tribe_sqlite_repository.py index b7d2c72..cc2a4e9 100644 --- a/backend/repository/tribe_sqlite_repository.py +++ b/backend/repository/tribe_sqlite_repository.py @@ -52,7 +52,7 @@ class TribeSQLiteRepository(AbstractRepository): if row: return Tribe(*row) - raise ValueError(f"The tribe {name} does not exists") + raise TribeRepositoryError(f"The tribe {name} does not exists") def list(self) -> list[Tribe]: cursor = self.conn.cursor() diff --git a/tests/e2e/test_api.py b/tests/e2e/test_api.py index 2ecf119..99922c4 100644 --- a/tests/e2e/test_api.py +++ b/tests/e2e/test_api.py @@ -74,15 +74,35 @@ def test_api_post_student(): @pytest.mark.usefixtures("restart_api") @pytest.mark.usefixtures("clean_db") -def test_api_post_student(): +def test_api_post_student_with_id(): 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} + data = {"id": "1234", "name": "zart", "tribe_name": tribe.name} + requests.post(f"{url}/students", json=data) 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"] + assert r.status_code == 409 + assert ( + r.json() + == f"You can't post a student with an id. It is already registrered. Use PUT to modify it." + ) + + +@pytest.mark.usefixtures("restart_api") +@pytest.mark.usefixtures("clean_db") +def test_api_post_student_in_non_existant_tribe(): + 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 + "_"} + requests.post(f"{url}/students", json=data) + r = requests.post(f"{url}/students", json=data) + + assert r.status_code == 409 + assert ( + r.json() + == f"The tribe {tribe.name+'_'} does not exists. You can't add a student in it." + )