Files
syops/backend/tests/test_shipping_customer_shadow_resolution.py
T

178 lines
7.7 KiB
Python

"""
backend/tests/test_shipping_customer_shadow_resolution.py
用途:验证客户影子识别的确定性候选、幂等、质量标签和零副作用边界。
依赖:内存数据库、客户主数据、Candidate/Intake、customer_shadow_resolution。
逻辑:构造真实 ORM 样本后刷新影子结果,断言业务单客户与业务编号始终不被写入。
"""
from __future__ import annotations
from app import db
from app.models import (
FileAsset,
ShippingCase,
ShippingCustomer,
ShippingCustomerIdentifier,
ShippingCustomerShadowResolution,
ShippingNoticeCandidate,
ShippingNoticeDocument,
ShippingNoticeIntake,
User,
)
from app.services.shipping_notice.document_candidate_persist import persist_documents_and_candidates
from app.services.shipping_notice.notice_upload import NoticeIntakeResult
from app.services.shipping_notice.customer_shadow_resolution import (
get_shadow_quality_report,
label_shadow_resolution,
refresh_candidate_shadow_resolution,
)
def _seed_candidate(*, customer_name: str, sender: str = '') -> ShippingNoticeCandidate:
"""创建影子识别所需的最小 Intake、Document 与 Candidate。"""
user = User(username=f'user-{customer_name}-{sender}', email=f'{db.session.query(User).count()}@example.com', role='user')
db.session.add(user)
db.session.flush()
asset = FileAsset(
asset_no=f'FA-{user.id}', owner_user_id=user.id, original_filename='notice.eml',
storage_provider='minio', storage_bucket='test', storage_key=f'notice-{user.id}',
content_hash=f'{user.id:064d}', file_size=1, upload_status='uploaded', lifecycle_status='temporary',
)
db.session.add(asset)
db.session.flush()
intake = ShippingNoticeIntake(
intake_no=f'SNI-{user.id}', asset_id=asset.id, user_id=user.id, parser_version='v6', parse_status='parsed',
structured_result_json={'email': {'from': sender}},
)
db.session.add(intake)
db.session.flush()
document = ShippingNoticeDocument(
intake_id=intake.id, asset_id=asset.id, document_type='attachment', attachment_key='file',
filename='notice.pdf', classification='order_notice', parse_status='parsed',
)
db.session.add(document)
db.session.flush()
candidate = ShippingNoticeCandidate(
candidate_no=f'SNC-{user.id}', intake_id=intake.id, primary_document_id=document.id,
candidate_key='document:1', validation_status='ready',
structured_result_json={'business_summary': {'customer_name': customer_name, 'lines': [{'sku': 'A', 'quantity': 1}]}},
)
db.session.add(candidate)
db.session.flush()
return candidate
def _create_customer(name: str, code: str) -> ShippingCustomer:
"""创建启用客户并返回 ORM 记录。"""
customer = ShippingCustomer(standard_name=name, short_code=code, status='active')
db.session.add(customer)
db.session.flush()
return customer
def test_shadow_resolution_uses_strong_evidence_without_binding_case(app):
"""完整邮箱可形成唯一候选,但业务单客户和业务编号保持为空。"""
with app.app_context():
customer = _create_customer('无锡宇辰有限公司', 'WYC')
db.session.add(ShippingCustomerIdentifier(
customer_id=customer.id, identifier_type='email', raw_value='buyer@wyc.example.com',
normalized_value='buyer@wyc.example.com', status='approved', source='manual', auto_match_allowed=True,
))
candidate = _seed_candidate(customer_name='不稳定解析名称', sender='Buyer <buyer@wyc.example.com>')
case = ShippingCase(case_no='CASE-SHADOW-1')
db.session.add(case)
db.session.flush()
resolution = refresh_candidate_shadow_resolution(candidate)
db.session.commit()
assert resolution.status == 'unique_candidate'
assert resolution.top_customer_id == customer.id
assert resolution.top_score == 100.0
assert case.customer_id is None
assert case.business_no is None
assert get_shadow_quality_report()['auto_bound_count'] == 0
def test_shadow_resolution_reports_ambiguous_and_unmatched(app):
"""同名客户必须保留歧义,无证据样本必须标记未匹配。"""
with app.app_context():
_create_customer('ACME', 'ACA')
_create_customer('ACME', 'ACB')
ambiguous = refresh_candidate_shadow_resolution(_seed_candidate(customer_name='ACME'))
unmatched = refresh_candidate_shadow_resolution(_seed_candidate(customer_name='UNKNOWN'))
db.session.commit()
assert ambiguous.status == 'ambiguous'
assert ambiguous.top_customer_id is None
assert len(ambiguous.candidate_matches_json) == 2
assert unmatched.status == 'unmatched'
assert unmatched.candidate_matches_json == []
def test_shadow_resolution_is_idempotent_and_accuracy_uses_labels_only(app):
"""重算复用同一记录;准确率只统计人工标签且不会反向绑定业务。"""
with app.app_context():
customer = _create_customer('ACME', 'ACM')
candidate = _seed_candidate(customer_name='ACME')
first = refresh_candidate_shadow_resolution(candidate)
first_id = first.id
second = refresh_candidate_shadow_resolution(candidate)
db.session.commit()
assert second.id == first_id
assert db.session.query(ShippingCustomerShadowResolution).count() == 1
labeled = label_shadow_resolution(first_id, customer_id=customer.id, actor_id=None)
report = get_shadow_quality_report()
assert labeled['is_correct'] is True
assert report['labeled_count'] == 1
assert report['correct_count'] == 1
assert report['accuracy'] == 1.0
assert report['auto_bound_count'] == 0
def test_shadow_failure_does_not_block_candidate_persistence(app, monkeypatch):
"""影子规则异常时 Candidate 主流程仍须创建并可提交。"""
with app.app_context():
user = User(username='shadow-safe-user', email='shadow-safe@example.com', role='user')
db.session.add(user)
db.session.flush()
asset = FileAsset(
asset_no='FA-SHADOW-SAFE', owner_user_id=user.id, original_filename='notice.txt',
storage_provider='minio', storage_bucket='test', storage_key='shadow-safe',
content_hash='a' * 64, file_size=10, upload_status='uploaded', lifecycle_status='temporary',
)
db.session.add(asset)
db.session.flush()
intake = ShippingNoticeIntake(
intake_no='SNI-SHADOW-SAFE', asset_id=asset.id, user_id=user.id,
parser_version='v6', parse_status='parsed', structured_result_json={},
)
db.session.add(intake)
db.session.flush()
monkeypatch.setattr(
'app.services.shipping_notice.customer_shadow_resolution.refresh_candidate_shadow_resolution',
lambda _candidate: (_ for _ in ()).throw(RuntimeError('shadow failure')),
)
result = NoticeIntakeResult(
filename='notice.txt', source_type='manual', source_file_type='text/plain',
text='Customer: ACME\nPO: PO-1\nSKU: A001 Qty: 1', content_hash='a' * 64,
file_size=10, status='accepted',
)
persisted = persist_documents_and_candidates(
intake=intake,
parent_asset=asset,
result=result,
run_duplicate_detection=False,
create_candidates=True,
)
db.session.commit()
assert persisted['candidate_count'] == 1
candidate = db.session.query(ShippingNoticeCandidate).one()
assert candidate.validation_status == 'ready'
shadow = db.session.query(ShippingCustomerShadowResolution).one()
assert shadow.status == 'failed'