""" backend/tests/test_shipping_document_layout_contract.py 用途:验证 shipping_document_layout.v1 的几何、引用、跨页关系、稳定 ID 和 checksum。 依赖:document_layout.contracts、Pydantic ValidationError。 逻辑:使用不可逆构造样本覆盖阶段 L0 契约门禁,不依赖客户原始 PDF 或敏感业务数据。 """ from __future__ import annotations from copy import deepcopy import pytest from pydantic import ValidationError from app.services.shipping_notice.document_layout.contracts import ( canonical_layout_checksum, stable_layout_id, validate_layout_document, ) def _bbox(x0: float, y0: float, x1: float, y1: float) -> dict: """构造原始或标准化矩形。""" return {'x0': x0, 'y0': y0, 'x1': x1, 'y1': y1} def _token(token_id: str, text: str, x0: float, x1: float) -> dict: """构造一页内的原生 PDF 词元。""" return { 'token_id': token_id, 'text': text, 'normalized_text': text, 'bbox': _bbox(x0, 10, x1, 20), 'normalized_bbox': _bbox(x0 / 100, 0.1, x1 / 100, 0.2), 'source': 'native_text', 'confidence': 1, 'line_id': 'line-1', } def _cell(cell_id: str, *, row: int, column: int, text: str, token_id: str) -> dict: """构造可追溯到一个词元的表格单元格。""" x0 = 10 + column * 40 return { 'cell_id': cell_id, 'row_index': row, 'column_index': column, 'text': text, 'normalized_text': text, 'bbox': _bbox(x0, 10 + row * 20, x0 + 30, 25 + row * 20), 'normalized_bbox': _bbox(x0 / 100, (10 + row * 20) / 100, (x0 + 30) / 100, (25 + row * 20) / 100), 'token_ids': [token_id], 'source': 'native_text', 'confidence': 1, 'role': 'header' if row == 0 else 'data', } def _table(table_id: str, *, continuation_of: str | None = None) -> dict: """构造两列表格;调用方负责提供同页对应 token。""" suffix = table_id.rsplit('-', 1)[-1] return { 'table_id': table_id, 'bbox': _bbox(5, 5, 95, 55), 'normalized_bbox': _bbox(0.05, 0.05, 0.95, 0.55), 'rows': [ { 'row_id': f'row-{suffix}-0', 'row_index': 0, 'role': 'header', 'cells': [ _cell(f'cell-{suffix}-0-0', row=0, column=0, text='Part', token_id=f'token-{suffix}-part'), _cell(f'cell-{suffix}-0-1', row=0, column=1, text='Qty', token_id=f'token-{suffix}-qty'), ], }, ], 'header_row_indices': [0], 'continuation_of': continuation_of, 'confidence': 1, 'status': 'accepted', } def _page(page_no: int, table_id: str, *, continuation_of: str | None = None) -> dict: """构造含真实坐标词元和单个表格的页面。""" suffix = table_id.rsplit('-', 1)[-1] return { 'page_no': page_no, 'width': 100, 'height': 100, 'rotation': 0, 'tokens': [ _token(f'token-{suffix}-part', 'Part', 10, 40), _token(f'token-{suffix}-qty', 'Qty', 50, 80), ], 'tables': [_table(table_id, continuation_of=continuation_of)], } def _document() -> dict: """构造带合法跨页 continuation 的完整布局文档。""" return { 'schema_version': 'shipping_document_layout.v1', 'document_id': 42, 'content_hash': 'a' * 64, 'parser': {'name': 'fixture-parser', 'version': '1.0.0'}, 'pages': [ _page(1, 'table-p1'), _page(2, 'table-p2', continuation_of='table-p1'), ], 'quality': {'status': 'accepted', 'confidence': 1, 'issues': []}, } def test_layout_contract_accepts_traceable_cross_page_table(): """合法结果必须保留页、表、行、列、单元格、词元和向前跨页引用。""" result = validate_layout_document(_document()) assert result.schema_version == 'shipping_document_layout.v1' assert result.pages[1].tables[0].continuation_of == 'table-p1' assert result.pages[0].tables[0].rows[0].cells[0].token_ids == ['token-p1-part'] def test_layout_contract_rejects_unknown_cell_token_reference(): """PDF/OCR 单元格引用不存在的词元时必须拒绝,防止证据链断裂。""" payload = _document() payload['pages'][0]['tables'][0]['rows'][0]['cells'][0]['token_ids'] = ['missing-token'] with pytest.raises(ValidationError, match='unknown token_id'): validate_layout_document(payload) def test_layout_contract_rejects_out_of_page_and_non_normalized_bbox(): """原始坐标越界或标准化坐标超过 0..1 均不能进入下游。""" outside_page = _document() outside_page['pages'][0]['tokens'][0]['bbox']['x1'] = 101 with pytest.raises(ValidationError, match='exceeds page bounds'): validate_layout_document(outside_page) outside_normalized = _document() outside_normalized['pages'][0]['tables'][0]['normalized_bbox']['x1'] = 1.1 with pytest.raises(ValidationError, match='within 0..1'): validate_layout_document(outside_normalized) def test_layout_contract_rejects_cell_outside_table_and_overlapping_span(): """单元格超出表格或 rowspan/colspan 相互覆盖时必须拒绝。""" outside_table = _document() outside_table['pages'][0]['tables'][0]['rows'][0]['cells'][0]['bbox']['x0'] = 1 with pytest.raises(ValidationError, match='within table bbox'): validate_layout_document(outside_table) overlapping = _document() cells = overlapping['pages'][0]['tables'][0]['rows'][0]['cells'] cells[0]['column_span'] = 2 with pytest.raises(ValidationError, match='overlapping'): validate_layout_document(overlapping) def test_layout_contract_rejects_forward_or_missing_continuation(): """跨页表只能引用更早页面的已知表,禁止循环、前向或悬空关系。""" forward = _document() forward['pages'][0]['tables'][0]['continuation_of'] = 'table-p2' with pytest.raises(ValidationError, match='earlier page'): validate_layout_document(forward) missing = _document() missing['pages'][1]['tables'][0]['continuation_of'] = 'table-missing' with pytest.raises(ValidationError, match='earlier page'): validate_layout_document(missing) def test_layout_contract_rejects_accepted_quality_with_blocking_issue(): """存在阻断质量问题的布局不能伪装成 accepted。""" payload = _document() payload['quality']['issues'] = [{ 'code': 'table_columns_ambiguous', 'severity': 'blocking', 'page_no': 1, 'table_id': 'table-p1', 'details': {}, }] with pytest.raises(ValidationError, match='must not contain blocking issues'): validate_layout_document(payload) def test_stable_id_and_checksum_are_deterministic_and_content_sensitive(): """相同输入必须生成相同标识/checksum,任何结构变化必须改变 checksum。""" payload = _document() copied = deepcopy(payload) assert stable_layout_id('cell', 'a' * 64, 1, 0, 0) == stable_layout_id('cell', 'a' * 64, 1, 0, 0) assert canonical_layout_checksum(payload) == canonical_layout_checksum(copied) copied['pages'][0]['tables'][0]['rows'][0]['cells'][0]['text'] = 'Changed Part' copied['pages'][0]['tables'][0]['rows'][0]['cells'][0]['normalized_text'] = 'Changed Part' assert canonical_layout_checksum(payload) != canonical_layout_checksum(copied)