From 5f2e089012748fcf11777ad1b1b86b2119938530 Mon Sep 17 00:00:00 2001 From: stone16 <12712299+stone16@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:38:58 +0800 Subject: [PATCH 1/2] docs(testing): add L1/L2/L3 local testing guide and synthetic E2E smoke script --- README.md | 110 +++++++++ scripts/smoke_local_e2e.py | 494 +++++++++++++++++++++++++++++++++++++ 2 files changed, 604 insertions(+) create mode 100755 scripts/smoke_local_e2e.py diff --git a/README.md b/README.md index 03b4275..243b70d 100644 --- a/README.md +++ b/README.md @@ -459,6 +459,116 @@ invoice_manager/ --- +## 🧪 本地测试与端到端试跑 | Testing & Local E2E + +仓库测试分为 **L1 / L2 / L3** 三层,全部使用 **100% 合成占位发票数据**,不依赖任何真实发票或第三方 LLM API Key。 + +### 当前已可测范围 + +- **已覆盖**:`packages/invoice-core` 纯 Python 内核单测(L1)、`backend` 配置/路由/兼容层单测(L2)、以及单张合成电子发票的本地脚本与 Docker 全链路 HTTP 闭环(健康检查 → 上传 → 解析 → 查询 → CSV/Excel 导出,L3)。 +- **后续补齐**:`invoice-cli` 整文件夹批量查重、报销单生成与 A4 拼版测试将在后续里程碑补齐。 + +--- + +### L1:纯 Python 内核单测(零 Docker / 零 DB / 零 PaddleOCR) + +仅需 Python 3.10+,在仓库外创建干净虚拟环境即可验证 `packages/invoice-core`: + +```bash +python3 -m venv /tmp/im-l1-venv +/tmp/im-l1-venv/bin/pip install -e ./packages/invoice-core pytest +/tmp/im-l1-venv/bin/pytest packages/invoice-core/tests -v +``` + +预期输出摘要:`28 passed`(包含字段提取快照、LLM JSON 归一化、OCR/LLM 对账、PDF 文字层提取、PDFium 8 线程并发渲染,以及 AST/运行时重依赖守卫)。 + +--- + +### L2:后端单测与兼容层验证 + +#### 方式一:Docker 容器运行(推荐,与 GitHub Actions CI 一致) + +无需在宿主机安装 `paddlepaddle`,跨 macOS / Linux / Windows 均可一键复现: + +```bash +docker build --target backend -t invoice-manager:local-test . +docker run --rm invoice-manager:local-test python -m pytest -v +``` + +预期输出摘要:`29 passed`(覆盖配置持久化与安全边界、SPA 路由、`/api/health` 503 降级、LLM 响应解析及 `backend` 对 `invoice_core` 的兼容重导出)。如需在同一镜像内复验内核单测,可追加: + +```bash +docker run --rm invoice-manager:local-test python -m pytest /packages/invoice-core/tests -v +``` + +#### 方式二:本机 venv 直跑(备选) + +若本机已使用 Python 3.11 并安装完 `backend/requirements.txt` 与 `-e ./packages/invoice-core`,可直接执行: + +```bash +cd backend && pytest tests -v +``` + +--- + +### L3:全合成假发票端到端试跑 + +#### L3(a) 纯 Python 一行命令试跑(零 Docker) + +复用 L1 干净虚拟环境,运行内置合成发票脚本 [`scripts/smoke_local_e2e.py`](scripts/smoke_local_e2e.py): + +```bash +/tmp/im-l1-venv/bin/python scripts/smoke_local_e2e.py +``` + +脚本会在内存中生成一份带 ToUnicode 文字层与矢量边框的合成中文数电发票 PDF(全部采用一眼可辨识的占位值,不含真实税号、发票号或抬头),自动校验文字层提取、`FieldExtractor` 全字段解析与 `render_pdf_pages` 首页 PNG 渲染。预期输出摘要: + +```text +[L3-core] PASS | pdf=3260B | text=266 chars | render=1190x1684 PNG (68215B) +[L3-core] fields | invoice_number=00000000000000000001 | issue_date=2025-11-05 | buyer=示例买方科技有限公司 | seller=示例卖方服务有限公司 | amount=1000.00 | tax=60.00 | total=1060.00 +``` + +如需将合成 PDF 或渲染 PNG 落盘检查,可附加 `--output-pdf /tmp/sample-invoice.pdf --output-png /tmp/sample-page1.png`。 + +#### L3(b) 本地 Docker 全链路 HTTP 闭环 + +使用独立 Compose 项目名启动 `db` 与 `backend`,向真实服务跑通「健康检查 → 上传合成 PDF → 轮询解析结果 → 列表/详情查询 → CSV & Excel 导出 → 自动清理记录」: + +```bash +# 1. 启动后端与 PostgreSQL(独立项目名与独立数据卷) +docker compose -p invoice-e2e-smoke up -d --build backend + +# 2. 等待健康检查返回 200 +curl -fsS http://127.0.0.1:18080/api/health + +# 3. 跑通 HTTP 端到端闭环(验证后自动删除测试记录;如需保留可加 --keep-record) +/tmp/im-l1-venv/bin/python scripts/smoke_local_e2e.py --api-url http://127.0.0.1:18080 + +# 4. 清理测试容器、临时卷与临时 venv +docker compose -p invoice-e2e-smoke down -v +rm -rf /tmp/im-l1-venv +``` + +预期输出摘要: + +```text +{"status":"ok","database":"healthy","service":"发票管理系统"} +[L3-core] PASS | pdf=3260B | text=266 chars | render=1190x1684 PNG (68215B) +[L3-core] fields | invoice_number=00000000000000000001 | issue_date=2025-11-05 | buyer=示例买方科技有限公司 | seller=示例卖方服务有限公司 | amount=1000.00 | tax=60.00 | total=1060.00 +[L3-api ] PASS | url=http://127.0.0.1:18080 | id=1 | status=已确认 | list_total=1 | csv=460B | excel=5538B | cleaned_up=True +``` + +--- + +### 排障提示 + +- **Python 版本与 venv 隔离**:L1 支持 Python 3.10+,建议始终在仓库外临时目录(如 `/tmp/im-l1-venv`)建虚拟环境;L2 因 `backend/requirements.txt` 锁定了 `paddlepaddle==2.6.2`(macOS ARM64 / Python 3.12+ 宿主机通常无对应 wheel),建议优先使用 Docker 容器方式运行。 +- **首次启动等待健康检查**:PostgreSQL 初始化与 `uvicorn` 建表需要数秒;若启动后立刻 `curl /api/health` 出现空响应或连接拒绝,等待 3–10 秒重试或运行 `docker compose -p invoice-e2e-smoke ps` 确认状态为 `healthy`。 +- **端口或容器名冲突**:`docker-compose.yml` 默认占用 `5435`(DB)、`18080`(Backend)、`15173`(Frontend)并带有固定 `container_name`。如宿主机端口已被占用,可创建临时 override 文件重置 `container_name` 并映射空闲端口(例如 `127.0.0.1:18180:18080`),再通过 `docker compose -p invoice-e2e-smoke -f docker-compose.yml -f /tmp/override.yml up -d --build backend` 启动,并对应调整 `--api-url`。 +- **纯文字层 PDF 与 OCR 模式差异**:`smoke_local_e2e.py` 生成的合成数电 PDF 带完整文字层,后端会直接通过 `pdfplumber` 快速解析,**不会触发 PaddleOCR 模型下载,也无需配置 LLM Key**;若测试扫描件 PDF 或 JPG/PNG 图片,首次会下载 PaddleOCR 中文模型并走图像识别路径(详见 [`deploy/README.md`](deploy/README.md))。 + +--- + ## 🤝 参与贡献 | Contributing 我们欢迎所有形式的贡献!无论是: diff --git a/scripts/smoke_local_e2e.py b/scripts/smoke_local_e2e.py new file mode 100755 index 0000000..c7e7f19 --- /dev/null +++ b/scripts/smoke_local_e2e.py @@ -0,0 +1,494 @@ +#!/usr/bin/env python3 +"""Minimal reproducible local E2E smoke test using a 100% synthetic Chinese e-invoice PDF. + +Runs with zero extra heavy dependencies beyond ``invoice-core`` (and Python stdlib): +1. Generates an in-memory synthetic PDF with an embedded ToUnicode text layer and vector frame. +2. Verifies ``extract_pdf_text_layer``, ``FieldExtractor``, and ``render_pdf_pages`` (first-page PNG). +3. Optionally runs an HTTP E2E loop against a running backend/app server (``--api-url``): + health check -> upload -> poll parsed detail -> list -> CSV & Excel export -> cleanup. +""" + +from __future__ import annotations + +import argparse +from decimal import Decimal +from io import BytesIO +import json +from pathlib import Path +import sys +import time +from typing import Any +from urllib.error import HTTPError, URLError +from urllib.parse import urlparse +from urllib.request import OpenerDirector, ProxyHandler, Request, build_opener +import uuid + +try: + from invoice_core.extract import FieldExtractor + from invoice_core.parsers.pdf_text import extract_pdf_text_layer, render_pdf_pages +except ModuleNotFoundError as exc: + raise SystemExit( + "Missing dependency 'invoice_core'. Install it first, e.g.:\n" + " pip install -e ./packages/invoice-core" + ) from exc + + +# Obviously synthetic placeholder values (zero real PII / real invoice numbers / real tax IDs). +SYNTH_INVOICE_NUMBER = "0" * 16 + "0001" +SYNTH_INVOICE_CODE = "012345678901" +SYNTH_ISSUE_DATE_CN = "2025年11月05日" +SYNTH_BUYER_NAME = "示例买方科技有限公司" +SYNTH_BUYER_TAX_ID = "TESTBUYER000000001" +SYNTH_SELLER_NAME = "示例卖方服务有限公司" +SYNTH_SELLER_TAX_ID = "TESTSELLER00000001" +SYNTH_ITEM_LINE = "*信息技术服务*云主机租用费" + +EXPECTED_CORE_FIELDS: dict[str, str] = { + "invoice_number": SYNTH_INVOICE_NUMBER, + "invoice_code": SYNTH_INVOICE_CODE, + "issue_date": "2025-11-05", + "buyer_name": SYNTH_BUYER_NAME, + "buyer_tax_id": SYNTH_BUYER_TAX_ID, + "seller_name": SYNTH_SELLER_NAME, + "seller_tax_id": SYNTH_SELLER_TAX_ID, + "item_name": "信息技术服务*云主机租用费", + "amount": "1000.00", + "tax_rate": "6%", + "tax_amount": "60.00", + "total_with_tax": "1060.00", +} + +NUMERIC_FIELD_NAMES = frozenset({"amount", "tax_amount", "total_with_tax"}) +IN_PROGRESS_STATUSES = frozenset({"已上传", "解析中"}) +CONFIRMED_STATUS = "已确认" + + +def build_synthetic_invoice_lines() -> list[str]: + """Return synthetic Chinese e-invoice lines for deterministic extraction.""" + return [ + "电子发票(普通发票)", + f"发票代码:{SYNTH_INVOICE_CODE}", + f"发票号码:{SYNTH_INVOICE_NUMBER}", + f"开票日期:{SYNTH_ISSUE_DATE_CN}", + "购买方信息", + f"名称:{SYNTH_BUYER_NAME}", + f"统一社会信用代码/纳税人识别号:{SYNTH_BUYER_TAX_ID}", + SYNTH_ITEM_LINE, + "税率:6%", + "合计 ¥1,000.00 ¥60.00", + "价税合计(小写)¥1,060.00", + "销售方信息", + f"名称:{SYNTH_SELLER_NAME}", + f"统一社会信用代码/纳税人识别号:{SYNTH_SELLER_TAX_ID}", + "备注:本地测试用全合成发票样本,不含任何真实信息。", + ] + + +def build_synthetic_invoice_pdf(lines: list[str] | None = None) -> bytes: + """Build a minimal valid single-page PDF with ToUnicode text layer and vector frame.""" + page_lines = lines if lines is not None else build_synthetic_invoice_lines() + + unique_chars: list[str] = [] + char_to_byte: dict[str, int] = {} + for line in page_lines: + for ch in line: + if ch not in char_to_byte: + code = len(unique_chars) + 1 + if code >= 255: + raise ValueError("Synthetic PDF text exceeds single-byte ToUnicode CMap limit (254 unique chars)") + char_to_byte[ch] = code + unique_chars.append(ch) + + bfchar_lines = [f"<{char_to_byte[ch]:02X}> <{ord(ch):04X}>" for ch in unique_chars] + cmap = ( + "/CIDInit /ProcSet findresource begin\n" + "12 dict begin\n" + "begincmap\n" + "/CIDSystemInfo << /Registry (Demo) /Ordering (UCS) /Supplement 0 >> def\n" + "/CMapName /Demo-UCS def\n" + "/CMapType 2 def\n" + "1 begincodespacerange\n" + "<01> \n" + "endcodespacerange\n" + f"{len(bfchar_lines)} beginbfchar\n" + + "\n".join(bfchar_lines) + + "\nendbfchar\n" + "endcmap\n" + "CMapName currentdict /CMap defineresource pop\n" + "end\n" + "end\n" + ).encode("ascii") + + # Simple vector layout (header accent bar + outer border + dividers) so rendered PNG is non-blank. + content_ops: list[str] = [ + "0.89 0.14 0.07 rg 36 782 523 24 re f", + "0.2 0.2 0.2 RG 1 w 36 420 523 362 re S", + "0.75 0.75 0.75 RG 0.75 w 36 690 m 559 690 l S", + "0.75 0.75 0.75 RG 0.75 w 36 590 m 559 590 l S", + "0.75 0.75 0.75 RG 0.75 w 36 500 m 559 500 l S", + "0 0 0 rg", + "BT", + "/F1 12 Tf", + ] + y = 760 + for line in page_lines: + hex_str = "".join(f"{char_to_byte[ch]:02X}" for ch in line) + content_ops.append(f"1 0 0 1 50 {y} Tm <{hex_str}> Tj") + y -= 20 + content_ops.append("ET") + content_stream = ("\n".join(content_ops) + "\n").encode("ascii") + + objects: list[bytes] = [ + b"<< /Type /Catalog /Pages 2 0 R >>", + b"<< /Type /Pages /Kids [5 0 R] /Count 1 >>", + b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /ToUnicode 4 0 R >>", + b"<< /Length " + str(len(cmap)).encode("ascii") + b" >>\nstream\n" + cmap + b"endstream", + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] " + b"/Resources << /Font << /F1 3 0 R >> >> /Contents 6 0 R >>", + b"<< /Length " + str(len(content_stream)).encode("ascii") + b" >>\nstream\n" + content_stream + b"endstream", + ] + + buf = BytesIO() + buf.write(b"%PDF-1.4\n") + offsets = [0] + for obj_num, obj in enumerate(objects, start=1): + offsets.append(buf.tell()) + buf.write(f"{obj_num} 0 obj\n".encode("ascii")) + buf.write(obj) + buf.write(b"\nendobj\n") + + xref_pos = buf.tell() + buf.write(f"xref\n0 {len(objects) + 1}\n".encode("ascii")) + buf.write(b"0000000000 65535 f \n") + for off in offsets[1:]: + buf.write(f"{off:010d} 00000 n \n".encode("ascii")) + buf.write( + f"trailer\n<< /Size {len(objects) + 1} /Root 1 0 R >>\nstartxref\n{xref_pos}\n%%EOF\n".encode("ascii") + ) + return buf.getvalue() + + +def run_core_smoke( + pdf_bytes: bytes, + dpi: int = 144, + output_png: Path | None = None, +) -> dict[str, Any]: + """Run pure-Python invoice_core smoke assertions on synthetic PDF bytes.""" + raw_text, has_useful = extract_pdf_text_layer(pdf_bytes) + if not has_useful: + raise AssertionError( + f"Expected useful PDF text layer, got has_useful=False (len={len(raw_text)})" + ) + + extracted = FieldExtractor().extract_fields(raw_text) + mismatches: list[str] = [] + for key, expected in EXPECTED_CORE_FIELDS.items(): + actual = extracted.get(key) + if actual != expected: + mismatches.append(f"{key}: expected {expected!r}, got {actual!r}") + if mismatches: + raise AssertionError("FieldExtractor mismatch:\n " + "\n ".join(mismatches)) + + images = render_pdf_pages(pdf_bytes, dpi=dpi, first_page=1, last_page=1) + if len(images) != 1: + raise AssertionError(f"Expected 1 rendered page, got {len(images)}") + + first_page = images[0] + width, height = first_page.size + if first_page.mode != "RGB" or width < 400 or height < 500: + raise AssertionError(f"Unexpected rendered image geometry: mode={first_page.mode}, size={first_page.size}") + if first_page.convert("L").getextrema()[0] >= 255: + raise AssertionError("Rendered first page image is completely blank white") + + png_buf = BytesIO() + first_page.save(png_buf, format="PNG") + png_bytes = png_buf.getvalue() + if not png_bytes.startswith(b"\x89PNG\r\n\x1a\n") or len(png_bytes) < 512: + raise AssertionError(f"Invalid rendered PNG output ({len(png_bytes)} bytes)") + + if output_png is not None: + output_png.parent.mkdir(parents=True, exist_ok=True) + output_png.write_bytes(png_bytes) + + return { + "pdf_bytes": len(pdf_bytes), + "text_chars": len(raw_text), + "extracted_fields": extracted, + "rendered_size": [width, height], + "rendered_png_bytes": len(png_bytes), + } + + +def _build_http_opener(api_url: str) -> OpenerDirector: + host = (urlparse(api_url).hostname or "").lower() + if host in {"127.0.0.1", "localhost", "::1"}: + return build_opener(ProxyHandler({})) + return build_opener() + + +def _http_request( + opener: OpenerDirector, + method: str, + url: str, + data: bytes | None = None, + headers: dict[str, str] | None = None, + timeout: float = 15.0, +) -> tuple[int, dict[str, str], bytes]: + req = Request(url, data=data, headers=headers or {}, method=method) + try: + with opener.open(req, timeout=timeout) as resp: + return resp.status, dict(resp.headers.items()), resp.read() + except HTTPError as exc: + body = exc.read() + return exc.code, dict(exc.headers.items()), body + except URLError as exc: + raise RuntimeError(f"HTTP request failed ({method} {url}): {exc}") from exc + + +def _encode_multipart_file(field_name: str, filename: str, payload: bytes, content_type: str) -> tuple[bytes, str]: + boundary = f"----InvoiceSmoke{uuid.uuid4().hex}" + body = ( + f"--{boundary}\r\n" + f'Content-Disposition: form-data; name="{field_name}"; filename="{filename}"\r\n' + f"Content-Type: {content_type}\r\n\r\n" + ).encode("utf-8") + payload + f"\r\n--{boundary}--\r\n".encode("utf-8") + return body, f"multipart/form-data; boundary={boundary}" + + +def _field_matches(field_name: str, actual: Any, expected: str) -> bool: + if actual is None: + return False + if field_name in NUMERIC_FIELD_NAMES: + try: + return Decimal(str(actual)) == Decimal(expected) + except Exception: + return False + return str(actual) == expected + + +def run_api_smoke( + api_url: str, + pdf_bytes: bytes, + poll_timeout: float = 30.0, + keep_record: bool = False, +) -> dict[str, Any]: + """Run HTTP E2E smoke loop against a running Invoice Manager backend/app.""" + base = api_url.rstrip("/") + opener = _build_http_opener(base) + + # 1. Health check + status, _, body = _http_request(opener, "GET", f"{base}/api/health") + if status != 200: + raise AssertionError(f"GET /api/health returned HTTP {status}: {body.decode('utf-8', 'replace')}") + health = json.loads(body.decode("utf-8")) + if health.get("status") != "ok" or health.get("database") != "healthy": + raise AssertionError(f"Unexpected /api/health payload: {health}") + + # 2. Upload synthetic PDF + multipart_body, content_type = _encode_multipart_file( + field_name="files", + filename="synthetic-smoke-invoice.pdf", + payload=pdf_bytes, + content_type="application/pdf", + ) + status, _, body = _http_request( + opener, + "POST", + f"{base}/api/invoices/upload", + data=multipart_body, + headers={"Content-Type": content_type}, + ) + if status != 200: + raise AssertionError(f"POST /api/invoices/upload returned HTTP {status}: {body.decode('utf-8', 'replace')}") + upload_items = json.loads(body.decode("utf-8")) + if not isinstance(upload_items, list) or not upload_items or upload_items[0].get("status") != "success": + raise AssertionError(f"Unexpected upload response: {upload_items}") + invoice_id = int(upload_items[0]["id"]) + + cleaned_up = False + try: + # 3. Poll detail endpoint until background processing settles + deadline = time.monotonic() + poll_timeout + detail: dict[str, Any] | None = None + while time.monotonic() < deadline: + status, _, body = _http_request(opener, "GET", f"{base}/api/invoices/{invoice_id}") + if status != 200: + raise AssertionError( + f"GET /api/invoices/{invoice_id} returned HTTP {status}: {body.decode('utf-8', 'replace')}" + ) + detail = json.loads(body.decode("utf-8")) + if detail.get("status") not in IN_PROGRESS_STATUSES: + break + time.sleep(0.5) + + if detail is None or detail.get("status") in IN_PROGRESS_STATUSES: + raise AssertionError( + f"Invoice {invoice_id} did not finish processing within {poll_timeout}s: {detail}" + ) + if detail.get("status") != CONFIRMED_STATUS: + raise AssertionError( + f"Expected invoice status {CONFIRMED_STATUS!r}, got {detail.get('status')!r}; detail={detail}" + ) + + # Verify persisted fields (invoice_code is not stored on the Invoice table, only core fields below) + expected_api_fields = { + k: v for k, v in EXPECTED_CORE_FIELDS.items() if k != "invoice_code" + } + mismatches = [ + f"{key}: expected {expected!r}, got {detail.get(key)!r}" + for key, expected in expected_api_fields.items() + if not _field_matches(key, detail.get(key), expected) + ] + if mismatches: + raise AssertionError("API parsed invoice mismatch:\n " + "\n ".join(mismatches)) + + # 4. Verify list endpoint includes the uploaded invoice + status, _, body = _http_request(opener, "GET", f"{base}/api/invoices?page=1&page_size=20") + if status != 200: + raise AssertionError(f"GET /api/invoices returned HTTP {status}: {body.decode('utf-8', 'replace')}") + listing = json.loads(body.decode("utf-8")) + listed_ids = [item.get("id") for item in listing.get("items", [])] + if invoice_id not in listed_ids: + raise AssertionError(f"Uploaded invoice id={invoice_id} not found in list response: {listed_ids}") + + # 5. Verify CSV export + status, _, csv_bytes = _http_request( + opener, "GET", f"{base}/api/invoices/export/csv?invoice_ids={invoice_id}" + ) + if status != 200 or not csv_bytes: + raise AssertionError(f"GET /api/invoices/export/csv failed: HTTP {status}, len={len(csv_bytes)}") + csv_text = csv_bytes.decode("utf-8-sig") + if SYNTH_INVOICE_NUMBER not in csv_text or SYNTH_BUYER_NAME not in csv_text: + raise AssertionError(f"CSV export missing expected synthetic values:\n{csv_text}") + + # 6. Verify Excel export + status, _, xlsx_bytes = _http_request( + opener, "GET", f"{base}/api/invoices/export/excel?invoice_ids={invoice_id}" + ) + if status != 200 or len(xlsx_bytes) < 100 or not xlsx_bytes.startswith(b"PK"): + raise AssertionError( + f"GET /api/invoices/export/excel returned invalid workbook: HTTP {status}, len={len(xlsx_bytes)}" + ) + + return { + "api_url": base, + "health": health, + "invoice_id": invoice_id, + "status": detail.get("status"), + "list_total": listing.get("total"), + "csv_bytes": len(csv_bytes), + "excel_bytes": len(xlsx_bytes), + "cleaned_up": not keep_record, + } + finally: + if not keep_record: + del_status, _, _ = _http_request(opener, "DELETE", f"{base}/api/invoices/{invoice_id}") + cleaned_up = del_status == 200 + if cleaned_up: + verify_status, _, _ = _http_request(opener, "GET", f"{base}/api/invoices/{invoice_id}") + if verify_status != 404: + raise AssertionError( + f"Expected HTTP 404 after deleting invoice {invoice_id}, got HTTP {verify_status}" + ) + + +def parse_args(argv: list[str] | None = None) -> argparse.Namespace: + parser = argparse.ArgumentParser( + description="Run local synthetic-invoice E2E smoke test (pure Python core + optional HTTP API loop)." + ) + parser.add_argument( + "--output-pdf", + type=Path, + default=None, + help="Optional path to save the generated synthetic PDF invoice.", + ) + parser.add_argument( + "--output-png", + type=Path, + default=None, + help="Optional path to save the rendered first-page PNG.", + ) + parser.add_argument( + "--dpi", + type=int, + default=144, + help="DPI used when rendering the first page via pypdfium2 (default: 144).", + ) + parser.add_argument( + "--api-url", + type=str, + default=None, + help="Optional running backend/app base URL (e.g. http://127.0.0.1:18080) to run the HTTP E2E loop.", + ) + parser.add_argument( + "--poll-timeout", + type=float, + default=30.0, + help="Max seconds to wait for background processing in HTTP E2E mode (default: 30).", + ) + parser.add_argument( + "--keep-record", + action="store_true", + help="Keep the uploaded synthetic invoice record instead of deleting it after HTTP E2E verification.", + ) + parser.add_argument( + "--json", + action="store_true", + help="Print structured JSON summary instead of human-readable lines.", + ) + return parser.parse_args(argv) + + +def main(argv: list[str] | None = None) -> int: + args = parse_args(argv) + pdf_bytes = build_synthetic_invoice_pdf() + + if args.output_pdf is not None: + args.output_pdf.parent.mkdir(parents=True, exist_ok=True) + args.output_pdf.write_bytes(pdf_bytes) + + summary: dict[str, Any] = { + "core": run_core_smoke(pdf_bytes, dpi=args.dpi, output_png=args.output_png), + } + + if args.api_url: + summary["api"] = run_api_smoke( + api_url=args.api_url, + pdf_bytes=pdf_bytes, + poll_timeout=args.poll_timeout, + keep_record=args.keep_record, + ) + + if args.json: + print(json.dumps(summary, ensure_ascii=False, indent=2)) + else: + core = summary["core"] + fields = core["extracted_fields"] + print( + f"[L3-core] PASS | pdf={core['pdf_bytes']}B | text={core['text_chars']} chars | " + f"render={core['rendered_size'][0]}x{core['rendered_size'][1]} PNG ({core['rendered_png_bytes']}B)" + ) + print( + f"[L3-core] fields | invoice_number={fields['invoice_number']} | " + f"issue_date={fields['issue_date']} | buyer={fields['buyer_name']} | " + f"seller={fields['seller_name']} | amount={fields['amount']} | " + f"tax={fields['tax_amount']} | total={fields['total_with_tax']}" + ) + if args.output_pdf is not None: + print(f"[L3-core] saved synthetic PDF -> {args.output_pdf}") + if args.output_png is not None: + print(f"[L3-core] saved rendered PNG -> {args.output_png}") + if "api" in summary: + api = summary["api"] + print( + f"[L3-api ] PASS | url={api['api_url']} | id={api['invoice_id']} | " + f"status={api['status']} | list_total={api['list_total']} | " + f"csv={api['csv_bytes']}B | excel={api['excel_bytes']}B | " + f"cleaned_up={api['cleaned_up']}" + ) + + return 0 + + +if __name__ == "__main__": + sys.exit(main()) From dcd82b82d6de393e4cbcb404949a577b44c23d97 Mon Sep 17 00:00:00 2001 From: stone16 <12712299+stone16@users.noreply.github.com> Date: Sat, 28 Nov 2026 13:58:09 +0800 Subject: [PATCH 2/2] fix(smoke,docs): harden Excel/cleanup checks and refine local testing guide --- README.md | 26 ++++---- scripts/smoke_local_e2e.py | 128 ++++++++++++++++++++++++++++++------- 2 files changed, 120 insertions(+), 34 deletions(-) diff --git a/README.md b/README.md index 243b70d..ec21399 100644 --- a/README.md +++ b/README.md @@ -461,7 +461,7 @@ invoice_manager/ ## 🧪 本地测试与端到端试跑 | Testing & Local E2E -仓库测试分为 **L1 / L2 / L3** 三层,全部使用 **100% 合成占位发票数据**,不依赖任何真实发票或第三方 LLM API Key。 +仓库测试分为 **L1 / L2 / L3** 三层,以下命令均在**仓库根目录**执行;全部使用 **100% 合成占位发票数据**,不依赖任何真实发票或第三方 LLM API Key。 ### 当前已可测范围 @@ -521,41 +521,43 @@ cd backend && pytest tests -v /tmp/im-l1-venv/bin/python scripts/smoke_local_e2e.py ``` -脚本会在内存中生成一份带 ToUnicode 文字层与矢量边框的合成中文数电发票 PDF(全部采用一眼可辨识的占位值,不含真实税号、发票号或抬头),自动校验文字层提取、`FieldExtractor` 全字段解析与 `render_pdf_pages` 首页 PNG 渲染。预期输出摘要: +脚本会在内存中生成一份标准电子普通发票文字层样例(带 ToUnicode 文字层与矢量边框,全部采用一眼可辨识的占位值,不含真实税号、发票号或抬头),自动校验文字层提取、`FieldExtractor` 全字段解析与 `render_pdf_pages` 首页 PNG 渲染。预期输出摘要: ```text [L3-core] PASS | pdf=3260B | text=266 chars | render=1190x1684 PNG (68215B) [L3-core] fields | invoice_number=00000000000000000001 | issue_date=2025-11-05 | buyer=示例买方科技有限公司 | seller=示例卖方服务有限公司 | amount=1000.00 | tax=60.00 | total=1060.00 ``` -如需将合成 PDF 或渲染 PNG 落盘检查,可附加 `--output-pdf /tmp/sample-invoice.pdf --output-png /tmp/sample-page1.png`。 +如需将合成 PDF 或渲染 PNG 落盘检查,可附加 `--output-pdf /tmp/sample-invoice.pdf --output-png /tmp/sample-page1.png`。注意:渲染出的 PNG 仅用于验证 PDFium 渲染管线——因合成 PDF 未内嵌中文字体,可视字形为 ASCII 占位符,而 PDF 文本层已通过 ToUnicode CMap 保存为正确的 UTF-16BE 中文(可被 `pdfplumber` 完整提取)。 #### L3(b) 本地 Docker 全链路 HTTP 闭环 -使用独立 Compose 项目名启动 `db` 与 `backend`,向真实服务跑通「健康检查 → 上传合成 PDF → 轮询解析结果 → 列表/详情查询 → CSV & Excel 导出 → 自动清理记录」: +使用独立 Compose 项目名隔离数据卷与网络,向真实 `db` + `backend` 服务跑通「健康检查 → 上传合成 PDF → 轮询解析结果 → 列表/详情查询 → CSV & Excel 内容校验 → 自动清理记录」(注意:`docker-compose.yml` 固定了 `container_name` `invoice_db` / `invoice_backend`,若本机已有同名容器运行,请先停止或按下方排障提示用 override 文件避免冲突): ```bash -# 1. 启动后端与 PostgreSQL(独立项目名与独立数据卷) +# 1. 启动后端与 PostgreSQL(独立数据卷与网络) docker compose -p invoice-e2e-smoke up -d --build backend -# 2. 等待健康检查返回 200 -curl -fsS http://127.0.0.1:18080/api/health +# 2. 等待健康检查返回 200(自动重试,规避容器刚启动时的瞬时连接重置) +curl --retry 15 --retry-all-errors --retry-delay 2 -fsS http://127.0.0.1:18080/api/health -# 3. 跑通 HTTP 端到端闭环(验证后自动删除测试记录;如需保留可加 --keep-record) +# 3. 跑通 HTTP 端到端闭环(验证后自动删除测试记录并校验 404;如需保留可加 --keep-record) /tmp/im-l1-venv/bin/python scripts/smoke_local_e2e.py --api-url http://127.0.0.1:18080 -# 4. 清理测试容器、临时卷与临时 venv -docker compose -p invoice-e2e-smoke down -v +# 4. 清理测试容器、临时卷、本次构建镜像与临时 venv +docker compose -p invoice-e2e-smoke down -v --rmi local rm -rf /tmp/im-l1-venv +# 可选:如已执行 L2,也可一并清理本地测试镜像 +docker image rm invoice-manager:local-test ``` -预期输出摘要: +预期输出摘要(其中 `excel` 体积含时间戳元数据,约 5.5 KB,存在数个字节浮动属正常现象): ```text {"status":"ok","database":"healthy","service":"发票管理系统"} [L3-core] PASS | pdf=3260B | text=266 chars | render=1190x1684 PNG (68215B) [L3-core] fields | invoice_number=00000000000000000001 | issue_date=2025-11-05 | buyer=示例买方科技有限公司 | seller=示例卖方服务有限公司 | amount=1000.00 | tax=60.00 | total=1060.00 -[L3-api ] PASS | url=http://127.0.0.1:18080 | id=1 | status=已确认 | list_total=1 | csv=460B | excel=5538B | cleaned_up=True +[L3-api ] PASS | url=http://127.0.0.1:18080 | id=1 | status=已确认 | list_total=1 | csv=460B | excel=5540B | cleaned_up=True ``` --- diff --git a/scripts/smoke_local_e2e.py b/scripts/smoke_local_e2e.py index c7e7f19..4ad114d 100755 --- a/scripts/smoke_local_e2e.py +++ b/scripts/smoke_local_e2e.py @@ -22,6 +22,8 @@ from urllib.parse import urlparse from urllib.request import OpenerDirector, ProxyHandler, Request, build_opener import uuid +import xml.etree.ElementTree as ET +import zipfile try: from invoice_core.extract import FieldExtractor @@ -266,6 +268,70 @@ def _field_matches(field_name: str, actual: Any, expected: str) -> bool: return str(actual) == expected +def _local_tag(tag: str) -> str: + return tag.rsplit("}", 1)[-1] + + +def _extract_xlsx_cell_texts(xlsx_bytes: bytes) -> list[str]: + """Extract cell text values from an .xlsx workbook using Python stdlib only.""" + try: + zf = zipfile.ZipFile(BytesIO(xlsx_bytes)) + except zipfile.BadZipFile as exc: + raise AssertionError("Exported Excel payload is not a valid ZIP/XLSX archive") from exc + + with zf: + names = set(zf.namelist()) + shared_strings: list[str] = [] + if "xl/sharedStrings.xml" in names: + root = ET.fromstring(zf.read("xl/sharedStrings.xml")) + for si in root: + if _local_tag(si.tag) != "si": + continue + parts = [ + elem.text or "" + for elem in si.iter() + if _local_tag(elem.tag) == "t" + ] + shared_strings.append("".join(parts)) + + sheet_names = sorted( + name for name in names if name.startswith("xl/worksheets/sheet") and name.endswith(".xml") + ) + if not sheet_names: + raise AssertionError("Exported Excel workbook contains no worksheet XML files") + + cell_texts: list[str] = [] + for sheet_name in sheet_names: + root = ET.fromstring(zf.read(sheet_name)) + for elem in root.iter(): + if _local_tag(elem.tag) != "c": + continue + cell_type = elem.attrib.get("t") + if cell_type == "s": + value_elem = next((child for child in elem if _local_tag(child.tag) == "v"), None) + if value_elem is not None and value_elem.text is not None: + try: + idx = int(value_elem.text.strip()) + if 0 <= idx < len(shared_strings): + cell_texts.append(shared_strings[idx]) + except ValueError: + pass + elif cell_type == "inlineStr": + parts = [ + t_elem.text or "" + for t_elem in elem.iter() + if _local_tag(t_elem.tag) == "t" + ] + if parts: + cell_texts.append("".join(parts)) + else: + value_elem = next((child for child in elem if _local_tag(child.tag) == "v"), None) + if value_elem is not None and value_elem.text is not None: + cell_texts.append(value_elem.text) + + return cell_texts + + def run_api_smoke( api_url: str, pdf_bytes: bytes, @@ -305,7 +371,6 @@ def run_api_smoke( raise AssertionError(f"Unexpected upload response: {upload_items}") invoice_id = int(upload_items[0]["id"]) - cleaned_up = False try: # 3. Poll detail endpoint until background processing settles deadline = time.monotonic() + poll_timeout @@ -361,7 +426,7 @@ def run_api_smoke( if SYNTH_INVOICE_NUMBER not in csv_text or SYNTH_BUYER_NAME not in csv_text: raise AssertionError(f"CSV export missing expected synthetic values:\n{csv_text}") - # 6. Verify Excel export + # 6. Verify Excel export (archive structure + worksheet cell contents) status, _, xlsx_bytes = _http_request( opener, "GET", f"{base}/api/invoices/export/excel?invoice_ids={invoice_id}" ) @@ -369,27 +434,46 @@ def run_api_smoke( raise AssertionError( f"GET /api/invoices/export/excel returned invalid workbook: HTTP {status}, len={len(xlsx_bytes)}" ) - - return { - "api_url": base, - "health": health, - "invoice_id": invoice_id, - "status": detail.get("status"), - "list_total": listing.get("total"), - "csv_bytes": len(csv_bytes), - "excel_bytes": len(xlsx_bytes), - "cleaned_up": not keep_record, - } - finally: + xlsx_cells = _extract_xlsx_cell_texts(xlsx_bytes) + if SYNTH_INVOICE_NUMBER not in xlsx_cells or SYNTH_BUYER_NAME not in xlsx_cells: + raise AssertionError( + f"Excel export worksheet missing expected synthetic invoice cells: {xlsx_cells!r}" + ) + except BaseException: if not keep_record: - del_status, _, _ = _http_request(opener, "DELETE", f"{base}/api/invoices/{invoice_id}") - cleaned_up = del_status == 200 - if cleaned_up: - verify_status, _, _ = _http_request(opener, "GET", f"{base}/api/invoices/{invoice_id}") - if verify_status != 404: - raise AssertionError( - f"Expected HTTP 404 after deleting invoice {invoice_id}, got HTTP {verify_status}" - ) + try: + _http_request(opener, "DELETE", f"{base}/api/invoices/{invoice_id}") + except Exception: + pass + raise + + # 7. Cleanup uploaded synthetic record and verify 404 unless --keep-record was passed + cleaned_up = False + if not keep_record: + del_status, _, del_body = _http_request(opener, "DELETE", f"{base}/api/invoices/{invoice_id}") + if del_status != 200: + raise AssertionError( + f"DELETE /api/invoices/{invoice_id} failed with HTTP {del_status}: " + f"{del_body.decode('utf-8', 'replace')}" + ) + verify_status, _, verify_body = _http_request(opener, "GET", f"{base}/api/invoices/{invoice_id}") + if verify_status != 404: + raise AssertionError( + f"Expected HTTP 404 after deleting invoice {invoice_id}, got HTTP {verify_status}: " + f"{verify_body.decode('utf-8', 'replace')}" + ) + cleaned_up = True + + return { + "api_url": base, + "health": health, + "invoice_id": invoice_id, + "status": detail.get("status"), + "list_total": listing.get("total"), + "csv_bytes": len(csv_bytes), + "excel_bytes": len(xlsx_bytes), + "cleaned_up": cleaned_up, + } def parse_args(argv: list[str] | None = None) -> argparse.Namespace: