""" backend/tests/test_shipping_document_layout_runtime.py 用途:验证 Intake 阶段 MinerU 紧凑快照、PDFium 页面复用、降级行为和容量门禁。 依赖:document_layout.runtime/mineru 构造候选、Flask 测试配置。 逻辑:Mock 客户端避免真实网络;只允许受预算文本块、表格 HTML 和能力摘要进入快照,原响应不得持久化。 """ from __future__ import annotations from unittest.mock import call, patch from app.core.errors import ServiceUnavailableError from app.services.shipping_notice.document_layout.contracts import LayoutBBox from app.services.shipping_notice.document_layout.mineru import ( MinerUCapabilityReport, MinerUPageCandidate, MinerUParseCandidate, MinerUTableCandidate, MinerUTextCandidate, ) from app.services.shipping_notice.document_layout.runtime import ( attach_mineru_layout_snapshots, build_mineru_table_snapshot, ) def _candidate() -> MinerUParseCandidate: """构造包含文本与表格的 MinerU 候选,验证紧凑快照内容。""" return MinerUParseCandidate( task_id='task-private', provider_version='3.1.14', backend='pipeline', pages=[MinerUPageCandidate( page_no=1, width=100, height=200, text_blocks=[MinerUTextCandidate( candidate_id='text-1', page_no=1, bbox=LayoutBBox(x0=1, y0=1, x1=10, y1=10), normalized_bbox=LayoutBBox(x0=.01, y0=.01, x1=.1, y1=.05), text='PRIVATE-NON-TABLE-TEXT', content_type='text', )], tables=[MinerUTableCandidate( candidate_id='table-1', page_no=1, bbox=LayoutBBox(x0=1, y0=20, x1=90, y1=100), normalized_bbox=LayoutBBox(x0=.01, y0=.1, x1=.9, y1=.5), html='
Part
A
', row_count=2, cell_count=2, has_rowspan=False, has_colspan=False, )], )], capability=MinerUCapabilityReport( provider_version='3.1.14', backend='pipeline', page_count=1, page_size_count=1, bbox_object_count=2, html_table_count=1, html_row_count=2, html_cell_count=2, text_block_count=1, cell_bbox_count=0, has_page_coordinates=True, has_table_structure=True, has_cell_coordinates=False, deterministic_cell_evidence_ready=False, issues=['mineru_cell_coordinates_missing'], ), ) def test_runtime_persists_compact_text_and_table_snapshot_without_raw_response(app): """快照保存受控文本和表格,但不得保存 task_id 或 Provider 原始响应。""" app.config.update( SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True, SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100', ) with app.app_context(), patch( 'app.services.shipping_notice.document_layout.runtime.MinerUClient.parse_file_async', return_value={'status': 'completed'}, ), patch( 'app.services.shipping_notice.document_layout.runtime.parse_mineru_candidate', return_value=_candidate(), ): snapshot = build_mineru_table_snapshot(filename='order.pdf', content=b'%PDF') assert snapshot['status'] == 'ready' assert snapshot['text_blocks'][0]['text'] == 'PRIVATE-NON-TABLE-TEXT' assert snapshot['tables'][0]['html'].startswith('') assert 'task-private' not in repr(snapshot) assert snapshot['issues'] == ['mineru_cell_coordinates_missing'] def test_runtime_limits_persisted_mineru_text(app): """MinerU 文本超过既有通知字符预算时应丢弃超额块并记录问题码。""" app.config.update( SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True, SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100', SHIPPING_NOTICE_NOTICE_TEXT_MAX_CHARS=10, ) with app.app_context(), patch( 'app.services.shipping_notice.document_layout.runtime.MinerUClient.parse_file_async', return_value={'status': 'completed'}, ), patch( 'app.services.shipping_notice.document_layout.runtime.parse_mineru_candidate', return_value=_candidate(), ): snapshot = build_mineru_table_snapshot(filename='order.pdf', content=b'%PDF') assert snapshot['text_blocks'] == [] assert 'mineru_text_budget_exceeded' in snapshot['issues'] def test_runtime_reuses_native_pdf_pages_across_fallback_layout_and_evidence(app): """单次 PDF 快照只允许提取/渲染一次页面,后续三个本地阶段必须复用同一对象。""" app.config.update( SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True, SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100', ) native_pages = [object()] timings: dict[str, int] = {} with app.app_context(), patch( 'app.services.shipping_notice.document_layout.runtime.MinerUClient.parse_file_async', return_value={'status': 'completed'}, ), patch( 'app.services.shipping_notice.document_layout.runtime.parse_mineru_candidate', return_value=_candidate().model_copy(update={'pages': [ _candidate().pages[0].model_copy(update={'tables': []}), ]}), ), patch( 'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages', return_value=native_pages, ) as extract_pages, patch( 'app.services.shipping_notice.document_layout.native_pdf.build_native_pdf_text_table_fallbacks', return_value=[], ) as fallback, patch( 'app.services.shipping_notice.document_layout.native_pdf.build_native_pdf_layout_candidate', ) as build_layout, patch( 'app.services.shipping_notice.document_layout.runtime._table_coordinate_evidence', return_value={'version': 'test'}, ) as build_evidence: build_layout.return_value.model_dump.return_value = {'version': 'layout.v1'} snapshot = build_mineru_table_snapshot( filename='order.pdf', content=b'%PDF', document_id=1, content_hash='hash', timings=timings, ) assert snapshot['status'] == 'ready' assert extract_pages.call_args_list == [ call(b'%PDF', render_images=False), call(b'%PDF'), ] assert fallback.call_args.kwargs['native_pages'] is native_pages assert build_layout.call_args.kwargs['native_pages'] is native_pages assert build_evidence.call_args.kwargs['pages'] is native_pages assert 'mineru_wait_ms' in timings assert 'native_pdf_extract_ms' in timings assert 'shipping_document_business_table_not_detected' in snapshot['issues'] def test_runtime_native_pdf_fast_path_skips_mineru_when_strict_table_evidence_exists(app): """文字型 PDF 可证明订单表格时应立即完成,不得继续等待 MinerU。""" app.config.update( SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True, SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100', ) page = type('Page', (), {'page_no': 1, 'width': 100, 'height': 200})() table = { 'table_id': 'native-1', 'page_no': 1, 'bbox': {'x0': 0, 'y0': 20, 'x1': 100, 'y1': 100}, 'normalized_bbox': {'x0': 0, 'y0': .1, 'x1': 1, 'y1': .5}, 'html': '
ItemMaterialQty
10A1
', 'row_count': 2, 'cell_count': 6, 'has_rowspan': False, 'has_colspan': False, } with app.app_context(), patch( 'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages', return_value=[page], ), patch( 'app.services.shipping_notice.document_layout.native_pdf.build_native_pdf_text_table_fallbacks', return_value=[table], ), patch( 'app.services.shipping_notice.document_layout.native_pdf.build_native_pdf_layout_candidate', ) as build_layout, patch( 'app.services.shipping_notice.document_layout.runtime._table_coordinate_evidence', return_value={'version': 'shipping_order_coordinate_evidence.v1'}, ), patch( 'app.services.shipping_notice.document_layout.runtime.MinerUClient.parse_file_async', ) as mineru: build_layout.return_value.model_dump.return_value = {'schema_version': 'shipping_document_layout.v1'} timings: dict[str, int] = {} snapshot = build_mineru_table_snapshot( filename='order.pdf', content=b'%PDF', document_id=1, content_hash='a' * 64, timings=timings, ) assert snapshot['status'] == 'ready' assert snapshot['provider'] == 'pdfium' assert snapshot['tables'][0]['table_id'] == 'native-1' assert timings['layout_fast_path'] == 1 mineru.assert_not_called() def test_runtime_native_fast_path_defers_page_rendering(app): """本地文字证据命中时只提取字符,不能预先渲染高分辨率页面图。""" app.config.update( SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True, SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100', ) page = type('Page', (), {'page_no': 1, 'width': 100, 'height': 200})() table = { 'table_id': 'native-1', 'page_no': 1, 'bbox': {'x0': 0, 'y0': 20, 'x1': 100, 'y1': 100}, 'normalized_bbox': {'x0': 0, 'y0': .1, 'x1': 1, 'y1': .5}, 'html': '
ItemQty
101
', 'row_count': 2, 'cell_count': 4, 'has_rowspan': False, 'has_colspan': False, } with app.app_context(), patch( 'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages', return_value=[page], ) as extract_pages, patch( 'app.services.shipping_notice.document_layout.native_pdf.build_native_pdf_text_table_fallbacks', return_value=[table], ), patch( 'app.services.shipping_notice.document_layout.native_pdf.build_native_pdf_layout_candidate', ) as build_layout, patch( 'app.services.shipping_notice.document_layout.runtime._table_coordinate_evidence', return_value={'version': 'test'}, ): build_layout.return_value.model_dump.return_value = {'schema_version': 'shipping_document_layout.v1'} snapshot = build_mineru_table_snapshot( filename='order.pdf', content=b'%PDF', document_id=1, content_hash='b' * 64, ) assert snapshot['provider'] == 'pdfium' extract_pages.assert_called_once_with(b'%PDF', render_images=False) def test_runtime_provider_failure_is_safe_fallback(app): """MinerU 失败只记录错误码并返回空表,不能抛出导致 Intake 文本解析失败。""" app.config.update( SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True, SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100', ) with app.app_context(), patch( 'app.services.shipping_notice.document_layout.runtime.MinerUClient.parse_file_async', side_effect=ServiceUnavailableError('failed', code='SHIPPING_NOTICE.LAYOUT_PROVIDER_UNAVAILABLE'), ): snapshot = build_mineru_table_snapshot(filename='order.pdf', content=b'%PDF') assert snapshot == { 'snapshot_version': 'shipping_document_table_snapshot.v1', 'provider': 'mineru', 'backend': 'pipeline', 'status': 'failed', 'tables': [], 'issues': ['SHIPPING_NOTICE.LAYOUT_PROVIDER_UNAVAILABLE'], } def test_runtime_attachment_budget_preserves_order_and_marks_overflow(app): """EML 多附件只并发处理预算内文档,超量附件显式降级且原顺序不变。""" app.config.update( SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True, SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100', SHIPPING_NOTICE_LAYOUT_MINERU_MAX_DOCUMENTS_PER_INTAKE=2, SHIPPING_NOTICE_LAYOUT_MINERU_CONCURRENCY=2, ) result = type('Result', (), {'meta': {'attachments': [ {'filename': 'first.pdf', '_payload_bytes': b'1'}, {'filename': 'second.pdf', '_payload_bytes': b'2'}, {'filename': 'third.pdf', '_payload_bytes': b'3'}, ]}})() with app.app_context(), patch( 'app.services.shipping_notice.document_layout.runtime.build_mineru_table_snapshot', side_effect=lambda *, filename, content, **_kwargs: { 'snapshot_version': 'shipping_document_table_snapshot.v1', 'provider': 'mineru', 'backend': 'pipeline', 'status': 'ready', 'tables': [], 'issues': [], 'marker': filename, }, ) as parse: attach_mineru_layout_snapshots(result) rows = result.meta['attachments'] assert parse.call_count == 2 assert rows[0]['layout_snapshot']['marker'] == 'first.pdf' assert rows[1]['layout_snapshot']['marker'] == 'second.pdf' assert rows[2]['layout_snapshot']['status'] == 'skipped_budget'