""" tests/test_shipping_xfa_structure_analysis.py 用途:验证 XFA 端到端结构分析、指纹稳定性与持久化摘要。 依赖:xfa_analysis、xfa_signature、ShippingXfaStructureAnalysis 模型、合成 PDF。 逻辑:值/行数变化不改指纹;层级/命名空间变化改指纹;不写 XML 到 DTO。 """ from __future__ import annotations import json import re from pathlib import Path import pytest from app import db from app.services.shipping_notice.document_layout.xfa_analysis import ( analyze_xfa_pdf, persist_xfa_structure_analysis, ) from app.services.shipping_notice.document_layout.xfa_contract import sanitize_xfa_dto from app.services.shipping_notice.document_layout.xfa_signature import ( compute_dataset_structure_fingerprint_from_nodes, ) from app.services.shipping_notice.document_layout.xfa_dataset import parse_xfa_datasets from tests.test_shipping_xfa_helpers import build_synthetic_xfa_hybrid_pdf, load_datasets_fixture FIXTURE_ROOT = Path(__file__).resolve().parent / 'fixtures' / 'shipping_xfa' EXPECTED = json.loads((FIXTURE_ROOT / 'annotation' / 'expected.json').read_text(encoding='utf-8')) def test_analyze_xfa_hybrid_pdf_produces_ready_snapshot(): """合成 hybrid PDF 分析必须返回 ready XFA capability,且不含 table。""" pdf_bytes = build_synthetic_xfa_hybrid_pdf(load_datasets_fixture()) outcome = analyze_xfa_pdf(pdf_bytes) assert outcome.snapshot['status'] == 'ready' assert outcome.snapshot['provider'] == 'xfa' assert outcome.snapshot['tables'] == [] capability = outcome.snapshot['xfa_capability'] assert capability['structure_analysis_ready'] is True assert capability['document_kind'] == 'xfa_hybrid' assert capability['dataset_structure_fingerprint'].startswith('sha256:') assert capability['template_packet_checksum'].startswith('sha256:') def test_fingerprint_stable_when_values_and_row_counts_change(): """业务值与明细行数量变化不得改变结构指纹。""" base = parse_xfa_datasets(load_datasets_fixture()) base_fp = compute_dataset_structure_fingerprint_from_nodes(base.nodes) changed_values = load_datasets_fixture().decode('utf-8') changed_values = changed_values.replace('4510039227', '9999999999') changed_values = changed_values.replace('30.000', '99.000') changed_analysis = parse_xfa_datasets(changed_values.encode('utf-8')) assert compute_dataset_structure_fingerprint_from_nodes(changed_analysis.nodes) == base_fp multi_row = load_datasets_fixture().decode('utf-8').replace( '\n ', '\n 00020OTHER\n ', 1, ) multi_analysis = parse_xfa_datasets(multi_row.encode('utf-8')) assert compute_dataset_structure_fingerprint_from_nodes(multi_analysis.nodes) == base_fp def test_fingerprint_changes_when_hierarchy_changes(): """节点/层级变化必须改变结构指纹。""" base = parse_xfa_datasets(load_datasets_fixture()) base_fp = compute_dataset_structure_fingerprint_from_nodes(base.nodes) without_items1 = load_datasets_fixture().decode('utf-8') without_items1 = re.sub(r'\s*.*?', '', without_items1, flags=re.DOTALL) reduced = parse_xfa_datasets(without_items1.encode('utf-8')) assert compute_dataset_structure_fingerprint_from_nodes(reduced.nodes) != base_fp def test_fingerprint_changes_when_namespace_changes(): """命名空间变化必须改变结构指纹。""" base = parse_xfa_datasets(load_datasets_fixture()) base_fp = compute_dataset_structure_fingerprint_from_nodes(base.nodes) namespaced = load_datasets_fixture().decode('utf-8').replace( '', '', 1, ) ns_analysis = parse_xfa_datasets(namespaced.encode('utf-8')) assert compute_dataset_structure_fingerprint_from_nodes(ns_analysis.nodes) != base_fp def test_snapshot_and_dto_exclude_forbidden_keys(): """分析快照与普通 DTO 不得包含 XML/PDF bytes 禁止键。""" pdf_bytes = build_synthetic_xfa_hybrid_pdf(load_datasets_fixture()) outcome = analyze_xfa_pdf(pdf_bytes) cleaned = sanitize_xfa_dto(outcome.snapshot) forbidden = {'xml', 'raw_xml', 'pdf_bytes', 'packet_bytes', 'datasets_xml', 'object_key'} assert forbidden.isdisjoint({key.lower() for key in cleaned}) def test_persist_structure_analysis_record(app): """Job 持久化必须写入 analysis 摘要字段。""" with app.app_context(): from tests.test_shipping_document_layout_lifecycle import _document document = _document() pdf_bytes = build_synthetic_xfa_hybrid_pdf(load_datasets_fixture()) outcome = analyze_xfa_pdf(pdf_bytes) record = persist_xfa_structure_analysis( document_id=int(document.id), layout_version_id=None, source_content_hash=str(document.content_hash or ''), outcome=outcome, ) db.session.commit() assert record.analysis_status == 'ready' assert record.document_kind == 'xfa_hybrid' assert record.dataset_structure_fingerprint.startswith('sha256:') assert record.datasets_packet_checksum.startswith('sha256:') assert record.encrypted_snapshot_ref is None assert record.stats_json.get('leaf_count', 0) > 0 assert record.security_summary_json.get('scripts_executed') is False