backend/tests/test_pagination.py

62 lines
2.3 KiB
Python

"""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