196 lines
7.4 KiB
Python
196 lines
7.4 KiB
Python
"""
|
|
tests/test_shipping_notice_field_adjudication.py
|
|
|
|
用途:锁定后端规则解析与 Dify LLM Observation 的字段级交叉裁决规则。
|
|
依赖:field_adjudication、ShippingOrderDocument 测试替身。
|
|
逻辑:覆盖单侧采用、共识、可信冲突、分差决策及不可变 Observation 审计。
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
from types import SimpleNamespace
|
|
|
|
from app.services.shipping_notice.field_adjudication import (
|
|
adjudicate_order_fields,
|
|
merge_observation_history,
|
|
trusted_required_fields,
|
|
)
|
|
|
|
|
|
def _schema_definition() -> dict:
|
|
"""构造裁决测试使用的显式行字段 Schema。"""
|
|
return {'fields': [
|
|
{
|
|
'field_id': 'part', 'field_code': 'part_number', 'scope': 'line', 'value_type': 'string',
|
|
'enabled': True, 'display_name': '内部料号', 'aliases': ['MPN'],
|
|
'normalizer_key': 'uppercase_trim', 'validator_keys': ['atomic_part_number'],
|
|
},
|
|
{
|
|
'field_id': 'qty', 'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal',
|
|
'enabled': True, 'display_name': '数量', 'aliases': ['Qty'],
|
|
'normalizer_key': 'decimal', 'validator_keys': ['positive_decimal'],
|
|
},
|
|
{
|
|
'field_id': 'reservation', 'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string',
|
|
'enabled': True, 'display_name': '预约单号', 'aliases': ['Reservation ID'],
|
|
'normalizer_key': 'trim', 'validator_keys': ['reservation_id'],
|
|
},
|
|
]}
|
|
|
|
|
|
def _document(document_id: int, text: str):
|
|
"""构造裁决服务所需的最小 Document 测试替身。"""
|
|
return SimpleNamespace(id=document_id, extracted_text=text)
|
|
|
|
|
|
def _raw_order(*, line: dict, document_id: int, evidence: bool = True) -> dict:
|
|
"""构造一条 Dify Observation 输入,可选择是否提供逐字可信证据。"""
|
|
items = []
|
|
if evidence:
|
|
items = [
|
|
{
|
|
"field": "lines[0].part_number",
|
|
"quote": str(line.get("part_number") or ""),
|
|
"document_id": document_id,
|
|
},
|
|
{
|
|
"field": "lines[0].qty",
|
|
"quote": f"Qty {line.get('qty')}",
|
|
"document_id": document_id,
|
|
},
|
|
]
|
|
return {
|
|
"lines": [line],
|
|
"evidence": items,
|
|
"field_confidence": {"part_number": 0.99, "qty": 0.99},
|
|
}
|
|
|
|
|
|
def test_adjudication_uses_verified_dify_when_backend_has_no_table():
|
|
"""只有 Dify 有可信字段时应采用,并保留 Dify Observation。"""
|
|
document = _document(1, "Email D4-A08AR12000002 Qty 10")
|
|
line = {"part_number": "D4-A08AR12000002", "qty": 10}
|
|
raw_order = _raw_order(line=line, document_id=1)
|
|
|
|
result = adjudicate_order_fields(
|
|
{"lines": [line]},
|
|
raw_order=raw_order,
|
|
documents=[document],
|
|
schema_definition=_schema_definition(),
|
|
field_confidence=raw_order["field_confidence"],
|
|
)
|
|
|
|
assert result["summary"]["lines"][0]["part_number"] == "D4-A08AR12000002"
|
|
assert trusted_required_fields(result) is True
|
|
assert {item["source"] for item in result["observations"]} == {"dify_llm"}
|
|
|
|
|
|
def test_adjudication_uses_backend_when_dify_field_is_missing():
|
|
"""Dify 缺内部料号但后端表格列关系明确时,应采用后端 Observation。"""
|
|
document = _document(1, "MPN\tQty\nD4-A08AR12000002\t10")
|
|
raw_order = {"lines": [{"qty": 10}], "evidence": [], "field_confidence": {}}
|
|
|
|
result = adjudicate_order_fields(
|
|
{"lines": [{"qty": 10}]},
|
|
raw_order=raw_order,
|
|
documents=[document],
|
|
schema_definition=_schema_definition(),
|
|
)
|
|
|
|
assert result["summary"]["lines"][0]["part_number"] == "D4-A08AR12000002"
|
|
assert trusted_required_fields(result) is True
|
|
assert any(item["source"] == "backend_table" for item in result["observations"])
|
|
|
|
|
|
def test_adjudication_marks_consensus_without_overwriting_observations():
|
|
"""双方一致时规范值标记 consensus,并同时保留两侧 Observation。"""
|
|
document = _document(1, "MPN\tQty\nD4-A08AR12000002\t10")
|
|
line = {"part_number": "D4-A08AR12000002", "qty": 10}
|
|
raw_order = _raw_order(line=line, document_id=1)
|
|
|
|
result = adjudicate_order_fields(
|
|
{"lines": [line]},
|
|
raw_order=raw_order,
|
|
documents=[document],
|
|
schema_definition=_schema_definition(),
|
|
field_confidence=raw_order["field_confidence"],
|
|
)
|
|
|
|
decision = next(item for item in result["decisions"] if item["field"] == "part_number")
|
|
assert decision["status"] == "consensus"
|
|
assert {item["source"] for item in result["observations"] if item["field"] == "part_number"} == {
|
|
"backend_table",
|
|
"dify_llm",
|
|
}
|
|
|
|
|
|
def test_adjudication_blocks_two_trusted_different_values():
|
|
"""双方证据都可信但字段不同必须生成 blocking 冲突,禁止静默覆盖。"""
|
|
document = _document(
|
|
1,
|
|
"MPN\tQty\nD4-BACKEND\t10\nLLM evidence D4-DIFY Qty 10",
|
|
)
|
|
line = {"part_number": "D4-DIFY", "qty": 10}
|
|
raw_order = _raw_order(line=line, document_id=1)
|
|
|
|
result = adjudicate_order_fields(
|
|
{"lines": [line]},
|
|
raw_order=raw_order,
|
|
documents=[document],
|
|
schema_definition=_schema_definition(),
|
|
field_confidence=raw_order["field_confidence"],
|
|
)
|
|
|
|
conflict = next(item for item in result["conflicts"] if item["field"] == "part_number")
|
|
assert conflict["severity"] == "blocking"
|
|
assert conflict["reason"] == "cross_source_conflict"
|
|
assert trusted_required_fields(result) is False
|
|
|
|
|
|
def test_adjudication_prefers_backend_when_dify_quote_is_unverified():
|
|
"""Dify 无可信 quote 且与后端不同,分差足够时应采用后端值而不产生冲突。"""
|
|
document = _document(1, "MPN\tQty\nD4-BACKEND\t10")
|
|
line = {"part_number": "D4-DIFY", "qty": 10}
|
|
raw_order = _raw_order(line=line, document_id=1, evidence=False)
|
|
|
|
result = adjudicate_order_fields(
|
|
{"lines": [line]},
|
|
raw_order=raw_order,
|
|
documents=[document],
|
|
schema_definition=_schema_definition(),
|
|
field_confidence=raw_order["field_confidence"],
|
|
)
|
|
|
|
assert result["summary"]["lines"][0]["part_number"] == "D4-BACKEND"
|
|
assert not [item for item in result["conflicts"] if item["field"] == "part_number"]
|
|
assert len([item for item in result["observations"] if item["field"] == "part_number"]) == 2
|
|
|
|
|
|
def test_adjudication_builds_multiple_lines_from_backend_only():
|
|
"""Dify 未产出行但后端有多行表格时,应逐行生成规范投影而非丢弃。"""
|
|
document = _document(
|
|
1,
|
|
"MPN\tQty\tReservation ID\nD4-A\t10\t10001\nD4-B\t20\t10002",
|
|
)
|
|
|
|
result = adjudicate_order_fields(
|
|
{"lines": []},
|
|
raw_order={"lines": [], "evidence": []},
|
|
documents=[document],
|
|
schema_definition=_schema_definition(),
|
|
)
|
|
|
|
assert [line["part_number"] for line in result["summary"]["lines"]] == ["D4-A", "D4-B"]
|
|
assert [line["reservation_id"] for line in result["summary"]["lines"]] == ["10001", "10002"]
|
|
assert trusted_required_fields(result) is True
|
|
|
|
|
|
def test_observation_history_is_append_only_and_deduplicated():
|
|
"""重裁决必须保留旧 Observation,并按稳定 ID 去重当前重复项。"""
|
|
old = {"observation_id": "old", "value": "D4-OLD"}
|
|
current = {"observation_id": "current", "value": "D4-NEW"}
|
|
|
|
merged = merge_observation_history([old], [old, current])
|
|
|
|
assert merged == [old, current]
|