Backend API: auth, projects/images/annotations, R2 presign, tracing, thumbnails, pagination, tests, docs
This commit is contained in:
parent
5c5deed2f5
commit
f8ed08b854
49 changed files with 2626 additions and 0 deletions
62
tests/test_annotations.py
Normal file
62
tests/test_annotations.py
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
"""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
|
||||
76
tests/test_auth.py
Normal file
76
tests/test_auth.py
Normal file
|
|
@ -0,0 +1,76 @@
|
|||
"""Auth: hashing, tokens, and route protection (no dev-DB writes)."""
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
from fastapi.security import HTTPAuthorizationCredentials
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
|
||||
|
||||
from models import User
|
||||
from src.core.db import Base
|
||||
from src.core.security import (
|
||||
create_token,
|
||||
decode_token,
|
||||
get_current_user,
|
||||
hash_password,
|
||||
verify_password,
|
||||
)
|
||||
from src.main import app
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
|
||||
@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()
|
||||
|
||||
|
||||
def test_password_roundtrip():
|
||||
h = hash_password("Admin123!")
|
||||
assert verify_password("Admin123!", h)
|
||||
assert not verify_password("wrong", h)
|
||||
assert not verify_password("x", "")
|
||||
|
||||
|
||||
def test_token_roundtrip():
|
||||
tok = create_token("u1", "admin")
|
||||
payload = decode_token(tok)
|
||||
assert payload and payload["sub"] == "u1" and payload["role"] == "admin"
|
||||
assert decode_token("garbage") is None
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_current_user_rejects_anonymous(db):
|
||||
from fastapi import HTTPException
|
||||
async with db() as s:
|
||||
with pytest.raises(HTTPException) as e:
|
||||
await get_current_user(None, s)
|
||||
assert e.value.status_code == 401
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_current_user_accepts_seeded(db):
|
||||
async with db() as s:
|
||||
s.add(User(id="u1", email="a@x.io", name="A", role="admin",
|
||||
status="active", password_hash=hash_password("pw"),
|
||||
assigned_project_ids=[]))
|
||||
await s.commit()
|
||||
tok = create_token("u1", "admin")
|
||||
creds = HTTPAuthorizationCredentials(scheme="Bearer", credentials=tok)
|
||||
user = await get_current_user(creds, s)
|
||||
assert user.email == "a@x.io"
|
||||
|
||||
|
||||
def test_protected_routes_reject_missing_token():
|
||||
with TestClient(app) as c:
|
||||
assert c.get("/api/v1/projects").status_code == 401
|
||||
assert c.get("/api/v1/activities").status_code == 401
|
||||
assert c.get("/api/v1/projects/x/images").status_code == 401
|
||||
|
||||
|
||||
def test_login_rejects_unknown_user():
|
||||
with TestClient(app) as c:
|
||||
r = c.post("/api/v1/auth/login",
|
||||
json={"email": "no-such-user@example.com", "password": "x"})
|
||||
assert r.status_code == 401
|
||||
62
tests/test_pagination.py
Normal file
62
tests/test_pagination.py
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
"""Pagination: one screenful per request, correct totals and filters."""
|
||||
import pytest
|
||||
import pytest_asyncio
|
||||
from sqlalchemy import text
|
||||
from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
|
||||
|
||||
from src.services import images as svc
|
||||
|
||||
|
||||
@pytest_asyncio.fixture
|
||||
async def db():
|
||||
engine = create_async_engine("sqlite+aiosqlite:///:memory:")
|
||||
from src.core.db import Base
|
||||
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()
|
||||
|
||||
|
||||
async def _seed(db, n=5):
|
||||
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')"))
|
||||
for i in range(n):
|
||||
await s.execute(text(
|
||||
"INSERT INTO images (id, project_id, file_name, r2_key, status, flags) "
|
||||
f"VALUES ('img{i}', 'p1', 'f{i}.jpg', 'k{i}', "
|
||||
f"'{'completed' if i % 2 == 0 else 'in_progress'}', '{{}}')"))
|
||||
await s.commit()
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_pages_cover_dataset_without_overlap(db):
|
||||
await _seed(db, 5)
|
||||
async with db() as s:
|
||||
p1 = await svc.list_images("p1", "all", s, limit=2, offset=0)
|
||||
p2 = await svc.list_images("p1", "all", s, limit=2, offset=2)
|
||||
p3 = await svc.list_images("p1", "all", s, limit=2, offset=4)
|
||||
assert p1["total"] == 5
|
||||
ids = [i["id"] for i in p1["items"]] + [i["id"] for i in p2["items"]] \
|
||||
+ [i["id"] for i in p3["items"]]
|
||||
assert sorted(ids) == ["img0", "img1", "img2", "img3", "img4"]
|
||||
assert len(p3["items"]) == 1
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_status_and_search_filter_server_side(db):
|
||||
await _seed(db, 5)
|
||||
async with db() as s:
|
||||
done = await svc.list_images("p1", "completed", s)
|
||||
assert done["total"] == 3
|
||||
one = await svc.list_images("p1", "all", s, search="f1")
|
||||
assert one["total"] == 1 and one["items"][0]["id"] == "img1"
|
||||
|
||||
|
||||
@pytest.mark.asyncio
|
||||
async def test_limit_is_clamped(db):
|
||||
await _seed(db, 2)
|
||||
async with db() as s:
|
||||
page = await svc.list_images("p1", "all", s, limit=10000, offset=-5)
|
||||
assert page["total"] == 2 and len(page["items"]) == 2
|
||||
30
tests/test_thumbnails.py
Normal file
30
tests/test_thumbnails.py
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
"""Thumbnail resize: pure bytes in/out, no R2, no DB."""
|
||||
from io import BytesIO
|
||||
|
||||
from PIL import Image as PILImage
|
||||
|
||||
from shared.thumbnails import resize_to_thumbnail
|
||||
|
||||
|
||||
def _jpeg(width: int, height: int) -> bytes:
|
||||
buf = BytesIO()
|
||||
PILImage.new("RGB", (width, height), (200, 30, 30)).save(buf, "JPEG", quality=90)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def test_resize_bounds_long_side():
|
||||
out = resize_to_thumbnail(_jpeg(2000, 1000))
|
||||
with PILImage.open(BytesIO(out)) as im:
|
||||
assert max(im.size) <= 512
|
||||
assert im.format == "JPEG"
|
||||
|
||||
|
||||
def test_resize_small_image_not_upscaled():
|
||||
out = resize_to_thumbnail(_jpeg(100, 60))
|
||||
with PILImage.open(BytesIO(out)) as im:
|
||||
assert im.size == (100, 60)
|
||||
|
||||
|
||||
def test_resize_output_is_smaller():
|
||||
big = _jpeg(1920, 1080)
|
||||
assert len(resize_to_thumbnail(big)) < len(big)
|
||||
42
tests/test_tracing.py
Normal file
42
tests/test_tracing.py
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
"""Trace layer: session echo, trace minting, client-event ingest."""
|
||||
import uuid
|
||||
|
||||
import pytest
|
||||
from fastapi.testclient import TestClient
|
||||
|
||||
from src.main import app
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def client():
|
||||
with TestClient(app) as c:
|
||||
yield c
|
||||
|
||||
|
||||
def test_trace_headers_echo_session(client):
|
||||
r = client.get("/", headers={"X-Session-ID": "sess-1", "X-User-Id": "u1"})
|
||||
assert r.status_code == 200
|
||||
assert r.headers["X-Session-ID"] == "sess-1"
|
||||
assert len(r.headers["X-Trace-ID"]) == 16
|
||||
|
||||
|
||||
def test_trace_headers_mint_session_when_missing(client):
|
||||
r = client.get("/")
|
||||
assert r.status_code == 200
|
||||
assert r.headers["X-Session-ID"]
|
||||
assert r.headers["X-Trace-ID"]
|
||||
|
||||
|
||||
def test_events_reject_missing_session(client):
|
||||
r = client.post("/api/v1/events", json={"session_id": " ", "events": []})
|
||||
assert r.status_code in (400, 422)
|
||||
|
||||
|
||||
def test_events_accept_batch(client):
|
||||
sid = f"sess-{uuid.uuid4().hex[:8]}"
|
||||
r = client.post("/api/v1/events", json={
|
||||
"session_id": sid,
|
||||
"events": [{"action": "image.next", "project_id": "p1", "payload": {"dir": 1}}],
|
||||
})
|
||||
assert r.status_code == 202
|
||||
assert r.json() == {"accepted": 1}
|
||||
Loading…
Add table
Add a link
Reference in a new issue