import json from dataclasses import replace from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from threading import Thread from uuid import uuid4 import pymupdf from Crypto.Cipher import DES from fastapi.testclient import TestClient from idp_service.api import create_app from idp_service.config import Settings from idp_service.db import Store from idp_service.decrypt import DEFAULT_KEY_HEX, DecryptionError, prepare_pdf from idp_service.ocr import InvalidOutput, validate_response from idp_service.worker import Worker from idp_service.webhdfs import download_pdf def settings_for(tmp_path): return replace(Settings(), data_dir=tmp_path / "data", storage="local", ocr_workers=2, poll_seconds=0.01) def make_pdf(path: Path, count=3): document = pymupdf.open() for index in range(count): page = document.new_page() page.insert_text((72, 72), f"Page {index + 1}") document.save(path) document.close() def test_api_idempotency_and_end_to_end(tmp_path, monkeypatch): settings = settings_for(tmp_path) source = tmp_path / "input.pdf" make_pdf(source) app = create_app(settings) request = {"request_id": str(uuid4()), "file_path": str(source), "file_type": "application/pdf"} with TestClient(app) as client: first = client.post("/process", json=request) assert first.status_code == 202 second = client.post("/process", json=request) assert second.status_code == 202 assert second.json()["job_id"] == first.json()["job_id"] assert second.headers["X-Idempotent-Replay"] == "true" assert client.post("/process", json={**request, "file_path": "/other.pdf"}).status_code == 409 def fake_infer(settings, source, page_no, **kwargs): return {"width": 100, "height": 100, "blocks": [ {"label": "Paragraph", "bbox": [1, 1, 500, 500], "html": f"Page {page_no}"}]} monkeypatch.setattr("idp_service.worker.infer_page", fake_infer) worker = Worker(settings) assert worker.coordinator_once() for _ in range(3): page = worker.store.claim_page(settings.lease_seconds, settings.ocr_workers) assert page worker.process_page(page) assert worker.coordinator_once() status = client.get(f"/jobs/{first.json()['job_id']}").json() assert status["status"] == "completed" assert status["completed_pages"] == 3 assert status["result_available"] is True bundle = client.get(f"/jobs/{first.json()['job_id']}/result").json() assert len(bundle["pages"]) == 3 assert all(page["status"] == "done" for page in bundle["pages"]) def drain(worker, settings): """Chạy hết job đang chờ: prepare, mọi trang, rồi finalize.""" assert worker.coordinator_once() while True: page = worker.store.claim_page(settings.lease_seconds, settings.ocr_workers) if not page: break worker.process_page(page) assert worker.coordinator_once() def test_upload_pdf_returns_bundle_without_gpu(tmp_path): settings = replace(settings_for(tmp_path), ocr_backend="pdf_text") source = tmp_path / "Giấy chứng nhận.pdf" make_pdf(source, count=2) app = create_app(settings) with TestClient(app) as client: with source.open("rb") as handle: reply = client.post("/parse", files={"file": (source.name, handle, "application/pdf")}) assert reply.status_code == 202 job_id = reply.json()["job_id"] assert reply.json()["result_url"] == f"/jobs/{job_id}/result" assert client.get(f"/jobs/{job_id}/result").status_code == 409 drain(Worker(settings), settings) assert client.get(f"/jobs/{job_id}").json()["status"] == "completed" bundle = client.get(f"/jobs/{job_id}/result").json() assert bundle["schema"] == "dla-document-bundle" assert bundle["source"] == {"filename": "Giấy chứng nhận.pdf", "media_type": "application/pdf", "page_count": 2, "render_dpi": 200} assert bundle["document_id"].startswith("doc_") page = bundle["pages"][0] assert page["page_id"] == f"{bundle['document_id']}/p001" assert page["width"] > 0 and page["height"] > 0 block = page["blocks"][0] assert block["block_id"] == f"{page['page_id']}/b000" assert block["label"] in {"Paragraph", "Image"} assert all(0 <= value <= 1000 for value in block["bbox"]) assert block["outline_no"] == "0.1" assert bundle["outline"][0]["block_ids"][0] == block["block_id"] # Upload đã dedupe theo sha256 được dọn sau khi finalize. assert list(settings.upload_dir.glob("*.pdf")) == [] def test_upload_rejects_non_pdf_and_replays_same_request_id(tmp_path): settings = settings_for(tmp_path) source = tmp_path / "input.pdf" make_pdf(source, count=1) request_id = str(uuid4()) app = create_app(settings) with TestClient(app) as client: assert client.post("/parse", files={"file": ("note.txt", b"hello", "text/plain")}).status_code == 422 assert client.post("/parse", files={"file": ("empty.pdf", b"", "application/pdf")}).status_code == 422 content = source.read_bytes() first = client.post("/parse", files={"file": ("input.pdf", content, "application/pdf")}, data={"request_id": request_id}) second = client.post("/parse", files={"file": ("input.pdf", content, "application/pdf")}, data={"request_id": request_id}) assert second.json()["job_id"] == first.json()["job_id"] assert second.headers["X-Idempotent-Replay"] == "true" conflict = client.post("/parse", files={"file": ("other.pdf", content, "application/pdf")}, data={"request_id": request_id}) assert conflict.status_code == 409 # Job đầu vẫn giữ được file của nó sau khi request xung đột bị từ chối. assert len(list(settings.upload_dir.glob("*.pdf"))) == 1 def test_page_retry_then_partial_failure(tmp_path, monkeypatch): settings = replace(settings_for(tmp_path), max_page_attempts=2) source = tmp_path / "bad.pdf" make_pdf(source, count=1) store = Store(settings.db_path) job, _ = store.create_job(str(uuid4()), str(source), None, None, 100) worker = Worker(settings, store) worker.coordinator_once() def fail(*args, **kwargs): raise InvalidOutput("Model reached max_tokens", truncated=True) monkeypatch.setattr("idp_service.worker.infer_page", fail) first = store.claim_page(settings.lease_seconds, settings.ocr_workers) worker.process_page(first) with store.tx() as db: db.execute("UPDATE pages SET next_at=0 WHERE job_id=?", (job["id"],)) second = store.claim_page(settings.lease_seconds, settings.ocr_workers) assert second["penalize_repetition"] == 1 worker.process_page(second) worker.coordinator_once() result = store.get_job(job["id"]) assert result["status"] == "partial_failed" assert result["failed_pages"] == 1 bundle = json.loads(result["result_json"]) assert bundle["pages"][0]["status"] == "failed" def test_pdf_text_backend_labels_pages_without_text(tmp_path): from idp_service.ocr import extract_text_blocks blank = tmp_path / "blank.pdf" document = pymupdf.open() document.new_page() document.save(blank) document.close() result = extract_text_blocks(blank, 1) assert result["blocks"] == [{"label": "Image", "bbox": [0, 0, 1000, 1000], "html": "
[no extractable text]
"}] def test_rejects_truncated_plain_text_and_invalid_bbox(): def response(content, finish="stop"): return {"choices": [{"finish_reason": finish, "message": {"content": content}}]} for content, finish in [("text only", "stop"), ('