278 lines
11 KiB
Python
278 lines
11 KiB
Python
"""
|
||
tests/test_shipping_xfa_ocr_matching.py
|
||
|
||
用途:阶段 3 OCR 匹配 / 视觉建议合并、阶段 5 合成预览门禁、阶段 6 审计补偿骨架单测。
|
||
依赖:xfa_ocr_matcher、xfa_visual_binding_service、assert_xfa_synthetic_preview_gate、
|
||
audit_compensation_service;合成 bbox/文本,不依赖真实 RapidOCR。
|
||
逻辑:断言 IoU/分层、mismatch→needs_review、Widget 优先 OCR 补框、门禁 fail-closed、
|
||
补偿记录与 retry stub。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import pytest
|
||
|
||
from app.core.errors import ValidationError
|
||
from app.services.shipping_notice.audit_compensation_service import (
|
||
list_pending_compensation,
|
||
record_audit_write_failure,
|
||
reset_compensation_store_for_tests,
|
||
retry_pending,
|
||
)
|
||
from app.services.shipping_notice.document_layout.xfa_contract import XFA_AUDIT_EVENT_TYPES
|
||
from app.services.shipping_notice.order_document_profile_validation_service import (
|
||
assert_xfa_synthetic_preview_gate,
|
||
)
|
||
from app.services.shipping_notice.xfa_ocr_matcher import (
|
||
classify_ocr_match,
|
||
compute_iou,
|
||
match_ocr_to_datasets,
|
||
normalize_match_text,
|
||
)
|
||
from app.services.shipping_notice.xfa_visual_binding_service import merge_visual_binding_suggestions
|
||
|
||
pytestmark = pytest.mark.pure_unit
|
||
|
||
|
||
def test_normalize_and_iou_helpers():
|
||
"""关键断言:文本规范化折叠空白;IoU 对重叠框为正。"""
|
||
assert normalize_match_text(' Po-123 ') == 'po-123'
|
||
iou = compute_iou(
|
||
{'x0': 0.1, 'y0': 0.1, 'x1': 0.5, 'y1': 0.3},
|
||
{'x0': 0.2, 'y0': 0.15, 'x1': 0.6, 'y1': 0.35},
|
||
)
|
||
assert 0.0 < iou < 1.0
|
||
assert compute_iou(
|
||
{'x0': 0.0, 'y0': 0.0, 'x1': 0.1, 'y1': 0.1},
|
||
{'x0': 0.9, 'y0': 0.9, 'x1': 1.0, 'y1': 1.0},
|
||
) == 0.0
|
||
|
||
|
||
def test_classify_high_medium_low_and_mismatch_needs_review():
|
||
"""关键断言:高/中/低分层;文本不匹配一律 needs_review。"""
|
||
assert classify_ocr_match(text_score=1.0, iou=0.6, ocr_confidence=0.95) == 'high'
|
||
assert classify_ocr_match(text_score=1.0, iou=0.35, ocr_confidence=0.85) == 'medium'
|
||
assert classify_ocr_match(text_score=0.5, iou=0.15, ocr_confidence=0.75) == 'low'
|
||
assert classify_ocr_match(text_score=0.0, iou=0.9, ocr_confidence=0.99) == 'needs_review'
|
||
|
||
|
||
def test_match_ocr_to_datasets_mismatch_never_auto_confirm():
|
||
"""关键断言:OCR 与 datasets 值不符 → needs_review,且 auto_confirm_blocked。"""
|
||
ocr_lines = [{
|
||
'text': 'WRONG-VALUE',
|
||
'confidence': 0.99,
|
||
'normalized_bbox': {'x0': 0.1, 'y0': 0.2, 'x1': 0.4, 'y1': 0.3},
|
||
}]
|
||
targets = [{
|
||
'field_key': 'path-po',
|
||
'value': 'PO-1001',
|
||
'normalized_bbox': {'x0': 0.1, 'y0': 0.2, 'x1': 0.4, 'y1': 0.3},
|
||
}]
|
||
suggestions = match_ocr_to_datasets(ocr_lines=ocr_lines, dataset_targets=targets)
|
||
assert len(suggestions) == 1
|
||
item = suggestions[0]
|
||
assert item['match_class'] == 'needs_review'
|
||
assert item['status'] == 'needs_review'
|
||
assert item['auto_confirm_blocked'] is True
|
||
|
||
|
||
def test_match_ocr_exact_value_suggested_high():
|
||
"""关键断言:精确文本 + 高 IoU/置信 → suggested/high,仍禁止自动确认。"""
|
||
bbox = {'x0': 0.2, 'y0': 0.4, 'x1': 0.5, 'y1': 0.5}
|
||
suggestions = match_ocr_to_datasets(
|
||
ocr_lines=[{'text': 'PO-1001', 'confidence': 0.96, 'normalized_bbox': bbox}],
|
||
dataset_targets=[{'field_key': 'path-po', 'value': 'PO-1001', 'normalized_bbox': bbox}],
|
||
)
|
||
assert suggestions[0]['match_class'] == 'high'
|
||
assert suggestions[0]['status'] == 'suggested'
|
||
assert suggestions[0]['auto_confirm_blocked'] is True
|
||
|
||
|
||
def test_merge_widget_first_then_ocr_fill():
|
||
"""关键断言:Widget 覆盖的 field 不被 OCR 覆盖;未覆盖目标由 OCR 填充。"""
|
||
widget_candidates = [{
|
||
'path_candidates': [{'path_id': 'path-po'}],
|
||
'page_no': 1,
|
||
'normalized_bbox': {'x0': 0.1, 'y0': 0.1, 'x1': 0.3, 'y1': 0.2},
|
||
'confidence': 0.9,
|
||
}]
|
||
result = merge_visual_binding_suggestions(
|
||
page_no=1,
|
||
widget_candidates=widget_candidates,
|
||
ocr_lines=[{
|
||
'text': 'LINE-A',
|
||
'confidence': 0.95,
|
||
'normalized_bbox': {'x0': 0.2, 'y0': 0.5, 'x1': 0.5, 'y1': 0.6},
|
||
}],
|
||
dataset_targets=[
|
||
{'field_key': 'path-po', 'value': 'PO-1', 'normalized_bbox': {'x0': 0.1, 'y0': 0.1, 'x1': 0.3, 'y1': 0.2}},
|
||
{'field_key': 'path-line', 'value': 'LINE-A', 'normalized_bbox': {'x0': 0.2, 'y0': 0.5, 'x1': 0.5, 'y1': 0.6}},
|
||
],
|
||
)
|
||
bindings = result['suggested_visual_bindings']
|
||
origins = {item['field_key']: item['suggestion_origin'] for item in bindings}
|
||
assert origins['path-po'] == 'widget_template'
|
||
assert origins['path-line'] == 'ocr'
|
||
assert all(item.get('auto_confirm_blocked') is True for item in bindings)
|
||
assert all(item.get('status') != 'confirmed' for item in bindings)
|
||
|
||
|
||
def test_assert_xfa_synthetic_preview_gate_blocks_not_ready():
|
||
"""关键断言:preview_status 非 ready → 抛 SYNTHETIC_PREVIEW_GATE。"""
|
||
with pytest.raises(ValidationError) as caught:
|
||
assert_xfa_synthetic_preview_gate(
|
||
template_mode='xfa_dataset',
|
||
preview_status='failed',
|
||
preview_render_checksum='sha256:' + ('a' * 64),
|
||
bindings=[{
|
||
'field_id': 'f-h-po',
|
||
'visual_binding': {'status': 'confirmed'},
|
||
}],
|
||
)
|
||
assert caught.value.code == 'SHIPPING.ORDER_DOCUMENT_PROFILE_XFA_SYNTHETIC_PREVIEW_GATE'
|
||
keys = {item['key'] for item in caught.value.details.get('blocking') or []}
|
||
assert 'xfa_synthetic_preview_not_ready' in keys
|
||
|
||
|
||
def test_assert_xfa_synthetic_preview_gate_blocks_missing_checksum_and_unconfirmed():
|
||
"""关键断言:缺 checksum + 未确认视觉绑定同时阻断。"""
|
||
with pytest.raises(ValidationError) as caught:
|
||
assert_xfa_synthetic_preview_gate(
|
||
template_mode='xfa_dataset',
|
||
preview_status='ready',
|
||
preview_render_checksum='',
|
||
bindings=[{
|
||
'field_id': 'f-h-po',
|
||
'visual_binding': {'status': 'suggested'},
|
||
}],
|
||
schema_field_ids={'f-h-po'},
|
||
)
|
||
keys = {item['key'] for item in caught.value.details.get('blocking') or []}
|
||
assert 'xfa_preview_render_checksum_missing' in keys
|
||
assert 'xfa_visual_binding_incomplete' in keys
|
||
|
||
|
||
def test_assert_xfa_synthetic_preview_gate_skips_coordinate_and_passes_ready():
|
||
"""关键断言:coordinate 跳过;XFA ready+页身份+confirmed 完整证据通过。"""
|
||
assert_xfa_synthetic_preview_gate(
|
||
template_mode='coordinate',
|
||
preview_status=None,
|
||
preview_render_checksum=None,
|
||
bindings=[],
|
||
)
|
||
checksum = 'sha256:' + ('b' * 64)
|
||
assert_xfa_synthetic_preview_gate(
|
||
template_mode='xfa_dataset',
|
||
preview_status='ready',
|
||
preview_render_checksum=checksum,
|
||
bindings=[{
|
||
'field_id': 'f-h-po',
|
||
'visual_binding': {
|
||
'status': 'confirmed',
|
||
'preview_render_checksum': checksum,
|
||
'confirmed_on': 'xfa_dataset_preview',
|
||
'renderer_version': 'hxops.xfa_static_preview.v1',
|
||
},
|
||
}],
|
||
schema_field_ids={'f-h-po'},
|
||
preview_meta={
|
||
'status': 'ready',
|
||
'preview_render_checksum': checksum,
|
||
'renderer_version': 'hxops.xfa_static_preview.v1',
|
||
'page_count': 1,
|
||
'pages_ready': [1],
|
||
'source_page_count': 1,
|
||
'synthetic_page_count': 1,
|
||
'pages': [{
|
||
'page_no': 1,
|
||
'source_page_box': {'x0': 0.0, 'y0': 0.0, 'x1': 612.0, 'y1': 792.0},
|
||
'synthetic_page_box': {'x0': 0.0, 'y0': 0.0, 'x1': 612.0, 'y1': 792.0},
|
||
'page_identity_hash': 'page-1',
|
||
}],
|
||
'unresolved_ocr_mismatch_count': 0,
|
||
},
|
||
current_renderer_version='hxops.xfa_static_preview.v1',
|
||
)
|
||
|
||
|
||
def test_assert_xfa_synthetic_preview_gate_blocks_missing_page_identity():
|
||
"""关键断言:缺 source/synthetic 页身份证据 → xfa_preview_page_identity_missing。"""
|
||
with pytest.raises(ValidationError) as caught:
|
||
assert_xfa_synthetic_preview_gate(
|
||
template_mode='xfa_dataset',
|
||
preview_status='ready',
|
||
preview_render_checksum='sha256:' + ('b' * 64),
|
||
bindings=[],
|
||
preview_meta={
|
||
'status': 'ready',
|
||
'page_count': 1,
|
||
'pages_ready': [1],
|
||
},
|
||
)
|
||
keys = {item['key'] for item in caught.value.details.get('blocking') or []}
|
||
assert 'xfa_preview_page_identity_missing' in keys
|
||
|
||
|
||
def test_assert_xfa_synthetic_preview_gate_blocks_missing_renderer_version():
|
||
"""关键断言:confirmed 缺 renderer_version → xfa_preview_renderer_version_mismatch(BE-4)。"""
|
||
checksum = 'sha256:' + ('b' * 64)
|
||
with pytest.raises(ValidationError) as caught:
|
||
assert_xfa_synthetic_preview_gate(
|
||
template_mode='xfa_dataset',
|
||
preview_status='ready',
|
||
preview_render_checksum=checksum,
|
||
bindings=[{
|
||
'field_id': 'f-h-po',
|
||
'visual_binding': {
|
||
'status': 'confirmed',
|
||
'preview_render_checksum': checksum,
|
||
'confirmed_on': 'xfa_dataset_preview',
|
||
# 故意缺 renderer_version
|
||
},
|
||
}],
|
||
schema_field_ids={'f-h-po'},
|
||
preview_meta={
|
||
'status': 'ready',
|
||
'preview_render_checksum': checksum,
|
||
'renderer_version': 'hxops.xfa_static_preview.v1',
|
||
'page_count': 1,
|
||
'pages_ready': [1],
|
||
'source_page_count': 1,
|
||
'synthetic_page_count': 1,
|
||
'pages': [{
|
||
'page_no': 1,
|
||
'source_page_box': {'x0': 0.0, 'y0': 0.0, 'x1': 612.0, 'y1': 792.0},
|
||
'synthetic_page_box': {'x0': 0.0, 'y0': 0.0, 'x1': 612.0, 'y1': 792.0},
|
||
'page_identity_hash': 'page-1',
|
||
}],
|
||
},
|
||
current_renderer_version='hxops.xfa_static_preview.v1',
|
||
)
|
||
keys = {item['key'] for item in caught.value.details.get('blocking') or []}
|
||
assert 'xfa_preview_renderer_version_mismatch' in keys
|
||
|
||
|
||
def test_audit_compensation_record_list_retry_stub():
|
||
"""关键断言:写失败入队、list pending、retry stub 标记 retried_stub。"""
|
||
reset_compensation_store_for_tests()
|
||
record = record_audit_write_failure(
|
||
event_type='xfa_visual_binding_suggested',
|
||
payload={'page_no': 1},
|
||
error='db_commit_failed',
|
||
profile_id=12,
|
||
)
|
||
assert record['status'] == 'pending'
|
||
pending = list_pending_compensation()
|
||
assert any(item['id'] == record['id'] for item in pending)
|
||
result = retry_pending(limit=10)
|
||
assert result['retried'] >= 1
|
||
assert result['note'] == 'stub_only_no_audit_replay'
|
||
assert all(item['status'] == 'retried_stub' for item in result['items'])
|
||
reset_compensation_store_for_tests()
|
||
|
||
|
||
def test_xfa_ocr_audit_event_names_registered():
|
||
"""关键断言:OCR 审计事件名已注册于 XFA_AUDIT_EVENT_TYPES。"""
|
||
for name in ('xfa_ocr_started', 'xfa_ocr_completed', 'xfa_ocr_failed', 'xfa_visual_binding_suggested'):
|
||
assert name in XFA_AUDIT_EVENT_TYPES
|