Spaces:
Build error
Build error
File size: 13,689 Bytes
f842a06 193eb98 f842a06 35a94af f842a06 35a94af f842a06 35a94af f842a06 35a94af f842a06 9097545 f842a06 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 | """
Tests des endpoints corrections et historique (Sprint 6 β Session B).
POST /api/v1/pages/{id}/corrections β corrections partielles, versionnement
GET /api/v1/pages/{id}/history β liste des versions archivΓ©es
"""
# 1. stdlib
import json
import uuid
from datetime import datetime, timezone
from pathlib import Path
# 2. third-party
import pytest
# 3. local
from app.models.corpus import CorpusModel, ManuscriptModel, PageModel
from tests.conftest_api import async_client, db_session # noqa: F401
_NOW = datetime.now(timezone.utc)
# ββ Helpers ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
async def _create_corpus(db_session, slug: str = "test-corpus") -> CorpusModel:
corpus = CorpusModel(
id=str(uuid.uuid4()),
slug=slug,
title="Test Corpus",
profile_id="medieval-illuminated",
created_at=_NOW,
updated_at=_NOW,
)
db_session.add(corpus)
await db_session.commit()
await db_session.refresh(corpus)
return corpus
async def _create_manuscript(db_session, corpus_id: str) -> ManuscriptModel:
ms = ManuscriptModel(
id=str(uuid.uuid4()),
corpus_id=corpus_id,
title="Test MS",
total_pages=1,
)
db_session.add(ms)
await db_session.commit()
await db_session.refresh(ms)
return ms
async def _create_page(db_session, manuscript_id: str) -> PageModel:
page = PageModel(
id=str(uuid.uuid4()),
manuscript_id=manuscript_id,
folio_label="f001r",
sequence=1,
image_master_path="/data/f001r.jpg",
processing_status="ANALYZED",
)
db_session.add(page)
await db_session.commit()
await db_session.refresh(page)
return page
def _make_master(
page_id: str, version: int = 1, status: str = "machine_draft"
) -> str:
return json.dumps({
"schema_version": "1.0",
"page_id": page_id,
"corpus_profile": "medieval-illuminated",
"manuscript_id": "ms-test",
"folio_label": "f001r",
"sequence": 1,
"image": {"master": "https://example.com/f.jpg", "width": 1500, "height": 2000},
"layout": {"regions": []},
"ocr": {
"diplomatic_text": "Incipit liber primus",
"blocks": [], "lines": [], "language": "la",
"confidence": 0.87, "uncertain_segments": [],
},
"translation": {"fr": "", "en": ""},
"summary": None,
"commentary": {
"public": "Texte public", "scholarly": "Analyse savante", "claims": [],
},
"editorial": {
"status": status,
"validated": False, "validated_by": None,
"version": version, "notes": [],
},
})
# ββ POST /api/v1/pages/{id}/corrections βββββββββββββββββββββββββββββββββββββββ
@pytest.mark.asyncio
async def test_corrections_page_not_found(async_client):
resp = await async_client.post(
"/api/v1/pages/nonexistent/corrections",
json={"ocr_diplomatic_text": "texte"},
)
assert resp.status_code == 404
@pytest.mark.asyncio
async def test_corrections_no_master_json(async_client, db_session, monkeypatch):
corpus = await _create_corpus(db_session)
ms = await _create_manuscript(db_session, corpus.id)
page = await _create_page(db_session, ms.id)
monkeypatch.setattr(Path, "exists", lambda self: False)
resp = await async_client.post(
f"/api/v1/pages/{page.id}/corrections",
json={"ocr_diplomatic_text": "texte"},
)
assert resp.status_code == 404
@pytest.mark.asyncio
async def test_corrections_updates_ocr_text(async_client, db_session, monkeypatch):
corpus = await _create_corpus(db_session)
ms = await _create_manuscript(db_session, corpus.id)
page = await _create_page(db_session, ms.id)
monkeypatch.setattr(Path, "exists", lambda self: True)
monkeypatch.setattr(Path, "read_text", lambda self, **kw: _make_master(page.id))
monkeypatch.setattr(Path, "write_text", lambda self, content, **kw: None)
resp = await async_client.post(
f"/api/v1/pages/{page.id}/corrections",
json={"ocr_diplomatic_text": "Texte corrigΓ© manuellement"},
)
assert resp.status_code == 200
assert resp.json()["ocr"]["diplomatic_text"] == "Texte corrigΓ© manuellement"
@pytest.mark.asyncio
async def test_corrections_increments_version(async_client, db_session, monkeypatch):
corpus = await _create_corpus(db_session)
ms = await _create_manuscript(db_session, corpus.id)
page = await _create_page(db_session, ms.id)
monkeypatch.setattr(Path, "exists", lambda self: True)
monkeypatch.setattr(Path, "read_text", lambda self, **kw: _make_master(page.id, version=1))
monkeypatch.setattr(Path, "write_text", lambda self, content, **kw: None)
resp = await async_client.post(
f"/api/v1/pages/{page.id}/corrections",
json={"editorial_status": "needs_review"},
)
assert resp.status_code == 200
assert resp.json()["editorial"]["version"] == 2
@pytest.mark.asyncio
async def test_corrections_updates_editorial_status(async_client, db_session, monkeypatch):
corpus = await _create_corpus(db_session)
ms = await _create_manuscript(db_session, corpus.id)
page = await _create_page(db_session, ms.id)
monkeypatch.setattr(Path, "exists", lambda self: True)
monkeypatch.setattr(Path, "read_text", lambda self, **kw: _make_master(page.id))
monkeypatch.setattr(Path, "write_text", lambda self, content, **kw: None)
resp = await async_client.post(
f"/api/v1/pages/{page.id}/corrections",
json={"editorial_status": "reviewed"},
)
assert resp.status_code == 200
assert resp.json()["editorial"]["status"] == "reviewed"
@pytest.mark.asyncio
async def test_corrections_updates_commentary_public(async_client, db_session, monkeypatch):
corpus = await _create_corpus(db_session)
ms = await _create_manuscript(db_session, corpus.id)
page = await _create_page(db_session, ms.id)
monkeypatch.setattr(Path, "exists", lambda self: True)
monkeypatch.setattr(Path, "read_text", lambda self, **kw: _make_master(page.id))
monkeypatch.setattr(Path, "write_text", lambda self, content, **kw: None)
resp = await async_client.post(
f"/api/v1/pages/{page.id}/corrections",
json={"commentary_public": "Commentaire public rΓ©visΓ©"},
)
assert resp.status_code == 200
assert resp.json()["commentary"]["public"] == "Commentaire public rΓ©visΓ©"
@pytest.mark.asyncio
async def test_corrections_updates_commentary_scholarly(async_client, db_session, monkeypatch):
corpus = await _create_corpus(db_session)
ms = await _create_manuscript(db_session, corpus.id)
page = await _create_page(db_session, ms.id)
monkeypatch.setattr(Path, "exists", lambda self: True)
monkeypatch.setattr(Path, "read_text", lambda self, **kw: _make_master(page.id))
monkeypatch.setattr(Path, "write_text", lambda self, content, **kw: None)
resp = await async_client.post(
f"/api/v1/pages/{page.id}/corrections",
json={"commentary_scholarly": "Analyse savante rΓ©visΓ©e"},
)
assert resp.status_code == 200
assert resp.json()["commentary"]["scholarly"] == "Analyse savante rΓ©visΓ©e"
@pytest.mark.asyncio
async def test_corrections_region_validations(async_client, db_session, monkeypatch):
corpus = await _create_corpus(db_session)
ms = await _create_manuscript(db_session, corpus.id)
page = await _create_page(db_session, ms.id)
monkeypatch.setattr(Path, "exists", lambda self: True)
monkeypatch.setattr(Path, "read_text", lambda self, **kw: _make_master(page.id))
monkeypatch.setattr(Path, "write_text", lambda self, content, **kw: None)
resp = await async_client.post(
f"/api/v1/pages/{page.id}/corrections",
json={"region_validations": {"r001": "validated", "r002": "rejected"}},
)
assert resp.status_code == 200
validations = resp.json().get("extensions", {}).get("region_validations", {})
assert validations.get("r001") == "validated"
assert validations.get("r002") == "rejected"
@pytest.mark.asyncio
async def test_corrections_archives_old_version(async_client, db_session, monkeypatch):
"""VΓ©rifie qu'une copie master_v1.json est Γ©crite avant la correction."""
corpus = await _create_corpus(db_session)
ms = await _create_manuscript(db_session, corpus.id)
page = await _create_page(db_session, ms.id)
written_data: dict[str, str] = {}
monkeypatch.setattr(Path, "exists", lambda self: True)
monkeypatch.setattr(Path, "read_text", lambda self, **kw: _make_master(page.id, version=1))
def _capture_write(self: Path, content: str, **kw: object) -> None:
written_data[str(self)] = content
monkeypatch.setattr(Path, "write_text", _capture_write)
await async_client.post(
f"/api/v1/pages/{page.id}/corrections",
json={"editorial_status": "needs_review"},
)
# Deux Γ©critures attendues : master_v1.json (archive) + master.json (nouveau)
written_paths = list(written_data.keys())
assert len(written_paths) >= 2
assert any("master_v1.json" in p for p in written_paths)
assert any("master.json" in p and "master_v" not in p for p in written_paths)
# VΓ©rifier que l'archive contient bien la version originale (v1)
import json as _json
archive_path = next(p for p in written_paths if "master_v1.json" in p)
archive_data = _json.loads(written_data[archive_path])
assert archive_data["editorial"]["version"] == 1
@pytest.mark.asyncio
async def test_corrections_multiple_fields(async_client, db_session, monkeypatch):
"""Plusieurs corrections peuvent Γͺtre envoyΓ©es en un seul appel."""
corpus = await _create_corpus(db_session)
ms = await _create_manuscript(db_session, corpus.id)
page = await _create_page(db_session, ms.id)
monkeypatch.setattr(Path, "exists", lambda self: True)
monkeypatch.setattr(Path, "read_text", lambda self, **kw: _make_master(page.id))
monkeypatch.setattr(Path, "write_text", lambda self, content, **kw: None)
resp = await async_client.post(
f"/api/v1/pages/{page.id}/corrections",
json={
"ocr_diplomatic_text": "Nouveau texte diplomatique",
"editorial_status": "reviewed",
"commentary_public": "Nouveau commentaire",
},
)
assert resp.status_code == 200
data = resp.json()
assert data["ocr"]["diplomatic_text"] == "Nouveau texte diplomatique"
assert data["editorial"]["status"] == "reviewed"
assert data["commentary"]["public"] == "Nouveau commentaire"
assert data["editorial"]["version"] == 2
# ββ GET /api/v1/pages/{id}/history ββββββββββββββββββββββββββββββββββββββββββββ
@pytest.mark.asyncio
async def test_history_page_not_found(async_client):
resp = await async_client.get("/api/v1/pages/nonexistent/history")
assert resp.status_code == 404
@pytest.mark.asyncio
async def test_history_returns_empty_list_when_no_dir(async_client, db_session, monkeypatch):
"""Retourne [] si le rΓ©pertoire de page n'existe pas."""
corpus = await _create_corpus(db_session)
ms = await _create_manuscript(db_session, corpus.id)
page = await _create_page(db_session, ms.id)
monkeypatch.setattr(Path, "exists", lambda self: False)
resp = await async_client.get(f"/api/v1/pages/{page.id}/history")
assert resp.status_code == 200
assert resp.json() == []
@pytest.mark.asyncio
async def test_history_returns_list(async_client, db_session, monkeypatch):
"""Le type de retour est une liste (mΓͺme vide)."""
corpus = await _create_corpus(db_session)
ms = await _create_manuscript(db_session, corpus.id)
page = await _create_page(db_session, ms.id)
monkeypatch.setattr(Path, "exists", lambda self: False)
resp = await async_client.get(f"/api/v1/pages/{page.id}/history")
assert resp.status_code == 200
assert isinstance(resp.json(), list)
@pytest.mark.asyncio
async def test_history_with_archived_files(async_client, db_session, tmp_path, monkeypatch):
"""Retourne les versions trouvΓ©es dans les fichiers master_v*.json."""
corpus = await _create_corpus(db_session, slug="hist-corpus")
ms = await _create_manuscript(db_session, corpus.id)
page = await _create_page(db_session, ms.id)
# CrΓ©e le rΓ©pertoire avec des fichiers de version
page_dir = tmp_path / "corpora" / corpus.slug / "pages" / page.folio_label
page_dir.mkdir(parents=True)
(page_dir / "master_v1.json").write_text(_make_master(page.id, version=1, status="machine_draft"))
(page_dir / "master_v2.json").write_text(_make_master(page.id, version=2, status="reviewed"))
import app.api.v1.pages as pages_module
import app.config as config_mod
original_data_dir = config_mod.settings.data_dir
config_mod.settings.__dict__["data_dir"] = tmp_path
try:
resp = await async_client.get(f"/api/v1/pages/{page.id}/history")
finally:
config_mod.settings.__dict__["data_dir"] = original_data_dir
assert resp.status_code == 200
versions = resp.json()
assert len(versions) == 2
statuses = [v["status"] for v in versions]
assert "machine_draft" in statuses
assert "reviewed" in statuses
|