256 lines
9.9 KiB
Python
256 lines
9.9 KiB
Python
"""
|
||
tests/test_shipping_xfa_dataset.py
|
||
|
||
用途:验证 hardened datasets 解析、路径树、Header/集合候选与安全拒绝。
|
||
依赖:xfa_dataset、fixtures/shipping_xfa/annotation。
|
||
逻辑:覆盖 Golden 路径读取、XXE/DTD、深度/节点/行数限制;不产生网络访问。
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
from pathlib import Path
|
||
from unittest.mock import patch
|
||
|
||
import pytest
|
||
|
||
from app.services.shipping_notice.document_layout.xfa_contract import (
|
||
XFA_DEFAULT_MAX_LINE_ROWS,
|
||
XFA_DEFAULT_MAX_XML_DEPTH,
|
||
XFA_DEFAULT_MAX_XML_NODES,
|
||
hash_data_path,
|
||
xfa_mapping_sample_display,
|
||
)
|
||
from app.services.shipping_notice.document_layout.xfa_dataset import (
|
||
XfaDatasetParseError,
|
||
build_xfa_leaf_value,
|
||
mask_value_for_dto,
|
||
parse_xfa_datasets,
|
||
read_collection_rows,
|
||
read_dataset_leaf_value,
|
||
read_dataset_value,
|
||
serialize_tree_node,
|
||
)
|
||
from tests.test_shipping_xfa_helpers import 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_parse_golden_datasets_reads_header_and_line_values():
|
||
"""Golden fixture 必须读出全部 Header/Line 原值。"""
|
||
analysis = parse_xfa_datasets(load_datasets_fixture())
|
||
paths = EXPECTED['paths']
|
||
assert read_dataset_value(analysis, paths['customer_po_no']) == '4510039227'
|
||
assert read_dataset_value(analysis, paths['order_date']) == '2026-07-07'
|
||
assert read_dataset_value(analysis, paths['currency']) == 'USD'
|
||
assert read_dataset_value(analysis, paths['total_amount']) == '26961.60'
|
||
assert read_dataset_value(analysis, paths['customer_po_line_no']) == '00010'
|
||
assert read_dataset_value(analysis, paths['material_no']) == 'TEMP-S000218922'
|
||
assert read_dataset_value(analysis, paths['quantity']) == '30.000'
|
||
# datasets 层返回原文字符串;正式提取层再拆为 unit_price + price_unit。
|
||
assert read_dataset_value(analysis, paths['unit_price']) == '898.72 / 1'
|
||
assert read_dataset_value(analysis, paths['amount']) == '26961.60'
|
||
assert read_dataset_value(analysis, paths['delivery_date']) == '2026-07-14'
|
||
|
||
|
||
def test_collection_candidates_include_items_and_items1_independently():
|
||
"""ITEMS/DATA 与 ITEMS1/DATA 必须作为独立集合候选。"""
|
||
analysis = parse_xfa_datasets(load_datasets_fixture())
|
||
collection_paths = {item.collection_path for item in analysis.collection_candidates}
|
||
assert '/data/ITEMS/DATA' in collection_paths
|
||
assert '/data/ITEMS1/DATA' in collection_paths
|
||
assert len(collection_paths) >= 2
|
||
|
||
|
||
def test_header_candidates_cover_golden_header_fields():
|
||
"""Header 候选必须覆盖 Golden Header 字段。"""
|
||
analysis = parse_xfa_datasets(load_datasets_fixture())
|
||
header_hashes = {item['data_path_hash'] for item in analysis.header_candidates}
|
||
for key in ('customer_po_no', 'order_date', 'currency', 'total_amount'):
|
||
assert hash_data_path(EXPECTED['paths'][key]) in header_hashes
|
||
|
||
|
||
def test_tree_nodes_have_path_id_and_no_raw_paths_in_serialized_dto():
|
||
"""API 序列化树节点只暴露 path_id 与 path hash,不暴露明文路径。"""
|
||
analysis = parse_xfa_datasets(load_datasets_fixture())
|
||
root = analysis.nodes[0]
|
||
payload = serialize_tree_node(root, include_values=True)
|
||
assert payload['path_id']
|
||
assert payload['data_path_hash'].startswith('sha256:')
|
||
assert 'data_path' not in payload
|
||
assert '4510039227' not in json.dumps(payload)
|
||
|
||
|
||
def test_mask_value_for_dto():
|
||
"""DTO 脱敏不得返回完整原值。"""
|
||
masked = mask_value_for_dto('4510039227')
|
||
assert masked != '4510039227'
|
||
assert '4510' in masked
|
||
|
||
|
||
def test_mapping_display_keeps_business_codes_and_limits_sensitive_text():
|
||
"""关键断言:映射台可辨识 USD/EA/数量,名称和地址仍需受控展开。"""
|
||
assert xfa_mapping_sample_display('WAERS', 'USD')['display_value'] == 'USD'
|
||
assert xfa_mapping_sample_display('MEINS', 'EA')['display_value'] == 'EA'
|
||
assert xfa_mapping_sample_display('MENGE', '30.000')['display_value'] == '30.000'
|
||
restricted = xfa_mapping_sample_display('NAME1', 'Cloud Network Technology Kft.')
|
||
assert restricted['display_policy'] == 'restricted'
|
||
assert restricted['can_reveal'] is True
|
||
assert restricted['display_value'] != 'Cloud Network Technology Kft.'
|
||
|
||
|
||
def test_rejects_doctype_before_parse():
|
||
"""带 DOCTYPE 的 XML 必须拒绝。"""
|
||
unsafe = b'<!DOCTYPE foo><data><HEADER/></data>'
|
||
with pytest.raises(XfaDatasetParseError) as exc:
|
||
parse_xfa_datasets(unsafe)
|
||
assert exc.value.error_code == 'XFA_UNSAFE_XML'
|
||
|
||
|
||
def test_rejects_external_entity_marker():
|
||
"""ENTITY 标记必须在解析前拒绝。"""
|
||
unsafe = b'<?xml version="1.0"?><!DOCTYPE foo [<!ENTITY xxe "x">]><data/>'
|
||
with pytest.raises(XfaDatasetParseError) as exc:
|
||
parse_xfa_datasets(unsafe)
|
||
assert exc.value.error_code == 'XFA_UNSAFE_XML'
|
||
|
||
|
||
def test_xml_depth_limit_enforced():
|
||
"""超过 max_xml_depth 必须失败关闭。"""
|
||
depth = XFA_DEFAULT_MAX_XML_DEPTH + 2
|
||
inner = ''.join(f'<l{i}>' for i in range(depth)) + 'x' + ''.join(f'</l{i}>' for i in reversed(range(depth)))
|
||
xml_bytes = f'<?xml version="1.0"?><data>{inner}</data>'.encode()
|
||
with pytest.raises(XfaDatasetParseError) as exc:
|
||
parse_xfa_datasets(xml_bytes, limits={'max_xml_depth': XFA_DEFAULT_MAX_XML_DEPTH})
|
||
assert exc.value.error_code == 'XFA_XML_DEPTH_EXCEEDED'
|
||
|
||
|
||
def test_xml_node_limit_enforced():
|
||
"""超过 max_xml_nodes 必须失败关闭。"""
|
||
limit = 32
|
||
nodes = ''.join(f'<n{i}>v</n{i}>' for i in range(limit + 5))
|
||
xml_bytes = f'<?xml version="1.0"?><data>{nodes}</data>'.encode()
|
||
with pytest.raises(XfaDatasetParseError) as exc:
|
||
parse_xfa_datasets(xml_bytes, limits={'max_xml_nodes': limit})
|
||
assert exc.value.error_code == 'XFA_XML_NODE_LIMIT_EXCEEDED'
|
||
|
||
|
||
def test_line_row_limit_enforced():
|
||
"""超过 max_line_rows 必须失败关闭。"""
|
||
limit = 4
|
||
rows = ''.join(
|
||
f'<ITEMS><DATA><EBELP>{i:05d}</EBELP></DATA></ITEMS>'
|
||
for i in range(limit + 1)
|
||
)
|
||
xml_bytes = f'<?xml version="1.0"?><data>{rows}</data>'.encode()
|
||
with pytest.raises(XfaDatasetParseError) as exc:
|
||
parse_xfa_datasets(xml_bytes, limits={'max_line_rows': limit})
|
||
assert exc.value.error_code == 'XFA_LINE_ROW_LIMIT_EXCEEDED'
|
||
|
||
|
||
def test_build_xfa_leaf_value_preserves_multiline_matnr():
|
||
"""关键断言:MATNR 五行原文保留换行,lines 可按行回放。"""
|
||
raw = (
|
||
'TEMP-S000218922\n'
|
||
'CAB 42.5U AR1.2 FRAME\n'
|
||
'MPN:D4-A08AR12000001\n'
|
||
'Cust nr:504-006043-001\n'
|
||
'S-ENC-FOBU260702-286'
|
||
)
|
||
leaf = build_xfa_leaf_value(raw)
|
||
assert leaf.raw_value == raw
|
||
assert leaf.normalized_value.startswith('TEMP-S000218922 CAB')
|
||
assert leaf.lines == [
|
||
'TEMP-S000218922',
|
||
'CAB 42.5U AR1.2 FRAME',
|
||
'MPN:D4-A08AR12000001',
|
||
'Cust nr:504-006043-001',
|
||
'S-ENC-FOBU260702-286',
|
||
]
|
||
|
||
|
||
def test_parse_multiline_leaf_keeps_raw_and_lines_on_tree():
|
||
"""关键断言:datasets 解析后叶子节点携带 raw/normalized/lines,DTO 仅暴露 line_count。"""
|
||
xml = """<?xml version="1.0" encoding="UTF-8"?>
|
||
<data>
|
||
<ITEMS>
|
||
<DATA>
|
||
<MATNR>TEMP-S000218922
|
||
CAB 42.5U AR1.2 FRAME
|
||
MPN:D4-A08AR12000001
|
||
Cust nr:504-006043-001
|
||
S-ENC-FOBU260702-286</MATNR>
|
||
<MENGE>30.000</MENGE>
|
||
</DATA>
|
||
</ITEMS>
|
||
</data>
|
||
"""
|
||
analysis = parse_xfa_datasets(xml.encode('utf-8'))
|
||
leaf = read_dataset_leaf_value(analysis, '/data/ITEMS/DATA/MATNR')
|
||
assert leaf is not None
|
||
assert len(leaf.lines) == 5
|
||
assert leaf.lines[0] == 'TEMP-S000218922'
|
||
assert leaf.lines[2].startswith('MPN:')
|
||
assert leaf.lines[4] == 'S-ENC-FOBU260702-286'
|
||
assert '\n' in (read_dataset_value(analysis, '/data/ITEMS/DATA/MATNR') or '')
|
||
dto = serialize_tree_node(analysis.nodes[0], include_values=True)
|
||
# 递归找到 MATNR 节点
|
||
matnr_dto = None
|
||
|
||
def _walk(node):
|
||
nonlocal matnr_dto
|
||
if node.get('local_name') == 'MATNR':
|
||
matnr_dto = node
|
||
return
|
||
for child in node.get('children') or []:
|
||
_walk(child)
|
||
|
||
_walk(dto)
|
||
assert matnr_dto is not None
|
||
assert matnr_dto['line_count'] == 5
|
||
assert 'raw_value' not in matnr_dto
|
||
assert 'lines' not in matnr_dto
|
||
|
||
|
||
def test_read_collection_rows_preserves_multirow_same_field_paths():
|
||
"""关键断言:同集合多行同名字段不得被 leaf_values_by_path 覆盖;正式行读取保留全部行。"""
|
||
xml = """<?xml version="1.0" encoding="UTF-8"?>
|
||
<data>
|
||
<HEADER><EBELN>4510039227</EBELN></HEADER>
|
||
<ITEMS>
|
||
<DATA>
|
||
<EBELP>00010</EBELP>
|
||
<MATNR>TEMP-S000218922</MATNR>
|
||
<MENGE>30.000</MENGE>
|
||
<AMOUNT>26961.60</AMOUNT>
|
||
</DATA>
|
||
<DATA>
|
||
<EBELP>00020</EBELP>
|
||
<MATNR>OTHER-PART</MATNR>
|
||
<MENGE>1.000</MENGE>
|
||
<AMOUNT>10.00</AMOUNT>
|
||
</DATA>
|
||
</ITEMS>
|
||
</data>
|
||
"""
|
||
analysis = parse_xfa_datasets(xml.encode('utf-8'))
|
||
rows = read_collection_rows(analysis, '/data/ITEMS/DATA')
|
||
assert len(rows) == 2
|
||
assert rows[0]['/data/ITEMS/DATA/MATNR'] == 'TEMP-S000218922'
|
||
assert rows[0]['/data/ITEMS/DATA/MENGE'] == '30.000'
|
||
assert rows[1]['/data/ITEMS/DATA/MATNR'] == 'OTHER-PART'
|
||
assert rows[1]['/data/ITEMS/DATA/MENGE'] == '1.000'
|
||
# leaf map 只能保留最后一行,正式提取不得依赖它做多行。
|
||
assert analysis.leaf_values_by_path['/data/ITEMS/DATA/MATNR'] == 'OTHER-PART'
|
||
collections = [item.collection_path for item in analysis.collection_candidates]
|
||
assert collections.count('/data/ITEMS/DATA') == 1
|
||
assert next(item.row_count for item in analysis.collection_candidates if item.collection_path == '/data/ITEMS/DATA') == 2
|
||
|
||
|
||
def test_parser_uses_no_network():
|
||
"""解析过程不得触发网络访问。"""
|
||
with patch('lxml.etree.parse') as mocked:
|
||
parse_xfa_datasets(load_datasets_fixture())
|
||
mocked.assert_not_called()
|