Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# Project : SPIDER7# File : tests/unit/extract/test_extract_document.py8# Module : Tests9# Repository : https://git.spboucher.ai/spider10# Project Website : Not specified11# Created : 2026-12-0412# Last Modified : 2026-12-0413#14# Author : Simon-Pierre Boucher15# Position : Professor of Finance16# Institution : Université du Québec en Outaouais (UQO)17# Organization : SP Boucher18# Website : https://spboucher.ai19# Git : https://git.spboucher.ai20#21# Preferred Contact: contact@spboucher.ai22# Development : dev@spboucher.ai23# Support : support@spboucher.ai24# Security/Admin : admin@spboucher.ai25#26# Copyright (c) 202627# Simon-Pierre Boucher28# All rights reserved where applicable. This file is governed by the29# applicable project license, copyright notices and relevant law.30# Existing third-party rights and notices remain unaffected.31#32# License : ISC33#34# Do not embed credentials, private keys, access tokens,35# certificates or confidential personal information.36#37# =============================================================================38# END OF SP BOUCHER SOURCE HEADER39# =============================================================================4041"""PDF text-layer extraction on hand-built fixtures."""42import io43from pathlib import Path4445import pypdf46import pytest47from pdf_fixtures import FILES, FIXTURES, build_pdf4849from spider.extract.document import extract_pdf505152@pytest.mark.parametrize("name", sorted(FILES))53def test_committed_fixtures_match_the_generator(name):54 assert (FIXTURES / name).read_bytes() == FILES[name]()555657def test_text_layer_and_page_without_text():58 doc = extract_pdf(FIXTURES / "text_and_scan.pdf")59 assert doc.ok and doc.error is None and doc.n_pages == 2 and not doc.truncated60 assert doc.pages[0].text == "Loyer mensuel : 1 250 $ - Monthly rent"61 assert doc.pages[0].has_text_layer is True62 assert doc.pages[1].text == "" and doc.pages[1].has_text_layer is False63 assert doc.needs_ocr_pages == [1]64 assert doc.metadata["Title"] == "SPIDER fixture"65 assert doc.flags == [] and len(doc.sha256) == 64 and doc.size > 0666768def test_accepts_path_str_and_bytes():69 path = FIXTURES / "text_and_scan.pdf"70 from_bytes = extract_pdf(path.read_bytes())71 assert extract_pdf(str(path)).pages[0].text == from_bytes.pages[0].text72 assert extract_pdf(bytearray(path.read_bytes())).sha256 == from_bytes.sha256737475def test_javascript_is_flagged_never_executed():76 doc = extract_pdf(FIXTURES / "with_javascript.pdf")77 assert doc.ok and doc.pages[0].text == "Page with an OpenAction"78 assert "javascript" in doc.flags and "open_action" in doc.flags798081def test_max_pages_truncates():82 doc = extract_pdf(build_pdf(["un", "deux", "trois"]), max_pages=2)83 assert doc.ok and doc.n_pages == 3 and doc.truncated84 assert [p.text for p in doc.pages] == ["un", "deux"]858687def test_max_bytes(tmp_path: Path):88 data = build_pdf(["x"])89 doc = extract_pdf(data, max_bytes=100)90 assert not doc.ok and doc.error.code == "too_large" and doc.pages == []91 path = tmp_path / "big.pdf"92 path.write_bytes(data)93 assert extract_pdf(path, max_bytes=100).error.code == "too_large"949596def _encrypted(user_password: str) -> bytes:97 writer = pypdf.PdfWriter(clone_from=io.BytesIO(build_pdf(["secret text"])))98 writer.encrypt(user_password, owner_password="owner")99 buffer = io.BytesIO()100 writer.write(buffer)101 return buffer.getvalue()102103104def test_encrypted_pdf_gives_structured_error():105 doc = extract_pdf(_encrypted("s3cret"))106 assert not doc.ok and doc.encrypted and doc.error.code == "encrypted"107 assert doc.pages == [] and "encrypted" in doc.flags108109110def test_empty_user_password_is_readable():111 doc = extract_pdf(_encrypted(""))112 assert doc.ok and doc.encrypted and doc.pages[0].text == "secret text"113114115@pytest.mark.parametrize(("data", "code"), [116 (b"", "empty"), (b" \n", "empty"), (b"<html>not a pdf</html>", "invalid"),117 (b"%PDF-1.4\nthis is truncated garbage", "invalid"), (b"%PDF-1.7\n" + b"\x00" * 2000, "invalid"),118])119def test_invalid_inputs_are_structured_errors(data, code):120 doc = extract_pdf(data)121 assert not doc.ok and doc.error.code == code and doc.pages == []122123124def test_missing_file():125 doc = extract_pdf("/nonexistent/spider/file.pdf")126 assert not doc.ok and doc.error.code == "not_found"127128129def test_truncated_real_pdf_does_not_raise():130 data = build_pdf(["texte complet"])131 doc = extract_pdf(data[: len(data) // 2])132 assert doc.ok in (True, False) # either recovered or reported, never an exception133 if not doc.ok:134 assert doc.error.code == "invalid"135