import base64 import json from dataclasses import replace from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from threading import Event, 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 import kie 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, kie_enabled=False) 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 drain(worker, settings): """Chạy hết job đang chờ: prepare, mọi trang, extract, rồi finalize và callback.""" 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) job = worker.store.claim_extract(settings.lease_seconds, settings.ocr_workers) if job: worker.extract(job) assert worker.coordinator_once() worker.callback_once() 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) drain(Worker(settings), settings) 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"]) # IDP_KIE_ENABLED=0: bundle vẫn giữ đủ khung extraction với các trường null. assert bundle["extraction"] == {"schema": kie.SCHEMA_NAME, "status": "skipped", "fields": kie.empty_answer(), "error": None} 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"] assert bundle["extraction"]["status"] == "skipped" # 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.extract(store.claim_extract(settings.lease_seconds, settings.ocr_workers)) 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]

"}] KIE_ANSWER = { "document_type": "QUYẾT ĐỊNH", "document_number": "123/QĐ-UBND", "issued_date": "09/09/2026", "issuing_authority": "ỦY BAN NHÂN DÂN TỈNH BẮC NINH", "title": "Về việc phê duyệt quy hoạch", "signer": {"name": "Nguyễn Văn A", "position": "KT. CHỦ TỊCH"}, } def model_server(kie_content): """Server giả đóng vai vLLM: nhận cả prompt DLA lẫn prompt KIE, và nhận callback.""" callbacks, kie_requests = [], [] class Handler(BaseHTTPRequestHandler): def do_POST(self): body = json.loads(self.rfile.read(int(self.headers["Content-Length"]))) if self.path == "/v1/chat/completions": content = body["messages"][0]["content"] assert content[0]["image_url"]["url"].startswith("data:image/png;base64,") if content[-1]["text"].startswith("Trích xuất thông tin"): kie_requests.append(body) answer = {"choices": [{"finish_reason": "stop", "message": {"content": kie_content}}]} else: answer = {"choices": [{"finish_reason": "stop", "message": {"content": '
Test
' '
'}}]} else: callbacks.append(body) answer = {"ok": True} data = json.dumps(answer).encode() self.send_response(200) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(data))) self.end_headers() self.wfile.write(data) def log_message(self, *_): pass return ThreadingHTTPServer(("127.0.0.1", 0), Handler), callbacks, kie_requests def test_extract_fixed_schema_end_to_end_and_callback(tmp_path): server, callbacks, kie_requests = model_server("```json\n" + json.dumps(KIE_ANSWER, ensure_ascii=False) + "\n```") thread = Thread(target=server.serve_forever, daemon=True) thread.start() try: url = f"http://127.0.0.1:{server.server_port}/v1/chat/completions" settings = replace(settings_for(tmp_path), ocr_url=url, kie_enabled=True, kie_url=url, kie_max_tokens=4096) source = tmp_path / "quyet-dinh.pdf" make_pdf(source, count=2) app = create_app(settings) with TestClient(app) as client: reply = client.post("/parse", files={"file": ("quyet-dinh.pdf", source.read_bytes(), "application/pdf")}, data={"callback_url": f"http://127.0.0.1:{server.server_port}/callback"}) job_id = reply.json()["job_id"] assert client.get(f"/jobs/{job_id}/extraction").status_code == 409 drain(Worker(settings), settings) # Lượt 1 hỏi trường đầu văn bản trên 3 trang đầu, lượt 2 hỏi người ký trên trang có chữ ký. assert len(kie_requests) == 2 header, signer = (request["messages"][0]["content"] for request in kie_requests) assert len(header) == 3 and '"document_type"' in header[-1]["text"] and '"signer"' not in header[-1]["text"] assert len(signer) == 3 and '"signer"' in signer[-1]["text"] and '"title"' not in signer[-1]["text"] assert kie_requests[0]["model"] == settings.kie_model assert kie_requests[0]["max_tokens"] == 4096 extraction = client.get(f"/jobs/{job_id}/extraction").json() assert extraction["status"] == "done" assert extraction["schema"] == kie.SCHEMA_NAME assert extraction["fields"] == KIE_ANSWER assert client.get(f"/jobs/{job_id}").json()["extract_status"] == "done" bundle = client.get(f"/jobs/{job_id}/result").json() assert bundle["extraction"]["fields"] == KIE_ANSWER assert bundle["extraction"]["status"] == "done" output = callbacks[0]["conf"]["output"] assert output["extraction"]["fields"] == KIE_ANSWER assert len(output["extraction"]["pages"]) == 2 finally: server.shutdown() server.server_close() thread.join() def test_extract_retries_bad_answer_then_gives_up(tmp_path): # Model trả JSON nhưng đặt khoá tiếng Việt: coi như hỏng chứ không im lặng trả null. server, _, kie_requests = model_server('{"loai_van_ban": "QUYẾT ĐỊNH"}') thread = Thread(target=server.serve_forever, daemon=True) thread.start() try: url = f"http://127.0.0.1:{server.server_port}/v1/chat/completions" settings = replace(settings_for(tmp_path), ocr_url=url, kie_enabled=True, kie_url=url, max_kie_attempts=2) source = tmp_path / "input.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() worker.process_page(store.claim_page(settings.lease_seconds, settings.ocr_workers)) for _ in range(settings.max_kie_attempts): with store.tx() as db: db.execute("UPDATE jobs SET extract_next_at=0 WHERE id=?", (job["id"],)) worker.extract(store.claim_extract(settings.lease_seconds, settings.ocr_workers)) assert len(kie_requests) == settings.max_kie_attempts worker.coordinator_once() # Extract hỏng không làm hỏng job: bundle vẫn completed, trường để null kèm lỗi. result = store.get_job(job["id"]) assert result["status"] == "completed" bundle = json.loads(result["result_json"]) assert bundle["extraction"]["status"] == "failed" assert bundle["extraction"]["fields"] == kie.empty_answer() assert bundle["extraction"]["error"] == "Đáp án không có trường nào của schema" finally: server.shutdown() server.server_close() thread.join() def test_kie_prompt_schema_and_answer_shape(): prompt = kie.render_prompt(3) assert prompt.startswith("Trích xuất thông tin từ ảnh tài liệu (3 trang, ảnh theo thứ tự trang)") assert '- "signer" (object): Người có thẩm quyền ký' in prompt and '\n - "name"' in prompt assert [line for line in prompt.splitlines() if line.startswith('- "')][:5] == [ line for line in kie.render_fields(kie.SCHEMA) if line.startswith('- "')][:5] assert kie.render_prompt(1).startswith("Trích xuất thông tin từ ảnh tài liệu và") # Khoá thừa bị bỏ, khoá thiếu thành null, chuỗi rỗng và mảng chuỗi được làm sạch. answer = kie.normalize_answer({"document_type": ["QUYẾT", "ĐỊNH"], "document_number": " ", "signer": {"name": "Nguyễn Văn A"}, "ghi_chu": "thừa"}) assert answer == {"document_type": "QUYẾT\nĐỊNH", "document_number": None, "issued_date": None, "issuing_authority": None, "title": None, "signer": {"name": "Nguyễn Văn A", "position": None}} assert list(answer) == [field["key"] for field in kie.SCHEMA] assert kie.normalize_answer({"signer": [{"name": "Lương Cường", "position": "CHỦ TỊCH"}, {"name": "B"}]}, kie.SIGNER_FIELDS) == {"signer": {"name": "Lương Cường", "position": "CHỦ TỊCH"}} # Trường đầu văn bản lấy 3 trang đầu; người ký lấy trang DLA có chữ ký/con dấu, tối đa N trang cuối. assert kie.header_pages(1) == [1] assert kie.header_pages(10) == [1, 2, 3] text = [{"label": "Paragraph", "bbox": [0, 0, 1000, 500]}] edge_stamp = [{"label": "Stamp", "bbox": [950, 100, 1000, 200]}] initials = [{"label": "Signature", "bbox": [400, 850, 600, 930]}] seal = [{"label": "Stamp", "bbox": [480, 400, 650, 530]}] assert kie.signer_pages({1: text, 2: text}, 5) == [] assert kie.signer_pages({1: edge_stamp, 2: text, 3: initials}, 5) == [1, 3] assert kie.signer_pages({no: edge_stamp for no in range(1, 11)}, 3) == [8, 9, 10] # Có dấu trong thân trang thì chỉ lấy trang đó, bỏ trang chữ ký nháy và dấu giáp lai. assert kie.signer_pages({1: initials + edge_stamp, 2: initials, 3: seal}, 5) == [3] def test_keeps_empty_visual_blocks_but_rejects_empty_text_blocks(): """Model trả div rỗng cho con dấu, QR, chữ ký; chỉ block chữ mà rỗng mới là output hỏng.""" def response(content): return {"choices": [{"finish_reason": "stop", "message": {"content": content}}]} blocks = validate_response(response( '
' '
' '

Nội dung

')) assert [block["label"] for block in blocks] == ["Stamp", "QR Code", "Paragraph"] assert [block["html"] for block in blocks[:2]] == ["", ""] try: validate_response(response('
')) except InvalidOutput as exc: assert "Paragraph" in str(exc) else: raise AssertionError("Block chữ rỗng đáng lẽ phải bị từ chối") 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"), ('
x
', "stop"), ('
x
', "length")]: try: validate_response(response(content, finish)) except InvalidOutput: pass else: raise AssertionError("Invalid output was accepted") assert validate_response(response(" \n")) == [] # trang trắng def test_locked_database_surfaces_and_does_not_kill_worker_thread(tmp_path, monkeypatch): import sqlite3 settings = replace(settings_for(tmp_path), ocr_workers=1) store = Store(settings.db_path) blocker = store.connect() blocker.execute("BEGIN IMMEDIATE") monkeypatch.setattr(store, "connect", lambda: sqlite3.connect(settings.db_path, timeout=0.05, isolation_level=None)) try: with store.tx(): pass except sqlite3.OperationalError as exc: assert "locked" in str(exc) else: raise AssertionError("Lock đáng lẽ phải làm BEGIN IMMEDIATE lỗi") worker = Worker(settings, store) calls = [] def step(): calls.append(1) if len(calls) == 3: worker.stop.set() return store.claim_page(settings.lease_seconds, settings.ocr_workers) worker.loop(step) # lỗi "database is locked" hai lần vẫn chạy tiếp tới lần thứ ba assert len(calls) == 3 blocker.execute("ROLLBACK") def test_worker_store_serializes_write_transactions(tmp_path, monkeypatch): import sqlite3 store = Store(settings_for(tmp_path).db_path) monkeypatch.setattr(store, "connect", lambda: sqlite3.connect(store.path, timeout=0.05, isolation_level=None)) first_entered = Event() release_first = Event() second_started = Event() second_done = Event() errors = [] def first_writer(): try: with store.tx(): first_entered.set() release_first.wait(2) except Exception as exc: errors.append(exc) def second_writer(): second_started.set() try: store.claim_page(1800, 2) except Exception as exc: errors.append(exc) finally: second_done.set() first = Thread(target=first_writer) second = Thread(target=second_writer) first.start() try: assert first_entered.wait(2) second.start() assert second_started.wait(2) assert not second_done.wait(0.1) finally: release_first.set() first.join(2) if second.ident is not None: second.join(2) assert second_done.is_set() assert not errors def test_worker_main_loop_exits_when_processing_thread_stops(tmp_path): worker = Worker(settings_for(tmp_path)) dead_thread = Thread(name="dead-ocr") try: worker.loop(lambda: False, [dead_thread]) except RuntimeError as exc: assert "dead-ocr" in str(exc) else: raise AssertionError("Worker must exit so Docker can restart it") def test_real_http_ocr_and_callback(tmp_path): callbacks = [] auth_headers = [] class Handler(BaseHTTPRequestHandler): def do_POST(self): size = int(self.headers["Content-Length"]) body = json.loads(self.rfile.read(size)) if self.path == "/v1/chat/completions": assert body["messages"][0]["content"][0]["image_url"]["url"].startswith("data:image/png;base64,") answer = {"choices": [{"finish_reason": "stop", "message": {"content": '
Test
'}}]} else: callbacks.append(body) auth_headers.append(self.headers.get("Authorization")) answer = {"detail": "DAG Run already exists"} data = json.dumps(answer).encode() self.send_response(200 if self.path == "/v1/chat/completions" else 409) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(data))) self.end_headers() self.wfile.write(data) def do_GET(self): assert self.path == "/api/v1/dags/test/dagRuns/callback_test_001" assert self.headers.get("Authorization") == auth_headers[0] data = json.dumps({"dag_run_id": callbacks[0]["dag_run_id"], "conf": callbacks[0]["conf"]}).encode() self.send_response(200) self.send_header("Content-Type", "application/json") self.send_header("Content-Length", str(len(data))) self.end_headers() self.wfile.write(data) def log_message(self, *_): pass server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) thread = Thread(target=server.serve_forever, daemon=True) thread.start() try: settings = replace(settings_for(tmp_path), ocr_url=f"http://127.0.0.1:{server.server_port}/v1/chat/completions", callback_basic_user="callback_handler", callback_basic_password="callback_handler") source = tmp_path / "input.pdf" make_pdf(source, count=1) app = create_app(settings) with TestClient(app) as client: reply = client.post("/process", json={"request_id": str(uuid4()), "file_path": str(source), "dag_run_id": "callback_test_001", "callback_url": f"http://127.0.0.1:{server.server_port}/api/v1/dags/test/dagRuns"}) assert reply.status_code == 202 drain(Worker(settings), settings) assert client.get(f"/jobs/{reply.json()['job_id']}").json()["callback_state"] == "delivered" assert callbacks[0]["dag_run_id"] == "callback_test_001" assert auth_headers == ["Basic " + base64.b64encode(b"callback_handler:callback_handler").decode("ascii")] assert set(callbacks[0]) == {"dag_run_id", "conf"} conf = callbacks[0]["conf"] assert conf["request_id"] == reply.json()["request_id"] assert conf["job_id"] == reply.json()["job_id"] assert conf["status"] == "done" assert conf["output"]["canonical"]["schema"] == "dla-document-bundle" assert conf["output"]["canonical"]["pages"][0]["status"] == "done" images = conf["output"]["extraction"]["pages"] assert len(images) == 1 assert images[0]["page_no"] == 1 assert images[0]["media_type"] == "image/png" assert base64.b64decode(images[0]["data_base64"]).startswith(b"\x89PNG\r\n\x1a\n") # Cùng dag_run_id nhưng job khác phải giữ lỗi 409, không đánh dấu delivered. second = client.post("/process", json={"request_id": str(uuid4()), "file_path": str(source), "dag_run_id": "callback_test_001", "callback_url": f"http://127.0.0.1:{server.server_port}/api/v1/dags/test/dagRuns"}) assert second.status_code == 202 drain(Worker(settings), settings) second_status = client.get(f"/jobs/{second.json()['job_id']}").json() assert second_status["callback_state"] == "pending" assert "409" in second_status["callback_error"] finally: server.shutdown() server.server_close() thread.join() def test_global_gpu_limit_and_fairness_across_files(tmp_path): settings = settings_for(tmp_path) store = Store(settings.db_path) for name in ("a", "b"): source = tmp_path / f"{name}.pdf" make_pdf(source, count=2) store.create_job(str(uuid4()), str(source), None, None, 100) worker = Worker(settings, store) worker.coordinator_once() worker.coordinator_once() first = store.claim_page(settings.lease_seconds, global_limit=2) second = store.claim_page(settings.lease_seconds, global_limit=2) assert first["job_id"] != second["job_id"] assert store.claim_page(settings.lease_seconds, global_limit=2) is None def test_slow_callback_does_not_block_next_job_or_callback(tmp_path, monkeypatch): settings = replace(settings_for(tmp_path), callback_workers=2) store = Store(settings.db_path) source = tmp_path / "input.pdf" make_pdf(source, count=1) bad, _ = store.create_job(str(uuid4()), str(source), "http://bad-callback", None, 100) good, _ = store.create_job(str(uuid4()), str(source), "http://good-callback", None, 100) later, _ = store.create_job(str(uuid4()), str(source), None, None, 100) with store.tx() as db: db.execute("UPDATE jobs SET status='completed', callback_state='pending' WHERE id IN (?, ?)", (bad["id"], good["id"])) worker = Worker(settings, store) started, release = Event(), Event() def fake_callback(job): if job["id"] == bad["id"]: started.set() assert release.wait(5) store.callback_done(job["id"], job["callback_attempts"]) monkeypatch.setattr(worker, "callback", fake_callback) thread = Thread(target=worker.callback_once) thread.start() try: assert started.wait(5) assert worker.coordinator_once() assert store.get_job(later["id"])["status"] == "processing" assert worker.callback_once() assert store.get_job(good["id"])["callback_state"] == "delivered" finally: release.set() thread.join(timeout=5) assert not thread.is_alive() def test_webhdfs_adapter_streams(tmp_path, monkeypatch): class FakeClient: def __init__(self): self.files = {"/input.pdf": b"pdf bytes"} def status(self, path, strict=True): if path not in self.files: return None return {"type": "FILE", "length": len(self.files[path])} def download(self, source, destination, overwrite=False): Path(destination).write_bytes(self.files[source]) client = FakeClient() monkeypatch.setattr("idp_service.webhdfs.make_client", lambda url: client) pdf = tmp_path / "input.pdf" download_pdf("http://namenode:9870", "/input.pdf", pdf, 100) assert pdf.read_bytes() == b"pdf bytes" def test_voffice_des_decryption_and_plain_pdf_passthrough(tmp_path): original = tmp_path / "original.pdf" make_pdf(original, count=2) content = original.read_bytes() padding = 8 - len(content) % 8 encrypted = tmp_path / "encrypted.bin" encrypted.write_bytes(DES.new(bytes.fromhex(DEFAULT_KEY_HEX), DES.MODE_ECB).encrypt( content + bytes([padding]) * padding)) decrypted = tmp_path / "decrypted.pdf" assert prepare_pdf(encrypted, decrypted, "auto", DEFAULT_KEY_HEX) is True assert decrypted.read_bytes() == content with pymupdf.open(decrypted) as document: assert document.page_count == 2 plain_input = tmp_path / "plain-input.pdf" plain_input.write_bytes(content) passthrough = tmp_path / "passthrough.pdf" assert prepare_pdf(plain_input, passthrough, "auto", DEFAULT_KEY_HEX) is False assert passthrough.read_bytes() == content def test_voffice_decryption_rejects_wrong_key(tmp_path): encrypted = tmp_path / "encrypted.bin" encrypted.write_bytes(b"12345678") try: prepare_pdf(encrypted, tmp_path / "out.pdf", "required", "0000000000000000") except DecryptionError: pass else: raise AssertionError("Invalid encrypted document was accepted")