"""Regression tests for the image/annotation flow (defects found in live smoke test).""" import pytest import pytest_asyncio from sqlalchemy import text from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine from src.core.db import Base from src.services import annotations as svc from shared.schemas import AnnotationUpsert, AnnotationShape @pytest_asyncio.fixture async def db(): engine = create_async_engine("sqlite+aiosqlite:///:memory:") async with engine.begin() as conn: await conn.run_sync(Base.metadata.create_all) yield async_sessionmaker(engine, expire_on_commit=False) await engine.dispose() @pytest.mark.asyncio async def test_raw_image_insert_gets_object_count_default(db): # Reported defect: raw SQL insert without object_count violated NOT NULL. async with db() as s: await s.execute(text( "INSERT INTO projects (id, slug, name, task_type, status) " "VALUES ('p1', 'p1', 'P', 'object_detection', 'annotating')")) await s.execute(text( "INSERT INTO images (id, project_id, file_name, r2_key, status, flags) " "VALUES ('img1', 'p1', 'a.jpg', 'k', 'in_progress', '{}')")) await s.commit() n = (await s.execute(text("SELECT object_count FROM images WHERE id='img1'"))).scalar() assert n == 0 @pytest.mark.asyncio async def test_upsert_missing_image_is_404(db): from fastapi import HTTPException async with db() as s: with pytest.raises(HTTPException) as e: await svc.upsert_annotation("p1", "nope", AnnotationUpsert(), s) assert e.value.status_code == 404 @pytest.mark.asyncio async def test_upsert_roundtrip_syncs_object_count(db): shape = AnnotationShape(id="s1", index=1, type="bbox", labelId="car", bbox={"x": 1, "y": 2, "width": 10, "height": 10}) async with db() as s: await s.execute(text( "INSERT INTO projects (id, slug, name, task_type, status) " "VALUES ('p1', 'p1', 'P', 'object_detection', 'annotating')")) await s.execute(text( "INSERT INTO images (id, project_id, file_name, r2_key, status, flags) " "VALUES ('img1', 'p1', 'a.jpg', 'k', 'in_progress', '{}')")) await s.commit() out = await svc.upsert_annotation("p1", "img1", AnnotationUpsert(shapes=[shape]), s) assert out == {"imageId": "img1", "saved": True, "shapeCount": 1} got = await svc.get_annotation("p1", "img1", s) assert len(got["shapes"]) == 1 n = (await s.execute(text("SELECT object_count FROM images WHERE id='img1'"))).scalar() assert n == 1