Files
syops/backend/tests/test_shipping_document_layout_runtime.py
T
hugo 1b6483a4ea feat(shipping-notice,receipt-report): 新增收料报表功能并优化发货通知流程
清理废弃的shipping xfa ocr automark相关代码和job配置
新增收料报表管理的前端页面、路由和侧边栏入口
新增后端收料报表配置接口、数据库模型和RPA脚本
优化发货通知流程的重试策略,将shipping相关job默认不自动重试
移除废弃的库存源确认相关逻辑,更新流程门禁规则
重构订单模板的值适配器模块,新增坐标OCR值适配器
清理前端shipping菜单和action的废弃选项
更新相关文档和测试用例,调整.gitignore忽略规则
2026-08-20 20:23:10 +08:00

391 lines
18 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"""
backend/tests/test_shipping_document_layout_runtime.py
用途:验证 MinerU 优先的紧凑快照、PDFium 页面复用、受控降级行为和容量门禁。
依赖:document_layout.runtime/mineru 构造候选、Flask 测试配置。
逻辑:Mock 客户端避免真实网络;MinerU 有表格时不得被 PDFium 替换,只有空表或失败才允许严格回退。
"""
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='<table><tr><th>Part</th></tr><tr><td>A</td></tr></table>',
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('<table>')
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_empty_mineru_tables_use_pdfium_provider_fallback(app):
"""MinerU 真正返回空表时,严格原生表须成为显式 PDFium 降级快照。"""
app.config.update(
SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED=True,
SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL='http://mineru.internal:8100',
)
empty_candidate = _candidate().model_copy(update={'pages': [
_candidate().pages[0].model_copy(update={'tables': []}),
]})
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': '<table><tr><th>Item</th><th>Qty</th></tr><tr><td>10</td><td>1</td></tr></table>',
'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],
), 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'},
), 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=empty_candidate,
):
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='d' * 64,
)
assert snapshot['provider'] == 'pdfium'
assert snapshot['backend'] == 'native_pdf'
assert snapshot['tables'][0]['table_id'] == 'native-1'
assert snapshot['layout_candidate']['schema_version'] == 'shipping_document_layout.v1'
assert 'mineru_provider_fallback_used' in snapshot['issues']
assert 'mineru_table_structure_missing' in snapshot['issues']
def test_runtime_mineru_table_remains_primary_when_native_table_evidence_exists(app):
"""本地文字可恢复表格时仍须先调用 MinerU,且不得替换 Provider 已返回的表格。"""
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': '<table><tr><th>Item</th><th>Material</th><th>Qty</th></tr><tr><td>10</td><td>A</td><td>1</td></tr></table>',
'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],
) 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': 'shipping_order_coordinate_evidence.v1'},
), patch(
'app.services.shipping_notice.document_layout.runtime.MinerUClient.parse_file_async',
return_value={'status': 'completed'},
) as mineru, patch(
'app.services.shipping_notice.document_layout.runtime.parse_mineru_candidate',
return_value=_candidate(),
):
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'] == 'mineru'
assert snapshot['tables'][0]['table_id'] == 'table-1'
assert 'layout_fast_path' not in timings
mineru.assert_called_once()
fallback.assert_not_called()
def test_runtime_provider_failure_uses_strict_native_fallback_without_page_rendering(app):
"""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': '<table><tr><th>Item</th><th>Qty</th></tr><tr><td>10</td><td>1</td></tr></table>',
'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'},
), patch(
'app.services.shipping_notice.document_layout.runtime.MinerUClient.parse_file_async',
side_effect=ServiceUnavailableError(
'failed', code='SHIPPING_NOTICE.LAYOUT_PROVIDER_UNAVAILABLE',
),
) as mineru:
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'
assert 'mineru_provider_fallback_used' in snapshot['issues']
assert 'SHIPPING_NOTICE.LAYOUT_PROVIDER_UNAVAILABLE' in snapshot['issues']
mineru.assert_called_once()
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_native_fallback_failure_preserves_mineru_error(app):
"""严格 PDFium 降级自身异常时不得覆盖 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})()
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',
side_effect=ValueError('invalid native table evidence'),
), 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', document_id=1, content_hash='c' * 64,
)
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'
def test_runtime_builds_xfa_visual_layout_without_creating_unfrozen_value_source_capability(app) -> None:
"""关键断言:runtime 只构建共享视觉 Layout;datasets 身份只能由正式 Layout Job 冻结。"""
candidate = _candidate()
with app.app_context(), patch(
'app.services.shipping_notice.document_layout.runtime.MinerUClient',
) as mineru, patch(
'app.services.shipping_notice.document_layout.runtime.parse_mineru_candidate',
return_value=candidate,
):
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_BASE_URL'] = 'http://mineru.test'
mineru.return_value.parse_file_async.return_value = {'ok': True}
snapshot = build_mineru_table_snapshot(
filename='order.pdf', content=b'%PDF-xfa', document_id=9, content_hash='c' * 64,
)
assert snapshot['status'] == 'ready'
assert 'xfa_capability' not in snapshot
assert snapshot['tables']
mineru.return_value.parse_file_async.assert_called_once()