From 285add0b98a465ffb6e00112dcdd11a453a20e05 Mon Sep 17 00:00:00 2001 From: kiskaadee Date: Tue, 13 Oct 2026 08:09:08 -0500 Subject: [PATCH] feat(api): implement sculptures read router with spatial coordinate serialization - Add GET /sculptures and GET /sculptures/{id} endpoints - Implement EWKB/WKT coordinate extractor for PostGIS geometry - Register router in FastAPI application - Configure NullPool test database fixture to prevent connection pool clashes - Add comprehensive integration and unit test suite (31 tests passing) - Update todo.txt milestone tracking --- api/src/api/main.py | 4 + api/src/api/models/sculpture.py | 12 ++- api/src/api/routers/__init__.py | 3 + api/src/api/routers/sculptures.py | 100 ++++++++++++++++++ api/tests/conftest.py | 30 ++++++ .../integration/test_sculptures_router.py | 66 ++++++++++++ api/tests/unit/test_sculptures_helpers.py | 77 ++++++++++++++ todo.txt | 2 +- 8 files changed, 289 insertions(+), 5 deletions(-) create mode 100644 api/src/api/routers/__init__.py create mode 100644 api/src/api/routers/sculptures.py create mode 100644 api/tests/integration/test_sculptures_router.py create mode 100644 api/tests/unit/test_sculptures_helpers.py diff --git a/api/src/api/main.py b/api/src/api/main.py index 83fad05..31d1534 100644 --- a/api/src/api/main.py +++ b/api/src/api/main.py @@ -3,6 +3,7 @@ from fastapi.middleware.cors import CORSMiddleware from api.core.config import settings from api.models.auth import DevTokenRequest, LoginResponse +from api.routers import sculptures from api.services.auth.service import AuthService app = FastAPI( @@ -20,6 +21,9 @@ app.add_middleware( allow_headers=["*"], ) +# Register routers +app.include_router(sculptures.router) + auth_service = AuthService() diff --git a/api/src/api/models/sculpture.py b/api/src/api/models/sculpture.py index 41c15a6..ecdee97 100644 --- a/api/src/api/models/sculpture.py +++ b/api/src/api/models/sculpture.py @@ -47,10 +47,14 @@ class SculptureDetails(Sculpture): Extended sculpture model containing cultural details, unlocked content, and audio resources. """ - description: str = Field(..., description="Public cultural description of the sculpture.") - audio_url: HttpUrl = Field(..., description="Direct link to the audio guide resource.") - unlocked_content: str = Field( - ..., description="Extended history/curation unlocked upon checking in." + description: str | None = Field( + default=None, description="Public cultural description of the sculpture." + ) + audio_url: HttpUrl | None = Field( + default=None, description="Direct link to the audio guide resource." + ) + unlocked_content: str | None = Field( + default=None, description="Extended history/curation unlocked upon checking in." ) model_config = { diff --git a/api/src/api/routers/__init__.py b/api/src/api/routers/__init__.py new file mode 100644 index 0000000..1396e8e --- /dev/null +++ b/api/src/api/routers/__init__.py @@ -0,0 +1,3 @@ +""" +API routers module. +""" diff --git a/api/src/api/routers/sculptures.py b/api/src/api/routers/sculptures.py new file mode 100644 index 0000000..5ee12a8 --- /dev/null +++ b/api/src/api/routers/sculptures.py @@ -0,0 +1,100 @@ +import struct +from typing import Annotated +from uuid import UUID + +from fastapi import APIRouter, Depends, HTTPException, status +from geoalchemy2.elements import WKBElement, WKTElement +from pydantic import HttpUrl, TypeAdapter +from sqlalchemy import select +from sqlalchemy.ext.asyncio import AsyncSession + +from api.database.session import get_db_session +from api.db_models.sculpture import SculptureDB +from api.models.sculpture import Sculpture, SculptureDetails, SculptureStatus + +router = APIRouter(prefix="/sculptures", tags=["Sculptures"]) + +http_url_adapter = TypeAdapter(HttpUrl) + + +def extract_coordinates(location: object) -> tuple[float, float]: + """ + Extract (longitude, latitude) from PostGIS WKBElement, WKTElement, or string representation. + """ + if isinstance(location, WKTElement) or (isinstance(location, str) and "POINT" in location): + raw_str = str(location).strip() + coords_str = raw_str[raw_str.find("(") + 1 : raw_str.find(")")] + lon, lat = map(float, coords_str.split()) + return lon, lat + + if isinstance(location, WKBElement): + raw = location.data + b = bytes.fromhex(raw) if isinstance(raw, str) else raw + byteorder = "<" if b[0] == 1 else ">" + geom_type = struct.unpack(byteorder + "I", b[1:5])[0] + # Check for SRID flag (EWKB: 0x20000000) + offset = 9 if (geom_type & 0x20000000) else 5 + lon, lat = struct.unpack(byteorder + "dd", b[offset : offset + 16]) + return lon, lat + + raise ValueError(f"Unsupported location geometry format: {type(location)}") + + +def to_sculpture_read(db_item: SculptureDB) -> Sculpture: + lon, lat = extract_coordinates(db_item.location) + return Sculpture( + id=db_item.id, + name=db_item.name, + artist=db_item.artist, + year=db_item.year, + latitude=lat, + longitude=lon, + status=SculptureStatus(db_item.status), + ) + + +def to_sculpture_details(db_item: SculptureDB) -> SculptureDetails: + lon, lat = extract_coordinates(db_item.location) + audio_url = http_url_adapter.validate_python(db_item.audio_url) if db_item.audio_url else None + return SculptureDetails( + id=db_item.id, + name=db_item.name, + artist=db_item.artist, + year=db_item.year, + latitude=lat, + longitude=lon, + status=SculptureStatus(db_item.status), + description=db_item.description, + audio_url=audio_url, + unlocked_content=db_item.unlocked_content, + ) + + +@router.get("", response_model=list[Sculpture], summary="List All Cat Sculptures") +async def list_sculptures( + db: Annotated[AsyncSession, Depends(get_db_session)], +) -> list[Sculpture]: + """ + Returns list of all sculptures with names, locations, and current status (Single Source of Truth). + """ + query = select(SculptureDB).order_by(SculptureDB.name) + result = await db.execute(query) + sculptures_db = result.scalars().all() + return [to_sculpture_read(item) for item in sculptures_db] + + +@router.get("/{id}", response_model=SculptureDetails, summary="Get Sculpture Details") +async def get_sculpture_by_id( + id: UUID, + db: Annotated[AsyncSession, Depends(get_db_session)], +) -> SculptureDetails: + """ + Detailed information about a sculpture, historical context, artist, and unlockable audio guides. + """ + sculpture = await db.get(SculptureDB, id) + if not sculpture: + raise HTTPException( + status_code=status.HTTP_404_NOT_FOUND, + detail="Sculpture not found.", + ) + return to_sculpture_details(sculpture) diff --git a/api/tests/conftest.py b/api/tests/conftest.py index 223d63d..e771e8e 100644 --- a/api/tests/conftest.py +++ b/api/tests/conftest.py @@ -2,9 +2,39 @@ from collections.abc import AsyncGenerator import pytest from httpx import ASGITransport, AsyncClient +from sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_engine +from sqlalchemy.pool import NullPool +from api.core.config import settings +from api.database.session import get_db_session from api.main import app +# Engine with NullPool prevents cross-loop asyncpg connection clashes in pytest +test_engine = create_async_engine( + settings.DATABASE_URL, + poolclass=NullPool, + echo=False, +) + +TestAsyncSessionLocal = async_sessionmaker( + bind=test_engine, + class_=AsyncSession, + expire_on_commit=False, + autocommit=False, + autoflush=False, +) + + +async def override_get_db_session() -> AsyncGenerator[AsyncSession, None]: + async with TestAsyncSessionLocal() as session: + try: + yield session + finally: + await session.close() + + +app.dependency_overrides[get_db_session] = override_get_db_session + @pytest.fixture async def async_client() -> AsyncGenerator[AsyncClient, None]: diff --git a/api/tests/integration/test_sculptures_router.py b/api/tests/integration/test_sculptures_router.py new file mode 100644 index 0000000..480c483 --- /dev/null +++ b/api/tests/integration/test_sculptures_router.py @@ -0,0 +1,66 @@ +import uuid + +import pytest +from httpx import AsyncClient + +from api.database.seed import INITIAL_SCULPTURES + + +@pytest.mark.asyncio +async def test_list_sculptures_endpoint(async_client: AsyncClient): + response = await async_client.get("/sculptures") + assert response.status_code == 200 + + data = response.json() + assert isinstance(data, list) + assert len(data) >= 3 + + # Check that our seeded sculptures are present + names = {item["name"] for item in data} + for seeded in INITIAL_SCULPTURES: + assert seeded["name"] in names + + # Verify schema fields and coordinates on each sculpture + for item in data: + assert "id" in item + assert "name" in item + assert "artist" in item + assert "year" in item + assert "latitude" in item + assert "longitude" in item + assert "status" in item + # Cali bounding box check + assert 3.30 <= item["latitude"] <= 3.60 + assert -76.60 <= item["longitude"] <= -76.40 + assert item["status"] in ("on-site", "moved", "missing") + + +@pytest.mark.asyncio +async def test_get_sculpture_by_id_success(async_client: AsyncClient): + target_id = str(INITIAL_SCULPTURES[0]["id"]) + response = await async_client.get(f"/sculptures/{target_id}") + assert response.status_code == 200 + + data = response.json() + assert data["id"] == target_id + assert data["name"] == INITIAL_SCULPTURES[0]["name"] + assert data["artist"] == INITIAL_SCULPTURES[0]["artist"] + assert data["year"] == INITIAL_SCULPTURES[0]["year"] + assert data["description"] == INITIAL_SCULPTURES[0]["description"] + assert data["audio_url"] == INITIAL_SCULPTURES[0]["audio_url"] + assert data["unlocked_content"] == INITIAL_SCULPTURES[0]["unlocked_content"] + + +@pytest.mark.asyncio +async def test_get_sculpture_by_id_not_found(async_client: AsyncClient): + non_existent_id = uuid.uuid4() + response = await async_client.get(f"/sculptures/{non_existent_id}") + assert response.status_code == 404 + data = response.json() + assert data["detail"] == "Sculpture not found." + + +@pytest.mark.asyncio +async def test_get_sculpture_by_id_invalid_uuid(async_client: AsyncClient): + response = await async_client.get("/sculptures/invalid-uuid-1234") + assert response.status_code == 422 diff --git a/api/tests/unit/test_sculptures_helpers.py b/api/tests/unit/test_sculptures_helpers.py new file mode 100644 index 0000000..d0ed2b1 --- /dev/null +++ b/api/tests/unit/test_sculptures_helpers.py @@ -0,0 +1,77 @@ +import struct +import uuid + +import pytest +from geoalchemy2.elements import WKBElement, WKTElement + +from api.db_models.sculpture import SculptureDB +from api.routers.sculptures import ( + extract_coordinates, + to_sculpture_details, + to_sculpture_read, +) + + +def test_extract_coordinates_from_wkt(): + wkt = WKTElement("POINT(-76.533282 3.450143)", srid=4326) + lon, lat = extract_coordinates(wkt) + assert abs(lon - (-76.533282)) < 1e-6 + assert abs(lat - 3.450143) < 1e-6 + + +def test_extract_coordinates_from_wkb_ewkb(): + # Build standard EWKB for POINT(-76.533282 3.450143) SRID 4326 + # byteorder: 1 (little-endian), type: 0x20000001 (Point + EWKB), srid: 4326 + packed = struct.pack("