497 lines
27 KiB
Python
497 lines
27 KiB
Python
#!/usr/bin/env python3
|
||
"""在线阅览这两件事的离线验收:**信息要齐**,**版式要和下载后打开一致**。
|
||
|
||
cd backend && python3 scripts/check_preview_layout.py
|
||
|
||
不连库、不起服务(只用到 app 包本身与三个延迟导入的解析库),钉的是这些口径:
|
||
|
||
1. **产物位置算得准**:源位置 + 字节数一样就必须是同一个位置(换进程、换后端都一样),
|
||
字节数一变就是新位置;三种源写法(``minio://`` / ``local://` / 老绝对路径)都不炸。
|
||
2. **三条路各自判**:浏览器直出 / 后端读正文 / 按原版式转换。哪条通、为什么不通,
|
||
两句reason不能互相顶掉;两道体积闸各管各的(正文 50MB 那条不该拦住 60MB 的转换)。
|
||
3. **没装转换器等于什么都不能变**:探测失败要安静退回正文,一条错误都不许冒到用户脸上;
|
||
老格式与 rtf/odt 这类后端读不出正文的格式,此时退回"只能下载",但话要说全。
|
||
4. **转换只跑一次**:产物在后端上存在就不再调 soffice(重启之后也不重转历史附件)。
|
||
5. **统计要齐**:Word 说段数与表数、Excel 说工作表数与行列数、PPT 说页数、
|
||
文本说字符与行数;中文按字、英文按词分开给,别混成一个没人看得懂的数。
|
||
6. **统计说的是全文**:正文有上限,裁掉的那部分照样要算进统计,
|
||
否则"这份文档 2000 段"会被读成"这份文档只有 2000 段"。
|
||
7. **回收不误伤**:sweep 只动 preview/ 那一层,刚转出来的(没到最小年龄)不删。
|
||
8. **接口那层的报文形状**:mode / views / stats / 三条地址,前端照着画面板,
|
||
少一个键界面就少说一句人话。
|
||
|
||
跑法只依赖标准库 + 项目自身的 app 包(python-docx / openpyxl / python-pptx 都在
|
||
requirements 里)。真调 LibreOffice 那几项在机器上没装时会自动降级为"跳过",
|
||
跳过会打在结果里,不会悄悄算通过。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import io
|
||
import os
|
||
import pathlib
|
||
import re
|
||
import sys
|
||
import tempfile
|
||
|
||
HERE = pathlib.Path(__file__).resolve().parent
|
||
sys.path.insert(0, str(HERE.parent))
|
||
|
||
# 不连库:这一份全程用假配置 + 本地磁盘临时目录
|
||
os.environ.setdefault("OA_SCHEDULER", "off")
|
||
os.environ.setdefault("OA_AUTO_CREATE_SCHEMA", "false")
|
||
|
||
from app.service import attachment_preview as preview_api # noqa: E402
|
||
from app.storage import convert, preview # noqa: E402
|
||
from app.storage.base import StorageError, StorageUnreadableError # noqa: E402
|
||
from app.storage.local import LocalStore # noqa: E402
|
||
from app.storageconfig import LocalConfig # noqa: E402
|
||
|
||
FAILS: list[str] = []
|
||
SKIPPED: list[str] = []
|
||
|
||
|
||
def eq(name: str, got, want) -> None:
|
||
if got != want:
|
||
FAILS.append(f"{name}:期望 {want!r},实得 {got!r}")
|
||
|
||
|
||
def ok(name: str, condition, detail=None) -> None:
|
||
if not condition:
|
||
FAILS.append(f"{name}:{detail if detail is not None else '条件不成立'}")
|
||
|
||
|
||
def skip(name: str, why: str) -> None:
|
||
SKIPPED.append(f"{name}:{why}")
|
||
|
||
|
||
# ---------------------------------------------------------------- fixtures
|
||
def make_docx() -> bytes:
|
||
from docx import Document
|
||
from docx.shared import RGBColor
|
||
|
||
doc = Document()
|
||
doc.add_heading("差旅报销申请单", 0)
|
||
line = doc.add_paragraph("申请人:")
|
||
run = line.add_run("张三")
|
||
run.bold = True
|
||
run.font.color.rgb = RGBColor(0xC0, 0x00, 0x00)
|
||
doc.add_paragraph("同意,请注意发票抬头。").style = doc.styles["List Bullet"]
|
||
table = doc.add_table(rows=2, cols=2)
|
||
table.style = "Table Grid"
|
||
table.rows[0].cells[0].text = "项目"
|
||
table.rows[0].cells[1].text = "金额"
|
||
table.rows[1].cells[0].text = "高铁票"
|
||
table.rows[1].cells[1].text = "1254.00"
|
||
buf = io.BytesIO()
|
||
doc.save(buf)
|
||
return buf.getvalue()
|
||
|
||
|
||
def make_long_docx() -> bytes:
|
||
"""一份真有好几页的 Word:验"共 N 页"这一句数得准,不是恒等于 1。"""
|
||
from docx import Document
|
||
from docx.enum.text import WD_BREAK
|
||
|
||
doc = Document()
|
||
for page in range(6):
|
||
for line in range(8):
|
||
doc.add_paragraph(f"第 {page + 1} 页 第 {line + 1} 行 差旅报销明细说明若干字")
|
||
if page < 5:
|
||
doc.add_paragraph().add_run().add_break(WD_BREAK.PAGE)
|
||
buf = io.BytesIO()
|
||
doc.save(buf)
|
||
return buf.getvalue()
|
||
|
||
|
||
def _pdf_pages(store: LocalStore, location: str) -> int:
|
||
"""问 PDF 自己有几页(只认页面树上的 /Count),与 convert 里那份实现互为对照。"""
|
||
counts = [int(value) for value in re.findall(rb"/Count\s+(\d+)", store.read_bytes(location))]
|
||
return max(counts) if counts else 0
|
||
|
||
|
||
def make_xlsx() -> bytes:
|
||
from openpyxl import Workbook
|
||
|
||
wb = Workbook()
|
||
ws = wb.active
|
||
ws.title = "费用明细"
|
||
ws.append(["项目", "金额", "备注"])
|
||
ws.append(["打车", 38.5, "含高速"])
|
||
wb.create_sheet("汇总").append(["合计", 358.5])
|
||
buf = io.BytesIO()
|
||
wb.save(buf)
|
||
return buf.getvalue()
|
||
|
||
|
||
def make_pptx() -> bytes:
|
||
from pptx import Presentation
|
||
|
||
prs = Presentation()
|
||
for index in range(3):
|
||
slide = prs.slides.add_slide(prs.slide_layouts[1])
|
||
slide.shapes.title.text = f"第 {index + 1} 页标题"
|
||
buf = io.BytesIO()
|
||
prs.save(buf)
|
||
return buf.getvalue()
|
||
|
||
|
||
def temp_store() -> LocalStore:
|
||
root = pathlib.Path(tempfile.mkdtemp(prefix="unisoa-check-"))
|
||
return LocalStore(LocalConfig(root=str(root)), root=root)
|
||
|
||
|
||
class ForcedSettings:
|
||
"""临时改写这一层的配置(存库即生效那条路在这里不方便,直接顶掉取值函数)。"""
|
||
|
||
def __init__(self, **overrides) -> None:
|
||
self.overrides = overrides
|
||
self.original = convert.settings
|
||
|
||
def __enter__(self):
|
||
base = convert.settings()
|
||
merged = {
|
||
"mode": self.overrides.get("mode", base.mode),
|
||
"max_mb": self.overrides.get("max_mb", base.max_mb),
|
||
"binary": self.overrides.get("binary", base.binary),
|
||
"timeout_seconds": self.overrides.get("timeout_seconds", base.timeout_seconds),
|
||
"concurrency": self.overrides.get("concurrency", base.concurrency),
|
||
}
|
||
convert.settings = lambda: convert.ConvertSettings(**merged) # type: ignore[assignment]
|
||
return self
|
||
|
||
def __exit__(self, *_exc):
|
||
convert.settings = self.original # type: ignore[assignment]
|
||
return False
|
||
|
||
|
||
class ForcedConverter:
|
||
"""假装机器上装了 / 没装 LibreOffice。"""
|
||
|
||
def __init__(self, available: bool) -> None:
|
||
self.available = available
|
||
self.original = convert.available
|
||
|
||
def __enter__(self):
|
||
convert.available = lambda: self.available # type: ignore[assignment]
|
||
return self
|
||
|
||
def __exit__(self, *_exc):
|
||
convert.available = self.original # type: ignore[assignment]
|
||
return False
|
||
|
||
|
||
def main() -> int: # noqa: C901 - 一份脚本按编号一路验到底,拆开会打断叙述
|
||
MB = 1024 * 1024
|
||
|
||
# 1 ---------------------------------------------------------------- 产物位置
|
||
uri = "minio://bucket/prefix/attachment/202611/deadbeef.docx"
|
||
first = convert.artifact_relative(uri, "minio", 1000)
|
||
eq("同一个源同一个大小算出同一个位置(换进程也一样)", first, convert.artifact_relative(uri, "minio", 1000))
|
||
ok("位置落在 preview/<后端>/ 这个区里", first.startswith("preview/minio/"), first)
|
||
ok("后缀一定是 pdf", first.endswith(".pdf"), first)
|
||
ok("字节数变了就是另一个位置", first != convert.artifact_relative(uri, "minio", 1001), first)
|
||
ok("源位置变了就是另一个位置", first != convert.artifact_relative(uri.replace("deadbeef", "cafebeef"), "minio", 1000))
|
||
for weird in ("local://attachment/中文.docx", "/abs/path/老数据.xlsx", "", "minio://b/k"):
|
||
try:
|
||
built = convert.artifact_relative(weird, "local", 12)
|
||
ok(f"奇怪的源写法也算得出位置:{weird!r}", built.startswith("preview/local/") and built.endswith(".pdf"), built)
|
||
except Exception as exc: # noqa: BLE001
|
||
FAILS.append(f"源写法 {weird!r} 算位置炸了:{exc!r}")
|
||
eq("键名里不带中文(对象存储与命令行都省事)", any(ch.isascii() and ch.isalpha() for ch in first), True)
|
||
ok("认得出这是派生文件", convert.is_artifact_key("pfx/preview/minio/a-1.pdf", "minio"))
|
||
ok("业务字节不会被误认成派生文件", not convert.is_artifact_key("pfx/attachment/a-1.docx", "minio"))
|
||
|
||
# 2 ---------------------------------------------------------------- 三条路各自判
|
||
with ForcedConverter(True), ForcedSettings(mode="auto", max_mb=100):
|
||
docx = preview.describe("差旅.docx", 40 * MB)
|
||
ok("docx 两条路都通", docx.text and docx.layout, docx.as_dict())
|
||
eq("正文那条路的渲染器还是 document(切换开关靠它画)", docx.renderer, preview.RENDER_DOCUMENT)
|
||
old_doc = preview.describe("红头文件.doc", 1024)
|
||
ok(".doc 只能按原版式看", old_doc.layout and not old_doc.text, old_doc.as_dict())
|
||
ok(".doc 依然给预览入口(装了转换器就该能看)", old_doc.previewable, True)
|
||
rtf = preview.describe("旧报告.rtf", 1024)
|
||
ok(".rtf 归到 word 这一类(图标与文案认得它)", rtf.kind, preview.KIND_WORD)
|
||
ok(".rtf 只能靠转换器", rtf.layout and not rtf.text, rtf.as_dict())
|
||
vsd = preview.describe("流程图.vsd", 1024)
|
||
ok(".vsd 归 visio 这一类", vsd.kind, preview.KIND_VISIO)
|
||
eq("pdf 是浏览器直出,不需要转换器,也不需要正文", preview.describe("a.pdf", 1024).renderer, preview.RENDER_PDF)
|
||
eq("pdf 那句 reason 不该被「没有转换器」污染", preview.describe("a.pdf", 1024).as_dict()["reason"], "")
|
||
eq("压缩包还是看不了", preview.describe("a.zip", 1024).previewable, False)
|
||
ok("压缩包说的是人话", "下载" in preview.describe("a.zip", 1024).reason)
|
||
# 两道闸各管各的:正文 50MB、转换 100MB
|
||
big = preview.describe("大簿子.docx", 60 * MB)
|
||
ok("60MB 的 docx:正文那条路被闸住了", not big.text, big.as_dict())
|
||
ok("60MB 的 docx:版式那条路照走(它自己的上限是 100MB)", big.layout, big.as_dict())
|
||
ok("60MB 的 docx 照样能预览", big.previewable, True)
|
||
huge = preview.describe("超大.pptx", 300 * MB)
|
||
ok("300MB:两条路都不通", not huge.text and not huge.layout, huge.as_dict())
|
||
ok("300MB:说清看不了", not huge.previewable)
|
||
ok("超限那句话优先念体积(比「这是旧格式」有用)", "300MB" in huge.reason or "50MB" in huge.reason, huge.reason)
|
||
|
||
# 没装转换器
|
||
with ForcedConverter(False), ForcedSettings(mode="auto"):
|
||
gone = preview.describe("差旅.docx", 1024)
|
||
ok("没装转换器:新版格式退回正文预览,用户无感", gone.text and not gone.layout and gone.previewable, gone.as_dict())
|
||
gone_doc = preview.describe("红头文件.doc", 1024)
|
||
ok("没装转换器:老格式只能下载", not gone_doc.previewable, gone_doc.as_dict())
|
||
ok("那句话把两件事都说到了(旧格式 + 装转换器可看)", "LibreOffice" in gone_doc.reason, gone_doc.reason)
|
||
eq("版式不通的原因写在 layout_reason", "LibreOffice" in gone_doc.layout_reason, True)
|
||
|
||
# 关掉这一层
|
||
with ForcedConverter(True), ForcedSettings(mode="off"):
|
||
off = preview.describe("差旅.docx", 1024)
|
||
ok("关掉之后不转换", not off.layout and off.text, off.as_dict())
|
||
eq("关掉的理由给界面看", off.layout_reason, "系统设置里关闭了按原版式在线阅览")
|
||
|
||
# 3 ---------------------------------------------------------------- 转换本身
|
||
store = temp_store()
|
||
docx_bytes = make_docx()
|
||
saved = store.save(purpose="attachment", name="差旅报销.docx", data=docx_bytes)
|
||
if not convert.available():
|
||
skip("真转换", "这台机器上没有 LibreOffice,下面三项只能验到退路,验不到版式")
|
||
else:
|
||
calls = {"n": 0}
|
||
original_run = convert._run_soffice
|
||
|
||
def counted(*args, **kwargs):
|
||
calls["n"] += 1
|
||
return original_run(*args, **kwargs)
|
||
|
||
convert._run_soffice = counted # type: ignore[assignment]
|
||
try:
|
||
location, size, pages = convert.convert(store, saved.uri, "差旅报销.docx", saved.size)
|
||
eq("真调了一次 soffice", calls["n"], 1)
|
||
ok("产物是个 PDF", store.read_bytes(location)[:4] == b"%PDF", store.read_bytes(location)[:8])
|
||
ok("转出来的 PDF 有体积", size > 1000, size)
|
||
ok("页数数出来了", pages >= 1, pages)
|
||
ok("产物落在 preview 区", convert.is_artifact_key(store.key(location), "local"), True)
|
||
eq("原件一个字节没动", store.size(saved.uri), len(docx_bytes))
|
||
|
||
# 进程内缓存:第二次不再调 soffice
|
||
convert.convert(store, saved.uri, "差旅报销.docx", saved.size)
|
||
eq("第二次点开直接吃缓存", calls["n"], 1)
|
||
|
||
# 后端上已经有了:换个进程(丢掉缓存)也不重转
|
||
convert.forget(saved.uri)
|
||
convert._artifacts.clear() # type: ignore[attr-defined]
|
||
again_location, again_size, _ = convert.convert(store, saved.uri, "差旅报销.docx", saved.size)
|
||
eq("缓存丢了但后端上有:不重转,位置同一个", calls["n"], 1)
|
||
eq("回的是同一个位置", again_location, location)
|
||
eq("体积对得上", again_size, size)
|
||
|
||
# 源换了(位置与字节数都变了)就是另一个产物,两份互不牵连
|
||
other = store.save(purpose="attachment", name="另一份.docx", data=make_docx())
|
||
other_location, _, _ = convert.convert(store, other.uri, "另一份.docx", other.size)
|
||
ok("同一目录下的不同源各留各的产物", other_location != location, other_location)
|
||
ok("两份产物都在", store.exists(location) and store.exists(other_location))
|
||
|
||
# Excel / PPT / 老格式 .doc 也转得动
|
||
xlsx_saved = store.save(purpose="attachment", name="费用.xlsx", data=make_xlsx())
|
||
xlsx_pdf, _, _ = convert.convert(store, xlsx_saved.uri, "费用.xlsx", xlsx_saved.size)
|
||
ok("Excel 转出 PDF", store.read_bytes(xlsx_pdf)[:4] == b"%PDF")
|
||
ppt_saved = store.save(purpose="attachment", name="汇报.pptx", data=make_pptx())
|
||
ppt_pdf, _, ppt_pages = convert.convert(store, ppt_saved.uri, "汇报.pptx", ppt_saved.size)
|
||
ok("PPT 转出 PDF", store.read_bytes(ppt_pdf)[:4] == b"%PDF")
|
||
ok("PPT 页数转得出来", ppt_pages >= 3, ppt_pages)
|
||
# 页数要说得准:面板上"共 N 页"这一句就是从这儿来的,少报几页等于骗人
|
||
long_saved = store.save(purpose="attachment", name="长文档.docx", data=make_long_docx())
|
||
long_location, long_size, long_pages = convert.convert(
|
||
store, long_saved.uri, "长文档.docx", long_saved.size
|
||
)
|
||
ok("多页文档的页数数得出来(不是恒等于 1)", long_pages >= 6, long_pages)
|
||
eq("数出来的页数与 PDF 自己写的对得上", long_pages, _pdf_pages(store, long_location))
|
||
ok("阅览版本身有体积", long_size > 0, long_size)
|
||
|
||
# 回收:只动 preview 区,且不动刚转出来的
|
||
report = convert.sweep(store, set())
|
||
eq("刚转出来的(没到最小年龄)不删", report["removed"], 0)
|
||
ok("确实数到了这些产物", report["listed"] >= 3, report)
|
||
kept = store.exists(location)
|
||
ok("原件还在", kept)
|
||
report_old = convert.sweep(store, set(), min_age_minutes=0)
|
||
ok("过了最小年龄才收", report_old["removed"] >= 3, report_old)
|
||
ok("收掉的正是 preview 区那几份", not store.exists(location), store.key(location))
|
||
ok("业务字节一个没动", store.exists(saved.uri), True)
|
||
ok("回收的字节数报得出来", report_old["freed"] > 0, report_old)
|
||
finally:
|
||
convert._run_soffice = original_run # type: ignore[assignment]
|
||
|
||
# 4 ---------------------------------------------------------------- 统计齐不齐
|
||
doc_stats = preview._render_docx(docx_bytes, "差旅.docx")["stats"]
|
||
eq("Word 报了段数", doc_stats["paragraphs"] >= 3, True)
|
||
eq("Word 报了表数", doc_stats["tables"], 1)
|
||
ok("Word 报了中文字数", doc_stats["cjk_characters"] > 0, doc_stats)
|
||
ok("中文按字数、英文按词数分开给", set(doc_stats) >= {"words", "cjk_characters", "characters"}, doc_stats)
|
||
|
||
book_stats = preview._render_workbook(make_xlsx(), "费用.xlsx")["stats"]
|
||
eq("Excel 报了工作表数", book_stats["sheets"], 2)
|
||
eq("Excel 报了行数(两个表加总:明细 2 行 + 汇总 1 行)", book_stats["rows"], 3)
|
||
eq("Excel 报了列数(取最宽那一个表)", book_stats["columns"], 3)
|
||
|
||
deck = preview._render_pptx(make_pptx(), "汇报.pptx")
|
||
eq("PPT 报了页数", deck["stats"]["slides"], 3)
|
||
eq("页数同时挂在 pages 上(面板那一句共用)", deck["stats"]["pages"], 3)
|
||
ok("PPT 把每页标题读出来了", deck["slides"][0]["title"].startswith("第"), deck["slides"][0])
|
||
|
||
csv_out = preview._render_csv("项目,金额\n打车,38.5\n住宿,320\n".encode("utf-8"), "明细.csv", "csv")
|
||
eq("CSV 报了行数", csv_out["stats"]["rows"], 3)
|
||
eq("CSV 报了列数", csv_out["stats"]["columns"], 2)
|
||
eq("GBK 的 CSV 照样解得开(回归:审批附件里全是这种)", preview.decode_text("姓名,备注\n张三,测试\n".encode("gb18030"))[1], "gb18030")
|
||
|
||
text_out = preview.render_bytes(b"first line\nsecond line\n", "note.txt")
|
||
eq("文本报了行数", text_out["stats"]["lines"], 3)
|
||
ok("文本报了字符数", text_out["stats"]["characters"] > 0, text_out["stats"])
|
||
|
||
# 统计说全文,不说"这里画了几行"
|
||
wide = [[f"r{index}", f"c{index}"] for index in range(preview.MAX_TABLE_ROWS + 300)]
|
||
clipped = preview._render_workbook(_one_sheet_book(wide), "长表.xlsx")
|
||
eq("被上限裁掉的行仍然算进统计", clipped["stats"]["rows"], len(wide))
|
||
ok("裁掉这件事本身标了出来", clipped["truncated"], True)
|
||
eq("画出来的行数是上限那一个", len(clipped["sheets"][0]["rows"]), preview.MAX_TABLE_ROWS)
|
||
|
||
# 5 ---------------------------------------------------------------- 读不了怎么分
|
||
for label, name, payload, want in (
|
||
("改了后缀的纯文本当 docx", "假word.docx", b"this is not a docx at all", StorageUnreadableError),
|
||
("空文件当 xlsx", "空表.xlsx", b"", StorageUnreadableError),
|
||
):
|
||
try:
|
||
preview.render_bytes(payload, name)
|
||
FAILS.append(f"{label}:本该报错,却当正常返回了")
|
||
except StorageError as exc:
|
||
ok(f"{label}:报的是「文件读不了」这一类", isinstance(exc, want), type(exc).__name__)
|
||
ok(f"{label}:那句话是给人看的", "下载" in str(exc), str(exc))
|
||
|
||
# 6 ---------------------------------------------------------------- 报文形状
|
||
with ForcedConverter(True), ForcedSettings(mode="auto"):
|
||
store2 = temp_store()
|
||
one = store2.save(purpose="attachment", name="单据.docx", data=docx_bytes)
|
||
original_resolve = preview_api.resolve_uri
|
||
preview_api.resolve_uri = lambda uri: store2 # type: ignore[assignment]
|
||
try:
|
||
auto = preview_api.payload("attachment", "A1", "单据.docx", one.size, one.uri, "auto")
|
||
eq("能转就默认给原版式", auto["mode"], "layout")
|
||
eq("原版式那一路的渲染器是 pdf", auto["renderer"], "pdf")
|
||
ok("给了取字节的地址", auto["url"].endswith("/attachment/A1/preview.pdf"), auto["url"])
|
||
eq("报上写了阅览版有多大", auto["converted_length"] > 0, True)
|
||
eq("报了页数", auto["stats"]["pages"] >= 1, True)
|
||
eq("两条路都通向界面交代清楚", (auto["views"]["layout"], auto["views"]["text"]), (True, True))
|
||
eq("实际给的是哪一条", auto["views"]["offered"], "layout")
|
||
|
||
forced_text = preview_api.payload("attachment", "A1", "单据.docx", one.size, one.uri, "text")
|
||
eq("强制正文给 payload", forced_text["mode"], "payload")
|
||
ok("正文那一路带统计", forced_text["stats"]["paragraphs"] >= 1, forced_text["stats"])
|
||
eq("切换信息还在(界面能切回去)", forced_text["views"]["offered"], "payload")
|
||
|
||
pdf_item = preview_api.payload("attachment", "A2", "扫描件.pdf", 5000, one.uri, "auto")
|
||
eq("浏览器直出那一路还是 inline", pdf_item["mode"], "inline")
|
||
ok("inline 给的是下载地址", pdf_item["url"].endswith("/download?inline=1"), pdf_item["url"])
|
||
|
||
# 转换失败但还有正文这条路:退回去,不当故障报。
|
||
# 这里直接顶掉 convert.convert 来验这条**策略**——真拿一个坏文件去验不靠谱:
|
||
# LibreOffice 对坏文件的容忍度忽高忽低,同一个文件今天转得出、明天可能就转不出,
|
||
# 那种抖法会把"策略对不对"糊成"这台机器的 soffice 今天心情如何"
|
||
original_convert = preview_api.convert.convert
|
||
preview_api.convert.convert = ( # type: ignore[assignment]
|
||
lambda *args, **kwargs: (_ for _ in ()).throw(StorageError("探针:转换就是不成"))
|
||
)
|
||
try:
|
||
fallback = preview_api.payload("attachment", "A3", "单据.docx", one.size, one.uri, "layout")
|
||
finally:
|
||
preview_api.convert.convert = original_convert # type: ignore[assignment]
|
||
eq("转换没成而正文可走:退回 payload", fallback["mode"], "payload")
|
||
ok("同时告诉用户为什么不是原版式", bool(fallback.get("layout_fallback")), fallback)
|
||
ok("退回之后正文照样有内容", fallback["renderer"], "document")
|
||
eq("切换信息里把这条路收掉了(别让用户一直点回来)", fallback["views"]["layout"], False)
|
||
|
||
# 两条路都不通才真报错:转换失败 + 后端也读不出正文
|
||
broken = store2.save(purpose="attachment", name="坏单据.doc", data="坏了".encode("utf-8") * 40)
|
||
original_convert = preview_api.convert.convert
|
||
preview_api.convert.convert = ( # type: ignore[assignment]
|
||
lambda *args, **kwargs: (_ for _ in ()).throw(StorageUnreadableError("探针:打不开"))
|
||
)
|
||
try:
|
||
try:
|
||
preview_api.payload("attachment", "A4", "坏单据.doc", broken.size, broken.uri, "layout")
|
||
FAILS.append("两条路都不通本该报错")
|
||
except Exception as exc: # noqa: BLE001
|
||
eq("报错带着文件读不了这个 reason", getattr(exc, "reason", ""), "STORAGE_UNREADABLE")
|
||
finally:
|
||
preview_api.convert.convert = original_convert # type: ignore[assignment]
|
||
|
||
# 没有正文这条路的东西,强制要正文就得说清楚
|
||
try:
|
||
preview_api.payload("attachment", "A9", "x.rtf", 10, one.uri, "text")
|
||
FAILS.append("rtf 强制走正文本该报读不出正文")
|
||
except Exception as exc: # noqa: BLE001
|
||
eq("rtf 没有正文这条路,报错带着 reason", getattr(exc, "reason", ""), "PREVIEW_UNSUPPORTED")
|
||
# 没装转换器:能看正文的东西仍可看,但强制要原版式就得说清是这一条路不通
|
||
with ForcedConverter(False):
|
||
try:
|
||
preview_api.payload("attachment", "A5", "单据.docx", one.size, one.uri, "layout")
|
||
FAILS.append("没装转换器时强制原版式本该报错")
|
||
except Exception as exc: # noqa: BLE001
|
||
eq("报错说的是「这一条路不通」而不是「看不了」",
|
||
getattr(exc, "reason", ""), "PREVIEW_LAYOUT_UNAVAILABLE")
|
||
# rtf 三条路全不通(没正文解析器 + 没转换器),那是"看不了",不是"换一副面孔"
|
||
try:
|
||
preview_api.payload("attachment", "A6", "x.rtf", 10, one.uri, "auto")
|
||
FAILS.append("rtf 三条路都不通本该报错")
|
||
except Exception as exc: # noqa: BLE001
|
||
eq("rtf 这时报的是不支持预览", getattr(exc, "reason", ""), "PREVIEW_UNSUPPORTED")
|
||
ok("那句 reason 告诉人装什么能看", "LibreOffice" in str(exc), str(exc))
|
||
|
||
# 序列化给前端的三条地址
|
||
described = preview_api.describe("attachment", "A1", "单据.docx", one.size)
|
||
eq("列表里也带三条地址", described["pdf_url"], "/api/v1/attachment/A1/preview.pdf")
|
||
eq("资讯附件是另一条路由", preview_api.describe("cms", "C1", "a.docx", 10)["pdf_url"], "/api/v1/cms/attachments/C1/preview.pdf")
|
||
eq("网盘又是另一条", preview_api.describe("file", "F1", "a.docx", 10)["pdf_url"], "/api/v1/files/F1/preview.pdf")
|
||
finally:
|
||
preview_api.resolve_uri = original_resolve # type: ignore[assignment]
|
||
|
||
# 7 ---------------------------------------------------------------- 历史快照跟着今天重算
|
||
snapshot = [{"id": "X1", "name": "去年的单据.doc", "extension": "doc", "length": 1024, "is_image": False}]
|
||
with ForcedConverter(True):
|
||
refreshed = preview_api.refresh_refs(snapshot)
|
||
eq("老快照里的 .doc 今天能按原版式看", refreshed[0]["preview"]["layout"], True)
|
||
eq("重算不丢原来的字段", refreshed[0]["name"], "去年的单据.doc")
|
||
with ForcedConverter(False):
|
||
eq("撤了转换器,老快照也退回只能下载", preview_api.refresh_refs(snapshot)[0]["preview"]["previewable"], False)
|
||
eq("不是字典的脏数据不会炸", preview_api.refresh_refs([None, {"id": "Y"}, "垃圾"]), [{"id": "Y", "preview": preview_api.describe("attachment", "Y", "", 0)}])
|
||
|
||
# 8 ---------------------------------------------------------------- 前端那张表跟后端同源
|
||
front = pathlib.Path(HERE).parent.parent / "frontend" / "src" / "utils" / "preview.ts"
|
||
if front.exists():
|
||
text = front.read_text(encoding="utf-8")
|
||
block = text[text.index("LAYOUT_EXTENSIONS") : text.index("])", text.index("LAYOUT_EXTENSIONS"))]
|
||
for extension in convert.CONVERTIBLE:
|
||
ok(f"前端兜底表里有 .{extension}(与后端 CONVERTIBLE 同源)", f"'{extension}'" in block, False)
|
||
else:
|
||
skip("前端兜底表对账", "找不到 frontend/src/utils/preview.ts")
|
||
|
||
for name in SKIPPED:
|
||
print(f"[SKIP] {name}")
|
||
if FAILS:
|
||
for line in FAILS:
|
||
print(f"[FAIL] {line}")
|
||
print(f"共 {len(FAILS)} 条不对")
|
||
return 1
|
||
print("通过:三条路各自判得清、版式转换只跑一次、统计报全文、报文形状齐")
|
||
return 0
|
||
|
||
|
||
def _one_sheet_book(rows: list[list[str]]) -> bytes:
|
||
from openpyxl import Workbook
|
||
|
||
wb = Workbook()
|
||
ws = wb.active
|
||
for row in rows:
|
||
ws.append(row)
|
||
buf = io.BytesIO()
|
||
wb.save(buf)
|
||
return buf.getvalue()
|
||
|
||
|
||
if __name__ == "__main__":
|
||
raise SystemExit(main())
|