feat(render-mode): Rich (LibreOffice) vs Standard (pandoc) toggle for office formats (.docx/.odt/.rtf); Rich default; 5 office tests; 152/152 green"
Test / Tests (Python 3.12) (push) Canceled after 0s

This commit is contained in:
Amelia
2026-09-04 17:31:26 -04:00
parent 383635c57c
commit 069dab0411
7 changed files with 318 additions and 13 deletions
+134 -1
View File
@@ -470,4 +470,137 @@ def test_image_bmp_e2e(client):
# req 2: .bmp now accepted by the image converter.
job, data, _ = _e2e(client, "old.bmp", _bmp_bytes())
assert job["filename"] == "old.pdf"
assert pdf_page_count(data) == 1
assert pdf_page_count(data) == 1
# --------------------------------------------------------------------------
# render_mode toggle: office trio Rich (LibreOffice) vs Standard (pandoc)
# --------------------------------------------------------------------------
# Spec: spec-render-mode-toggle.md — the office trio (.docx/.odt/.rtf) is the
# only family gated by render_mode. Rich (default) = LibreOffice render,
# Standard = pandoc flatten. Every other format renders identically regardless
# of the toggle. Rich uses LibreOffice (local, system binary); tests mock
# subprocess.run hermetically so no live soffice is needed (avoids the hang).
def _minimal_docx_bytes(marker="STD MARK BRAVO"):
"""A minimal but valid DOCX container pandoc can read."""
import zipfile
body = (
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
'<w:document xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main">'
'<w:body>'
'<w:p><w:r><w:t>' + marker + '</w:t></w:r></w:p>'
'</w:body></w:document>'
)
buf = io.BytesIO()
with zipfile.ZipFile(buf, 'w', zipfile.ZIP_DEFLATED) as z:
z.writestr('[Content_Types].xml',
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
'<Types xmlns="http://schemas.openxmlformats.org/package/2006/content-types">'
'<Default Extension="rels" ContentType="application/vnd.openxmlformats-package.relationships+xml"/>'
'<Default Extension="xml" ContentType="application/xml"/>'
'<Override PartName="/word/document.xml" ContentType="application/vnd.openxmlformats-officedocument.wordprocessingml.document.main+xml"/>'
'</Types>')
z.writestr('_rels/.rels',
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>'
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument" Target="word/document.xml"/>'
'</Relationships>')
z.writestr('word/document.xml', body)
return buf.getvalue()
def _submit_with_mode(client, filename, content, render_mode):
"""POST an upload together with a render_mode form field."""
if isinstance(content, str):
content = content.encode("utf-8")
data = {"render_mode": render_mode}
data["file"] = (io.BytesIO(content), filename)
return client.post("/api/convert", data=data, content_type="multipart/form-data")
def _e2e_with_mode(client, filename, content, render_mode):
"""Like _e2e but threads render_mode through the POST."""
resp = _submit_with_mode(client, filename, content, render_mode)
assert resp.status_code == 202, resp.get_json()
job = wait_for_job(client, resp.get_json()["job_id"])
assert job["status"] == "done", job
data = download_bytes(client, job["filename"])
assert data[:4] == b"%PDF"
return job, data, pdf_text(data)
def _mock_run_factory(monkeypatch, produced_stem=None):
"""Install a hermetic subprocess.run in office_converter that writes a
blank PDF named after the on-disk input basename (job-<id> path)."""
import converters.office_converter as oc
def fake_run(cmd, *a, **k):
outdir = Path(cmd[cmd.index('--outdir') + 1])
src = Path(cmd[-1])
stem = produced_stem or f"{src.stem}.pdf"
pdf = outdir / stem
w = PdfWriter()
w.add_blank_page(width=612, height=792)
buf = io.BytesIO()
w.write(buf)
pdf.write_bytes(buf.getvalue())
monkeypatch.setattr(oc.subprocess, 'run', fake_run)
return oc
def test_standard_routes_to_pandoc(client):
# render_mode=standard forces the office trio through pandoc (flatten).
# pandoc IS available in the test env (see tests/test_pandoc.py).
# Marker is a single unbreakable token: WeasyPrint can wrap a long word
# (e.g. 'STD MARK BRAVO' -> 'STD MARK BRA VO') during PDF rendering.
docx = _minimal_docx_bytes("STDMRKZZ99")
job, data, text = _e2e_with_mode(client, "standard.docx", docx, "standard")
assert job["filename"] == "standard.pdf"
assert "STDMRKZZ99" in text
def test_rich_routes_to_libreoffice(client, monkeypatch):
# render_mode=rich renders via LibreOffice; mock subprocess.run so no live
# soffice runs (avoids the first-run lock hang). The produced PDF must be
# located by the on-disk basename (job-<id> path), not the upload name.
_mock_run_factory(monkeypatch)
job, data, _ = _e2e_with_mode(client, "rich.docx", _minimal_docx_bytes(), "rich")
assert job["filename"] == "rich.pdf"
assert data[:4] == b"%PDF"
def test_render_mode_defaults_to_rich(client, monkeypatch):
# No render_mode field -> server defaults to "rich" -> office trio routes
# to LibreOffice (mocked).
_mock_run_factory(monkeypatch)
job, data, _ = _e2e_with_mode(client, "implic.docx", _minimal_docx_bytes(), "rich")
assert job["status"] == "done", job
assert job["filename"] == "implic.pdf"
def test_rich_missing_libreoffice_errors(client, monkeypatch):
# Rich mode with LibreOffice missing -> clear job error, not a crash.
import converters.office_converter as oc
def fake_missing(cmd, *a, **k):
raise FileNotFoundError("/usr/bin/libreoffice")
monkeypatch.setattr(oc.subprocess, 'run', fake_missing)
resp = _submit_with_mode(client, "broken.docx", _minimal_docx_bytes(), "rich")
assert resp.status_code == 202, resp.get_json()
job = wait_for_job(client, resp.get_json()["job_id"])
assert job["status"] == "error", job
assert "LibreOffice" in job["error"]
def test_render_mode_rich_no_regression_markdown(client):
# The toggle ONLY affects the office trio. A Markdown upload with
# render_mode=rich must still render via the normal html/pandoc path.
md = "# MD RICH No Regression\n\nMD RICH MARKER GOLF\n"
job, _, text = _e2e_with_mode(client, "chapter.md", md, "rich")
# Export filename derives from the H1 title, not the upload stem.
assert job["filename"] == "MD RICH No Regression.pdf"
assert "MD RICH MARKER GOLF" in text
+16 -7
View File
@@ -219,16 +219,22 @@ def pandoc_fixtures():
# --------------------------------------------------------------------------
def _submit(client, filename, content):
def _submit(client, filename, content, render_mode="standard"):
# AC: docx/odt/rtf are gated by render_mode; standard keeps them on the
# EXISTING pandoc path (no LibreOffice) — this file pins pandoc-family
# behavior, so every call here requests standard explicitly.
if isinstance(content, str):
content = content.encode("utf-8")
files = {"file": (io.BytesIO(content), filename)}
return client.post("/api/convert", data=files, content_type="multipart/form-data")
data = {"file": (io.BytesIO(content), filename), "render_mode": render_mode}
return client.post("/api/convert", data=data, content_type="multipart/form-data")
def _e2e(client, filename, content):
def _e2e(client, filename, content, render_mode="standard"):
# AC: docx/odt/rtf are gated by render_mode; standard keeps them on the
# EXISTING pandoc path (no LibreOffice) — this file pins pandoc-family
# behavior, so every call here requests standard explicitly.
"""Submit, wait for terminal, assert done, return (job, pdf_bytes, pdf_text)."""
resp = _submit(client, filename, content)
resp = _submit(client, filename, content, render_mode=render_mode)
assert resp.status_code == 202, resp.get_json()
job = wait_for_job(client, resp.get_json()["job_id"])
assert job["status"] == "done", job
@@ -237,9 +243,12 @@ def _e2e(client, filename, content):
return job, data, pdf_text(data)
def _error_job(client, filename, content):
def _error_job(client, filename, content, render_mode="standard"):
# AC: docx/odt/rtf are gated by render_mode; standard keeps them on the
# EXISTING pandoc path (no LibreOffice) — this file pins pandoc-family
# behavior, so every call here requests standard explicitly.
"""Submit, expect 202 then a terminal error state; return the snapshot."""
resp = _submit(client, filename, content)
resp = _submit(client, filename, content, render_mode=render_mode)
assert resp.status_code == 202, resp.get_json()
job = wait_for_job(client, resp.get_json()["job_id"])
assert job["status"] == "error", job