"""Tests for deeptutor.utils.document_extractor."""
from __future__ import annotations
import base64
import io
from docx import Document as DocxDocument
from openpyxl import Workbook
from pptx import Presentation
from pptx.util import Inches
import pytest
from deeptutor.utils import document_extractor as document_extractor_module
from deeptutor.utils.document_extractor import (
MAX_DOC_BYTES,
MAX_EXTRACTED_CHARS_PER_DOC,
CorruptDocumentError,
DocumentTooLargeError,
EmptyDocumentError,
UnsupportedDocumentError,
extract_documents_from_records,
extract_text_from_bytes,
extract_text_from_path,
is_document_extension,
)
# ---------------------------------------------------------------------------
# Fixtures — generate office docs on the fly
# ---------------------------------------------------------------------------
def _make_docx(paragraphs: list[str]) -> bytes:
doc = DocxDocument()
for p in paragraphs:
doc.add_paragraph(p)
buf = io.BytesIO()
doc.save(buf)
return buf.getvalue()
def _make_xlsx(sheets: dict[str, list[list[object]]]) -> bytes:
wb = Workbook()
default = wb.active
first = True
for name, rows in sheets.items():
ws = default if first else wb.create_sheet()
ws.title = name
for row in rows:
ws.append(row)
first = False
buf = io.BytesIO()
wb.save(buf)
return buf.getvalue()
def _make_pptx(slides_text: list[list[str]]) -> bytes:
prs = Presentation()
for slide_texts in slides_text:
slide = prs.slides.add_slide(prs.slide_layouts[5]) # blank-ish layout
for i, text in enumerate(slide_texts):
tb = slide.shapes.add_textbox(Inches(1), Inches(1 + i * 0.5), Inches(6), Inches(0.5))
tb.text_frame.text = text
buf = io.BytesIO()
prs.save(buf)
return buf.getvalue()
# ---------------------------------------------------------------------------
# is_document_extension
# ---------------------------------------------------------------------------
class TestIsDocumentExtension:
def test_office(self) -> None:
assert is_document_extension("foo.pdf")
assert is_document_extension("foo.DOCX")
assert is_document_extension("report.xlsx")
assert is_document_extension("deck.pptx")
def test_text_and_code(self) -> None:
# Any extension in FileTypeRouter.TEXT_EXTENSIONS should be supported.
assert is_document_extension("notes.txt")
assert is_document_extension("readme.md")
assert is_document_extension("module.py")
assert is_document_extension("config.yaml")
assert is_document_extension("data.json")
assert is_document_extension("index.html")
assert is_document_extension("table.csv")
def test_unsupported(self) -> None:
assert not is_document_extension("foo.png")
assert not is_document_extension("foo.zip")
assert not is_document_extension("foo.exe")
assert not is_document_extension("foo")
assert not is_document_extension("")
# ---------------------------------------------------------------------------
# extract_text_from_bytes — happy paths
# ---------------------------------------------------------------------------
class TestExtractDocx:
def test_basic_paragraphs(self) -> None:
data = _make_docx(["Hello world", "Second paragraph", ""])
text = extract_text_from_bytes("doc.docx", data)
assert "Hello world" in text
assert "Second paragraph" in text
def test_path_helper_can_disable_chat_truncation(self, tmp_path) -> None:
data = _make_docx(["a" * (MAX_EXTRACTED_CHARS_PER_DOC + 10)])
path = tmp_path / "long.docx"
path.write_bytes(data)
text = extract_text_from_path(path, max_chars=None)
assert len(text) > MAX_EXTRACTED_CHARS_PER_DOC
assert "truncated" not in text
def test_ooxml_fallback_without_python_docx(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(document_extractor_module, "DocxDocument", None)
data = _make_docx(["Fallback paragraph", "第二段"])
text = extract_text_from_bytes("doc.docx", data)
assert "Fallback paragraph" in text
assert "第二段" in text
class TestExtractXlsx:
def test_multiple_sheets(self) -> None:
data = _make_xlsx(
{
"Alpha": [["a1", "b1"], ["a2", 42]],
"Beta": [["x", "y"]],
}
)
text = extract_text_from_bytes("book.xlsx", data)
assert "--- Sheet: Alpha ---" in text
assert "--- Sheet: Beta ---" in text
assert "a1" in text and "42" in text
assert "x" in text
def test_ooxml_fallback_without_openpyxl(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(document_extractor_module, "load_workbook", None)
data = _make_xlsx({"Alpha": [["name", "score"], ["alice", 98]]})
text = extract_text_from_bytes("book.xlsx", data)
assert "--- Sheet: Alpha ---" in text
assert "alice" in text
assert "98" in text
class TestExtractPptx:
def test_basic_slides(self) -> None:
data = _make_pptx([["Slide 1 title", "Slide 1 body"], ["Slide 2 only text"]])
text = extract_text_from_bytes("deck.pptx", data)
assert "--- Slide 1 ---" in text
assert "--- Slide 2 ---" in text
assert "Slide 1 title" in text
assert "Slide 2 only text" in text
def test_ooxml_fallback_without_python_pptx(self, monkeypatch: pytest.MonkeyPatch) -> None:
monkeypatch.setattr(document_extractor_module, "PptxPresentation", None)
data = _make_pptx([["Fallback slide", "第二行"]])
text = extract_text_from_bytes("deck.pptx", data)
assert "--- Slide 1 ---" in text
assert "Fallback slide" in text
assert "第二行" in text
class TestExtractTextLike:
def test_plain_txt(self) -> None:
text = extract_text_from_bytes("note.txt", "hello world\nline two".encode("utf-8"))
assert "hello world" in text
assert "line two" in text
def test_python_source(self) -> None:
src = b"def greet(name: str) -> str:\n return f'hi {name}'\n"
text = extract_text_from_bytes("greet.py", src)
assert "def greet" in text
def test_json(self) -> None:
text = extract_text_from_bytes("data.json", b'{"x": 42, "y": "ok"}')
assert '"x": 42' in text
def test_csv(self) -> None:
text = extract_text_from_bytes("table.csv", b"a,b,c\n1,2,3\n")
assert "a,b,c" in text
assert "1,2,3" in text
def test_markdown(self) -> None:
text = extract_text_from_bytes("doc.md", b"# Heading\n\nBody.\n")
assert "# Heading" in text
def test_utf8_with_bom(self) -> None:
# The candidate chain has utf-8 before utf-8-sig (same order as KB
# pipeline), so BOM-prefixed bytes decode as utf-8 and the BOM is
# retained. Mirror that behavior here.
text = extract_text_from_bytes("note.txt", b"\xef\xbb\xbfhello")
assert "hello" in text
def test_gbk_fallback(self) -> None:
# "你好" in GBK
text = extract_text_from_bytes("note.txt", "你好".encode("gbk"))
assert text == "你好"
def test_svg(self) -> None:
svg = (
b''
b'"
)
text = extract_text_from_bytes("logo.svg", svg)
assert "