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

issue #161: delete inspection fastapi #202

Merged
merged 3 commits into from
Nov 5, 2024
Merged
Show file tree
Hide file tree
Changes from 2 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
45 changes: 43 additions & 2 deletions app/controllers/inspections.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
from uuid import UUID

from azure.storage.blob import ContainerClient
from fertiscan import delete_inspection as db_delete_inspection
from fertiscan import (
get_full_inspection_json,
get_user_analysis_by_verified,
Expand All @@ -13,7 +14,7 @@
from psycopg_pool import ConnectionPool

from app.exceptions import InspectionNotFoundError, MissingUserAttributeError, log_error
from app.models.inspections import Inspection, InspectionData
from app.models.inspections import DeletedInspection, Inspection, InspectionData
from app.models.label_data import LabelData
from app.models.users import User

Expand Down Expand Up @@ -71,7 +72,7 @@ async def read_inspection(cp: ConnectionPool, user: User, id: UUID | str):
Args:
cp (ConnectionPool): The connection pool to manage database connections.
user (User): User instance containing user details, including the user ID.
id (UUID | str): Unique identifier of the inspection, as a UUID or a string convertible to UUID.
id (UUID | str): The UUID of the inspection to read.

Returns:
Inspection: An `Inspection` object with the inspection details.
Expand Down Expand Up @@ -134,3 +135,43 @@ async def create_inspection(
)

return Inspection.model_validate(inspection)


async def delete_inspection(
cp: ConnectionPool,
user: User,
id: UUID | str,
connection_string: str,
):
"""
Deletes an inspection record and its associated picture set from the database.

Args:
cp (ConnectionPool): The connection pool for database management.
user (User): The user requesting the deletion.
id (UUID | str): The UUID of the inspection to delete.
connection_string (str): Connection string for Azure Blob Storage.

Returns:
DeletedInspection: The deleted inspection data.

Raises:
MissingUserAttributeError: If the user ID is missing.
ValueError: If id or connection_string are invalid.
"""
if not user.id:
raise MissingUserAttributeError("User ID is required to delete an inspection.")
if not id:
raise ValueError("Inspection ID is required for deletion.")
if not connection_string:
raise ValueError("Connection string is required for blob storage access.")
if not isinstance(id, UUID):
id = UUID(id)

container_client = ContainerClient.from_connection_string(
connection_string, container_name=f"user-{user.id}"
)

with cp.connection() as conn, conn.cursor() as cursor:
deleted = await db_delete_inspection(cursor, id, user.id, container_client)
return DeletedInspection.model_validate(deleted.model_dump())
23 changes: 20 additions & 3 deletions app/main.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,18 @@
from http import HTTPStatus
from typing import Annotated
from uuid import UUID

from fastapi import Depends, FastAPI, Form, HTTPException, Request, UploadFile
from fastapi.concurrency import asynccontextmanager
from fastapi.responses import JSONResponse
from pipeline import GPT, OCR
from psycopg_pool import ConnectionPool
from pydantic import UUID4

from app.config import Settings, configure
from app.controllers.data_extraction import extract_data
from app.controllers.inspections import (
create_inspection,
delete_inspection,
read_all_inspections,
read_inspection,
)
Expand All @@ -26,7 +27,7 @@
validate_files,
)
from app.exceptions import InspectionNotFoundError, UserConflictError, log_error
from app.models.inspections import Inspection, InspectionData
from app.models.inspections import DeletedInspection, Inspection, InspectionData
from app.models.label_data import LabelData
from app.models.monitoring import HealthStatus
from app.models.users import User
Expand Down Expand Up @@ -95,7 +96,7 @@ async def get_inspections(
async def get_inspection(
cp: Annotated[ConnectionPool, Depends(get_connection_pool)],
user: Annotated[User, Depends(fetch_user)],
id: UUID4,
id: UUID,
):
try:
return await read_inspection(cp, user, id)
Expand All @@ -117,3 +118,19 @@ async def post_inspection(
label_images = [await f.read() for f in files]
conn_string = settings.fertiscan_storage_url
return await create_inspection(cp, user, label_data, label_images, conn_string)


@app.delete("/inspections/{id}", tags=["Inspections"], response_model=DeletedInspection)
async def delete_inspection_(
cp: Annotated[ConnectionPool, Depends(get_connection_pool)],
user: Annotated[User, Depends(fetch_user)],
settings: Annotated[Settings, Depends(get_settings)],
id: UUID,
):
try:
conn_string = settings.fertiscan_storage_url
return await delete_inspection(cp, user, id, conn_string)
except InspectionNotFoundError:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="Inspection not found"
)
5 changes: 5 additions & 0 deletions app/models/inspections.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from datetime import datetime

from fertiscan.db.metadata.inspection import DBInspection
from fertiscan.db.metadata.inspection import Inspection as DatastoreInspection
from pydantic import UUID4, BaseModel

Expand All @@ -19,3 +20,7 @@ class InspectionData(BaseModel):

class Inspection(DatastoreInspection):
inspection_id: UUID4


class DeletedInspection(DBInspection):
deleted: bool = True
21 changes: 20 additions & 1 deletion tests/test_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@
)
from app.exceptions import InspectionNotFoundError, UserConflictError, UserNotFoundError
from app.main import app
from app.models.inspections import Inspection, InspectionData
from app.models.inspections import DeletedInspection, Inspection, InspectionData
from app.models.label_data import LabelData
from app.models.users import User

Expand Down Expand Up @@ -383,3 +383,22 @@ def test_create_inspection_unauthenticated(self):
files=self.files,
)
self.assertEqual(response.status_code, 401)

@patch("app.main.delete_inspection")
def test_delete_inspection(self, mock_delete_inspection):
mock_deleted_inspection = DeletedInspection(id=uuid.uuid4())
mock_delete_inspection.return_value = mock_deleted_inspection
response = self.client.delete(f"/inspections/{mock_deleted_inspection.id}")
self.assertEqual(response.status_code, 200)
DeletedInspection.model_validate(response.json())

@patch("app.main.delete_inspection")
def test_delete_inspection_not_found(self, mock_delete_inspection):
mock_delete_inspection.side_effect = InspectionNotFoundError()
response = self.client.delete(f"/inspections/{uuid.uuid4()}")
self.assertEqual(response.status_code, 404)

def test_delete_inspection_unauthenticated(self):
del app.dependency_overrides[fetch_user]
response = self.client.delete(f"/inspections/{uuid.uuid4()}")
self.assertEqual(response.status_code, 401)
80 changes: 79 additions & 1 deletion tests/test_inspections.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,12 @@

from app.controllers.inspections import (
create_inspection,
delete_inspection,
read_all_inspections,
read_inspection,
)
from app.exceptions import InspectionNotFoundError, MissingUserAttributeError
from app.models.inspections import Inspection
from app.models.inspections import DeletedInspection, Inspection
from app.models.label_data import LabelData
from app.models.users import User

Expand Down Expand Up @@ -273,3 +274,80 @@ async def test_create_inspection_success(
)
self.assertIsInstance(inspection, Inspection)
self.assertEqual(inspection.inspection_id, inspection_id)


class TestDeleteFunction(unittest.IsolatedAsyncioTestCase):
async def test_missing_user_id_raises_error(self):
cp = MagicMock()
user = User(id=None)
inspection_id = uuid.uuid4()
connection_string = "fake_conn_str"

with self.assertRaises(MissingUserAttributeError):
await delete_inspection(cp, user, inspection_id, connection_string)

async def test_missing_inspection_id_raises_error(self):
cp = MagicMock()
user = User(id=uuid.uuid4())
connection_string = "fake_conn_str"

with self.assertRaises(ValueError):
await delete_inspection(cp, user, None, connection_string)

async def test_missing_connection_string_raises_error(self):
cp = MagicMock()
user = User(id=uuid.uuid4())
inspection_id = uuid.uuid4()

with self.assertRaises(ValueError):
await delete_inspection(cp, user, inspection_id, None)

async def test_invalid_inspection_id_format(self):
cp = MagicMock()
user = User(id=uuid.uuid4())
invalid_id = "not-a-uuid"
connection_string = "fake_conn_str"

with self.assertRaises(ValueError):
await delete_inspection(cp, user, invalid_id, connection_string)

@patch("app.controllers.inspections.db_delete_inspection")
@patch("app.controllers.inspections.ContainerClient")
async def test_delete_inspection_success(
self, mock_container_client, mock_db_delete_inspection
):
cp = MagicMock()
conn_mock = MagicMock()
cursor_mock = MagicMock()
conn_mock.cursor.return_value.__enter__.return_value = cursor_mock
cp.connection.return_value.__enter__.return_value = conn_mock

user = User(id=uuid.uuid4())
inspection_id = uuid.uuid4()
connection_string = "fake_conn_str"

mock_deleted_inspection_data = {
"id": inspection_id,
"deleted": True,
}
mock_db_delete_inspection.return_value = DeletedInspection(
**mock_deleted_inspection_data
)

container_client_instance = (
mock_container_client.from_connection_string.return_value
)

deleted_inspection = await delete_inspection(
cp, user, inspection_id, connection_string
)

mock_container_client.from_connection_string.assert_called_once_with(
connection_string, container_name=f"user-{user.id}"
)
mock_db_delete_inspection.assert_called_once_with(
cursor_mock, inspection_id, user.id, container_client_instance
)
self.assertIsInstance(deleted_inspection, DeletedInspection)
self.assertEqual(deleted_inspection.id, inspection_id)
self.assertTrue(deleted_inspection.deleted)
Loading