Merge branch 'hugo-shipping-notice' into dev
# Conflicts: # backend/app/api/__init__.py # backend/app/jobs/types.py # backend/app/models/__init__.py # backend/app/services/schedule/job_registry.py # docs/features/README.md # docs/funclist.md # docs/tec.md # frontend/src/locales/zh-CN/admin.json
This commit is contained in:
commit
dac31e48bd
691 files changed
+53341
-14863
No files matched your search
@@ -0,0 +1,448 @@
|
||||
"""在途调拨预检 API 契约测试(L2,Flask test client)。
|
||||
|
||||
用途:验证 POST /prechecks 创建(含 envelope/权限/参数校验)与
|
||||
GET /prechecks/{id} 进度恢复;无权限 403、未认证 401。
|
||||
依赖:app fixture、client、issue_local_access_token、fakes/repo_fakes。
|
||||
逻辑:API 依赖经 deps._override 注入 Fake 替身;权限按 admin 放行或
|
||||
in_transit_transfer Agent 授权校验。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.models import Agent, User
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
API_PREFIX = "/api/in-transit-transfer"
|
||||
|
||||
|
||||
def _jwt_headers(user: User) -> dict:
|
||||
"""为指定用户签发 Bearer JWT 请求头。"""
|
||||
token = issue_local_access_token(user)
|
||||
return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def transfer_deps(monkeypatch, dbs_ready_file):
|
||||
"""注入 Fake 预检依赖,并预置可执行库存。"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1200")
|
||||
erp.seed_inventory("INV-002", "1200")
|
||||
monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps)
|
||||
return deps
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admin_headers(app):
|
||||
"""创建 admin 用户并返回 JWT 请求头(token 在 app context 内签发)。"""
|
||||
with app.app_context():
|
||||
user = db.session.query(User).filter_by(username="admin").first()
|
||||
if not user:
|
||||
user = User(username="admin", email="admin@example.com", role="admin", status="active")
|
||||
user.set_password("admin")
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
token = issue_local_access_token(user)
|
||||
return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def warehouse_headers(app):
|
||||
"""创建持有 in_transit_transfer Agent 权限的仓库管理员并返回 JWT 请求头。"""
|
||||
with app.app_context():
|
||||
agent = Agent.query.filter_by(agent_code="in_transit_transfer").first()
|
||||
if not agent:
|
||||
agent = Agent(name="在途仓调拨", agent_code="in_transit_transfer",
|
||||
type="api", is_active=True)
|
||||
db.session.add(agent)
|
||||
db.session.flush()
|
||||
user = db.session.query(User).filter_by(username="warehouse").first()
|
||||
if not user:
|
||||
user = User(username="warehouse", email="warehouse@example.com",
|
||||
role="user", status="active")
|
||||
user.set_password("x")
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
if agent not in user.agents:
|
||||
user.agents.append(agent)
|
||||
db.session.commit()
|
||||
token = issue_local_access_token(user)
|
||||
return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def unauthorized_headers(app):
|
||||
"""无 Agent 权限的普通用户 JWT 请求头。"""
|
||||
with app.app_context():
|
||||
user = db.session.query(User).filter_by(username="no_perm").first()
|
||||
if not user:
|
||||
user = User(username="no_perm", email="no_perm@example.com", role="user", status="active")
|
||||
user.set_password("x")
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
token = issue_local_access_token(user)
|
||||
return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
|
||||
|
||||
|
||||
def test_create_precheck_returns_envelope_with_precheck_id(app, client, admin_headers, transfer_deps):
|
||||
"""POST /prechecks → 201 envelope,data 含 precheck_id/hash/计数。"""
|
||||
response = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
})
|
||||
assert response.status_code == 201
|
||||
body = response.get_json()
|
||||
assert body["success"] is True
|
||||
data = body["data"]
|
||||
assert data["precheck_id"].startswith("TPC-")
|
||||
assert data["precheck_hash"].startswith("sha256:")
|
||||
assert data["estimated_erp_write_count"] == 2
|
||||
assert body.get("request_id")
|
||||
|
||||
|
||||
def test_create_precheck_requires_authentication(client):
|
||||
"""未认证 → 401(envelope error)。"""
|
||||
response = client.post(f"{API_PREFIX}/prechecks", json={"source_codes": ["DBS-AWSBI"]})
|
||||
assert response.status_code == 401
|
||||
assert response.get_json()["success"] is False
|
||||
|
||||
|
||||
def test_create_precheck_forbidden_without_agent_permission(client, unauthorized_headers):
|
||||
"""无 in_transit_transfer Agent 权限 → 403。"""
|
||||
response = client.post(f"{API_PREFIX}/prechecks", headers=unauthorized_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
})
|
||||
assert response.status_code == 403
|
||||
assert response.get_json()["error"]["code"] == "AUTH.FORBIDDEN"
|
||||
|
||||
|
||||
def test_create_precheck_warehouse_manager_allowed(app, client, warehouse_headers, transfer_deps):
|
||||
"""持有 Agent 权限的仓库管理员可创建预检。"""
|
||||
response = client.post(f"{API_PREFIX}/prechecks", headers=warehouse_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
})
|
||||
assert response.status_code == 201
|
||||
assert response.get_json()["data"]["precheck_id"]
|
||||
|
||||
|
||||
def test_create_precheck_validates_source_codes(app, client, admin_headers, transfer_deps):
|
||||
"""缺少 source_codes → 400 参数错误。"""
|
||||
response = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={"business_date": "2026-08-06"})
|
||||
assert response.status_code == 400
|
||||
assert response.get_json()["success"] is False
|
||||
|
||||
|
||||
def test_restore_precheck_progress(app, client, admin_headers, transfer_deps):
|
||||
"""GET /prechecks/{id} 恢复预检进度(Hash/明细一致)。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
restored = client.get(f"{API_PREFIX}/prechecks/{created['precheck_id']}", headers=admin_headers)
|
||||
assert restored.status_code == 200
|
||||
body = restored.get_json()["data"]
|
||||
assert body["summary"]["precheck_hash"] == created["precheck_hash"]
|
||||
assert {item["invoice_no"] for item in body["items"]} == {"INV-001", "INV-002"}
|
||||
|
||||
|
||||
def test_restore_unknown_precheck_404(app, client, admin_headers, transfer_deps):
|
||||
"""未知 precheck → 404。"""
|
||||
response = client.get(f"{API_PREFIX}/prechecks/TPC-NOT-EXIST", headers=admin_headers)
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
def test_execute_precheck_creates_run_and_projects_documents(app, client, admin_headers, transfer_deps):
|
||||
"""执行预检 → 201 run_no;GET run 返回 ERP 单号聚合结果。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
executed = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={"invoice_nos": ["INV-001", "INV-002"]},
|
||||
)
|
||||
assert executed.status_code == 201
|
||||
run_no = executed.get_json()["data"]["run_no"]
|
||||
assert run_no.startswith("RUN-")
|
||||
|
||||
run = client.get(f"{API_PREFIX}/runs/{run_no}", headers=admin_headers)
|
||||
assert run.status_code == 200
|
||||
result = run.get_json()["data"]["result"]
|
||||
assert len(result["erp_documents"]) == 2
|
||||
assert result["exceptions"] == []
|
||||
|
||||
|
||||
def test_execute_unconfirmed_precheck_rejected(app, client, admin_headers, transfer_deps):
|
||||
"""预检未就绪时执行 → 400 领域错误,不产生 Run。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
with app.app_context():
|
||||
from app.models import TransferPrecheck
|
||||
|
||||
precheck = TransferPrecheck.query.filter_by(precheck_no=created["precheck_id"]).first()
|
||||
precheck.status = "prechecking"
|
||||
db.session.commit()
|
||||
response = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={"invoice_nos": ["INV-001"]},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert response.get_json()["error"]["code"] == "TRANSFER_CONFIRMATION_REQUIRED"
|
||||
|
||||
|
||||
def test_cancel_run_requires_reason(app, client, admin_headers, transfer_deps):
|
||||
"""取消缺少原因 → 400。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
executed = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={},
|
||||
)
|
||||
run_no = executed.get_json()["data"]["run_no"]
|
||||
response = client.post(f"{API_PREFIX}/runs/{run_no}/cancel", headers=admin_headers, json={"reason": ""})
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_cancel_run_marks_remaining_cancelled(app, client, admin_headers, transfer_deps):
|
||||
"""取消未开始项并保留成功单据。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
executed = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={"invoice_nos": ["INV-001", "INV-002"]},
|
||||
)
|
||||
run_no = executed.get_json()["data"]["run_no"]
|
||||
# 模拟执行中状态:Run 回退 executing,INV-002 尚未开始
|
||||
with app.app_context():
|
||||
from app.models import TransferInvoiceItem, TransferRun
|
||||
|
||||
run = TransferRun.query.filter_by(run_no=run_no).first()
|
||||
run.status = "executing"
|
||||
item = TransferInvoiceItem.query.filter_by(run_id=run.id, invoice_no="INV-002").first()
|
||||
item.status = "ready_to_execute"
|
||||
item.erp_document_no = None
|
||||
db.session.commit()
|
||||
response = client.post(f"{API_PREFIX}/runs/{run_no}/cancel", headers=admin_headers, json={
|
||||
"reason": "货源调整,停止剩余",
|
||||
})
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["data"]["cancelled_count"] == 1
|
||||
|
||||
|
||||
def test_manual_close_item_requires_reason(app, client, admin_headers, transfer_deps):
|
||||
"""人工关闭缺少原因 → 400。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
with app.app_context():
|
||||
from app.models import TransferInvoiceItem
|
||||
|
||||
item = TransferInvoiceItem.query.filter_by(invoice_no="INV-001").first()
|
||||
item.status = "blocked_recoverable"
|
||||
item.result_code = "blocked_quantity_mismatch"
|
||||
db.session.commit()
|
||||
item_id = item.id
|
||||
response = client.post(f"{API_PREFIX}/items/{item_id}/manual-close", headers=admin_headers, json={"reason": ""})
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_manual_close_item_success(app, client, admin_headers, transfer_deps):
|
||||
"""人工关闭成功 → 状态 manually_closed。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
with app.app_context():
|
||||
from app.models import TransferInvoiceItem
|
||||
|
||||
item = TransferInvoiceItem.query.filter_by(invoice_no="INV-001").first()
|
||||
item.status = "blocked_recoverable"
|
||||
item.result_code = "blocked_quantity_mismatch"
|
||||
db.session.commit()
|
||||
item_id = item.id
|
||||
response = client.post(f"{API_PREFIX}/items/{item_id}/manual-close", headers=admin_headers, json={
|
||||
"reason": "线下已处理",
|
||||
})
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["data"]["status"] == "manually_closed"
|
||||
|
||||
|
||||
def test_exceptions_excel_download(app, transfer_db, client, admin_headers, transfer_deps):
|
||||
"""下载异常 Excel → 200 xlsx,且记录访问审计。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
executed = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={"invoice_nos": ["INV-001", "INV-002"]},
|
||||
)
|
||||
run_no = executed.get_json()["data"]["run_no"]
|
||||
response = client.get(f"{API_PREFIX}/runs/{run_no}/exceptions.xlsx", headers=admin_headers)
|
||||
assert response.status_code == 200
|
||||
assert response.content_type.startswith("application/vnd.openxmlformats")
|
||||
with app.app_context():
|
||||
from app.models import TransferAuditEvent
|
||||
|
||||
audit = TransferAuditEvent.query.filter_by(event_type="TRANSFER_EXCEL_DOWNLOADED").first()
|
||||
assert audit is not None
|
||||
assert audit.run_no == run_no
|
||||
|
||||
|
||||
def test_receipt_files_download_records_access_audit(app, transfer_db, client, admin_headers, transfer_deps):
|
||||
"""下载收料来源文件 → 200(zip),记录访问审计。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
executed = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={"invoice_nos": ["INV-001", "INV-002"]},
|
||||
)
|
||||
run_no = executed.get_json()["data"]["run_no"]
|
||||
response = client.get(f"{API_PREFIX}/runs/{run_no}/receipt-files", headers=admin_headers)
|
||||
assert response.status_code == 200
|
||||
assert response.content_type.startswith("application/zip")
|
||||
with app.app_context():
|
||||
from app.models import TransferAuditEvent
|
||||
|
||||
audit = TransferAuditEvent.query.filter_by(event_type="TRANSFER_RECEIPT_FILES_DOWNLOADED").first()
|
||||
assert audit is not None
|
||||
|
||||
|
||||
def test_erp_inventory_download_records_access_audit(app, transfer_db, client, admin_headers, transfer_deps):
|
||||
"""下载预检冻结的 ERP 库存表 → 200(csv),记录访问审计。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
executed = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={"invoice_nos": ["INV-001", "INV-002"]},
|
||||
)
|
||||
run_no = executed.get_json()["data"]["run_no"]
|
||||
response = client.get(f"{API_PREFIX}/runs/{run_no}/erp-inventory", headers=admin_headers)
|
||||
assert response.status_code == 200
|
||||
assert "csv" in response.content_type
|
||||
assert b"INV-001" in response.data
|
||||
with app.app_context():
|
||||
from app.models import TransferAuditEvent
|
||||
|
||||
audit = TransferAuditEvent.query.filter_by(event_type="TRANSFER_ERP_INVENTORY_DOWNLOADED").first()
|
||||
assert audit is not None
|
||||
|
||||
|
||||
def test_downloads_forbidden_without_permission(app, transfer_db, client, admin_headers, unauthorized_headers, transfer_deps):
|
||||
"""无权限下载 → 403(越权检查)。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
executed = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={},
|
||||
)
|
||||
run_no = executed.get_json()["data"]["run_no"]
|
||||
for path in (f"{API_PREFIX}/runs/{run_no}/receipt-files",
|
||||
f"{API_PREFIX}/runs/{run_no}/erp-inventory",
|
||||
f"{API_PREFIX}/runs/{run_no}/exceptions.xlsx"):
|
||||
response = client.get(path, headers=unauthorized_headers)
|
||||
assert response.status_code == 403, path
|
||||
|
||||
|
||||
def test_execute_ignores_forged_warehouse_and_quantity(app, transfer_db, client, admin_headers, transfer_deps):
|
||||
"""前端伪造来源仓/目标仓/数量 → 服务端忽略,使用冻结快照值(防篡改)。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
executed = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={
|
||||
"invoice_nos": ["INV-001"],
|
||||
"from_warehouse": "FAKE-TRANSIT",
|
||||
"to_warehouse": "FAKE-HUB",
|
||||
"quantity": "1",
|
||||
},
|
||||
)
|
||||
assert executed.status_code == 201
|
||||
run_no = executed.get_json()["data"]["run_no"]
|
||||
run = client.get(f"{API_PREFIX}/runs/{run_no}", headers=admin_headers).get_json()["data"]
|
||||
documents = run["result"]["erp_documents"]
|
||||
assert documents[0]["from_warehouse"] == "DBS-TRANSIT" # 冻结值,非伪造值
|
||||
assert documents[0]["to_warehouse"] == "HUB-CN01"
|
||||
assert documents[0]["total_quantity"] == "1200"
|
||||
|
||||
|
||||
def test_backlog_list_and_summary(app, transfer_db, client, admin_headers, transfer_deps):
|
||||
"""待处理异常列表/汇总 API:收纳 blocked 项、排除 success、含老化等级。"""
|
||||
# 预检含 1 个数量不一致(blocked)项
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
with app.app_context():
|
||||
from app.models import TransferInvoiceItem
|
||||
|
||||
item = TransferInvoiceItem.query.filter_by(invoice_no="INV-001").first()
|
||||
item.status = "blocked_recoverable"
|
||||
item.result_code = "blocked_quantity_mismatch"
|
||||
item.result_message = "收料 1200 / ERP 1000"
|
||||
db.session.commit()
|
||||
|
||||
listed = client.get(f"{API_PREFIX}/backlog", headers=admin_headers)
|
||||
assert listed.status_code == 200
|
||||
invoice_set = {entry["invoice_no"] for entry in listed.get_json()["data"]}
|
||||
assert "INV-001" in invoice_set
|
||||
assert "INV-002" not in invoice_set # 可执行项不在待处理池
|
||||
assert listed.get_json()["data"][0]["aging_level"] in {"normal", "warn_3d", "escalate_5d", "critical_7d"}
|
||||
|
||||
summary = client.get(f"{API_PREFIX}/backlog/summary", headers=admin_headers)
|
||||
assert summary.status_code == 200
|
||||
assert summary.get_json()["data"]["recoverable"] >= 1
|
||||
|
||||
|
||||
def test_backlog_forbidden_without_permission(app, transfer_db, client, unauthorized_headers, transfer_deps):
|
||||
"""无权限访问待处理池 → 403(越权检查)。"""
|
||||
response = client.get(f"{API_PREFIX}/backlog", headers=unauthorized_headers)
|
||||
assert response.status_code == 403
|
||||
|
||||
|
||||
def test_list_transfer_sources(app, client, admin_headers):
|
||||
"""来源实例列表:返回启用来源(平台=connector_type,来源实例为执行边界)。"""
|
||||
response = client.get(f"{API_PREFIX}/sources", headers=admin_headers)
|
||||
assert response.status_code == 200
|
||||
sources = response.get_json()["data"]
|
||||
assert isinstance(sources, list)
|
||||
# 测试种子来源 DSV360_AWSDU(dbs)应在列表中
|
||||
assert any(item["source_code"] == "DSV360_AWSDU" for item in sources)
|
||||
for item in sources:
|
||||
assert item["source_code"]
|
||||
assert item["platform"] in {"dbs", "crane"}
|
||||
assert item["enabled"] is True
|
||||
|
||||
|
||||
def test_list_transfer_sources_forbidden(app, client, unauthorized_headers):
|
||||
"""无权限查看来源实例 → 403。"""
|
||||
response = client.get(f"{API_PREFIX}/sources", headers=unauthorized_headers)
|
||||
assert response.status_code == 403
|
||||
|
||||
|
||||
def test_metrics_endpoint(app, transfer_db, client, admin_headers, transfer_deps):
|
||||
"""运营指标端点:返回 Run/明细/待处理/通知失败结构。"""
|
||||
response = client.get(f"{API_PREFIX}/metrics", headers=admin_headers)
|
||||
assert response.status_code == 200
|
||||
data = response.get_json()["data"]
|
||||
assert "runs" in data and "items" in data and "backlog" in data
|
||||
assert "notification_failed_runs" in data["runs"]
|
||||
@@ -0,0 +1,290 @@
|
||||
"""tests/api/test_integration_connector_api.py
|
||||
|
||||
用途:Integration Connector Admin API 契约测试——能力清单、客户端 CRUD、能力调用、
|
||||
interface_id 拒绝、连接测试、鉴权(401/403)。依赖 Fake 网关注入。
|
||||
依赖:app fixture、client、issue_local_access_token、gateway 覆盖注入。
|
||||
逻辑:Admin API 全部 require_admin;能力调用只暴露 Capability,拒绝传 interface_id。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.models import User
|
||||
from app.services.integration_connector.transports.base import IntegrationCallResult
|
||||
from app.services.integration_connector.gateway import set_capability_gateway
|
||||
|
||||
API_PREFIX = "/api/integration-connector"
|
||||
|
||||
|
||||
class FakeTransport:
|
||||
connector_type = "rest"
|
||||
|
||||
def call(self, *, client, interface, request):
|
||||
return {"found": True, "quantity": "100"}
|
||||
|
||||
|
||||
class _FakeGateway:
|
||||
"""纯替代网关:call 直接返回,不解析绑定;transports 供连接测试。"""
|
||||
|
||||
def __init__(self):
|
||||
self.transports = {"rest": FakeTransport()}
|
||||
|
||||
def call(self, **kwargs):
|
||||
return IntegrationCallResult(status="success", data={"found": True, "quantity": None})
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admin_headers(app):
|
||||
with app.app_context():
|
||||
user = db.session.query(User).filter_by(username="admin").first()
|
||||
if not user:
|
||||
user = User(username="admin", email="admin@example.com", role="admin", status="active")
|
||||
user.set_password("admin")
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
token = issue_local_access_token(user)
|
||||
return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def plain_headers(app):
|
||||
with app.app_context():
|
||||
user = db.session.query(User).filter_by(username="plain").first()
|
||||
if not user:
|
||||
user = User(username="plain", email="plain@example.com", role="user", status="active")
|
||||
user.set_password("x")
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
token = issue_local_access_token(user)
|
||||
return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fake_gateway():
|
||||
gw = _FakeGateway()
|
||||
set_capability_gateway(gw)
|
||||
yield gw
|
||||
set_capability_gateway(None)
|
||||
|
||||
|
||||
def _params():
|
||||
return {"invoice_no": "INV-001", "from_warehouse": "W1", "to_warehouse": "W2", "quantity": 100}
|
||||
|
||||
|
||||
def test_list_capabilities(app, client, admin_headers):
|
||||
"""GET /capabilities → 200,含 3 个在途调拨能力。"""
|
||||
response = client.get(f"{API_PREFIX}/capabilities", headers=admin_headers)
|
||||
assert response.status_code == 200
|
||||
names = {item["name"] for item in response.get_json()["data"]}
|
||||
assert {"in_transit_transfer.query_inventory", "in_transit_transfer.create_transfer", "in_transit_transfer.verify_duplicate"}.issubset(names)
|
||||
|
||||
|
||||
def test_create_and_list_client_instance(app, client, admin_headers):
|
||||
"""POST /client-instances → 201;GET 列表可查。"""
|
||||
created = client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "ERP-T100", "name": "T100 ERP", "connector_type": "soap", "environment": "prod",
|
||||
"config_json": {"endpoint": "https://t100.invalid/ws"},
|
||||
})
|
||||
assert created.status_code == 201
|
||||
assert created.get_json()["data"]["code"] == "ERP-T100"
|
||||
|
||||
listed = client.get(f"{API_PREFIX}/client-instances", headers=admin_headers)
|
||||
assert listed.status_code == 200
|
||||
assert any(item["code"] == "ERP-T100" for item in listed.get_json()["data"])
|
||||
|
||||
|
||||
def test_client_instance_invalid_connector_type(app, client, admin_headers):
|
||||
"""非法 connector_type → 400。"""
|
||||
response = client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "X", "name": "x", "connector_type": "ftp",
|
||||
})
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_call_capability_success(app, client, admin_headers, fake_gateway):
|
||||
"""POST /capabilities/<name> → 200 success。"""
|
||||
response = client.post(f"{API_PREFIX}/capabilities/in_transit_transfer.query_inventory",
|
||||
headers=admin_headers, json={"params": _params(), "context": {}})
|
||||
assert response.status_code == 200
|
||||
data = response.get_json()["data"]
|
||||
assert data["status"] == "success"
|
||||
assert data["data"]["found"] is True
|
||||
|
||||
|
||||
def test_call_capability_rejects_interface_id(app, client, admin_headers, fake_gateway):
|
||||
"""body 携带 interface_id → 400(禁止覆盖 Binding)。"""
|
||||
response = client.post(f"{API_PREFIX}/capabilities/in_transit_transfer.query_inventory",
|
||||
headers=admin_headers, json={"params": _params(), "context": {}, "interface_id": "X"})
|
||||
assert response.status_code == 400
|
||||
assert response.get_json()["error"]["code"] == "INTEGRATION.INTERFACE_ID_NOT_ALLOWED"
|
||||
|
||||
|
||||
def test_call_requires_authentication(client):
|
||||
"""未认证 → 401。"""
|
||||
response = client.post(f"{API_PREFIX}/capabilities/in_transit_transfer.query_inventory",
|
||||
json={"params": _params()})
|
||||
assert response.status_code == 401
|
||||
|
||||
|
||||
def test_admin_only_forbidden(app, client, plain_headers):
|
||||
"""普通用户访问 Admin API → 403。"""
|
||||
response = client.get(f"{API_PREFIX}/client-instances", headers=plain_headers)
|
||||
assert response.status_code == 403
|
||||
|
||||
|
||||
def test_client_instance_test_connection(app, client, admin_headers, fake_gateway):
|
||||
"""POST /client-instances/<code>/test → 200(用注入的 Fake transport)。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-A", "name": "client", "connector_type": "rest", "environment": "prod",
|
||||
"config_json": {"endpoint": "https://erp.invalid"},
|
||||
})
|
||||
response = client.post(f"{API_PREFIX}/client-instances/CLI-A/test", headers=admin_headers)
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["data"]["ok"] is True
|
||||
|
||||
|
||||
def test_update_client_instance(app, client, admin_headers):
|
||||
"""PUT /client-instances/<code> → 200,更新 name/config/enabled。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-U", "name": "old", "connector_type": "rest", "environment": "prod",
|
||||
"config_json": {"endpoint": "https://old.invalid"},
|
||||
})
|
||||
response = client.put(f"{API_PREFIX}/client-instances/CLI-U", headers=admin_headers, json={
|
||||
"name": "new", "config_json": {"endpoint": "https://new.invalid"}, "enabled": False,
|
||||
})
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["data"]["name"] == "new"
|
||||
assert response.get_json()["data"]["enabled"] is False
|
||||
assert response.get_json()["data"]["config_json"] == {"endpoint": "https://new.invalid"}
|
||||
|
||||
|
||||
def test_update_interface_definition(app, client, admin_headers):
|
||||
"""PUT /interface-definitions/<code> → 200,更新模板/回传映射/状态。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-I", "name": "cli", "connector_type": "rest", "environment": "prod",
|
||||
"config_json": {},
|
||||
})
|
||||
client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
|
||||
"code": "IF-U", "name": "iface", "client_instance_code": "CLI-I", "connector_type": "rest",
|
||||
"request_spec_json": {"path": "/v1/old"}, "status": "draft",
|
||||
})
|
||||
response = client.put(f"{API_PREFIX}/interface-definitions/IF-U", headers=admin_headers, json={
|
||||
"request_spec_json": {"path": "/v1/new"}, "response_mapping_json": {"qty": "data.quantity"},
|
||||
"status": "published",
|
||||
})
|
||||
assert response.status_code == 200
|
||||
data = response.get_json()["data"]
|
||||
assert data["status"] == "published"
|
||||
assert data["request_spec_json"] == {"path": "/v1/new"}
|
||||
|
||||
|
||||
def test_update_binding(app, client, admin_headers):
|
||||
"""PUT /bindings/<id> → 200,更新映射版本/优先级/状态。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-B", "name": "cli", "connector_type": "rest", "environment": "prod",
|
||||
"config_json": {},
|
||||
})
|
||||
client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
|
||||
"code": "IF-B", "name": "iface", "client_instance_code": "CLI-B", "connector_type": "rest",
|
||||
})
|
||||
created = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={
|
||||
"capability": "in_transit_transfer.query_inventory", "client_instance_code": "CLI-B",
|
||||
"interface_definition_code": "IF-B", "status": "draft",
|
||||
})
|
||||
binding_id = created.get_json()["data"]["id"]
|
||||
response = client.put(f"{API_PREFIX}/bindings/{binding_id}", headers=admin_headers, json={
|
||||
"priority": 5, "mapping_version": 2, "status": "published",
|
||||
})
|
||||
assert response.status_code == 200
|
||||
data = response.get_json()["data"]
|
||||
assert data["priority"] == 5
|
||||
assert data["mapping_version"] == 2
|
||||
assert data["status"] == "published"
|
||||
|
||||
|
||||
def test_update_credential_reference(app, client, admin_headers):
|
||||
"""PUT /credential-references/<code> → 200,更新 secret_ref/status,且不回显明文。"""
|
||||
client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={
|
||||
"code": "CRED-U", "secret_ref": "IN_TRANSIT_ERP_PASSWORD",
|
||||
})
|
||||
response = client.put(f"{API_PREFIX}/credential-references/CRED-U", headers=admin_headers, json={
|
||||
"secret_ref": "IN_TRANSIT_ERP_PASSWORD_ROTATED", "status": "rotating",
|
||||
})
|
||||
assert response.status_code == 200
|
||||
data = response.get_json()["data"]
|
||||
assert data["secret_ref"] == "IN_TRANSIT_ERP_PASSWORD_ROTATED"
|
||||
assert data["status"] == "rotating"
|
||||
assert "secret" not in str(data).lower() or data.get("secret") is None
|
||||
|
||||
|
||||
def test_client_instance_split_columns(app, client, admin_headers):
|
||||
"""POST /client-instances 写 endpoint/timeout_seconds 独立列,config_json 仅存扩展。"""
|
||||
created = client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-COL", "name": "col client", "connector_type": "soap", "environment": "prod",
|
||||
"endpoint": "https://erp.invalid/wsdl", "timeout_seconds": 90,
|
||||
"config_json": {"headers": {"X-Tenant": "A"}},
|
||||
})
|
||||
assert created.status_code == 201
|
||||
data = created.get_json()["data"]
|
||||
assert data["endpoint"] == "https://erp.invalid/wsdl"
|
||||
assert data["timeout_seconds"] == 90
|
||||
assert data["config_json"] == {"headers": {"X-Tenant": "A"}}
|
||||
|
||||
updated = client.put(f"{API_PREFIX}/client-instances/CLI-COL", headers=admin_headers, json={
|
||||
"endpoint": "https://erp2.invalid/wsdl", "timeout_seconds": 120,
|
||||
})
|
||||
assert updated.status_code == 200
|
||||
assert updated.get_json()["data"]["endpoint"] == "https://erp2.invalid/wsdl"
|
||||
assert updated.get_json()["data"]["timeout_seconds"] == 120
|
||||
|
||||
|
||||
def test_interface_definition_split_columns(app, client, admin_headers):
|
||||
"""POST/PUT /interface-definitions 写 http_method/request_path 独立列。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-IF", "name": "cli", "connector_type": "rest", "environment": "prod",
|
||||
"endpoint": "https://erp.invalid",
|
||||
})
|
||||
created = client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
|
||||
"code": "IF-COL", "name": "iface", "client_instance_code": "CLI-IF", "connector_type": "rest",
|
||||
"http_method": "post", "request_path": "/transfer/{invoice_no}",
|
||||
"request_spec_json": {"template": {"qty": "{quantity}"}},
|
||||
})
|
||||
assert created.status_code == 201
|
||||
data = created.get_json()["data"]
|
||||
assert data["http_method"] == "POST"
|
||||
assert data["request_path"] == "/transfer/{invoice_no}"
|
||||
|
||||
updated = client.put(f"{API_PREFIX}/interface-definitions/IF-COL", headers=admin_headers, json={
|
||||
"http_method": "get", "request_path": "/inventory/{invoice_no}",
|
||||
})
|
||||
assert updated.status_code == 200
|
||||
assert updated.get_json()["data"]["http_method"] == "GET"
|
||||
assert updated.get_json()["data"]["request_path"] == "/inventory/{invoice_no}"
|
||||
|
||||
|
||||
def test_binding_split_columns(app, client, admin_headers):
|
||||
"""POST/PUT /bindings 写 context_source_code 独立列并回显。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-BC", "name": "cli", "connector_type": "rest", "environment": "prod",
|
||||
"endpoint": "https://erp.invalid",
|
||||
})
|
||||
client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
|
||||
"code": "IF-BC", "name": "iface", "client_instance_code": "CLI-BC", "connector_type": "rest",
|
||||
})
|
||||
created = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={
|
||||
"capability": "in_transit_transfer.query_inventory",
|
||||
"client_instance_code": "CLI-BC", "interface_definition_code": "IF-BC",
|
||||
"context_source_code": "DBS-AWSBI", "status": "published",
|
||||
})
|
||||
assert created.status_code == 201
|
||||
data = created.get_json()["data"]
|
||||
assert data["context_source_code"] == "DBS-AWSBI"
|
||||
|
||||
updated = client.put(f"{API_PREFIX}/bindings/{data['id']}", headers=admin_headers, json={
|
||||
"context_source_code": "CRANE-SZ",
|
||||
})
|
||||
assert updated.status_code == 200
|
||||
assert updated.get_json()["data"]["context_source_code"] == "CRANE-SZ"
|
||||
+194
-90
@@ -26,38 +26,6 @@ def pytest_configure(config):
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _capture_legacy_order_rows_for_tests(monkeypatch):
|
||||
"""将旧测试夹具的 lines_json 参数暂存为动态订单输入,生产模型不保留该属性。"""
|
||||
from app.models import ShippingNotice
|
||||
|
||||
original_init = ShippingNotice.__init__
|
||||
legacy_headers = ('customer_name', 'customer_code', 'ship_to', 'po_number', 'required_date')
|
||||
|
||||
def _init(self, **kwargs):
|
||||
rows = kwargs.pop('lines_json', None)
|
||||
kwargs.pop('order_lines_migration_status', None)
|
||||
header_values = {key: kwargs.pop(key) for key in legacy_headers if key in kwargs}
|
||||
original_init(self, **kwargs)
|
||||
if rows is not None:
|
||||
self._test_order_rows = [dict(item) for item in rows if isinstance(item, dict)]
|
||||
for key, value in header_values.items():
|
||||
setattr(self, f'_test_{key}', value)
|
||||
|
||||
monkeypatch.setattr(ShippingNotice, '__init__', _init)
|
||||
for key in (*legacy_headers, 'lines_json'):
|
||||
storage = f'_test_{key}' if key != 'lines_json' else '_test_order_rows'
|
||||
monkeypatch.setattr(
|
||||
ShippingNotice,
|
||||
key,
|
||||
property(
|
||||
lambda task, name=storage: getattr(task, name, None),
|
||||
lambda task, value, name=storage: setattr(task, name, value),
|
||||
),
|
||||
raising=False,
|
||||
)
|
||||
|
||||
|
||||
def parse_api_error(body: dict) -> dict:
|
||||
"""
|
||||
从标准 API 错误 envelope 中提取 error 子对象,供测试断言 error.code / details。
|
||||
@@ -193,12 +161,17 @@ def seed_task_inventory_source(
|
||||
*,
|
||||
source_code: str = "DSV360_AWSDU",
|
||||
) -> None:
|
||||
"""测试辅助:为直接构造的 ShippingNotice 写入稳定库存源独立字段。"""
|
||||
"""测试辅助:冻结库存候选集,供库存门禁从正式事实源读取。"""
|
||||
_ensure_test_task_dynamic_order(task)
|
||||
from app.services.shipping_notice.inventory_source_rules import (
|
||||
compute_routing_fingerprint,
|
||||
extract_routing_context,
|
||||
)
|
||||
from app import db
|
||||
from app.models import ShippingOrderTask
|
||||
if not isinstance(task, ShippingOrderTask) and getattr(task, 'order_task_id', None) is None:
|
||||
_ensure_test_task_dynamic_order(task)
|
||||
owner = task if isinstance(task, ShippingOrderTask) else db.session.get(ShippingOrderTask, getattr(task, 'order_task_id', None))
|
||||
if owner is None:
|
||||
raise ValueError('test task must be linked to ShippingOrderTask')
|
||||
from app.services.shipping_notice.inventory_candidate_freeze_service import freeze_candidates_for_task
|
||||
from app.services.shipping_notice.inventory_source_rules import InventorySourceAdjudication
|
||||
from app.services.shipping_notice.inventory_source_repository import (
|
||||
get_database_inventory_source,
|
||||
inventory_sources_runtime_version,
|
||||
@@ -207,35 +180,39 @@ def seed_task_inventory_source(
|
||||
source = get_database_inventory_source(source_code)
|
||||
if not source:
|
||||
raise ValueError(f"unknown inventory source for tests: {source_code}")
|
||||
from app.services.shipping_notice.inventory_source_identity import resolve_inventory_source_identity
|
||||
|
||||
context = extract_routing_context(task)
|
||||
resolution = resolve_inventory_source_identity(source, context)
|
||||
if not resolution.ok or not resolution.identity:
|
||||
raise ValueError(
|
||||
f"cannot seed stable inventory source {source_code}: {resolution.reason or 'identity_incomplete'}"
|
||||
)
|
||||
identity = resolution.identity
|
||||
task.inventory_source_code = identity.source_code
|
||||
task.inventory_connector_type = identity.connector_type
|
||||
task.inventory_warehouse_id = identity.warehouse_id
|
||||
task.inventory_source_status = "resolved"
|
||||
task.inventory_source_method = "rule_exact"
|
||||
task.inventory_source_config_version = inventory_sources_runtime_version()
|
||||
task.inventory_routing_fingerprint = compute_routing_fingerprint(extract_routing_context(task))
|
||||
if getattr(task, '_test_customer_confirmed', False) and not task.order_snapshot_id:
|
||||
if getattr(task, '_test_customer_confirmed', False) and not owner.order_snapshot_id:
|
||||
freeze_test_task_order_snapshot(task)
|
||||
if not owner.order_snapshot_id:
|
||||
raise ValueError('test task must have a frozen order snapshot before inventory source selection')
|
||||
freeze_candidates_for_task(
|
||||
owner,
|
||||
adjudication=InventorySourceAdjudication(
|
||||
status='resolved',
|
||||
method='test_fixture',
|
||||
source_code=str(source.get('source_code') or source_code).strip().upper(),
|
||||
candidates=[source],
|
||||
config_version=inventory_sources_runtime_version(),
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
def freeze_test_task_order_snapshot(task: "ShippingNotice") -> None:
|
||||
"""将旧式直接构造任务迁移为正式动态订单 + 冻结快照,供库存链路测试复用。"""
|
||||
from app.services.shipping_notice.order_freeze_service import freeze_order_snapshot
|
||||
|
||||
if task.order_snapshot_id:
|
||||
from app import db
|
||||
from app.models import ShippingOrderTask
|
||||
if not isinstance(task, ShippingOrderTask) and getattr(task, 'order_task_id', None) is None:
|
||||
_ensure_test_task_dynamic_order(task)
|
||||
owner = task if isinstance(task, ShippingOrderTask) else db.session.get(ShippingOrderTask, getattr(task, 'order_task_id', None))
|
||||
if owner is None:
|
||||
raise ValueError('test task must be linked to ShippingOrderTask')
|
||||
if owner.order_snapshot_id:
|
||||
return
|
||||
rows = list(getattr(task, '_test_order_rows', []) or [])
|
||||
if not rows:
|
||||
lines = task.lines_json if isinstance(task.lines_json, list) else []
|
||||
lines = getattr(task, 'lines_json', None)
|
||||
lines = lines if isinstance(lines, list) else []
|
||||
rows = [
|
||||
{
|
||||
'part_number': row.get('part_number'),
|
||||
@@ -244,33 +221,19 @@ def freeze_test_task_order_snapshot(task: "ShippingNotice") -> None:
|
||||
}
|
||||
for row in lines if isinstance(row, dict)
|
||||
]
|
||||
task._test_order_rows = rows
|
||||
_ensure_test_task_dynamic_order(task)
|
||||
task.order_data_version = int(task.order_data_version or 1)
|
||||
from app import db
|
||||
from app.models import ShippingOrderCustomerMatch, ShippingOrderExtraction
|
||||
owner._test_order_rows = rows
|
||||
_ensure_test_task_dynamic_order(owner)
|
||||
owner.order_data_version = int(owner.order_data_version or 1)
|
||||
from app.models import ShippingOrderExtraction
|
||||
db.session.flush()
|
||||
extraction = db.session.get(ShippingOrderExtraction, task.current_order_extraction_id)
|
||||
customer = getattr(task, 'customer', None)
|
||||
if extraction is not None and customer is not None and ShippingOrderCustomerMatch.query.filter_by(
|
||||
extraction_id=extraction.id, role='bill_to',
|
||||
).one_or_none() is None:
|
||||
db.session.add(ShippingOrderCustomerMatch(
|
||||
extraction_id=extraction.id, role='bill_to',
|
||||
raw_name=customer.standard_name,
|
||||
normalized_name=str(customer.standard_name or '').upper(), status='confirmed',
|
||||
customer_id=customer.id,
|
||||
customer_name_snapshot=customer.standard_name,
|
||||
customer_short_code_snapshot=customer.short_code,
|
||||
identity_fingerprint='r' * 64,
|
||||
identity_rule_version='test.v1', resolution_method='manual',
|
||||
confirmation_reason='测试确认', confirmed_by_id=None,
|
||||
))
|
||||
db.session.flush()
|
||||
extraction = db.session.get(ShippingOrderExtraction, owner.current_order_extraction_id)
|
||||
customer = getattr(owner, 'customer', None)
|
||||
if extraction is not None and customer is not None:
|
||||
confirm_test_customer_resolution(owner, customer=customer, extraction=extraction)
|
||||
freeze_order_snapshot(
|
||||
task,
|
||||
owner,
|
||||
actor_id=None,
|
||||
expected_order_data_version=int(task.order_data_version),
|
||||
expected_order_data_version=int(owner.order_data_version),
|
||||
freeze_mode='auto',
|
||||
auto_freeze_policy={
|
||||
'test_fixture': True,
|
||||
@@ -284,6 +247,47 @@ def freeze_test_task_order_snapshot(task: "ShippingNotice") -> None:
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def confirm_test_customer_resolution(task: "ShippingOrderTask", *, customer, extraction=None) -> None:
|
||||
"""为测试 OT 写入唯一客户真相源,不构造已退役的角色匹配记录。"""
|
||||
from app import db
|
||||
from app.models import ShippingCustomerShadowResolution, ShippingOrderCandidate, ShippingOrderIntake
|
||||
|
||||
candidate = db.session.get(ShippingOrderCandidate, task.candidate_id) if task.candidate_id else None
|
||||
if candidate is None:
|
||||
intake = ShippingOrderIntake(
|
||||
intake_no=f'INT-TEST-RESOLUTION-{task.id}', asset_id=int(task.id),
|
||||
user_id=int(task.user_id), parser_version='test',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no=f'CAND-TEST-RESOLUTION-{task.id}', intake_id=intake.id,
|
||||
primary_document_id=1, candidate_key=f'test-resolution-{task.id}',
|
||||
candidate_status='accepted',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
task.candidate_id = candidate.id
|
||||
if extraction is not None:
|
||||
candidate.order_extraction_id = int(extraction.id)
|
||||
resolution = ShippingCustomerShadowResolution.query.filter_by(candidate_id=candidate.id).one_or_none()
|
||||
if resolution is None:
|
||||
resolution = ShippingCustomerShadowResolution(
|
||||
candidate_id=candidate.id,
|
||||
intake_id=candidate.intake_id,
|
||||
resolution_version='test.v1', status='confirmed',
|
||||
evidence_json=[{'definition_code': 'test_customer', 'normalized_value': customer.short_code}],
|
||||
candidate_matches_json=[{'customer_id': customer.id, 'score': 100}],
|
||||
resolution_context_json={'rule_set': {'checksum': 't' * 64}},
|
||||
identity_rule_set_checksum='t' * 64,
|
||||
)
|
||||
db.session.add(resolution)
|
||||
resolution.status = 'confirmed'
|
||||
resolution.confirmed_customer_id = customer.id
|
||||
resolution.confirmation_method = 'test_fixture'
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def _ensure_test_task_dynamic_order(task: "ShippingNotice") -> None:
|
||||
"""将 RPA 测试显式构造的旧行样例转换为当前测试所需的动态 FieldValue。"""
|
||||
from decimal import Decimal
|
||||
@@ -292,16 +296,35 @@ def _ensure_test_task_dynamic_order(task: "ShippingNotice") -> None:
|
||||
from app.models import (
|
||||
ShippingOrderExtraction, ShippingOrderFieldDecision, ShippingOrderFieldValue,
|
||||
ShippingOrderLine, ShippingOrderSchemaVersion,
|
||||
ShippingOrderTask, User,
|
||||
)
|
||||
from app.services.shipping_notice.order_schema import service as order_schema_service
|
||||
|
||||
if task.current_order_extraction_id is not None:
|
||||
if not isinstance(task, ShippingOrderTask) and getattr(task, 'order_task_id', None) is None:
|
||||
if task.id is None:
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
user_id = getattr(task, 'user_id', None) or db.session.query(User.id).order_by(User.id).first()
|
||||
user_id = user_id[0] if isinstance(user_id, tuple) else user_id
|
||||
owner = ShippingOrderTask(
|
||||
task_no=f'OT-TEST-{task.task_no}',
|
||||
user_id=int(user_id or 1),
|
||||
status='ready',
|
||||
current_step='customer_review',
|
||||
)
|
||||
db.session.add(owner)
|
||||
db.session.flush()
|
||||
task.order_task_id = owner.id
|
||||
owner = task if isinstance(task, ShippingOrderTask) else db.session.get(ShippingOrderTask, task.order_task_id)
|
||||
if owner is None:
|
||||
raise ValueError('test task must be linked to ShippingOrderTask')
|
||||
if owner.current_order_extraction_id is not None:
|
||||
return
|
||||
rows = list(getattr(task, '_test_order_rows', []) or [])
|
||||
if not rows:
|
||||
return
|
||||
if task.id is None:
|
||||
db.session.add(task)
|
||||
if owner.id is None:
|
||||
db.session.add(owner)
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').one_or_none()
|
||||
if version is None:
|
||||
@@ -335,11 +358,11 @@ def _ensure_test_task_dynamic_order(task: "ShippingNotice") -> None:
|
||||
required = {'part_number', 'reservation_id', 'qty'}
|
||||
if not required.issubset(field_ids):
|
||||
raise ValueError('RPA test schema lacks required order business purposes')
|
||||
extraction = ShippingOrderExtraction(task_id=task.id, schema_version_id=version.id, input_snapshot_hash='t' * 64, status='accepted')
|
||||
extraction = ShippingOrderExtraction(task_id=owner.id, schema_version_id=version.id, input_snapshot_hash='t' * 64, status='accepted')
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
for position, row in enumerate(rows):
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=position)
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=position, line_no=position + 1)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
for code in required:
|
||||
@@ -358,7 +381,7 @@ def _ensure_test_task_dynamic_order(task: "ShippingNotice") -> None:
|
||||
value_text=str(value) if code != 'qty' else None, value_decimal=value if code == 'qty' else None,
|
||||
value_json=json_value,
|
||||
))
|
||||
task.current_order_extraction_id = extraction.id
|
||||
owner.current_order_extraction_id = extraction.id
|
||||
db.session.flush()
|
||||
|
||||
|
||||
@@ -425,9 +448,14 @@ def inventory_csv_with_warehouse(
|
||||
|
||||
def batch_rpa_item_identity(task: "ShippingNotice") -> dict[str, str]:
|
||||
"""构造 batch 成功回调 item 须携带的 Source/Warehouse 身份字段。"""
|
||||
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
|
||||
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
|
||||
|
||||
source_code = next(iter(task_frozen_inventory_source_codes(task)), '')
|
||||
source = get_database_inventory_source(source_code) or {}
|
||||
return {
|
||||
"source_code": str(task.inventory_source_code or ""),
|
||||
"warehouse_id": str(task.inventory_warehouse_id or ""),
|
||||
"source_code": str(source_code or ""),
|
||||
"warehouse_id": str(source.get("fixed_warehouse_id") or ""),
|
||||
}
|
||||
|
||||
|
||||
@@ -464,6 +492,11 @@ def rpa_callback_payload(
|
||||
status: str = "success",
|
||||
) -> dict:
|
||||
"""构造通过单源 RPA v2 身份/run_no 校验的最小成功 payload。"""
|
||||
from app.services.shipping_notice.inventory_source_repository import get_database_inventory_source
|
||||
from app.services.shipping_notice.stp_inventory_freeze import task_frozen_inventory_source_codes
|
||||
|
||||
source_code = next(iter(task_frozen_inventory_source_codes(task)), '')
|
||||
source = get_database_inventory_source(source_code) or {}
|
||||
return {
|
||||
"schema_version": "shipping_inventory_rpa.v2",
|
||||
"callback_id": f"test-callback:{run_no}",
|
||||
@@ -472,8 +505,8 @@ def rpa_callback_payload(
|
||||
"file_path": str(file_path),
|
||||
"run_no": run_no,
|
||||
"source_run_no": run_no,
|
||||
"source_code": task.inventory_source_code,
|
||||
"warehouse_id": task.inventory_warehouse_id,
|
||||
"source_code": source_code,
|
||||
"warehouse_id": str(source.get("fixed_warehouse_id") or ""),
|
||||
"attempt_no": 1,
|
||||
"lease_token": "test-lease-token",
|
||||
"candidate_set_id": 1,
|
||||
@@ -651,6 +684,77 @@ def client(app):
|
||||
return app.test_client()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def dbs_ready_file() -> dict:
|
||||
"""当日 ready 收料全量文件(DBS-AWSBI),含重复 Invoice 多行。"""
|
||||
return {
|
||||
"source_code": "DBS-AWSBI",
|
||||
"business_date": "2026-08-06",
|
||||
"file_purpose": "receipt",
|
||||
"file_no": "REC-20260806-001",
|
||||
"file_version": "v3",
|
||||
"checksum": "d" * 64,
|
||||
"status": "ready",
|
||||
"rows": [
|
||||
{"sheet": "Receipt", "row_no": 10, "invoice_no": "INV-001", "material_no": "MAT-001",
|
||||
"material_name": "连接器组件", "specification": "A 型 / 24PIN",
|
||||
"receipt_date": "2026-08-05", "receipt_quantity": "500", "source_code": "DBS-AWSBI"},
|
||||
{"sheet": "Receipt", "row_no": 11, "invoice_no": "INV-001", "material_no": "MAT-001",
|
||||
"material_name": "连接器组件", "specification": "A 型 / 24PIN",
|
||||
"receipt_date": "2026-08-05", "receipt_quantity": "700", "source_code": "DBS-AWSBI"},
|
||||
{"sheet": "Receipt", "row_no": 20, "invoice_no": "INV-002", "material_no": "MAT-002",
|
||||
"material_name": "控制器组件", "specification": "标准型 / 48V",
|
||||
"receipt_date": "2026-08-05", "receipt_quantity": "1200", "source_code": "DBS-AWSBI"},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def crane_ready_file() -> dict:
|
||||
"""当日 ready 收料全量文件(CRANE-SZ),独立来源。"""
|
||||
return {
|
||||
"source_code": "CRANE-SZ",
|
||||
"business_date": "2026-08-06",
|
||||
"file_purpose": "receipt",
|
||||
"file_no": "REC-20260806-002",
|
||||
"file_version": "v4",
|
||||
"checksum": "c" * 64,
|
||||
"status": "ready",
|
||||
"rows": [
|
||||
{"sheet": "Inbound", "row_no": 5, "invoice_no": "INV-008", "material_no": "MAT-200",
|
||||
"material_name": "传感器模组", "specification": "SZ-8 / IP67",
|
||||
"receipt_date": "2026-08-05", "receipt_quantity": "600", "source_code": "CRANE-SZ"},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def same_day_receipt_file() -> dict:
|
||||
"""含业务日期当天收料的文件;这些 Invoice 必须标记 not_matured。"""
|
||||
return {
|
||||
"source_code": "DBS-AWSSG",
|
||||
"business_date": "2026-08-06",
|
||||
"file_purpose": "receipt",
|
||||
"file_no": "REC-20260806-003",
|
||||
"file_version": "v2",
|
||||
"checksum": "s" * 64,
|
||||
"status": "ready",
|
||||
"rows": [
|
||||
{"sheet": "Receipt", "row_no": 3, "invoice_no": "INV-041", "material_no": "MAT-041",
|
||||
"material_name": "连接器组件", "specification": "C 型",
|
||||
"receipt_date": "2026-08-06", "receipt_quantity": "400", "source_code": "DBS-AWSSG"},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def transfer_db(app):
|
||||
"""请求 app 后返回 db 实例;表由 create_all/drop_all 随 app 生命周期隔离。"""
|
||||
from app import db
|
||||
|
||||
return db
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admin_headers():
|
||||
return {
|
||||
|
||||
@@ -0,0 +1,101 @@
|
||||
"""在途调拨预检 Job Handler 测试(L1)。
|
||||
|
||||
用途:验证 in_transit_transfer_precheck JobType 已注册、handler 能驱动
|
||||
precheck_service 落库更新预检状态;缺失 precheck 时报错。
|
||||
依赖:app fixture、transfer_db、fakes/repo_fakes、jobs.handlers。
|
||||
逻辑:直接调用 handler 函数(不经过 Worker 队列),payload 携带 precheck_id。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import app.jobs.handlers # noqa: F401 —— 触发 @register_handler 注册
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.jobs.registry import get_handler
|
||||
from app.jobs.types import JobType
|
||||
from app.models import TransferInvoiceItem, TransferPrecheck, TransferRun
|
||||
from app.services.in_transit_transfer.precheck_service import create_precheck
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def transfer_deps(monkeypatch, dbs_ready_file):
|
||||
"""注入 Fake 依赖并预置库存。"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1200")
|
||||
erp.seed_inventory("INV-002", "1200")
|
||||
monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps)
|
||||
return deps
|
||||
|
||||
|
||||
def test_precheck_job_type_registered():
|
||||
"""in_transit_transfer_precheck handler 必须注册于 JobType 注册表。"""
|
||||
handler = get_handler(JobType.TRANSFER_PRECHECK)
|
||||
assert handler is not None
|
||||
|
||||
|
||||
def test_precheck_job_handler_runs_and_updates_precheck(transfer_db, dbs_ready_file, transfer_deps):
|
||||
"""handler 执行后预检状态进入 ready_to_execute,明细落库。"""
|
||||
summary = create_precheck(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=transfer_deps,
|
||||
)
|
||||
handler = get_handler(JobType.TRANSFER_PRECHECK)
|
||||
handler(None, {"precheck_id": summary.precheck_id})
|
||||
|
||||
precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first()
|
||||
assert precheck is not None
|
||||
assert precheck.status == "ready_to_execute"
|
||||
assert precheck.precheck_hash.startswith("sha256:")
|
||||
assert len(precheck.items) == 2
|
||||
|
||||
|
||||
def test_precheck_job_handler_missing_precheck_raises(transfer_db):
|
||||
"""缺失 precheck_id → handler 抛 RuntimeError(fail-closed)。"""
|
||||
handler = get_handler(JobType.TRANSFER_PRECHECK)
|
||||
with pytest.raises(RuntimeError):
|
||||
handler(None, {"precheck_id": "TPC-NOT-EXIST"})
|
||||
|
||||
|
||||
def test_run_and_item_job_types_registered():
|
||||
"""TRANSFER_RUN / TRANSFER_ITEM handler 必须注册。"""
|
||||
assert get_handler(JobType.TRANSFER_RUN) is not None
|
||||
assert get_handler(JobType.TRANSFER_ITEM) is not None
|
||||
|
||||
|
||||
def test_run_job_handler_executes_precheck(transfer_db, dbs_ready_file, transfer_deps):
|
||||
"""run handler 执行预检并创建成功 Run。"""
|
||||
summary = create_precheck(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=transfer_deps,
|
||||
)
|
||||
handler = get_handler(JobType.TRANSFER_RUN)
|
||||
handler(None, {"precheck_id": summary.precheck_id})
|
||||
|
||||
from app.models import TransferRun as RunModel
|
||||
|
||||
run = db.session.query(RunModel).filter(
|
||||
RunModel.status != "prechecking",
|
||||
).order_by(RunModel.id.desc()).first()
|
||||
assert run is not None
|
||||
assert run.status == "success"
|
||||
|
||||
|
||||
def test_item_job_handler_executes_single_item(transfer_db, dbs_ready_file, transfer_deps):
|
||||
"""item handler 执行单个 Invoice 写入并置 success。"""
|
||||
summary = create_precheck(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=transfer_deps,
|
||||
)
|
||||
precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first()
|
||||
from app.services.in_transit_transfer.orchestrator import create_execution_run
|
||||
|
||||
create_execution_run(precheck, deps=transfer_deps, actor_id=None)
|
||||
item = db.session.query(TransferInvoiceItem).filter_by(
|
||||
invoice_no="INV-001",
|
||||
).first()
|
||||
handler = get_handler(JobType.TRANSFER_ITEM)
|
||||
handler(None, {"item_id": item.id})
|
||||
|
||||
refreshed = db.session.get(TransferInvoiceItem, item.id)
|
||||
assert refreshed.status == "success"
|
||||
assert refreshed.erp_document_no
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
"""在途调拨性能与规模测试(Phase 4,L6 子集)。
|
||||
|
||||
用途:验证大批量 Invoice 预检可完成且不退化(O(n) 汇总),投影读取正常。
|
||||
依赖:transfer_db、precheck_service、repo_fakes。
|
||||
逻辑:300 行收料文件 → 预检 300 个 Invoice;仅断言正确性,耗时打印参考。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.in_transit_transfer.precheck_service import create_precheck, restore_precheck
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
|
||||
def _bulk_file(count: int) -> dict:
|
||||
"""生成 count 行收料文件(每 Invoice 单行)。"""
|
||||
rows = []
|
||||
for index in range(1, count + 1):
|
||||
rows.append({
|
||||
"sheet": "Receipt",
|
||||
"row_no": index,
|
||||
"invoice_no": f"INV-BULK-{index:04d}",
|
||||
"material_no": f"MAT-{index:04d}",
|
||||
"material_name": "批量物料",
|
||||
"specification": "T-100",
|
||||
"receipt_date": "2026-08-05",
|
||||
"receipt_quantity": "100",
|
||||
"source_code": "DBS-AWSBI",
|
||||
})
|
||||
return {
|
||||
"source_code": "DBS-AWSBI", "business_date": "2026-08-06",
|
||||
"file_no": "REC-BULK", "file_version": "v1", "checksum": "b" * 64,
|
||||
"status": "ready", "rows": rows,
|
||||
}
|
||||
|
||||
|
||||
def test_bulk_precheck_300_invoices(transfer_db):
|
||||
"""300 Invoice 预检完成且数量正确;耗时打印参考(不设脆断言)。"""
|
||||
deps, erp, _ = make_transfer_deps(_bulk_file(300))
|
||||
for index in range(1, 301):
|
||||
erp.seed_inventory(f"INV-BULK-{index:04d}", "100")
|
||||
|
||||
started = time.perf_counter()
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
elapsed = time.perf_counter() - started
|
||||
assert summary.counts.executable_count == 300
|
||||
assert summary.counts.file_invoice_count == 300
|
||||
restored = restore_precheck(summary.precheck_id)
|
||||
assert len(restored["items"]) == 300
|
||||
print(f"\n[perf] bulk precheck 300 invoices: {elapsed:.3f}s")
|
||||
@@ -16,7 +16,8 @@ from app import db
|
||||
from app.core.errors import ConflictError, NotFoundError, ValidationError
|
||||
from app.models import (
|
||||
ShippingBusinessSequence,
|
||||
ShippingNotice,
|
||||
ShippingNotice, ShippingOrderTask, ShippingOrderExtraction,
|
||||
ShippingOrderSchema, ShippingOrderSchemaVersion,
|
||||
ShippingCustomer,
|
||||
ShippingCustomerExternalRef,
|
||||
ShippingCustomerIdentifier,
|
||||
@@ -53,6 +54,41 @@ def _context_field() -> ShippingOrderField:
|
||||
return ShippingOrderField.query.filter_by(field_code='bill_to_customer').one()
|
||||
|
||||
|
||||
def _notice_for_customer(customer: ShippingCustomer, task_no: str) -> ShippingNotice:
|
||||
"""按当前事实链构造带客户引用的正式 Notice,避免写入已删除的 Notice.customer_id。"""
|
||||
schema = ShippingOrderSchema(
|
||||
schema_code=f'LIFECYCLE-{task_no}',
|
||||
display_name='生命周期测试 Schema',
|
||||
status='active',
|
||||
)
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id,
|
||||
version=1,
|
||||
status='published',
|
||||
definition_json={'fields': []},
|
||||
checksum='lifecycle-test',
|
||||
)
|
||||
task = ShippingOrderTask(task_no=f'OT-{task_no}', user_id=1, status='completed')
|
||||
db.session.add_all([version, task])
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
task_id=task.id,
|
||||
schema_version_id=version.id,
|
||||
input_snapshot_hash=f'{task_no:0<64}'[:64],
|
||||
status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
task.current_order_extraction_id = extraction.id
|
||||
from tests.conftest import confirm_test_customer_resolution
|
||||
confirm_test_customer_resolution(task, customer=customer, extraction=extraction)
|
||||
notice = ShippingNotice(task_no=task_no, order_task_id=task.id)
|
||||
db.session.add(notice)
|
||||
return notice
|
||||
|
||||
|
||||
def test_unused_customer_can_delete_and_identifiers_are_cascade_only(app):
|
||||
"""仅有识别证据的误建客户可删除,证据不应成为业务阻断引用。"""
|
||||
with app.app_context():
|
||||
@@ -74,15 +110,13 @@ def test_unused_customer_can_delete_and_identifiers_are_cascade_only(app):
|
||||
|
||||
|
||||
@pytest.mark.parametrize('reference_kind', [
|
||||
'notice', 'sequence', 'external_ref', 'import_target', 'import_result', 'shadow_top', 'shadow_manual', 'shadow_match',
|
||||
'sequence', 'external_ref', 'import_target', 'import_result', 'shadow_top', 'shadow_manual', 'shadow_match',
|
||||
])
|
||||
def test_business_and_audit_references_block_delete(app, reference_kind: str):
|
||||
"""每类业务或识别审计引用都必须在统一影响结果中阻断永久删除。"""
|
||||
with app.app_context():
|
||||
customer = _customer()
|
||||
if reference_kind == 'notice':
|
||||
db.session.add(ShippingNotice(task_no='SN-LIFECYCLE', customer_id=customer.id))
|
||||
elif reference_kind == 'sequence':
|
||||
if reference_kind == 'sequence':
|
||||
db.session.add(ShippingBusinessSequence(customer_id=customer.id, business_date=date(2026, 7, 16)))
|
||||
elif reference_kind == 'external_ref':
|
||||
db.session.add(ShippingCustomerExternalRef(customer_id=customer.id, source_system='ERP', legacy_customer_key='C-1'))
|
||||
@@ -201,7 +235,7 @@ def test_delete_rechecks_every_lifecycle_blocker(app, reference_kind: str):
|
||||
with app.app_context():
|
||||
customer = _customer('BLK')
|
||||
if reference_kind == 'notice':
|
||||
db.session.add(ShippingNotice(task_no='SN-DELETE-BLOCK', customer_id=customer.id))
|
||||
_notice_for_customer(customer, 'SN-DELETE-BLOCK')
|
||||
elif reference_kind == 'sequence':
|
||||
db.session.add(ShippingBusinessSequence(customer_id=customer.id, business_date=date(2026, 7, 16)))
|
||||
elif reference_kind == 'external_ref':
|
||||
@@ -267,7 +301,7 @@ def test_delete_blocks_reference_created_after_preview(app):
|
||||
preview = get_customer_lifecycle_impact(customer.id)
|
||||
assert preview['can_delete'] is True
|
||||
|
||||
db.session.add(ShippingNotice(task_no='SN-DELETE-RACE', customer_id=customer.id))
|
||||
_notice_for_customer(customer, 'SN-DELETE-RACE')
|
||||
db.session.commit()
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
delete_customer(customer.id, confirmation_short_code='RCE', reason='误建', actor_id=None)
|
||||
|
||||
@@ -26,7 +26,8 @@ from app.models import (
|
||||
ShippingCustomerMerge,
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingOrderField,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchema, ShippingOrderSchemaVersion, ShippingOrderTask,
|
||||
ShippingOrderExtraction,
|
||||
)
|
||||
from app.services.admin.shipping_customer_lifecycle_service import get_customer_lifecycle_impact
|
||||
from app.services.admin.shipping_customer_merge_service import get_customer_merge_impact, merge_customer
|
||||
@@ -52,6 +53,30 @@ def _context_field() -> ShippingOrderField:
|
||||
return ShippingOrderField.query.filter_by(field_code='bill_to_customer').one()
|
||||
|
||||
|
||||
def _notice_with_customer_history(customer: ShippingCustomer) -> ShippingNotice:
|
||||
"""按 OT→Resolution 构造历史 Notice 客户事实。"""
|
||||
schema = ShippingOrderSchema(schema_code='MERGE-HISTORY', display_name='归并历史测试', status='active')
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published', definition_json={'fields': []}, checksum='merge-history',
|
||||
)
|
||||
task = ShippingOrderTask(task_no='OT-SN-MERGE-HISTORY', user_id=1, status='completed')
|
||||
db.session.add_all([version, task])
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
task_id=task.id, schema_version_id=version.id, input_snapshot_hash='m' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
task.current_order_extraction_id = extraction.id
|
||||
from tests.conftest import confirm_test_customer_resolution
|
||||
confirm_test_customer_resolution(task, customer=customer, extraction=extraction)
|
||||
notice = ShippingNotice(task_no='SN-MERGE-HISTORY', business_no='SRC26071601', order_task_id=task.id)
|
||||
db.session.add(notice)
|
||||
return notice
|
||||
|
||||
|
||||
def test_merge_moves_future_configuration_and_preserves_history(app):
|
||||
"""归并迁移证据和来源键,但业务单、流水及其客户快照始终保留源客户。"""
|
||||
with app.app_context():
|
||||
@@ -71,10 +96,7 @@ def test_merge_moves_future_configuration_and_preserves_history(app):
|
||||
normalized_value='same@example.com', status='approved', source='manual',
|
||||
),
|
||||
ShippingCustomerExternalRef(customer_id=source.id, source_system='ERP', legacy_customer_key='LEGACY-SRC'),
|
||||
ShippingNotice(
|
||||
task_no='SN-MERGE-HISTORY', customer_id=source.id, business_no='SRC26071601',
|
||||
customer_name_snapshot=source.standard_name, customer_short_code_snapshot=source.short_code,
|
||||
),
|
||||
_notice_with_customer_history(source),
|
||||
ShippingBusinessSequence(customer_id=source.id, business_date=date(2026, 7, 16), current_value=1),
|
||||
])
|
||||
db.session.commit()
|
||||
@@ -106,9 +128,12 @@ def test_merge_moves_future_configuration_and_preserves_history(app):
|
||||
assert db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=target_id).count() == 2
|
||||
assert db.session.query(ShippingCustomerExternalRef).filter_by(customer_id=target_id).count() == 1
|
||||
historical_notice = db.session.query(ShippingNotice).filter_by(task_no='SN-MERGE-HISTORY').one()
|
||||
assert historical_notice.customer_id == source_id
|
||||
historical_task = db.session.get(ShippingOrderTask, historical_notice.order_task_id)
|
||||
historical_resolution = ShippingCustomerShadowResolution.query.filter_by(
|
||||
candidate_id=historical_task.candidate_id,
|
||||
).one()
|
||||
assert historical_resolution.confirmed_customer_id == source_id
|
||||
assert historical_notice.business_no == 'SRC26071601'
|
||||
assert historical_notice.customer_short_code_snapshot == 'SRC'
|
||||
assert db.session.query(ShippingBusinessSequence).filter_by(customer_id=source_id).count() == 1
|
||||
merge = db.session.get(ShippingCustomerMerge, result['merge_id'])
|
||||
assert merge is not None and merge.source_customer_id_snapshot == source_id
|
||||
|
||||
@@ -13,7 +13,11 @@ from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import ShippingCustomer, ShippingCustomerIdentifier, ShippingCustomerLifecycleEvent, ShippingNotice
|
||||
from app.models import (
|
||||
ShippingCustomer, ShippingCustomerIdentifier, ShippingCustomerLifecycleEvent, ShippingNotice,
|
||||
ShippingOrderExtraction, ShippingOrderSchema, ShippingOrderSchemaVersion,
|
||||
ShippingOrderTask,
|
||||
)
|
||||
from app.services.admin.shipping_customer_service import (
|
||||
create_customer,
|
||||
create_identifier,
|
||||
@@ -28,6 +32,30 @@ def _create_customer(*, name: str = '无锡宇辰有限公司', short_code: str
|
||||
return create_customer({'standard_name': name, 'short_code': short_code}, actor_id=None)
|
||||
|
||||
|
||||
def _notice_for_customer(customer_id: int) -> ShippingNotice:
|
||||
"""按正式客户事实链创建 Notice,列表统计不得依赖已删除的 Notice.customer_id。"""
|
||||
schema = ShippingOrderSchema(schema_code='CUSTOMER-LIST', display_name='客户列表测试', status='active')
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published', definition_json={'fields': []}, checksum='customer-list',
|
||||
)
|
||||
task = ShippingOrderTask(task_no='OT-CUSTOMER-LIST', user_id=1, status='completed')
|
||||
db.session.add_all([version, task])
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
task_id=task.id, schema_version_id=version.id, input_snapshot_hash='c' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
task.current_order_extraction_id = extraction.id
|
||||
from tests.conftest import confirm_test_customer_resolution
|
||||
confirm_test_customer_resolution(task, customer=db.session.get(ShippingCustomer, customer_id), extraction=extraction)
|
||||
notice = ShippingNotice(task_no='SN-COUNT-1', order_task_id=task.id)
|
||||
db.session.add(notice)
|
||||
return notice
|
||||
|
||||
|
||||
def test_customer_short_code_is_normalized_and_unique(app):
|
||||
"""简码统一转大写,且标准化后重复必须返回冲突。"""
|
||||
with app.app_context():
|
||||
@@ -219,7 +247,7 @@ def test_customer_list_returns_preaggregated_reference_counts(app):
|
||||
"""列表返回业务单和识别证据数量,避免管理端逐客户补查。"""
|
||||
with app.app_context():
|
||||
customer = _create_customer()
|
||||
db.session.add(ShippingNotice(task_no='SN-COUNT-1', customer_id=customer['id']))
|
||||
_notice_for_customer(customer['id'])
|
||||
db.session.add(ShippingCustomerIdentifier(
|
||||
customer_id=customer['id'],
|
||||
identifier_type='name_alias',
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
"""在途仓自动调拨 Agent 领域测试包。"""
|
||||
@@ -0,0 +1,44 @@
|
||||
"""在途调拨测试断言辅助。
|
||||
|
||||
用途:统一断言外部调用次数、审计字段完整率与 Hash 可复算。
|
||||
依赖:fakes.ErpCallRecord。
|
||||
逻辑:所有副作用断言优先读 Fake 的 call log,不猜测实现内部状态。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
from tests.services.in_transit_transfer.fakes import ErpCallRecord, FakeERP
|
||||
|
||||
|
||||
def assert_erp_calls(erp: FakeERP, expected: int, *, invoice_no: str | None = None) -> None:
|
||||
"""断言 ERP 调用次数(可按 Invoice 过滤)。"""
|
||||
calls = erp.calls(invoice_no=invoice_no)
|
||||
assert len(calls) == expected, f"expected {expected} ERP calls, got {len(calls)}: {calls}"
|
||||
|
||||
|
||||
def assert_erp_write_zero(erp: FakeERP) -> None:
|
||||
"""断言没有任何 ERP 写调用(fail-closed 场景通用断言)。"""
|
||||
writes = erp.write_calls()
|
||||
assert not writes, f"unexpected ERP write calls: {writes}"
|
||||
|
||||
|
||||
def assert_call_fields(record: ErpCallRecord) -> None:
|
||||
"""断言单次 ERP 调用携带全部必需追踪字段。"""
|
||||
assert record.operation_id
|
||||
assert record.invoice_no
|
||||
assert record.erp_org
|
||||
assert record.from_warehouse
|
||||
assert record.to_warehouse
|
||||
assert isinstance(record.quantity, Decimal)
|
||||
assert record.call_seq > 0
|
||||
assert record.returned_status
|
||||
|
||||
|
||||
def assert_audit_complete(event: dict[str, Any]) -> None:
|
||||
"""断言一条审计事件字段完整(操作者、关联、前后快照、Hash)。"""
|
||||
for key in ("event_type", "aggregate_type", "aggregate_id", "actor_type", "operation_id",
|
||||
"request_id", "before_hash", "after_hash", "event_hash"):
|
||||
assert event.get(key), f"audit event missing {key}: {event}"
|
||||
@@ -0,0 +1,39 @@
|
||||
"""在途调拨测试固定夹具:时钟、收料文件样例、外部替身与数据库隔离。
|
||||
|
||||
用途:为 tests/services/in_transit_transfer 提供与 TDD 文档一致的固定输入
|
||||
(fixed_clock 默认 2026-08-06 09:00:00+08:00、dbs/crane ready 文件、
|
||||
same_day_receipt_file),并组装 FakeERP/FakeRPA/FakeWeCom。
|
||||
依赖:根 tests/conftest 的 app fixture(SQLite 内存库)、fakes 模块。
|
||||
逻辑:纯单元用例(marker pure_unit 且未请求 app)不创建 Flask/DB;
|
||||
请求 transfer_db 的用例复用 app fixture 的 create_all/drop_all 隔离。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.services.in_transit_transfer.fakes import FakeClock, FakeERP, FakeRPA, FakeWeCom
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fixed_clock() -> FakeClock:
|
||||
"""固定时钟:默认 2026-08-06 09:00:00+08:00(业务日 T=2026-08-06)。"""
|
||||
return FakeClock()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def erp_fake() -> FakeERP:
|
||||
"""FakeERP:账面库存与写响应全部可注入,调用记录可断言。"""
|
||||
return FakeERP()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def rpa_fake() -> FakeRPA:
|
||||
"""FakeRPA:按来源实例独立注入失败/延迟。"""
|
||||
return FakeRPA()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def wecom_fake() -> FakeWeCom:
|
||||
"""FakeWeCom:记录投递事实,可注入附件失败。"""
|
||||
return FakeWeCom()
|
||||
@@ -0,0 +1,63 @@
|
||||
"""在途调拨领域测试的对象工厂。
|
||||
|
||||
用途:集中构造合法 Invoice / 文件行 / 预检 DTO,避免各测试重复内联样板。
|
||||
依赖:标准库(dataclasses / decimal)。
|
||||
逻辑:工厂只生成业务合法的默认值;测试用 override 注入变体。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ReceiptRow:
|
||||
"""单行收料文件记录(含 Sheet/行号追溯证据)。"""
|
||||
|
||||
sheet: str = "Receipt"
|
||||
row_no: int = 1
|
||||
invoice_no: str = "INV-001"
|
||||
material_no: str = "MAT-001"
|
||||
material_name: str = "连接器组件"
|
||||
specification: str = "A 型 / 24PIN"
|
||||
receipt_date: str = "2026-08-05"
|
||||
receipt_quantity: str = "1200"
|
||||
source_code: str = "DBS-AWSBI"
|
||||
|
||||
def to_dict(self) -> dict[str, Any]:
|
||||
"""转 dict,供 parser/aggregator 输入。"""
|
||||
return {
|
||||
"sheet": self.sheet,
|
||||
"row_no": self.row_no,
|
||||
"invoice_no": self.invoice_no,
|
||||
"material_no": self.material_no,
|
||||
"material_name": self.material_name,
|
||||
"specification": self.specification,
|
||||
"receipt_date": self.receipt_date,
|
||||
"receipt_quantity": self.receipt_quantity,
|
||||
"source_code": self.source_code,
|
||||
}
|
||||
|
||||
|
||||
def make_invoice_item(
|
||||
*,
|
||||
invoice_no: str = "INV-001",
|
||||
source_code: str = "DBS-AWSBI",
|
||||
material_no: str = "MAT-001",
|
||||
receipt_quantity: Decimal | str | int = "1200",
|
||||
erp_quantity: Decimal | str | int | None = "1200",
|
||||
receipt_date: str = "2026-08-05",
|
||||
) -> dict[str, Any]:
|
||||
"""构造一条预检明细项(默认严格匹配、可执行)。"""
|
||||
return {
|
||||
"invoice_no": invoice_no,
|
||||
"source_code": source_code,
|
||||
"material_no": material_no,
|
||||
"material_name": "连接器组件",
|
||||
"specification": "A 型 / 24PIN",
|
||||
"receipt_date": receipt_date,
|
||||
"receipt_quantity": Decimal(str(receipt_quantity)),
|
||||
"erp_quantity": None if erp_quantity is None else Decimal(str(erp_quantity)),
|
||||
}
|
||||
@@ -0,0 +1,242 @@
|
||||
"""在途调拨测试的可控外部系统替身:FakeERP / FakeRPA / FakeWeCom / FakeClock。
|
||||
|
||||
用途:让 L0/L1 测试在不接触真实 RPA、ERP、企业微信的前提下覆盖全部业务分支,
|
||||
并把每一次外部调用完整记录到 call log,供断言副作用与调用次数。
|
||||
依赖:标准库(dataclasses / decimal / zoneinfo)。
|
||||
逻辑:FakeERP 以 invoice_no 为业务键维护账面库存与已生成单据;
|
||||
create_transfer 按注入的 scenario 返回 success / duplicate_success /
|
||||
business_failed / timeout_before_commit / timeout_after_commit;
|
||||
所有调用均追加一条 ErpCallRecord(operation_id、invoice_no、erp_org、
|
||||
来源仓、目标仓、数量、调用序号、方法、返回状态、ERP 单号)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from app.services.in_transit_transfer.erp_adapter import ErpWriteTimeoutError
|
||||
|
||||
|
||||
class FakeClock:
|
||||
"""固定时钟:默认 2026-08-06 09:00:00+08:00,可推进业务日。"""
|
||||
|
||||
def __init__(self, iso: str = "2026-08-06T09:00:00+08:00") -> None:
|
||||
self.now_value = datetime.fromisoformat(iso)
|
||||
|
||||
def now(self) -> datetime:
|
||||
"""返回当前固定时刻(带 Asia/Shanghai 时区)。"""
|
||||
return self.now_value
|
||||
|
||||
def advance(self, *, seconds: int = 0, days: int = 0) -> None:
|
||||
"""按秒或天推进固定时钟(保持 Asia/Shanghai 时区)。"""
|
||||
self.now_value = self.now_value.replace(tzinfo=ZoneInfo("Asia/Shanghai"))
|
||||
if seconds:
|
||||
self.now_value = self.now_value + timedelta(seconds=seconds)
|
||||
if days:
|
||||
self.now_value = self.now_value + timedelta(days=days)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ErpCallRecord:
|
||||
"""FakeERP 单次调用的事实记录;测试断言优先读取该记录。"""
|
||||
|
||||
operation_id: str
|
||||
invoice_no: str
|
||||
erp_org: str
|
||||
from_warehouse: str
|
||||
to_warehouse: str
|
||||
quantity: Decimal
|
||||
call_seq: int
|
||||
returned_status: str
|
||||
method: str
|
||||
document_no: str | None = None
|
||||
|
||||
|
||||
class FakeERP:
|
||||
"""可注入账面库存与响应场景的 ERP 替身;每次调用写入 call log。"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.inventory: dict[str, dict[str, Any]] = {}
|
||||
self.documents: dict[str, str] = {}
|
||||
self.verified_posted: dict[str, bool] = {}
|
||||
self.query_scenario: str = "normal"
|
||||
self.write_scenario: str = "success"
|
||||
# 按 Invoice 覆盖写场景(Key=invoice_no);未配置时回落到 write_scenario。
|
||||
self.write_scenarios: dict[str, str] = {}
|
||||
self.call_log: list[ErpCallRecord] = []
|
||||
self._seq = 0
|
||||
|
||||
# -- 控制注入 ----------------------------------------------------------
|
||||
def seed_inventory(self, invoice_no: str, quantity: str | int | Decimal) -> None:
|
||||
"""设置指定 Invoice 的账面库存。"""
|
||||
self.inventory[str(invoice_no).strip()] = {"quantity": Decimal(str(quantity))}
|
||||
|
||||
def seed_document(self, invoice_no: str, document_no: str, *, posted: bool = True) -> None:
|
||||
"""预置某 Invoice 已存在的 ERP 单据(幂等重复场景)。"""
|
||||
self.documents[str(invoice_no).strip()] = document_no
|
||||
self.verified_posted[str(invoice_no).strip()] = posted
|
||||
|
||||
def set_query_scenario(self, scenario: str) -> None:
|
||||
"""normal | inventory_not_found | timeout。"""
|
||||
self.query_scenario = scenario
|
||||
|
||||
def set_write_scenario(self, scenario: str) -> None:
|
||||
"""success | duplicate_success | business_failed | timeout_before_commit | timeout_after_commit。"""
|
||||
self.write_scenario = scenario
|
||||
|
||||
# -- ERP 能力 ----------------------------------------------------------
|
||||
def query_inventory(self, *, operation_id: str, run_no: str, attempt_no: int,
|
||||
invoice_no: str, erp_org: str, from_warehouse: str,
|
||||
to_warehouse: str, quantity: Decimal) -> dict[str, Any]:
|
||||
"""按 Invoice 返回账面库存;timeout 场景抛超时异常。"""
|
||||
self._seq += 1
|
||||
key = str(invoice_no).strip()
|
||||
if self.query_scenario == "timeout":
|
||||
raise TimeoutError(f"query timeout operation_id={operation_id}")
|
||||
if self.query_scenario == "inventory_not_found" or key not in self.inventory:
|
||||
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
|
||||
quantity, self._seq, "inventory_not_found", "query_inventory")
|
||||
self.call_log.append(record)
|
||||
return {"found": False, "quantity": Decimal("0")}
|
||||
qty = self.inventory[key]["quantity"]
|
||||
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
|
||||
quantity, self._seq, "success", "query_inventory")
|
||||
self.call_log.append(record)
|
||||
return {"found": True, "quantity": qty}
|
||||
|
||||
def create_transfer(self, *, operation_id: str, run_no: str, attempt_no: int,
|
||||
invoice_no: str, erp_org: str, from_warehouse: str,
|
||||
to_warehouse: str, quantity: Decimal) -> dict[str, Any]:
|
||||
"""原子建单/审核/过账;按注入场景返回结果并记录调用。"""
|
||||
self._seq += 1
|
||||
key = str(invoice_no).strip()
|
||||
scenario = self.write_scenarios.get(key, self.write_scenario)
|
||||
if scenario == "timeout_before_commit":
|
||||
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
|
||||
quantity, self._seq, "timeout_before_commit", "create_transfer")
|
||||
self.call_log.append(record)
|
||||
raise ErpWriteTimeoutError(
|
||||
"write timeout before commit", committed=False, operation_id=operation_id,
|
||||
)
|
||||
if self.write_scenario == "timeout_after_commit" or scenario == "timeout_after_commit":
|
||||
# 已落单但无法确认:调用方必须投 result_unknown,禁止自动重试。
|
||||
self.documents.setdefault(key, f"TRF-{self._seq:05d}")
|
||||
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
|
||||
quantity, self._seq, "timeout_after_commit", "create_transfer",
|
||||
self.documents[key])
|
||||
self.call_log.append(record)
|
||||
raise ErpWriteTimeoutError(
|
||||
"write timeout after commit", committed=True,
|
||||
document_no=self.documents[key], operation_id=operation_id,
|
||||
)
|
||||
if scenario == "business_failed" or self.write_scenario == "business_failed":
|
||||
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
|
||||
quantity, self._seq, "business_failed", "create_transfer")
|
||||
self.call_log.append(record)
|
||||
return {"status": "business_failed", "code": "ERP_BUSINESS_REJECT", "rolled_back": True}
|
||||
if key in self.documents:
|
||||
document_no = self.documents[key]
|
||||
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
|
||||
quantity, self._seq, "duplicate_success", "create_transfer",
|
||||
document_no)
|
||||
self.call_log.append(record)
|
||||
return {
|
||||
"status": "duplicate_success",
|
||||
"document_no": document_no,
|
||||
"verified_posted": self.verified_posted.get(key, False),
|
||||
}
|
||||
document_no = f"TRF-{self._seq:05d}"
|
||||
self.documents[key] = document_no
|
||||
self.verified_posted[key] = True
|
||||
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
|
||||
quantity, self._seq, "success", "create_transfer", document_no)
|
||||
self.call_log.append(record)
|
||||
return {"status": "success", "document_no": document_no, "posted": True}
|
||||
|
||||
def verify_duplicate(self, *, operation_id: str, run_no: str, attempt_no: int,
|
||||
invoice_no: str, erp_org: str, from_warehouse: str,
|
||||
to_warehouse: str, quantity: Decimal) -> dict[str, Any]:
|
||||
"""核实重复 Invoice 原单状态(已审核过账/未确认)。"""
|
||||
self._seq += 1
|
||||
key = str(invoice_no).strip()
|
||||
if key not in self.documents:
|
||||
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
|
||||
quantity, self._seq, "duplicate_unverified", "verify_duplicate")
|
||||
self.call_log.append(record)
|
||||
return {"status": "duplicate_unverified", "document_no": None, "verified_posted": False}
|
||||
document_no = self.documents[key]
|
||||
posted = self.verified_posted.get(key, False)
|
||||
status = "duplicate_success" if posted else "duplicate_unverified"
|
||||
record = ErpCallRecord(operation_id, key, erp_org, from_warehouse, to_warehouse,
|
||||
quantity, self._seq, status, "verify_duplicate", document_no)
|
||||
self.call_log.append(record)
|
||||
return {"status": status, "document_no": document_no, "verified_posted": posted}
|
||||
|
||||
# -- 断言辅助 ----------------------------------------------------------
|
||||
def calls(self, *, invoice_no: str | None = None) -> list[ErpCallRecord]:
|
||||
"""按 Invoice 过滤调用记录(默认返回全部)。"""
|
||||
if invoice_no is None:
|
||||
return list(self.call_log)
|
||||
return [record for record in self.call_log if record.invoice_no == str(invoice_no).strip()]
|
||||
|
||||
def write_calls(self) -> list[ErpCallRecord]:
|
||||
"""仅返回 create_transfer 调用记录(写副作用断言)。"""
|
||||
return [record for record in self.call_log if record.method == "create_transfer"]
|
||||
|
||||
|
||||
class FakeRPA:
|
||||
"""可独立按来源注入失败/延迟的收料 RPA 替身。"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.triggered: list[dict[str, Any]] = []
|
||||
self.fail_on: set[str] = set()
|
||||
|
||||
def trigger(self, *, source_code: str, business_date: str, reason: str) -> dict[str, Any]:
|
||||
"""触发一次来源收料抓取并记录。"""
|
||||
self.triggered.append({
|
||||
"source_code": source_code,
|
||||
"business_date": business_date,
|
||||
"reason": reason,
|
||||
})
|
||||
if source_code in self.fail_on:
|
||||
return {"ok": False, "error_code": "RPA_TRIGGER_FAILED"}
|
||||
return {"ok": True, "callback_id": f"receipt:{source_code}:{business_date}"}
|
||||
|
||||
|
||||
class FakeWeCom:
|
||||
"""企业微信通知替身;记录投递事实,可注入附件失败。"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.deliveries: list[dict[str, Any]] = []
|
||||
self.attach_fail = False
|
||||
|
||||
def send_summary(self, *, run_no: str, summary: dict[str, Any],
|
||||
recipients: list[str], excel_path: str | None = None) -> dict[str, Any]:
|
||||
"""发送一次汇总通知;附件失败时返回 failed 但不抛异常。"""
|
||||
if self.attach_fail and excel_path:
|
||||
record = {"run_no": run_no, "status": "failed", "error_code": "WECOM_ATTACH_FAILED"}
|
||||
self.deliveries.append(record)
|
||||
return {"status": "failed", "error_code": "WECOM_ATTACH_FAILED"}
|
||||
record = {"run_no": run_no, "status": "success", "recipients": recipients, "excel": excel_path}
|
||||
self.deliveries.append(record)
|
||||
return {"status": "success"}
|
||||
|
||||
|
||||
@dataclass
|
||||
class FakeAuditSink:
|
||||
"""审计落点替身;记录 before/after、Diff、Hash 与关联上下文。"""
|
||||
|
||||
events: list[dict[str, Any]] = field(default_factory=list)
|
||||
|
||||
def append(self, event: dict[str, Any]) -> None:
|
||||
"""追加一条审计事件 dict。"""
|
||||
self.events.append(event)
|
||||
|
||||
|
||||
def utc_now_iso() -> str:
|
||||
"""返回当前 UTC 时间的 ISO 字符串(测试断言用)。"""
|
||||
return datetime.now(timezone.utc).isoformat()
|
||||
@@ -0,0 +1,88 @@
|
||||
"""在途调拨测试的仓库/路由/依赖替身。
|
||||
|
||||
用途:为 file_preparation / precheck_service / API / Job 测试提供可注入的
|
||||
ReceiptFileRepository、RouteResolver 与组装好的 TransferDeps。
|
||||
依赖:app.services.in_transit_transfer(仅类型)、fakes。
|
||||
逻辑:所有替身只返回测试注入的值,不触碰真实存储;
|
||||
TransferDeps.erp 统一使用 ErpAdapter(FakeERP) 以匹配 Adapter 契约。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.in_transit_transfer.erp_adapter import ErpAdapter
|
||||
from app.services.in_transit_transfer.file_preparation import ReadyReceiptFile
|
||||
from app.services.in_transit_transfer.precheck_service import RouteMapping, TransferDeps
|
||||
from tests.services.in_transit_transfer.fakes import FakeERP, FakeRPA
|
||||
|
||||
|
||||
class FakeReceiptFileRepository:
|
||||
"""按 (source_code, business_date) 返回可注入 ready 文件。"""
|
||||
|
||||
def __init__(self, files: dict[tuple[str, str], ReadyReceiptFile] | None = None) -> None:
|
||||
self.files = files or {}
|
||||
self.lookups: list[tuple[str, str]] = []
|
||||
|
||||
def latest_ready_file(self, *, source_code: str, business_date: str) -> ReadyReceiptFile | None:
|
||||
"""记录查询并返回匹配文件。"""
|
||||
self.lookups.append((source_code, business_date))
|
||||
return self.files.get((source_code, business_date))
|
||||
|
||||
|
||||
def make_ready_repo(*files: dict) -> FakeReceiptFileRepository:
|
||||
"""由 fixture 文件 dict 构建仓库;rows 透传为 ReadyReceiptFile.rows。"""
|
||||
repository = FakeReceiptFileRepository()
|
||||
for item in files:
|
||||
repository.files[(item["source_code"], item["business_date"])] = ReadyReceiptFile(
|
||||
source_code=item["source_code"],
|
||||
business_date=item["business_date"],
|
||||
file_no=item["file_no"],
|
||||
file_version=item["file_version"],
|
||||
checksum=item["checksum"],
|
||||
rows=tuple(item["rows"]),
|
||||
)
|
||||
return repository
|
||||
|
||||
|
||||
def make_transfer_deps(
|
||||
*files: dict,
|
||||
erp: FakeERP | None = None,
|
||||
rpa: FakeRPA | None = None,
|
||||
routes: dict[str, RouteMapping] | None = None,
|
||||
) -> tuple[TransferDeps, FakeERP, FakeRPA]:
|
||||
"""组装注入 Fake 的 TransferDeps(erp 统一包装为 ErpAdapter)。
|
||||
|
||||
Returns:
|
||||
(deps, erp_fake, rpa_fake) 元组。
|
||||
"""
|
||||
erp = erp or FakeERP()
|
||||
rpa = rpa or FakeRPA()
|
||||
deps = TransferDeps(
|
||||
file_repository=make_ready_repo(*files),
|
||||
rpa_trigger=rpa,
|
||||
route_resolver=FakeRouteResolver(routes=routes),
|
||||
erp=ErpAdapter(transport=erp, default_org="HX-CN01"),
|
||||
)
|
||||
return deps, erp, rpa
|
||||
|
||||
|
||||
class FakeRouteResolver:
|
||||
"""按来源返回固定路由(ERP 组织/拨出仓/拨入仓)。"""
|
||||
|
||||
def __init__(self, routes: dict[str, RouteMapping] | None = None) -> None:
|
||||
self.routes = routes if routes is not None else {
|
||||
"DBS-AWSBI": RouteMapping(erp_org="HX-CN01", from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01"),
|
||||
"DBS-AWSSG": RouteMapping(erp_org="HX-CN01", from_warehouse="AWSSG-TRANSIT", to_warehouse="HUB-SG"),
|
||||
"CRANE-SZ": RouteMapping(erp_org="HX-CN01", from_warehouse="CRANE-SZ-TRANSIT", to_warehouse="HUB-SZ"),
|
||||
}
|
||||
self.raised_on: set[str] = set()
|
||||
|
||||
def resolve(self, *, source_code: str, invoice_no: str) -> RouteMapping:
|
||||
"""返回来源路由;未配置来源抛 RouteNotResolvedError。"""
|
||||
if source_code in self.raised_on:
|
||||
raise RuntimeError("route resolution failed")
|
||||
mapping = self.routes.get(source_code)
|
||||
if mapping is None:
|
||||
from app.services.in_transit_transfer.precheck_service import RouteNotResolvedError
|
||||
|
||||
raise RouteNotResolvedError(source_code=source_code)
|
||||
return mapping
|
||||
@@ -0,0 +1,97 @@
|
||||
"""在途调拨 MinIO 归档与 Hash 校验测试(Phase 4,L1)。
|
||||
|
||||
用途:验证归档对象写入 MinIO(Fake 替身)并持久化索引记录,
|
||||
归档 Hash 可复算,损坏数据复核失败。
|
||||
依赖:transfer_db、archive、FakeObjectStore。
|
||||
逻辑:归档记录含 provider/bucket/key/sha256;校验重新下载并复算。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import TransferArchive, TransferAuditEvent
|
||||
from app.services.in_transit_transfer.archive import (
|
||||
archive_snapshot,
|
||||
restore_archive_bytes,
|
||||
verify_archive_hash,
|
||||
)
|
||||
|
||||
|
||||
class FakeObjectStore:
|
||||
"""内存对象存储替身(Key → bytes)。"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.objects: dict[str, bytes] = {}
|
||||
|
||||
def put_bytes(self, *, bucket: str, key: str, data: bytes, content_type: str) -> str:
|
||||
"""保存对象并返回对象键。"""
|
||||
self.objects[f"{bucket}/{key}"] = data
|
||||
return key
|
||||
|
||||
def get_bytes(self, *, bucket: str, key: str) -> bytes:
|
||||
"""读取对象字节。"""
|
||||
return self.objects[f"{bucket}/{key}"]
|
||||
|
||||
def delete_object(self, *, bucket: str, key: str) -> None:
|
||||
"""删除对象。"""
|
||||
self.objects.pop(f"{bucket}/{key}", None)
|
||||
|
||||
|
||||
def _sample_data() -> bytes:
|
||||
return b"erp-inventory-snapshot,2026-08-06,INV-001,1200,1200,executable\n"
|
||||
|
||||
|
||||
def test_archive_snapshot_persists_index_and_audit(transfer_db):
|
||||
"""归档后记录 TransferArchive(含 sha256)并写入审计。"""
|
||||
store = FakeObjectStore()
|
||||
data = _sample_data()
|
||||
archive = archive_snapshot(
|
||||
object_type="erp_inventory_snapshot",
|
||||
object_id="TPC-20260806-001",
|
||||
data=data,
|
||||
original_filename="erp-inventory-20260806.csv",
|
||||
content_type="text/csv",
|
||||
object_store=store,
|
||||
bucket="hxops-transfer",
|
||||
)
|
||||
assert archive.sha256 == hashlib.sha256(data).hexdigest()
|
||||
assert archive.storage_provider == "minio"
|
||||
assert archive.object_type == "erp_inventory_snapshot"
|
||||
assert store.objects # 对象已写入存储
|
||||
audit = TransferAuditEvent.query.filter_by(event_type="TRANSFER_ARCHIVED").first()
|
||||
assert audit is not None
|
||||
assert audit.aggregate_id == "TPC-20260806-001"
|
||||
|
||||
|
||||
def test_verify_archive_hash_ok_and_corruption_detected(transfer_db):
|
||||
"""Hash 复算一致;对象损坏 → 复核失败。"""
|
||||
store = FakeObjectStore()
|
||||
data = _sample_data()
|
||||
archive = archive_snapshot(
|
||||
object_type="erp_inventory_snapshot", object_id="OBJ-1", data=data,
|
||||
original_filename="a.csv", content_type="text/csv",
|
||||
object_store=store, bucket="hxops-transfer",
|
||||
)
|
||||
assert verify_archive_hash(archive, object_store=store) is True
|
||||
|
||||
# 篡改存储对象后复核必须失败
|
||||
key = f"{archive.storage_bucket}/{archive.storage_key}"
|
||||
store.objects[key] = data + b"tampered"
|
||||
assert verify_archive_hash(archive, object_store=store) is False
|
||||
|
||||
|
||||
def test_restore_archive_bytes_roundtrip(transfer_db):
|
||||
"""归档对象可恢复为原始字节。"""
|
||||
store = FakeObjectStore()
|
||||
data = _sample_data()
|
||||
archive = archive_snapshot(
|
||||
object_type="erp_inventory_snapshot", object_id="OBJ-2", data=data,
|
||||
original_filename="a.csv", content_type="text/csv",
|
||||
object_store=store, bucket="hxops-transfer",
|
||||
)
|
||||
restored = restore_archive_bytes(archive, object_store=store)
|
||||
assert restored == data
|
||||
@@ -0,0 +1,145 @@
|
||||
"""在途调拨审计完整性测试(L0 纯单元 + 一次 DB 落库冒烟)。
|
||||
|
||||
用途:验证审计快照脱敏(Secret 不进快照/Hash)、Hash 可复算、Diff 语义正确,
|
||||
以及审计事件携带操作者、operation_id、request_id 等关联上下文。
|
||||
依赖:app.services.in_transit_transfer.audit(纯函数)+ transfer_db(模型冒烟)。
|
||||
逻辑:L0 部分不创建 Flask;模型冒烟用例请求 app fixture 验证落库字段。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.in_transit_transfer.audit import (
|
||||
canonical_hash,
|
||||
build_transfer_audit_event,
|
||||
compute_event_hash,
|
||||
sanitize_snapshot,
|
||||
snapshot_diff,
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_canonical_hash_is_deterministic():
|
||||
"""相同快照两次计算 Hash 必须一致(键排序 + 紧凑 JSON)。"""
|
||||
snapshot = {"invoice_no": "INV-001", "quantity": "1200", "org": "HX-CN01"}
|
||||
assert canonical_hash(snapshot) == canonical_hash(snapshot)
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_hash_changes_when_snapshot_changes():
|
||||
"""任一字段变化 Hash 必须变化。"""
|
||||
before = {"invoice_no": "INV-001", "quantity": "1200"}
|
||||
after = {"invoice_no": "INV-001", "quantity": "1201"}
|
||||
assert canonical_hash(before) != canonical_hash(after)
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_hash_ignores_key_order():
|
||||
"""字段顺序不影响 Hash。"""
|
||||
a = {"x": 1, "y": 2}
|
||||
b = {"y": 2, "x": 1}
|
||||
assert canonical_hash(a) == canonical_hash(b)
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_sanitize_snapshot_strips_secrets():
|
||||
"""快照必须剔除密码/Token/密钥等敏感字段,绝不进入 Hash。"""
|
||||
snapshot = {
|
||||
"invoice_no": "INV-001",
|
||||
"password": "P@ssw0rd",
|
||||
"credential": {"api_key": "sk-xxx", "username_ciphertext": "abc"},
|
||||
"webhook_url": "https://hooks.example/secret-token",
|
||||
}
|
||||
clean = sanitize_snapshot(snapshot)
|
||||
serialized = str(clean)
|
||||
assert "P@ssw0rd" not in serialized
|
||||
assert "sk-xxx" not in serialized
|
||||
assert "abc" not in serialized
|
||||
assert "secret-token" not in serialized
|
||||
assert clean["invoice_no"] == "INV-001"
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_snapshot_diff_reports_added_removed_changed():
|
||||
"""Diff 必须区分新增/删除/修改三类变化。"""
|
||||
diff = snapshot_diff(
|
||||
{"invoice_no": "INV-001", "quantity": "1200", "old_key": "x"},
|
||||
{"invoice_no": "INV-001", "quantity": "1100", "new_key": "y"},
|
||||
)
|
||||
assert diff["changed"]["quantity"] == ("1200", "1100")
|
||||
assert diff["removed"] == {"old_key": "x"}
|
||||
assert diff["added"] == {"new_key": "y"}
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_build_event_carries_actor_and_correlation_ids():
|
||||
"""审计事件必须包含 actor、operation_id、request_id 与前后快照 Hash。"""
|
||||
event = build_transfer_audit_event(
|
||||
event_type="TRANSFER_CONFIRMED",
|
||||
aggregate_type="transfer_item",
|
||||
aggregate_id="item-1",
|
||||
run_no="RUN-20260806-001",
|
||||
precheck_no="TPC-20260806-001",
|
||||
invoice_no="INV-001",
|
||||
actor_type="user",
|
||||
actor_id="u-42",
|
||||
actor_role="warehouse_manager",
|
||||
actor_display="李仓储",
|
||||
request_id="req_001",
|
||||
operation_id="op_001",
|
||||
result="success",
|
||||
before={"status": "prechecking"},
|
||||
after={"status": "ready_to_execute"},
|
||||
)
|
||||
assert event.actor_id == "u-42"
|
||||
assert event.operation_id == "op_001"
|
||||
assert event.request_id == "req_001"
|
||||
assert event.run_no == "RUN-20260806-001"
|
||||
assert event.before_hash and event.after_hash and event.event_hash
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_event_hash_recomputable_from_fields():
|
||||
"""审计 Hash 必须可由存储字段复算(Phase 4 Hash 校验基础)。"""
|
||||
event = build_transfer_audit_event(
|
||||
event_type="TRANSFER_EXECUTED",
|
||||
aggregate_type="transfer_item",
|
||||
aggregate_id="item-2",
|
||||
run_no="RUN-20260806-001",
|
||||
invoice_no="INV-002",
|
||||
actor_type="worker",
|
||||
operation_id="op_002",
|
||||
result="success",
|
||||
after={"erp_document_no": "TRF-10001"},
|
||||
)
|
||||
assert compute_event_hash(event) == event.event_hash
|
||||
|
||||
|
||||
def test_audit_event_persists_with_required_fields(transfer_db):
|
||||
"""DB 冒烟:审计事件可落库并回读(含 Hash 与关联字段)。"""
|
||||
event = build_transfer_audit_event(
|
||||
event_type="TRANSFER_CREATED",
|
||||
aggregate_type="transfer_run",
|
||||
aggregate_id="RUN-20260806-001",
|
||||
run_no="RUN-20260806-001",
|
||||
actor_type="user",
|
||||
actor_id="u-1",
|
||||
operation_id="op_003",
|
||||
request_id="req_003",
|
||||
result="success",
|
||||
after={"status": "queued"},
|
||||
)
|
||||
transfer_db.session.add(event)
|
||||
transfer_db.session.commit()
|
||||
|
||||
from app.models import TransferAuditEvent
|
||||
|
||||
loaded = transfer_db.session.get(TransferAuditEvent, event.id)
|
||||
assert loaded is not None
|
||||
assert loaded.run_no == "RUN-20260806-001"
|
||||
assert loaded.operation_id == "op_003"
|
||||
assert loaded.event_hash == event.event_hash
|
||||
# 复算一致率 100% 的落库断言
|
||||
assert compute_event_hash(loaded) == loaded.event_hash
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
"""在途调拨历史待处理池与老化测试(Phase 3,L1)。
|
||||
|
||||
用途:验证待处理池只收纳可恢复/已关闭/结果未知项,并正确计算 3/5/7 天老化等级。
|
||||
依赖:transfer_db、precheck_service、backlog_service、repo_fakes。
|
||||
逻辑:老化按最近一次 Attempt 或明细更新时间计算;result_unknown 单独高风险展示。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import TransferInvoiceItem
|
||||
from app.services.in_transit_transfer.backlog_service import (
|
||||
aging_level_for,
|
||||
backlog_summary,
|
||||
list_backlog,
|
||||
)
|
||||
from app.services.in_transit_transfer.precheck_service import create_precheck
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
|
||||
def _blocked_precheck(dbs_ready_file):
|
||||
"""构造含数量不一致(blocked)项的预检。"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1000") # 1200 ≠ 1000 → blocked
|
||||
erp.seed_inventory("INV-002", "1200") # executable
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
return summary
|
||||
|
||||
|
||||
def test_aging_level_thresholds():
|
||||
"""3/5/7 天老化阈值正确。"""
|
||||
assert aging_level_for(0) == "normal"
|
||||
assert aging_level_for(1) == "normal"
|
||||
assert aging_level_for(2) == "normal"
|
||||
assert aging_level_for(3) == "warn_3d"
|
||||
assert aging_level_for(5) == "escalate_5d"
|
||||
assert aging_level_for(7) == "critical_7d"
|
||||
assert aging_level_for(10) == "critical_7d"
|
||||
|
||||
|
||||
def test_list_backlog_includes_blocked_only(transfer_db, dbs_ready_file):
|
||||
"""待处理池收纳 blocked_recoverable,排除 success / not_matured。"""
|
||||
_blocked_precheck(dbs_ready_file)
|
||||
items = list_backlog()
|
||||
invoice_set = {item.invoice_no for item in items}
|
||||
assert "INV-001" in invoice_set
|
||||
assert "INV-002" not in invoice_set
|
||||
|
||||
|
||||
def test_backlog_aging_from_attempt_age(transfer_db, dbs_ready_file):
|
||||
"""老化等级按明细更新日期计算。"""
|
||||
_blocked_precheck(dbs_ready_file)
|
||||
item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="INV-001").first()
|
||||
item.updated_at = datetime.utcnow() - timedelta(days=6)
|
||||
db.session.commit()
|
||||
items = list_backlog(now=datetime.utcnow())
|
||||
target = next(item_dto for item_dto in items if item_dto.invoice_no == "INV-001")
|
||||
assert target.age_days == 6
|
||||
assert target.aging_level == "escalate_5d"
|
||||
|
||||
|
||||
def test_backlog_summary_counts_and_aging(transfer_db, dbs_ready_file):
|
||||
"""汇总包含可恢复/已关闭/未知计数与老化分级。"""
|
||||
_blocked_precheck(dbs_ready_file)
|
||||
item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="INV-001").first()
|
||||
item.status = "manually_closed"
|
||||
item.manually_closed_reason = "线下处理"
|
||||
db.session.commit()
|
||||
summary = backlog_summary()
|
||||
assert summary.closed_count == 1
|
||||
assert summary.recoverable_count == 0
|
||||
@@ -0,0 +1,59 @@
|
||||
"""在途调拨请求停止(取消)测试(Phase 2,L1)。
|
||||
|
||||
用途:验证停止剩余任务只取消未开始项、已成功单据保留、原因必填。
|
||||
依赖:transfer_db、execution_service、cancellation、repo_fakes。
|
||||
逻辑:取消前快照与原因写入审计;成功后不可取消。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import TransferInvoiceItem, TransferRun
|
||||
from app.services.in_transit_transfer.cancellation import cancel_run
|
||||
from app.services.in_transit_transfer.execution_service import execute_precheck
|
||||
from app.services.in_transit_transfer.precheck_service import create_precheck
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
|
||||
def _ready_precheck(dbs_ready_file):
|
||||
erp = __import__("tests.services.in_transit_transfer.fakes", fromlist=["FakeERP"]).FakeERP()
|
||||
erp.seed_inventory("INV-001", "1200")
|
||||
erp.seed_inventory("INV-002", "1200")
|
||||
deps, _, _ = make_transfer_deps(dbs_ready_file, erp=erp)
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
return deps, summary
|
||||
|
||||
|
||||
def test_cancel_requires_reason(transfer_db, dbs_ready_file):
|
||||
"""取消原因必填;无副作用(不创建执行 Run)。"""
|
||||
deps, summary = _ready_precheck(dbs_ready_file)
|
||||
with pytest.raises(ValidationError):
|
||||
cancel_run(run_no="RUN-X", reason="")
|
||||
# 仅存在预检关联 Run(prechecking),无执行 Run
|
||||
runs = db.session.query(TransferRun).all()
|
||||
assert len(runs) == 1
|
||||
assert runs[0].status != "executing"
|
||||
|
||||
|
||||
def test_cancel_marks_unstarted_items_only(transfer_db, dbs_ready_file):
|
||||
"""取消只作用于未开始项;已成功单据保留。"""
|
||||
deps, summary = _ready_precheck(dbs_ready_file)
|
||||
outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
run = db.session.query(TransferRun).filter_by(run_no=outcome.run_no).first()
|
||||
# 模拟执行中状态:Run 回退到 executing,INV-002 尚未开始,INV-001 保持 success
|
||||
run.status = "executing"
|
||||
item = db.session.query(TransferInvoiceItem).filter_by(
|
||||
run_id=run.id, invoice_no="INV-002",
|
||||
).first()
|
||||
item.status = "ready_to_execute"
|
||||
item.erp_document_no = None
|
||||
db.session.commit()
|
||||
|
||||
result = cancel_run(run_no=outcome.run_no, reason="业务原因")
|
||||
items = {i.invoice_no: i for i in db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all()}
|
||||
assert items["INV-001"].status == "success" # 已成功单据保留
|
||||
assert items["INV-002"].status == "cancelled" # 未开始项取消
|
||||
assert result["cancelled_count"] == 1
|
||||
@@ -0,0 +1,114 @@
|
||||
"""在途调拨 Chat Action 测试(L2 契约,SQLite 内存库)。
|
||||
|
||||
用途:验证 transfer.precheck / transfer.execute 已注册、agent 权限映射正确、
|
||||
stream 产出结构化卡片事件(transfer-precheck / transfer-result)。
|
||||
依赖:app fixture、transfer_db、repo_fakes、action_registry、chat_actions、turn_context。
|
||||
逻辑:直接构造 TurnContext 调用 handler.stream,断言事件载荷与卡片契约。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ForbiddenError
|
||||
from app.services.chat.action_registry import ACTION_AGENT_CODES, ensure_handlers_loaded, resolve_action_handler
|
||||
from app.services.chat.action_schema import TurnInput
|
||||
from app.services.chat.turn_context import TurnContext
|
||||
from app.services.in_transit_transfer.chat_actions import (
|
||||
ACTION_TRANSFER_EXECUTE,
|
||||
ACTION_TRANSFER_PRECHECK,
|
||||
TransferExecuteAction,
|
||||
TransferPrecheckAction,
|
||||
)
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
|
||||
class _Agent:
|
||||
"""带 agent_code 的假 Agent。"""
|
||||
|
||||
def __init__(self, agent_code: str) -> None:
|
||||
self.agent_code = agent_code
|
||||
self.id = 1
|
||||
self.name = "test-agent"
|
||||
|
||||
|
||||
class _User:
|
||||
id = 99
|
||||
|
||||
|
||||
def _ctx(agent_code: str, action_type: str, payload: dict) -> TurnContext:
|
||||
return TurnContext(
|
||||
turn_id="turn-1",
|
||||
run_id="run-1",
|
||||
session_id="session-1",
|
||||
request_id="req-1",
|
||||
user=_User(),
|
||||
agent=_Agent(agent_code),
|
||||
input=TurnInput(type="action", display_text="调拨预检", action_type=action_type, payload=payload),
|
||||
refs={},
|
||||
)
|
||||
|
||||
|
||||
def test_transfer_actions_registered():
|
||||
"""两个 transfer action 必须注册。"""
|
||||
ensure_handlers_loaded()
|
||||
assert "transfer." in ACTION_AGENT_CODES
|
||||
assert ACTION_AGENT_CODES["transfer."] == ("in_transit_transfer",)
|
||||
assert TransferPrecheckAction.action_type == ACTION_TRANSFER_PRECHECK
|
||||
assert TransferExecuteAction.action_type == ACTION_TRANSFER_EXECUTE
|
||||
|
||||
|
||||
def test_transfer_action_agent_permission_enforced():
|
||||
"""transfer.* 仅允许 in_transit_transfer agent;其他 agent 拒绝。"""
|
||||
ensure_handlers_loaded()
|
||||
ctx = _ctx("generic", ACTION_TRANSFER_PRECHECK, {"source_codes": ["DBS-AWSBI"]})
|
||||
with pytest.raises(ForbiddenError):
|
||||
resolve_action_handler(ctx)
|
||||
allowed = _ctx("in_transit_transfer", ACTION_TRANSFER_PRECHECK, {"source_codes": ["DBS-AWSBI"]})
|
||||
assert resolve_action_handler(allowed).action_type == ACTION_TRANSFER_PRECHECK
|
||||
|
||||
|
||||
def test_precheck_action_streams_card(transfer_db, dbs_ready_file, monkeypatch):
|
||||
"""transfer.precheck 流式产出 transfer-precheck 卡片(含明细与来源进度)。"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1200")
|
||||
erp.seed_inventory("INV-002", "1200")
|
||||
monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps)
|
||||
|
||||
events = list(TransferPrecheckAction().stream(_ctx("in_transit_transfer", ACTION_TRANSFER_PRECHECK, {
|
||||
"source_codes": ["DBS-AWSBI"], "business_date": "2026-08-06",
|
||||
})))
|
||||
assert len(events) == 1
|
||||
event = events[0]
|
||||
assert event.event == "message.completed"
|
||||
assert event.data["message_type"] == "transfer-precheck"
|
||||
payload = event.data["payload"]
|
||||
assert payload["kind"] == "precheck"
|
||||
assert payload["summary"]["estimated_erp_write_count"] == 2
|
||||
assert {item["invoice_no"] for item in payload["items"]} == {"INV-001", "INV-002"}
|
||||
assert payload["sources"][0]["source_code"] == "DBS-AWSBI"
|
||||
|
||||
|
||||
def test_execute_action_streams_result_card(transfer_db, dbs_ready_file, monkeypatch):
|
||||
"""transfer.execute 流式产出 transfer-result 卡片(按 ERP 单号聚合)。"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1200")
|
||||
erp.seed_inventory("INV-002", "1200")
|
||||
monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps)
|
||||
|
||||
# 先跑预检拿 precheck_id
|
||||
precheck_events = list(TransferPrecheckAction().stream(_ctx(
|
||||
"in_transit_transfer", ACTION_TRANSFER_PRECHECK,
|
||||
{"source_codes": ["DBS-AWSBI"], "business_date": "2026-08-06"},
|
||||
)))
|
||||
precheck_id = precheck_events[0].data["payload"]["summary"]["precheck_id"]
|
||||
|
||||
execute_events = list(TransferExecuteAction().stream(_ctx(
|
||||
"in_transit_transfer", ACTION_TRANSFER_EXECUTE,
|
||||
{"precheck_id": precheck_id, "invoice_nos": ["INV-001", "INV-002"]},
|
||||
)))
|
||||
assert len(execute_events) == 1
|
||||
payload = execute_events[0].data["payload"]
|
||||
assert payload["kind"] == "result"
|
||||
assert payload["status"] == "success"
|
||||
assert len(payload["run"]["result"]["erp_documents"]) == 2
|
||||
@@ -0,0 +1,145 @@
|
||||
"""在途调拨 DTO 与错误码契约测试(L0 纯单元)。
|
||||
|
||||
用途:验证预检 DTO 字段(范围、数量、预计写入数、过期时间、Hash)、
|
||||
ERP 单据按单号聚合投影,以及一期冻结错误码完整且唯一。
|
||||
依赖:app.services.in_transit_transfer.contracts。
|
||||
逻辑:DTO 为 frozen dataclass,聚合函数按 ERP 单号分组并统计物料数/总数量。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.in_transit_transfer.contracts import (
|
||||
KNOWN_TRANSFER_ERROR_CODES,
|
||||
TRANSFER_PERMISSION_DENIED,
|
||||
TRANSFER_PRECHECK_EXPIRED,
|
||||
TRANSFER_QUANTITY_MISMATCH,
|
||||
TRANSFER_RESULT_UNKNOWN,
|
||||
PrecheckCountsDTO,
|
||||
PrecheckInvoiceItemDTO,
|
||||
PrecheckSummaryDTO,
|
||||
aggregate_erp_documents,
|
||||
require_known_error_code,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
EXPECTED_ERROR_CODES = {
|
||||
"TRANSFER_PERMISSION_DENIED",
|
||||
"TRANSFER_RECEIPT_NOT_MATURED",
|
||||
"TRANSFER_FILE_NOT_READY",
|
||||
"TRANSFER_FILE_SCHEMA_INVALID",
|
||||
"TRANSFER_INVOICE_CONFLICT",
|
||||
"TRANSFER_QUANTITY_MISMATCH",
|
||||
"TRANSFER_ERP_INVENTORY_NOT_FOUND",
|
||||
"TRANSFER_PRECHECK_EXPIRED",
|
||||
"TRANSFER_CONFIRMATION_REQUIRED",
|
||||
"TRANSFER_DUPLICATE_NOT_VERIFIED",
|
||||
"TRANSFER_RESULT_UNKNOWN",
|
||||
"TRANSFER_MANUAL_CLOSE_REASON_REQUIRED",
|
||||
"TRANSFER_CONFIG_PUBLISH_BLOCKED",
|
||||
"TRANSFER_SECRET_NOT_EXPOSED",
|
||||
"TRANSFER_NOTIFICATION_FAILED",
|
||||
}
|
||||
|
||||
|
||||
def test_error_codes_match_tdd_frozen_list():
|
||||
"""TDD §7.3 冻结的 15 个错误码必须全部存在且唯一。"""
|
||||
assert EXPECTED_ERROR_CODES <= KNOWN_TRANSFER_ERROR_CODES
|
||||
assert len(KNOWN_TRANSFER_ERROR_CODES) == len(EXPECTED_ERROR_CODES)
|
||||
|
||||
|
||||
def test_require_known_error_code_accepts_frozen_codes():
|
||||
"""冻结错误码可被契约校验接受。"""
|
||||
require_known_error_code(TRANSFER_QUANTITY_MISMATCH)
|
||||
require_known_error_code(TRANSFER_PRECHECK_EXPIRED)
|
||||
require_known_error_code(TRANSFER_RESULT_UNKNOWN)
|
||||
require_known_error_code(TRANSFER_PERMISSION_DENIED)
|
||||
|
||||
|
||||
def test_require_known_error_code_rejects_unknown():
|
||||
"""未知错误码必须抛 ValueError。"""
|
||||
with pytest.raises(ValueError):
|
||||
require_known_error_code("TRANSFER_NO_SUCH_CODE")
|
||||
|
||||
|
||||
def test_precheck_counts_dto_fields():
|
||||
"""预检计数 DTO 包含文件内/未成熟/已预检/可执行/阻断五类计数。"""
|
||||
counts = PrecheckCountsDTO(
|
||||
file_invoice_count=40, not_matured_count=8, prechecked_count=32,
|
||||
executable_count=27, blocked_count=5,
|
||||
)
|
||||
assert counts.executable_count == 27
|
||||
assert counts.not_matured_count == 8
|
||||
|
||||
|
||||
def test_precheck_summary_dto_carries_estimate_and_hash():
|
||||
"""预检摘要 DTO 必须携带预计调拨数量、预计 ERP 写入数与预检 Hash。"""
|
||||
summary = PrecheckSummaryDTO(
|
||||
precheck_id="TPC-20260806-001",
|
||||
status="ready_to_execute",
|
||||
business_date="2026-08-06",
|
||||
eligible_receipt_date_to="2026-08-05",
|
||||
expires_at="2026-08-06T09:20:00+08:00",
|
||||
counts=PrecheckCountsDTO(40, 8, 32, 27, 5),
|
||||
estimated_transfer_quantity="18460",
|
||||
estimated_erp_write_count=27,
|
||||
precheck_hash="sha256:abc",
|
||||
)
|
||||
assert summary.estimated_transfer_quantity == "18460"
|
||||
assert summary.estimated_erp_write_count == 27
|
||||
assert summary.precheck_hash.startswith("sha256:")
|
||||
|
||||
|
||||
def test_invoice_item_dto_carries_warehouse_and_quantity_pairs():
|
||||
"""预检明细 DTO 必须包含拨出/拨入仓库与数量对(决策 6/7)。"""
|
||||
item = PrecheckInvoiceItemDTO(
|
||||
source_code="DBS-AWSBI", material_no="MAT-001", material_name="连接器组件",
|
||||
specification="A 型 / 24PIN", invoice_no="INV-001",
|
||||
from_warehouse="DBS-TRANSIT", from_quantity=Decimal("1200"),
|
||||
to_warehouse="HUB-CN01", to_quantity=Decimal("1200"),
|
||||
result="executable",
|
||||
)
|
||||
assert item.from_warehouse == "DBS-TRANSIT"
|
||||
assert item.to_warehouse == "HUB-CN01"
|
||||
assert item.from_quantity == item.to_quantity
|
||||
|
||||
|
||||
def test_aggregate_erp_documents_groups_by_document_no():
|
||||
"""结果页按 ERP 单号聚合:物料数、调拨总数量、拨出/拨入仓。"""
|
||||
items = [
|
||||
PrecheckInvoiceItemDTO(
|
||||
source_code="DBS-AWSBI", material_no="MAT-001", material_name="连接器组件",
|
||||
specification="A 型 / 24PIN", invoice_no="INV-001",
|
||||
from_warehouse="DBS-TRANSIT", from_quantity=Decimal("500"),
|
||||
to_warehouse="HUB-CN01", to_quantity=Decimal("500"),
|
||||
result="success", erp_document_no="TRF-10001",
|
||||
),
|
||||
PrecheckInvoiceItemDTO(
|
||||
source_code="DBS-AWSBI", material_no="MAT-002", material_name="控制器组件",
|
||||
specification="标准型 / 48V", invoice_no="INV-002",
|
||||
from_warehouse="DBS-TRANSIT", from_quantity=Decimal("1200"),
|
||||
to_warehouse="HUB-CN01", to_quantity=Decimal("1200"),
|
||||
result="success", erp_document_no="TRF-10001",
|
||||
),
|
||||
PrecheckInvoiceItemDTO(
|
||||
source_code="CRANE-SZ", material_no="MAT-200", material_name="传感器模组",
|
||||
specification="SZ-8 / IP67", invoice_no="INV-008",
|
||||
from_warehouse="CRANE-TRANSIT", from_quantity=Decimal("600"),
|
||||
to_warehouse="HUB-SH", to_quantity=Decimal("600"),
|
||||
result="success", erp_document_no="TRF-10008",
|
||||
),
|
||||
]
|
||||
documents = aggregate_erp_documents(items)
|
||||
assert len(documents) == 2
|
||||
by_no = {document.document_no: document for document in documents}
|
||||
first = by_no["TRF-10001"]
|
||||
assert first.material_count == 2
|
||||
assert first.total_quantity == Decimal("1700")
|
||||
assert first.from_warehouse == "DBS-TRANSIT"
|
||||
assert first.to_warehouse == "HUB-CN01"
|
||||
assert first.posting_status == "posted"
|
||||
assert [line.invoice_no for line in first.lines] == ["INV-001", "INV-002"]
|
||||
@@ -0,0 +1,78 @@
|
||||
"""在途调拨日期成熟度策略测试(L0 纯单元)。
|
||||
|
||||
用途:验证 D+1 成熟规则、当天 not_matured、未来日期阻断与上海业务时区。
|
||||
依赖:app.services.in_transit_transfer.date_policy(纯函数)。
|
||||
逻辑:全部断言只依赖业务日期与收料日期,不接触 Flask/DB(pure_unit)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime, timezone
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.in_transit_transfer.date_policy import (
|
||||
business_date_now,
|
||||
eligible_receipt_date_to,
|
||||
maturity_status,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
BUSINESS_T = date(2026, 8, 6)
|
||||
|
||||
|
||||
def test_same_day_receipt_is_not_matured():
|
||||
"""当天收料必须返回 not_matured;成熟门禁不查询 ERP(调用次数由服务层保证为 0)。"""
|
||||
assert maturity_status(date(2026, 8, 6), BUSINESS_T) == "not_matured"
|
||||
|
||||
|
||||
def test_yesterday_receipt_is_eligible():
|
||||
"""昨天(T-1)收料进入预检。"""
|
||||
assert maturity_status(date(2026, 8, 5), BUSINESS_T) == "eligible"
|
||||
|
||||
|
||||
def test_older_receipt_is_eligible():
|
||||
"""更早收料同样可预检。"""
|
||||
assert maturity_status(date(2026, 8, 1), BUSINESS_T) == "eligible"
|
||||
|
||||
|
||||
def test_future_receipt_is_blocked():
|
||||
"""未来日期收料返回结构化阻断值。"""
|
||||
assert maturity_status(date(2026, 8, 7), BUSINESS_T) == "future"
|
||||
|
||||
|
||||
def test_maturity_status_accepts_iso_strings():
|
||||
"""字符串日期与 date 对象等价。"""
|
||||
assert maturity_status("2026-08-05", "2026-08-06") == "eligible"
|
||||
assert maturity_status("2026-08-06", "2026-08-06") == "not_matured"
|
||||
|
||||
|
||||
def test_eligible_receipt_date_to_is_previous_day():
|
||||
"""可调拨收料截止日期 = 业务日期 - 1 天。"""
|
||||
assert eligible_receipt_date_to(BUSINESS_T) == date(2026, 8, 5)
|
||||
|
||||
|
||||
def test_business_date_now_uses_shanghai_across_utc_midnight():
|
||||
"""UTC 17:00(北京时间次日 01:00)业务日期不得漂移回 UTC 日期。"""
|
||||
moment = datetime(2026, 8, 5, 17, 0, 0, tzinfo=timezone.utc)
|
||||
assert business_date_now(moment) == date(2026, 8, 6)
|
||||
|
||||
|
||||
def test_business_date_now_naive_moment_treated_as_utc():
|
||||
"""naive 时刻按 UTC 兼容处理(与 business_numbering_service 口径一致)。"""
|
||||
moment = datetime(2026, 8, 6, 0, 30, 0)
|
||||
assert business_date_now(moment) == date(2026, 8, 6)
|
||||
|
||||
|
||||
def test_business_date_now_defaults_to_shanghai_now():
|
||||
"""无参调用返回 Asia/Shanghai 当前日期。"""
|
||||
today = datetime.now(ZoneInfo("Asia/Shanghai")).date()
|
||||
assert business_date_now() == today
|
||||
|
||||
|
||||
def test_invalid_date_string_raises():
|
||||
"""非法日期字符串必须抛 ValueError,不得静默解析。"""
|
||||
with pytest.raises(ValueError):
|
||||
maturity_status("2026/13/99", BUSINESS_T)
|
||||
@@ -0,0 +1,219 @@
|
||||
"""在途调拨 ERP Adapter 查询契约测试(L0 纯单元)。
|
||||
|
||||
用途:验证 query_inventory 请求携带全部必需追踪字段(operation_id/run_no/
|
||||
attempt_no/invoice_no/erp_org/拨出仓/拨入仓/数量),并正确分类
|
||||
有库存/无库存/超时;SOAP 传输在 WSDL 未冻结前 fail-closed。
|
||||
依赖:app.services.in_transit_transfer.erp_adapter + fakes.FakeERP。
|
||||
逻辑:Adapter 是唯一 ERP 访问边界;测试注入 FakeERP 作为 transport。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.in_transit_transfer.erp_adapter import (
|
||||
ErpAdapter,
|
||||
ErpNotFrozenError,
|
||||
ErpQueryTimeoutError,
|
||||
ErpTransport,
|
||||
ErpWriteTimeoutError,
|
||||
InventoryQuery,
|
||||
SoapErpTransport,
|
||||
TransferWriteResult,
|
||||
)
|
||||
from tests.services.in_transit_transfer.assertions import assert_call_fields
|
||||
from tests.services.in_transit_transfer.fakes import FakeERP
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def _adapter(erp: FakeERP) -> ErpAdapter:
|
||||
return ErpAdapter(transport=erp, default_org="HX-CN01")
|
||||
|
||||
|
||||
def _query_kwargs(**overrides):
|
||||
kwargs = {
|
||||
"operation_id": "op-001",
|
||||
"run_no": "RUN-20260806-001",
|
||||
"attempt_no": 1,
|
||||
"invoice_no": "INV-001",
|
||||
"erp_org": "HX-CN01",
|
||||
"from_warehouse": "DBS-TRANSIT",
|
||||
"to_warehouse": "HUB-CN01",
|
||||
"quantity": Decimal("1200"),
|
||||
}
|
||||
kwargs.update(overrides)
|
||||
return kwargs
|
||||
|
||||
|
||||
def test_query_inventory_found():
|
||||
"""有库存 → InventoryQuery(found=True, quantity)。"""
|
||||
erp = FakeERP()
|
||||
erp.seed_inventory("INV-001", "1200")
|
||||
adapter = _adapter(erp)
|
||||
result = adapter.query_inventory(**_query_kwargs())
|
||||
assert isinstance(result, InventoryQuery)
|
||||
assert result.found is True
|
||||
assert result.quantity == Decimal("1200")
|
||||
|
||||
|
||||
def test_query_inventory_not_found():
|
||||
"""无库存 → found=False。"""
|
||||
erp = FakeERP()
|
||||
adapter = _adapter(erp)
|
||||
result = adapter.query_inventory(**_query_kwargs())
|
||||
assert result.found is False
|
||||
assert result.quantity is None
|
||||
|
||||
|
||||
def test_query_request_carries_all_trace_fields():
|
||||
"""调用记录包含全部追踪字段(提示词 §五 强制字段)。"""
|
||||
erp = FakeERP()
|
||||
erp.seed_inventory("INV-001", "1200")
|
||||
adapter = _adapter(erp)
|
||||
adapter.query_inventory(**_query_kwargs())
|
||||
records = erp.calls(invoice_no="INV-001")
|
||||
assert len(records) == 1
|
||||
assert_call_fields(records[0])
|
||||
assert records[0].operation_id == "op-001"
|
||||
assert records[0].erp_org == "HX-CN01"
|
||||
assert records[0].from_warehouse == "DBS-TRANSIT"
|
||||
assert records[0].to_warehouse == "HUB-CN01"
|
||||
|
||||
|
||||
def test_query_timeout_classified_retryable():
|
||||
"""查询超时 → ErpQueryTimeoutError(可重试,只读路径不落未知态)。"""
|
||||
erp = FakeERP()
|
||||
erp.set_query_scenario("timeout")
|
||||
adapter = _adapter(erp)
|
||||
with pytest.raises(ErpQueryTimeoutError) as excinfo:
|
||||
adapter.query_inventory(**_query_kwargs())
|
||||
assert excinfo.value.retryable is True
|
||||
|
||||
|
||||
def test_soap_transport_fails_closed_before_wsdl_frozen():
|
||||
"""WSDL/endpoint 未冻结 → SoapErpTransport 调用必须抛 ErpNotFrozenError。"""
|
||||
transport = SoapErpTransport(config={})
|
||||
adapter = ErpAdapter(transport=transport, default_org="HX-CN01")
|
||||
with pytest.raises(ErpNotFrozenError):
|
||||
adapter.query_inventory(**_query_kwargs())
|
||||
|
||||
|
||||
def test_soap_transport_refuses_without_frozen_config():
|
||||
"""未配置 endpoint 的传输对象直接拒绝查询。"""
|
||||
transport = SoapErpTransport(config={})
|
||||
with pytest.raises(ErpNotFrozenError):
|
||||
transport.query_inventory(**_query_kwargs())
|
||||
|
||||
|
||||
def test_request_payload_never_contains_credentials():
|
||||
"""Adapter 请求体不得携带任何凭据字段(Secret 边界)。"""
|
||||
|
||||
class RecordingTransport:
|
||||
def __init__(self) -> None:
|
||||
self.seen: dict | None = None
|
||||
|
||||
def query_inventory(self, **kwargs):
|
||||
self.seen = kwargs
|
||||
return {"found": True, "quantity": Decimal("1200")}
|
||||
|
||||
def create_transfer(self, **kwargs):
|
||||
self.seen = kwargs
|
||||
return {"status": "success", "document_no": "TRF-1", "posted": True}
|
||||
|
||||
def verify_duplicate(self, **kwargs):
|
||||
return {"status": "duplicate_success", "document_no": "TRF-1", "verified_posted": True}
|
||||
|
||||
transport = RecordingTransport()
|
||||
adapter = ErpAdapter(transport=transport, default_org="HX-CN01")
|
||||
adapter.query_inventory(**_query_kwargs())
|
||||
serialized = str(transport.seen)
|
||||
for fragment in ("password", "secret", "token", "ciphertext", "credential", "api_key"):
|
||||
assert fragment not in serialized.lower()
|
||||
|
||||
|
||||
# ---- Phase 2:create_transfer / verify_duplicate ---------------------------
|
||||
|
||||
def test_create_transfer_success():
|
||||
"""成功写入 → TransferWriteResult(success, document_no)。"""
|
||||
erp = FakeERP()
|
||||
adapter = _adapter(erp)
|
||||
result = adapter.create_transfer(**_query_kwargs())
|
||||
assert isinstance(result, TransferWriteResult)
|
||||
assert result.status == "success"
|
||||
assert result.document_no.startswith("TRF-")
|
||||
|
||||
|
||||
def test_create_transfer_duplicate_success_when_posted():
|
||||
"""重复 Invoice 且原单已审核过账 → duplicate_success(含原单号)。"""
|
||||
erp = FakeERP()
|
||||
erp.seed_document("INV-001", "TRF-00001", posted=True)
|
||||
adapter = _adapter(erp)
|
||||
result = adapter.create_transfer(**_query_kwargs())
|
||||
assert result.status == "duplicate_success"
|
||||
assert result.document_no == "TRF-00001"
|
||||
assert result.verified_posted is True
|
||||
|
||||
|
||||
def test_create_transfer_duplicate_unverified_blocks():
|
||||
"""重复 Invoice 但无法证明原单已过账 → duplicate_unverified(阻断)。"""
|
||||
erp = FakeERP()
|
||||
erp.seed_document("INV-001", "TRF-00001", posted=False)
|
||||
adapter = _adapter(erp)
|
||||
result = adapter.create_transfer(**_query_kwargs())
|
||||
assert result.status == "duplicate_unverified"
|
||||
assert result.document_no == "TRF-00001"
|
||||
assert result.verified_posted is False
|
||||
|
||||
|
||||
def test_create_transfer_business_failed():
|
||||
"""明确业务失败且原子回滚 → business_failed(不得产生单据)。"""
|
||||
erp = FakeERP()
|
||||
erp.set_write_scenario("business_failed")
|
||||
adapter = _adapter(erp)
|
||||
result = adapter.create_transfer(**_query_kwargs())
|
||||
assert result.status == "business_failed"
|
||||
assert result.error_code == "ERP_BUSINESS_REJECT"
|
||||
assert result.document_no is None
|
||||
|
||||
|
||||
def test_create_transfer_timeout_before_commit_is_technical_failed():
|
||||
"""提交前超时(可证明未落单)→ technical_failed,非 result_unknown。"""
|
||||
erp = FakeERP()
|
||||
erp.set_write_scenario("timeout_before_commit")
|
||||
adapter = _adapter(erp)
|
||||
result = adapter.create_transfer(**_query_kwargs())
|
||||
assert result.status == "technical_failed"
|
||||
assert result.document_no is None
|
||||
|
||||
|
||||
def test_create_transfer_timeout_after_commit_is_result_unknown():
|
||||
"""提交后超时(无法确认是否落单)→ result_unknown,禁止自动重试。"""
|
||||
erp = FakeERP()
|
||||
erp.set_write_scenario("timeout_after_commit")
|
||||
adapter = _adapter(erp)
|
||||
result = adapter.create_transfer(**_query_kwargs())
|
||||
assert result.status == "result_unknown"
|
||||
assert result.document_no is not None # Fake 已知落单,但业务层视为无法确认
|
||||
|
||||
|
||||
def test_verify_duplicate_returns_original_document():
|
||||
"""verify_duplicate 获取原 ERP 单号并确认已过账。"""
|
||||
erp = FakeERP()
|
||||
erp.seed_document("INV-001", "TRF-OLD-1", posted=True)
|
||||
adapter = _adapter(erp)
|
||||
result = adapter.verify_duplicate(**_query_kwargs())
|
||||
assert result.status == "duplicate_success"
|
||||
assert result.document_no == "TRF-OLD-1"
|
||||
|
||||
|
||||
def test_verify_duplicate_unverified_when_not_posted():
|
||||
"""原单未确认过账 → duplicate_unverified。"""
|
||||
erp = FakeERP()
|
||||
erp.seed_document("INV-001", "TRF-OLD-1", posted=False)
|
||||
adapter = _adapter(erp)
|
||||
result = adapter.verify_duplicate(**_query_kwargs())
|
||||
assert result.status == "duplicate_unverified"
|
||||
assert result.verified_posted is False
|
||||
@@ -0,0 +1,79 @@
|
||||
"""在途调拨七 Sheet 异常 Excel 测试(Phase 3,L1)。
|
||||
|
||||
用途:验证异常 Excel 七 Sheet 齐全、内容按状态归类、原始行追溯存在、
|
||||
Secret 明文不出现(凭据不出现在 Excel)。
|
||||
依赖:transfer_db、execution_service、excel_export、openpyxl。
|
||||
逻辑:以真实 Run 数据生成 workbook 字节并回读断言。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import io
|
||||
|
||||
import pytest
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from app import db
|
||||
from app.models import TransferInvoiceItem
|
||||
from app.services.in_transit_transfer.excel_export import EXCEL_SHEET_NAMES, build_exceptions_workbook
|
||||
from app.services.in_transit_transfer.execution_service import execute_precheck
|
||||
from app.services.in_transit_transfer.precheck_service import create_precheck
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
|
||||
def _executed_run(dbs_ready_file):
|
||||
"""构造含 1 成功 + 1 业务失败(未生成单据)的 Run。"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1200")
|
||||
erp.seed_inventory("INV-002", "1200")
|
||||
erp.write_scenarios["INV-001"] = "business_failed"
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
return outcome.run_no, deps
|
||||
|
||||
|
||||
def test_workbook_has_seven_sheets(transfer_db, dbs_ready_file):
|
||||
"""异常 Excel 必须包含规格定义的 7 个 Sheet。"""
|
||||
run_no, _ = _executed_run(dbs_ready_file)
|
||||
data = build_exceptions_workbook(run_no)
|
||||
workbook = load_workbook(io.BytesIO(data))
|
||||
assert workbook.sheetnames == EXCEL_SHEET_NAMES
|
||||
|
||||
|
||||
def test_workbook_classifies_exceptions(transfer_db, dbs_ready_file):
|
||||
"""业务失败项进入失败 Sheet,成功项出现在汇总 Sheet。"""
|
||||
run_no, _ = _executed_run(dbs_ready_file)
|
||||
workbook = load_workbook(io.BytesIO(build_exceptions_workbook(run_no)))
|
||||
summary_sheet = workbook["执行汇总"]
|
||||
summary_text = _sheet_text(summary_sheet)
|
||||
assert "INV-002" in summary_text
|
||||
failed_sheet = workbook["ERP技术失败"]
|
||||
failed_text = _sheet_text(failed_sheet)
|
||||
assert "INV-001" in failed_text
|
||||
|
||||
|
||||
def test_workbook_contains_raw_line_trace(transfer_db, dbs_ready_file):
|
||||
"""原始文件追溯 Sheet 保留 Sheet/行号(决策 11)。"""
|
||||
run_no, _ = _executed_run(dbs_ready_file)
|
||||
workbook = load_workbook(io.BytesIO(build_exceptions_workbook(run_no)))
|
||||
trace_sheet = workbook["原始文件追溯"]
|
||||
text = _sheet_text(trace_sheet)
|
||||
assert "Receipt" in text and "10" in text
|
||||
|
||||
|
||||
def test_workbook_never_contains_secrets(transfer_db, dbs_ready_file):
|
||||
"""Secret 明文不得出现在 Excel(密码/Token/密文片段)。"""
|
||||
run_no, _ = _executed_run(dbs_ready_file)
|
||||
workbook = load_workbook(io.BytesIO(build_exceptions_workbook(run_no)))
|
||||
for sheet in workbook.worksheets:
|
||||
text = _sheet_text(sheet).lower()
|
||||
for fragment in ("password", "secret", "token", "ciphertext", "api_key", "webhook"):
|
||||
assert fragment not in text
|
||||
|
||||
|
||||
def _sheet_text(sheet) -> str:
|
||||
"""拼接 Sheet 全部单元格文本。"""
|
||||
rows = []
|
||||
for row in sheet.iter_rows(values_only=True):
|
||||
rows.append(" ".join(str(cell) for cell in row if cell is not None))
|
||||
return "\n".join(rows)
|
||||
@@ -0,0 +1,224 @@
|
||||
"""在途调拨执行服务测试(Phase 2 核心,L1,SQLite 内存库)。
|
||||
|
||||
用途:验证确认门禁(未确认/过期/快照变化均写入 0)、写前复查(库存变化阻断)、
|
||||
Invoice 幂等(重复成功)、result_unknown 不自动重试、单项失败不阻断其他项、
|
||||
选择子集执行、重复点击防重与按 ERP 单号投影最终结果。
|
||||
依赖:app fixture、transfer_db、fakes、repo_fakes、precheck_service、execution_service。
|
||||
逻辑:全部经真实 ORM 落库;外部依赖注入 Fake 替身。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError
|
||||
from app.models import TransferAttempt, TransferInvoiceItem, TransferPrecheck, TransferRun
|
||||
from app.services.in_transit_transfer.contracts import (
|
||||
TRANSFER_CONFIRMATION_REQUIRED,
|
||||
TRANSFER_PRECHECK_EXPIRED,
|
||||
)
|
||||
from app.services.in_transit_transfer.execution_service import execute_precheck, get_run
|
||||
from app.services.in_transit_transfer.precheck_service import create_precheck
|
||||
from tests.services.in_transit_transfer.fakes import FakeERP
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
|
||||
def _ready_precheck(*files: dict, erp=None, source_codes=None) -> tuple:
|
||||
"""创建已预检(ready_to_execute)的 precheck 并返回 (deps, erp_fake, summary)。"""
|
||||
deps, erp_fake, _ = make_transfer_deps(*files, erp=erp)
|
||||
source_codes = source_codes or [files[0]["source_code"]]
|
||||
summary = create_precheck(source_codes=source_codes, business_date="2026-08-06", deps=deps)
|
||||
return deps, erp_fake, summary
|
||||
|
||||
|
||||
def _erp_with_stock(dbs_ready_file, *seeds) -> FakeERP:
|
||||
"""按 Invoice 预置账面库存的 FakeERP。"""
|
||||
erp = FakeERP()
|
||||
for invoice_no, quantity in seeds:
|
||||
erp.seed_inventory(invoice_no, quantity)
|
||||
return erp
|
||||
|
||||
|
||||
def _load_items(run_no: str) -> dict[str, TransferInvoiceItem]:
|
||||
run = db.session.query(TransferRun).filter_by(run_no=run_no).first()
|
||||
return {
|
||||
item.invoice_no: item
|
||||
for item in db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all()
|
||||
}
|
||||
|
||||
|
||||
def test_execute_happy_path(transfer_db, dbs_ready_file):
|
||||
"""两个可执行 Invoice → Run 成功,按 ERP 单号投影两张单据,Attempt 落库。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200"))
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp)
|
||||
|
||||
outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
assert outcome.status == "success"
|
||||
assert outcome.run_no.startswith("RUN-")
|
||||
assert len(outcome.result.erp_documents) == 2
|
||||
assert outcome.result.exceptions == ()
|
||||
|
||||
items = _load_items(outcome.run_no)
|
||||
assert all(item.status == "success" for item in items.values())
|
||||
assert all(item.erp_document_no for item in items.values())
|
||||
run = db.session.query(TransferRun).filter_by(run_no=outcome.run_no).first()
|
||||
attempts = db.session.query(TransferAttempt).join(TransferInvoiceItem).filter(
|
||||
TransferInvoiceItem.run_id == run.id,
|
||||
).all()
|
||||
assert len([a for a in attempts if a.kind == "erp_write"]) == 2
|
||||
|
||||
|
||||
def test_execute_duplicate_invoice_maps_duplicate_success(transfer_db, dbs_ready_file):
|
||||
"""重复 Invoice(原单已过账)→ item duplicate_success + 原单号。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200"))
|
||||
erp.seed_document("INV-002", "TRF-OLD-002", posted=True)
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp)
|
||||
|
||||
outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
assert outcome.status == "success"
|
||||
items = _load_items(outcome.run_no)
|
||||
assert items["INV-002"].status == "duplicate_success"
|
||||
assert items["INV-002"].erp_document_no == "TRF-OLD-002"
|
||||
# 同 Invoice 不重复建单:每 Invoice 恰 1 次写调用
|
||||
assert len(erp.write_calls()) == 2
|
||||
|
||||
|
||||
def test_execute_business_failure_does_not_block_others(transfer_db, dbs_ready_file):
|
||||
"""单项明确业务失败 → 该项阻断,其余项成功,Run partial_failed。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200"))
|
||||
erp.write_scenarios["INV-001"] = "business_failed"
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp)
|
||||
|
||||
outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
assert outcome.status == "partial_failed"
|
||||
items = _load_items(outcome.run_no)
|
||||
assert items["INV-001"].status == "blocked_recoverable"
|
||||
assert items["INV-002"].status == "success"
|
||||
# 异常项进入结果页"未生成单据"区
|
||||
assert any(exc.invoice_no == "INV-001" for exc in outcome.result.exceptions)
|
||||
|
||||
|
||||
def test_execute_result_unknown_no_auto_retry(transfer_db, dbs_ready_file):
|
||||
"""result_unknown:状态终态、每 Invoice 写调用仅 1 次。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200"))
|
||||
erp.set_write_scenario("timeout_after_commit")
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp)
|
||||
|
||||
outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
assert outcome.status == "partial_failed"
|
||||
items = _load_items(outcome.run_no)
|
||||
assert all(item.status == "result_unknown" for item in items.values())
|
||||
# 禁止自动重试:每个 Invoice 写调用恰 1 次
|
||||
assert len(erp.write_calls()) == 2
|
||||
|
||||
|
||||
def test_execute_unconfirmed_precheck_no_write(transfer_db, dbs_ready_file):
|
||||
"""预检未就绪(prechecking)→ 拒绝执行,ERP 写入为 0。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200"))
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp)
|
||||
precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first()
|
||||
precheck.status = "prechecking"
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(AppError) as excinfo:
|
||||
execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
assert excinfo.value.code == TRANSFER_CONFIRMATION_REQUIRED
|
||||
assert erp.write_calls() == []
|
||||
|
||||
|
||||
def test_execute_expired_precheck_no_write(transfer_db, dbs_ready_file):
|
||||
"""确认过期(超过 10 分钟)→ 拒绝执行,ERP 写入为 0。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200"))
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp)
|
||||
precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first()
|
||||
precheck.expires_at = datetime.utcnow() - timedelta(seconds=1)
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(AppError) as excinfo:
|
||||
execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
assert excinfo.value.code == TRANSFER_PRECHECK_EXPIRED
|
||||
assert erp.write_calls() == []
|
||||
|
||||
|
||||
def test_execute_snapshot_change_blocks_write(transfer_db, dbs_ready_file):
|
||||
"""预检快照(数量)变化 → fail-closed,ERP 写入为 0。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200"))
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp)
|
||||
precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first()
|
||||
item = db.session.query(TransferInvoiceItem).filter_by(precheck_id=precheck.id).first()
|
||||
item.receipt_quantity = "999"
|
||||
db.session.commit()
|
||||
|
||||
with pytest.raises(AppError) as excinfo:
|
||||
execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
assert excinfo.value.code == TRANSFER_PRECHECK_EXPIRED
|
||||
assert erp.write_calls() == []
|
||||
|
||||
|
||||
def test_execute_selected_subset_only(transfer_db, dbs_ready_file):
|
||||
"""仅选择 INV-001 → 只写入该 Invoice。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200"))
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp)
|
||||
|
||||
outcome = execute_precheck(
|
||||
precheck_id=summary.precheck_id, deps=deps, selected_invoice_nos=["INV-001"],
|
||||
)
|
||||
assert outcome.status == "success"
|
||||
assert len(outcome.result.erp_documents) == 1
|
||||
assert [record.invoice_no for record in erp.write_calls()] == ["INV-001"]
|
||||
|
||||
|
||||
def test_execute_rejects_not_matured_selection(transfer_db, same_day_receipt_file):
|
||||
"""勾选当天收料项 → 拒绝,ERP 写入为 0。"""
|
||||
deps, erp_fake, summary = _ready_precheck(same_day_receipt_file, source_codes=["DBS-AWSSG"])
|
||||
with pytest.raises(AppError):
|
||||
execute_precheck(
|
||||
precheck_id=summary.precheck_id, deps=deps, selected_invoice_nos=["INV-041"],
|
||||
)
|
||||
assert erp_fake.write_calls() == []
|
||||
|
||||
|
||||
def test_execute_double_click_rejected(transfer_db, dbs_ready_file):
|
||||
"""重复点击执行 → 第二次 409,不创建重复 Run。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200"))
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp)
|
||||
|
||||
first = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
with pytest.raises(AppError) as excinfo:
|
||||
execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
assert excinfo.value.http_status == 409
|
||||
# 只存在一个执行 Run(其余为预检关联 Run)
|
||||
execution_runs = db.session.query(TransferRun).filter(
|
||||
TransferRun.status != "prechecking",
|
||||
).count()
|
||||
assert execution_runs == 1
|
||||
assert first.run_no
|
||||
|
||||
|
||||
def test_execute_write_before_recheck_inventory_change_blocks(transfer_db, dbs_ready_file):
|
||||
"""写前复查发现 ERP 库存变化 → 该项阻断不写,其余项正常。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200"))
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp)
|
||||
erp.seed_inventory("INV-001", "999") # 预检后库存变化
|
||||
|
||||
outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
items = _load_items(outcome.run_no)
|
||||
assert items["INV-001"].status == "blocked_recoverable"
|
||||
assert items["INV-002"].status == "success"
|
||||
assert [record.invoice_no for record in erp.write_calls()] == ["INV-002"]
|
||||
|
||||
|
||||
def test_get_run_restores_document_projection(transfer_db, dbs_ready_file):
|
||||
"""GET run → 按 ERP 单号聚合单据 + 未生成单据异常分开展示。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("INV-001", "1200"), ("INV-002", "1200"))
|
||||
erp.write_scenarios["INV-001"] = "business_failed"
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp)
|
||||
outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
|
||||
restored = get_run(outcome.run_no)
|
||||
assert restored["run_no"] == outcome.run_no
|
||||
assert len(restored["result"]["erp_documents"]) == 1
|
||||
assert any(exc["invoice_no"] == "INV-001" for exc in restored["result"]["exceptions"])
|
||||
@@ -0,0 +1,128 @@
|
||||
"""在途调拨文件 Ready 复用与 RPA 触发测试(L0 纯单元)。
|
||||
|
||||
用途:验证当日 ready 文件可复用(不触发 RPA)、缺文件时同一来源只触发一次
|
||||
RPA、存在活动 Source Job 时绑定已有任务、触发失败 fail-closed。
|
||||
依赖:app.services.in_transit_transfer.file_preparation + fakes。
|
||||
逻辑:仓库与 RPA 触发均通过协议注入,测试使用 Fake 替身。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.in_transit_transfer.file_preparation import (
|
||||
FilePreparationResult,
|
||||
ReadyReceiptFile,
|
||||
ReceiptFileRepository,
|
||||
ensure_receipt_file_ready,
|
||||
)
|
||||
from tests.services.in_transit_transfer.fakes import FakeRPA
|
||||
from tests.services.in_transit_transfer.repo_fakes import FakeReceiptFileRepository
|
||||
|
||||
|
||||
def _ready_file(source_code: str = "DBS-AWSBI", *, business_date: str = "2026-08-06") -> ReadyReceiptFile:
|
||||
return ReadyReceiptFile(
|
||||
source_code=source_code,
|
||||
business_date=business_date,
|
||||
file_no=f"REC-{source_code}-001",
|
||||
file_version="v3",
|
||||
checksum="d" * 64,
|
||||
rows=(),
|
||||
)
|
||||
|
||||
|
||||
def test_ready_file_reused_without_rpa_trigger():
|
||||
"""当日 ready 文件存在 → 复用(stage=file_ready),不触发 RPA。"""
|
||||
repository = FakeReceiptFileRepository({("DBS-AWSBI", "2026-08-06"): _ready_file()})
|
||||
rpa = FakeRPA()
|
||||
result = ensure_receipt_file_ready(
|
||||
source_code="DBS-AWSBI", business_date="2026-08-06",
|
||||
repository=repository, rpa_trigger=rpa,
|
||||
)
|
||||
assert result.stage == "file_ready"
|
||||
assert result.file is not None
|
||||
assert rpa.triggered == []
|
||||
|
||||
|
||||
def test_missing_file_triggers_rpa_once():
|
||||
"""缺文件 → 触发 RPA 一次并进入 waiting_rpa_callback。"""
|
||||
repository = FakeReceiptFileRepository()
|
||||
rpa = FakeRPA()
|
||||
result = ensure_receipt_file_ready(
|
||||
source_code="DBS-AWSBI", business_date="2026-08-06",
|
||||
repository=repository, rpa_trigger=rpa,
|
||||
)
|
||||
assert result.stage == "waiting_rpa_callback"
|
||||
assert result.file is None
|
||||
assert len(rpa.triggered) == 1
|
||||
assert rpa.triggered[0]["source_code"] == "DBS-AWSBI"
|
||||
|
||||
|
||||
def test_active_source_job_binds_existing_task_no_new_trigger():
|
||||
"""存在活动 Source Job → 绑定已有任务,不重复触发 RPA。"""
|
||||
repository = FakeReceiptFileRepository()
|
||||
rpa = FakeRPA()
|
||||
result = ensure_receipt_file_ready(
|
||||
source_code="DBS-AWSBI", business_date="2026-08-06",
|
||||
repository=repository, rpa_trigger=rpa, active_source_job_key="RUN-1/DBS-AWSBI",
|
||||
)
|
||||
assert result.stage == "waiting_rpa_callback"
|
||||
assert rpa.triggered == []
|
||||
|
||||
|
||||
def test_concurrent_requests_share_one_trigger():
|
||||
"""并发请求携带同一活动键 → 全部绑定已有任务,不重复触发 RPA。"""
|
||||
repository = FakeReceiptFileRepository()
|
||||
rpa = FakeRPA()
|
||||
for _ in range(3):
|
||||
result = ensure_receipt_file_ready(
|
||||
source_code="DBS-AWSBI", business_date="2026-08-06",
|
||||
repository=repository, rpa_trigger=rpa, active_source_job_key="RUN-1/DBS-AWSBI",
|
||||
)
|
||||
assert result.stage == "waiting_rpa_callback"
|
||||
assert rpa.triggered == []
|
||||
|
||||
|
||||
def test_without_active_key_each_call_triggers_once():
|
||||
"""无活动键时每次调用各触发一次;幂等由调用方 SourceJob 唯一键兜底。"""
|
||||
repository = FakeReceiptFileRepository()
|
||||
rpa = FakeRPA()
|
||||
ensure_receipt_file_ready(
|
||||
source_code="DBS-AWSBI", business_date="2026-08-06",
|
||||
repository=repository, rpa_trigger=rpa,
|
||||
)
|
||||
ensure_receipt_file_ready(
|
||||
source_code="DBS-AWSBI", business_date="2026-08-06",
|
||||
repository=repository, rpa_trigger=rpa,
|
||||
)
|
||||
assert len(rpa.triggered) == 2
|
||||
|
||||
|
||||
def test_rpa_trigger_failure_is_fail_closed():
|
||||
"""RPA 触发失败 → stage=failed 且带错误码,不误报 file_ready。"""
|
||||
repository = FakeReceiptFileRepository()
|
||||
rpa = FakeRPA()
|
||||
rpa.fail_on.add("DBS-AWSBI")
|
||||
result = ensure_receipt_file_ready(
|
||||
source_code="DBS-AWSBI", business_date="2026-08-06",
|
||||
repository=repository, rpa_trigger=rpa,
|
||||
)
|
||||
assert result.stage == "failed"
|
||||
assert result.error_code == "RPA_TRIGGER_FAILED"
|
||||
|
||||
|
||||
def test_dbs_and_crane_sources_isolated():
|
||||
"""DBS 失败不影响 Crane 的文件准备(来源隔离)。"""
|
||||
repository = FakeReceiptFileRepository({("CRANE-SZ", "2026-08-06"): _ready_file("CRANE-SZ")})
|
||||
rpa = FakeRPA()
|
||||
rpa.fail_on.add("DBS-AWSBI")
|
||||
dbs_result = ensure_receipt_file_ready(
|
||||
source_code="DBS-AWSBI", business_date="2026-08-06",
|
||||
repository=repository, rpa_trigger=rpa,
|
||||
)
|
||||
crane_result = ensure_receipt_file_ready(
|
||||
source_code="CRANE-SZ", business_date="2026-08-06",
|
||||
repository=repository, rpa_trigger=rpa,
|
||||
)
|
||||
assert dbs_result.stage == "failed"
|
||||
assert crane_result.stage == "file_ready"
|
||||
@@ -0,0 +1,117 @@
|
||||
"""在途调拨 Invoice 多行汇总与冲突测试(L0 纯单元)。
|
||||
|
||||
用途:验证相同 Invoice 多行只汇总收料数量并永久保留原始行追溯;
|
||||
同一 Invoice 出现多料号/多收料日期时整单阻断(InvoiceConflictError)。
|
||||
依赖:app.services.in_transit_transfer.invoice_aggregator + file_parser。
|
||||
逻辑:汇总键为 (source_code, invoice_no);冲突判定基于料号与收料日期。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.in_transit_transfer.file_parser import parse_receipt_rows
|
||||
from app.services.in_transit_transfer.invoice_aggregator import (
|
||||
AggregatedInvoice,
|
||||
InvoiceConflictError,
|
||||
aggregate_invoices,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def _parsed(rows: list[dict]) -> list:
|
||||
"""将原始行解析为 ParsedReceiptRow。"""
|
||||
return parse_receipt_rows(source_code="DBS-AWSBI", rows=rows)
|
||||
|
||||
|
||||
def _row(invoice_no: str, *, material_no: str = "MAT-001", material_name: str = "连接器组件",
|
||||
specification: str = "A 型 / 24PIN", receipt_date: str = "2026-08-05",
|
||||
quantity: str = "500", row_no: int = 10, sheet: str = "Receipt") -> dict:
|
||||
return {
|
||||
"sheet": sheet, "row_no": row_no, "invoice_no": invoice_no,
|
||||
"material_no": material_no, "material_name": material_name,
|
||||
"specification": specification, "receipt_date": receipt_date,
|
||||
"receipt_quantity": quantity, "source_code": "DBS-AWSBI",
|
||||
}
|
||||
|
||||
|
||||
def test_same_invoice_multiple_rows_sum_quantity():
|
||||
"""同 Invoice 同料号两行 → 数量相加,保留两条原始行。"""
|
||||
rows = [
|
||||
_row("INV-001", quantity="500", row_no=10),
|
||||
_row("INV-001", quantity="700", row_no=11),
|
||||
]
|
||||
invoices = aggregate_invoices(_parsed(rows))
|
||||
assert len(invoices) == 1
|
||||
invoice = invoices[0]
|
||||
assert invoice.invoice_no == "INV-001"
|
||||
assert invoice.receipt_quantity == Decimal("1200")
|
||||
assert len(invoice.raw_lines) == 2
|
||||
assert invoice.raw_lines[0].row_no == 10
|
||||
assert invoice.raw_lines[1].row_no == 11
|
||||
assert all(line.sheet == "Receipt" for line in invoice.raw_lines)
|
||||
|
||||
|
||||
def test_distinct_invoices_stay_separate_and_sorted():
|
||||
"""不同 Invoice 保持独立并按 Invoice 排序。"""
|
||||
rows = [
|
||||
_row("INV-002", row_no=5),
|
||||
_row("INV-001", row_no=3),
|
||||
]
|
||||
invoices = aggregate_invoices(_parsed(rows))
|
||||
assert [item.invoice_no for item in invoices] == ["INV-001", "INV-002"]
|
||||
|
||||
|
||||
def test_multiple_material_no_conflict_blocks_invoice():
|
||||
"""同一 Invoice 出现多个料号 → 整单阻断。"""
|
||||
rows = [
|
||||
_row("INV-001", material_no="MAT-001", row_no=1),
|
||||
_row("INV-001", material_no="MAT-002", row_no=2),
|
||||
]
|
||||
with pytest.raises(InvoiceConflictError) as excinfo:
|
||||
aggregate_invoices(_parsed(rows))
|
||||
assert excinfo.value.details.get("invoice_no") == "INV-001"
|
||||
|
||||
|
||||
def test_multiple_receipt_date_conflict_blocks_invoice():
|
||||
"""同一 Invoice 出现多个收料日期 → 整单阻断。"""
|
||||
rows = [
|
||||
_row("INV-001", receipt_date="2026-08-05", row_no=1),
|
||||
_row("INV-001", receipt_date="2026-08-06", row_no=2),
|
||||
]
|
||||
with pytest.raises(InvoiceConflictError):
|
||||
aggregate_invoices(_parsed(rows))
|
||||
|
||||
|
||||
def test_aggregated_invoice_keeps_material_identity():
|
||||
"""汇总结果保留料号、品名、规格与收料日期。"""
|
||||
rows = [
|
||||
_row("INV-001", material_no="MAT-001", material_name="连接器组件",
|
||||
specification="A 型 / 24PIN", receipt_date="2026-08-05", row_no=1),
|
||||
_row("INV-001", material_no="MAT-001", row_no=2),
|
||||
]
|
||||
invoices = aggregate_invoices(_parsed(rows))
|
||||
invoice = invoices[0]
|
||||
assert invoice.material_no == "MAT-001"
|
||||
assert invoice.material_name == "连接器组件"
|
||||
assert invoice.specification == "A 型 / 24PIN"
|
||||
assert invoice.receipt_date == date(2026, 8, 5)
|
||||
|
||||
|
||||
def test_raw_lines_carry_file_version():
|
||||
"""原始行追溯包含文件版本(决策 11:来源证据)。"""
|
||||
rows = [
|
||||
_row("INV-001", row_no=10),
|
||||
_row("INV-001", row_no=11),
|
||||
]
|
||||
invoices = aggregate_invoices(_parsed(rows), file_version="v3")
|
||||
assert all(line.file_version == "v3" for line in invoices[0].raw_lines)
|
||||
|
||||
|
||||
def test_empty_input_returns_empty():
|
||||
"""空行输入返回空汇总。"""
|
||||
assert aggregate_invoices([]) == []
|
||||
@@ -0,0 +1,46 @@
|
||||
"""在途调拨运营指标测试(Phase 4,L1)。
|
||||
|
||||
用途:验证指标聚合(Run/明细状态分布、待处理老化、通知失败数)正确。
|
||||
依赖:transfer_db、precheck/execution/metrics、repo_fakes。
|
||||
逻辑:指标由数据库现状投影,便于上线观察板使用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import TransferInvoiceItem, TransferRun
|
||||
from app.services.in_transit_transfer.execution_service import execute_precheck
|
||||
from app.services.in_transit_transfer.metrics import collect_metrics
|
||||
from app.services.in_transit_transfer.precheck_service import create_precheck
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
|
||||
def test_collect_metrics_counts_runs_and_items(transfer_db, dbs_ready_file):
|
||||
"""指标包含 Run 状态分布与明细状态分布。"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1200")
|
||||
erp.seed_inventory("INV-002", "1200")
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
|
||||
metrics = collect_metrics()
|
||||
assert metrics["runs"]["success"] >= 1
|
||||
assert metrics["items"]["success"] >= 2
|
||||
|
||||
|
||||
def test_collect_metrics_backlog_and_notification_failure(transfer_db, dbs_ready_file):
|
||||
"""指标含待处理老化与通知失败计数。"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1000") # mismatch → blocked
|
||||
erp.seed_inventory("INV-002", "1200")
|
||||
create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="INV-001").first()
|
||||
item.updated_at = item.updated_at # 保持默认年龄
|
||||
db.session.commit()
|
||||
|
||||
metrics = collect_metrics()
|
||||
assert metrics["backlog"]["recoverable"] == 1
|
||||
assert "aging" in metrics["backlog"]
|
||||
assert "notification_failed_runs" in metrics["runs"]
|
||||
@@ -0,0 +1,72 @@
|
||||
"""在途调拨迁移升级/回滚执行测试。
|
||||
|
||||
用途:在 SQLite 内存库上真实执行 it1a2b3c4d5e 迁移的 upgrade 与 downgrade,
|
||||
证明建表/回滚 DDL 可运行(Phase 0 验收:迁移 upgrade/downgrade 成功)。
|
||||
依赖:Alembic Operations、SQLAlchemy SQLite、it1a2b3c4d5e 迁移模块。
|
||||
逻辑:upgrade 后断言 7 张调拨表存在;downgrade 后断言全部删除。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
EXPECTED_TABLES = {
|
||||
"transfer_runs",
|
||||
"transfer_source_jobs",
|
||||
"transfer_prechecks",
|
||||
"transfer_invoice_items",
|
||||
"transfer_attempts",
|
||||
"transfer_audit_events",
|
||||
"transfer_archives",
|
||||
}
|
||||
|
||||
|
||||
def _load_migration():
|
||||
"""加载新增调拨迁移模块。"""
|
||||
path = Path(__file__).parents[3] / "migrations" / "versions" / "it1a2b3c4d5e_add_in_transit_transfer.py"
|
||||
spec = importlib.util.spec_from_file_location("in_transit_transfer_migration", path)
|
||||
assert spec is not None and spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def test_transfer_migration_upgrade_creates_all_tables():
|
||||
"""升级必须创建全部 7 张调拨表。"""
|
||||
engine = sa.create_engine("sqlite:///:memory:")
|
||||
with engine.begin() as connection:
|
||||
context = MigrationContext.configure(connection)
|
||||
operations = Operations(context)
|
||||
migration = _load_migration()
|
||||
migration.op = operations
|
||||
|
||||
migration.upgrade()
|
||||
tables = set(sa.inspect(connection).get_table_names())
|
||||
assert EXPECTED_TABLES <= tables, f"missing tables: {EXPECTED_TABLES - tables}"
|
||||
|
||||
# 关键约束抽查:Invoice 唯一键与状态检查约束落库
|
||||
columns = {item["name"] for item in sa.inspect(connection).get_columns("transfer_invoice_items")}
|
||||
assert "invoice_no" in columns and "raw_lines_json" in columns
|
||||
|
||||
|
||||
def test_transfer_migration_downgrade_drops_all_tables():
|
||||
"""回滚必须删除全部调拨表且不残留索引。"""
|
||||
engine = sa.create_engine("sqlite:///:memory:")
|
||||
with engine.begin() as connection:
|
||||
context = MigrationContext.configure(connection)
|
||||
operations = Operations(context)
|
||||
migration = _load_migration()
|
||||
migration.op = operations
|
||||
|
||||
migration.upgrade()
|
||||
migration.downgrade()
|
||||
tables = set(sa.inspect(connection).get_table_names())
|
||||
assert not (EXPECTED_TABLES & tables), f"leftover tables: {EXPECTED_TABLES & tables}"
|
||||
@@ -0,0 +1,59 @@
|
||||
"""在途调拨数据库迁移链测试。
|
||||
|
||||
用途:验证新增迁移 revision 存在、正确挂在当前 head 之后,且不产生分叉。
|
||||
依赖:alembic 迁移脚本目录(backend/migrations/versions)。
|
||||
逻辑:读取版本文件头部 revision/down_revision 文本,不加载 Flask 应用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
MIGRATIONS_DIR = Path(__file__).resolve().parents[3] / "migrations" / "versions"
|
||||
# 在途调拨迁移根:ic1a2b3c4d5f(Add integration connector)挂在其上。
|
||||
NEW_REVISION = "ic1a2b3c4d5f"
|
||||
# ic1a2b3c4d5f 的直接 parent(仍是线性链,未被分叉)。
|
||||
CURRENT_HEAD = "it1a2b3c4d5e"
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def _migration_file(revision: str) -> Path:
|
||||
"""按 revision 定位迁移文件(命名规则 <revision>_<slug>.py)。"""
|
||||
for path in MIGRATIONS_DIR.glob("*.py"):
|
||||
if path.name.startswith(f"{revision}_"):
|
||||
return path
|
||||
raise AssertionError(f"migration file for revision {revision} not found")
|
||||
|
||||
|
||||
def test_migration_file_exists_and_chains_from_head():
|
||||
"""新增迁移必须存在并挂在当前 head(it1a2b3c4d5e)之后。"""
|
||||
path = _migration_file(NEW_REVISION)
|
||||
text = path.read_text(encoding="utf-8")
|
||||
assert f"revision = '{NEW_REVISION}'" in text or f'revision = "{NEW_REVISION}"' in text
|
||||
assert f"down_revision = '{CURRENT_HEAD}'" in text or f'down_revision = "{CURRENT_HEAD}"' in text
|
||||
|
||||
|
||||
def test_new_revision_is_not_referenced_as_parent():
|
||||
"""没有歧义分叉:ic1a2b3c4d5f 后续仅允许线性延伸(if1b2c3d4e5g),禁止其余分支。"""
|
||||
allowed_children = {"if1b2c3d4e5g"}
|
||||
for path in MIGRATIONS_DIR.glob("*.py"):
|
||||
if path.name.startswith(f"{NEW_REVISION}_"):
|
||||
continue
|
||||
text = path.read_text(encoding="utf-8", errors="ignore")
|
||||
match = re.search(rf"down_revision\s*=\s*['\"]{NEW_REVISION}['\"]", text)
|
||||
if match and path.name.split("_", 1)[0] not in allowed_children:
|
||||
raise AssertionError(f"unexpected branch from {NEW_REVISION}: {path.name}")
|
||||
|
||||
|
||||
def test_head_still_linear_after_new_migration():
|
||||
"""当前 in_transit_transfer 链保持线性:it1a2b3c4d5e 之后仅 ic1a2b3c4d5f 一个后继。"""
|
||||
allowed_children = {"ic1a2b3c4d5f"}
|
||||
for path in MIGRATIONS_DIR.glob("*.py"):
|
||||
text = path.read_text(encoding="utf-8", errors="ignore")
|
||||
match = re.search(rf"down_revision\s*=\s*['\"]{CURRENT_HEAD}['\"]", text)
|
||||
if match and path.name.split("_", 1)[0] not in allowed_children:
|
||||
raise AssertionError(f"unexpected branch from head: {path.name}")
|
||||
@@ -0,0 +1,213 @@
|
||||
"""在途调拨领域模型测试(L1,使用 SQLite 内存库)。
|
||||
|
||||
用途:验证 7 个核心模型可建表、可持久化回读,唯一约束与状态约束生效,
|
||||
审计事件只追加不可改删。
|
||||
依赖:app fixture(create_all 自动建表)、models/in_transit_transfer。
|
||||
逻辑:全部走真实 ORM 落库,不 Mock 模型本身。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
from sqlalchemy import inspect
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
TransferArchive,
|
||||
TransferAttempt,
|
||||
TransferAuditEvent,
|
||||
TransferInvoiceItem,
|
||||
TransferPrecheck,
|
||||
TransferRun,
|
||||
TransferSourceJob,
|
||||
)
|
||||
|
||||
TRANSFER_TABLES = {
|
||||
"transfer_runs", "transfer_source_jobs", "transfer_prechecks",
|
||||
"transfer_invoice_items", "transfer_attempts", "transfer_audit_events",
|
||||
"transfer_archives",
|
||||
}
|
||||
|
||||
|
||||
def test_create_all_includes_transfer_tables(app):
|
||||
"""create_all 必须包含全部调拨表(迁移与测试建表同源)。"""
|
||||
inspector = inspect(db.engine)
|
||||
tables = set(inspector.get_table_names())
|
||||
assert TRANSFER_TABLES <= tables
|
||||
|
||||
|
||||
def test_run_source_job_item_attempt_roundtrip(transfer_db):
|
||||
"""Run → SourceJob → InvoiceItem → Attempt 全链路持久化回读。"""
|
||||
run = TransferRun(
|
||||
run_no="RUN-20260806-001",
|
||||
trigger_type="manual",
|
||||
business_date="2026-08-06",
|
||||
status="prechecking",
|
||||
source_codes_json=["DBS-AWSBI"],
|
||||
counts_json={"file_invoice_count": 3, "executable_count": 2},
|
||||
)
|
||||
transfer_db.session.add(run)
|
||||
transfer_db.session.flush()
|
||||
|
||||
source_job = TransferSourceJob(
|
||||
run_id=run.id,
|
||||
source_code="DBS-AWSBI",
|
||||
source_config_version=5,
|
||||
status="checking_file",
|
||||
)
|
||||
precheck = TransferPrecheck(
|
||||
precheck_no="TPC-20260806-001",
|
||||
run_id=run.id,
|
||||
business_date="2026-08-06",
|
||||
status="ready_to_execute",
|
||||
scope_json={"source_codes": ["DBS-AWSBI"]},
|
||||
counts_json={"executable_count": 1},
|
||||
precheck_hash="sha256:test",
|
||||
)
|
||||
item = TransferInvoiceItem(
|
||||
precheck=precheck,
|
||||
run_id=run.id,
|
||||
source_code="DBS-AWSBI",
|
||||
invoice_no="INV-001",
|
||||
material_no="MAT-001",
|
||||
material_name="连接器组件",
|
||||
specification="A 型 / 24PIN",
|
||||
receipt_date="2026-08-05",
|
||||
from_warehouse="DBS-TRANSIT",
|
||||
to_warehouse="HUB-CN01",
|
||||
receipt_quantity="1200",
|
||||
erp_quantity="1200",
|
||||
status="ready_to_execute",
|
||||
raw_lines_json=[{"sheet": "Receipt", "row_no": 10, "file_version": "v3"}],
|
||||
)
|
||||
transfer_db.session.add_all([source_job, precheck, item])
|
||||
transfer_db.session.flush()
|
||||
|
||||
attempt = TransferAttempt(
|
||||
item_id=item.id,
|
||||
attempt_no=1,
|
||||
kind="erp_query",
|
||||
status="success",
|
||||
request_snapshot_json={"invoice_no": "INV-001"},
|
||||
operation_id="op_001",
|
||||
)
|
||||
transfer_db.session.add(attempt)
|
||||
transfer_db.session.commit()
|
||||
|
||||
loaded_run = transfer_db.session.get(TransferRun, run.id)
|
||||
assert loaded_run.run_no == "RUN-20260806-001"
|
||||
loaded_item = transfer_db.session.get(TransferInvoiceItem, item.id)
|
||||
assert loaded_item.raw_lines_json[0]["row_no"] == 10
|
||||
loaded_attempt = transfer_db.session.get(TransferAttempt, attempt.id)
|
||||
assert loaded_attempt.operation_id == "op_001"
|
||||
assert loaded_attempt.attempt_no == 1
|
||||
|
||||
|
||||
def test_invoice_item_unique_per_precheck(transfer_db):
|
||||
"""同一预检内同一 Invoice 只能出现一次(防重复建单底座)。"""
|
||||
precheck = TransferPrecheck(
|
||||
precheck_no="TPC-20260806-002",
|
||||
business_date="2026-08-06",
|
||||
status="prechecking",
|
||||
scope_json={},
|
||||
counts_json={},
|
||||
precheck_hash="sha256:test2",
|
||||
)
|
||||
transfer_db.session.add(precheck)
|
||||
transfer_db.session.flush()
|
||||
|
||||
def _item(invoice_no: str) -> TransferInvoiceItem:
|
||||
return TransferInvoiceItem(
|
||||
precheck_id=precheck.id,
|
||||
source_code="DBS-AWSBI",
|
||||
invoice_no=invoice_no,
|
||||
material_no="MAT-001",
|
||||
receipt_date="2026-08-05",
|
||||
from_warehouse="DBS-TRANSIT",
|
||||
to_warehouse="HUB-CN01",
|
||||
receipt_quantity="1200",
|
||||
erp_quantity="1200",
|
||||
status="ready_to_execute",
|
||||
raw_lines_json=[],
|
||||
)
|
||||
|
||||
transfer_db.session.add(_item("INV-001"))
|
||||
transfer_db.session.flush()
|
||||
transfer_db.session.add(_item("INV-001"))
|
||||
with pytest.raises(IntegrityError):
|
||||
transfer_db.session.flush()
|
||||
transfer_db.session.rollback()
|
||||
|
||||
|
||||
def test_run_no_unique(transfer_db):
|
||||
"""run_no 唯一约束生效。"""
|
||||
transfer_db.session.add(TransferRun(run_no="RUN-UNIQUE-1", trigger_type="manual",
|
||||
business_date="2026-08-06", status="queued"))
|
||||
transfer_db.session.flush()
|
||||
transfer_db.session.add(TransferRun(run_no="RUN-UNIQUE-1", trigger_type="manual",
|
||||
business_date="2026-08-06", status="queued"))
|
||||
with pytest.raises(IntegrityError):
|
||||
transfer_db.session.flush()
|
||||
transfer_db.session.rollback()
|
||||
|
||||
|
||||
def test_invoice_item_status_check_constraint(transfer_db):
|
||||
"""Invoice 状态必须属于冻结枚举(数据库级门禁兜底)。"""
|
||||
precheck = TransferPrecheck(
|
||||
precheck_no="TPC-20260806-003", business_date="2026-08-06",
|
||||
status="prechecking", scope_json={}, counts_json={}, precheck_hash="x",
|
||||
)
|
||||
transfer_db.session.add(precheck)
|
||||
transfer_db.session.flush()
|
||||
transfer_db.session.add(TransferInvoiceItem(
|
||||
precheck_id=precheck.id, source_code="DBS-AWSBI", invoice_no="INV-999",
|
||||
material_no="MAT-9", receipt_date="2026-08-05",
|
||||
from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01",
|
||||
receipt_quantity="1", erp_quantity="1",
|
||||
status="no_such_status", raw_lines_json=[],
|
||||
))
|
||||
with pytest.raises(IntegrityError):
|
||||
transfer_db.session.flush()
|
||||
transfer_db.session.rollback()
|
||||
|
||||
|
||||
def test_audit_event_is_append_only(transfer_db):
|
||||
"""审计事件禁止更新与删除(ORM 门禁)。"""
|
||||
event = TransferAuditEvent(
|
||||
event_type="TRANSFER_READ", aggregate_type="transfer_run",
|
||||
aggregate_id="RUN-X", run_no="RUN-X", actor_type="user",
|
||||
actor_id="u-1", result="success",
|
||||
)
|
||||
transfer_db.session.add(event)
|
||||
transfer_db.session.commit()
|
||||
|
||||
event.result = "failure"
|
||||
with pytest.raises(Exception):
|
||||
transfer_db.session.commit()
|
||||
transfer_db.session.rollback()
|
||||
|
||||
transfer_db.session.delete(event)
|
||||
with pytest.raises(Exception):
|
||||
transfer_db.session.commit()
|
||||
transfer_db.session.rollback()
|
||||
|
||||
|
||||
def test_archive_roundtrip(transfer_db):
|
||||
"""归档记录保存对象路径与 Hash,供 Phase 4 MinIO 归档校验。"""
|
||||
archive = TransferArchive(
|
||||
archive_no="ARC-20260806-001",
|
||||
object_type="erp_inventory_snapshot",
|
||||
object_id="TPC-20260806-001",
|
||||
storage_provider="minio",
|
||||
storage_bucket="hxops-transfer",
|
||||
storage_key="transfer/20260806/snapshot.xlsx",
|
||||
original_filename="erp-inventory-20260806.xlsx",
|
||||
file_size=1024,
|
||||
sha256="a" * 64,
|
||||
)
|
||||
transfer_db.session.add(archive)
|
||||
transfer_db.session.commit()
|
||||
loaded = transfer_db.session.get(TransferArchive, archive.id)
|
||||
assert loaded.sha256 == "a" * 64
|
||||
assert loaded.object_type == "erp_inventory_snapshot"
|
||||
@@ -0,0 +1,62 @@
|
||||
"""在途调拨通用异动表领域字段契约测试(L0 纯单元)。
|
||||
|
||||
用途:锁定调拨定死的 10 个通用异动/移动字段契约(领域定死、不配置化),
|
||||
以及通用异动解析器 parse_movement_rows 把字段映射到调拨 ParsedReceiptRow。
|
||||
依赖:app.services.in_transit_transfer.movement_contract + file_parser(纯函数)。
|
||||
逻辑:字段契约是 immutable 常量;解析只认契约字段,供未来出货/入库 Excel 复用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.in_transit_transfer.file_parser import ParsedReceiptRow
|
||||
from app.services.in_transit_transfer.movement_contract import (
|
||||
MOVEMENT_FIELDS,
|
||||
MovementField,
|
||||
movement_match_key,
|
||||
movement_quantity_field,
|
||||
movement_identity_fields,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def test_movement_fields_contract_is_frozen_and_complete():
|
||||
"""领域字段契约定死:10 个字段、名称唯一、不可变。"""
|
||||
assert len(MOVEMENT_FIELDS) == 10
|
||||
codes = {field.code for field in MOVEMENT_FIELDS}
|
||||
assert codes == {
|
||||
"doc_no", "line_no", "in_out_flag", "material_code", "material_name",
|
||||
"warehouse_code", "storage_code", "lot_no", "quantity", "movement_date",
|
||||
}
|
||||
|
||||
|
||||
def test_movement_field_metadata():
|
||||
"""每个字段携带中文名、类型与使用标记。"""
|
||||
by_code = {field.code: field for field in MOVEMENT_FIELDS}
|
||||
doc_no = by_code["doc_no"]
|
||||
assert doc_no.label == "单号"
|
||||
assert doc_no.value_type == "text"
|
||||
assert doc_no.is_identity is True
|
||||
assert by_code["quantity"].value_type == "decimal"
|
||||
assert by_code["movement_date"].value_type == "date"
|
||||
|
||||
|
||||
def test_match_key_is_doc_no():
|
||||
"""调拨幂等/汇总键为 doc_no(单号)。"""
|
||||
assert movement_match_key() == "doc_no"
|
||||
|
||||
|
||||
def test_quantity_field_is_quantity():
|
||||
"""数量严格匹配字段为 quantity。"""
|
||||
assert movement_quantity_field() == "quantity"
|
||||
|
||||
|
||||
def test_identity_fields_cover_match_predicates():
|
||||
"""幂等/匹配字段集至少含 doc_no + material_code + movement_date。"""
|
||||
ids = movement_identity_fields()
|
||||
assert {"doc_no", "material_code", "movement_date"} <= ids
|
||||
@@ -0,0 +1,81 @@
|
||||
"""真实异动文件仓库的 xlsx→领域行解析测试。
|
||||
|
||||
用途:验证 _extract_movement_rows 用 movement field_mapping(定死领域字段 code→表头别名)
|
||||
把 xlsx 原始列映射为领域行 dict,供 parse_movement_rows 校验。纯单元(内存 xlsx)。
|
||||
依赖:openpyxl(构造内存工作簿)、movement_file_repository._extract_movement_rows。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from io import BytesIO
|
||||
|
||||
import pytest
|
||||
from openpyxl import Workbook
|
||||
|
||||
from app.services.in_transit_transfer.movement_file_repository import _extract_movement_rows
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
MOVEMENT_MAPPING = {
|
||||
'doc_no': '单据编号',
|
||||
'line_no': '项次',
|
||||
'in_out_flag': '进出库别',
|
||||
'material_code': '料号',
|
||||
'material_name': '品名',
|
||||
'warehouse_code': '仓库',
|
||||
'storage_code': '储位',
|
||||
'lot_no': '批号',
|
||||
'quantity': '数量',
|
||||
'movement_date': '异动日期',
|
||||
}
|
||||
|
||||
|
||||
def _movement_xlsx_bytes() -> bytes:
|
||||
"""构造含表头 + 两行数据的 xlsx。"""
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = 'Movement'
|
||||
ws.append(['单据编号', '项次', '进出库别', '料号', '品名', '仓库', '储位', '批号', '数量', '异动日期'])
|
||||
ws.append(['MOV-001', 1, 'I', 'MAT-001', '连接器', 'DBS-T', 'A-01', 'LOT-9', 500, '2026-08-05'])
|
||||
ws.append(['MOV-001', 2, 'I', 'MAT-001', '连接器', 'DBS-T', 'A-01', 'LOT-9', 300, '2026-08-05'])
|
||||
buf = BytesIO()
|
||||
wb.save(buf)
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
def test_extract_movement_rows_maps_columns_to_domain_fields():
|
||||
"""表头别名被映射为定死领域字段 code 的行字段。"""
|
||||
rows = _extract_movement_rows(
|
||||
_movement_xlsx_bytes(),
|
||||
field_mapping=MOVEMENT_MAPPING,
|
||||
sheet_name='Movement',
|
||||
header_row_index=1,
|
||||
)
|
||||
assert len(rows) == 2
|
||||
first = rows[0]
|
||||
assert first['doc_no'] == 'MOV-001'
|
||||
assert first['material_code'] == 'MAT-001'
|
||||
assert first['quantity'] == 500
|
||||
assert str(first['movement_date']) == '2026-08-05'
|
||||
second = rows[1]
|
||||
assert second['quantity'] == 300
|
||||
|
||||
|
||||
def test_extract_movement_rows_skips_missing_alias_columns():
|
||||
"""表头缺某别名列时,对应领域字段不输出(行仍保留其余字段)。"""
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = 'S'
|
||||
ws.append(['单据编号', '料号', '数量'])
|
||||
ws.append(['MOV-9', 'MAT-9', 120])
|
||||
buf = BytesIO()
|
||||
wb.save(buf)
|
||||
rows = _extract_movement_rows(
|
||||
buf.getvalue(),
|
||||
field_mapping={'doc_no': '单据编号', 'material_code': '料号', 'quantity': '数量', 'movement_date': '异动日期'},
|
||||
sheet_name='S',
|
||||
header_row_index=1,
|
||||
)
|
||||
assert rows[0]['doc_no'] == 'MOV-9'
|
||||
assert rows[0]['quantity'] == 120
|
||||
assert 'movement_date' not in rows[0]
|
||||
@@ -0,0 +1,94 @@
|
||||
"""通用异动表解析器测试(L0 纯单元)。
|
||||
|
||||
用途:验证 parse_movement_rows 把通用异动字段(doc_no/line_no/...)映射到
|
||||
调拨 ParsedReceiptRow(invoice_no=doc_no, receipt_quantity=quantity,
|
||||
receipt_date=movement_date),并保留既有校验(必填/非法值/来源一致)。
|
||||
依赖:app.services.in_transit_transfer.movement_parser(纯函数)。
|
||||
逻辑:字段映射后进入既有 file_parser 校验链路,保证下游 invoice_aggregator 不变。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.in_transit_transfer.file_parser import (
|
||||
ParsedReceiptRow,
|
||||
ReceiptFileSchemaError,
|
||||
parse_movement_rows,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
VALID_MOVEMENT_ROW = {
|
||||
"sheet": "Movement",
|
||||
"row_no": 7,
|
||||
"doc_no": "MOV-001",
|
||||
"line_no": 1,
|
||||
"in_out_flag": "I",
|
||||
"material_code": "MAT-001",
|
||||
"material_name": "连接器组件",
|
||||
"warehouse_code": "DBS-TRANSIT",
|
||||
"storage_code": "A-01",
|
||||
"lot_no": "LOT-9",
|
||||
"quantity": "500",
|
||||
"movement_date": "2026-08-05",
|
||||
"source_code": "DBS-AWSBI",
|
||||
}
|
||||
|
||||
|
||||
def _rows(**overrides) -> list[dict]:
|
||||
base = dict(VALID_MOVEMENT_ROW)
|
||||
base.update(overrides)
|
||||
return [base]
|
||||
|
||||
|
||||
def test_valid_movement_row_maps_to_parsed_rows():
|
||||
"""通用字段映射为调拨行:doc_no→invoice_no、quantity→receipt_quantity、movement_date→receipt_date。"""
|
||||
parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=_rows())
|
||||
assert len(parsed) == 1
|
||||
row = parsed[0]
|
||||
assert isinstance(row, ParsedReceiptRow)
|
||||
assert row.invoice_no == "MOV-001"
|
||||
assert row.material_no == "MAT-001"
|
||||
assert row.material_name == "连接器组件"
|
||||
assert row.receipt_date == date(2026, 8, 5)
|
||||
assert row.receipt_quantity == Decimal("500")
|
||||
assert row.sheet == "Movement"
|
||||
assert row.row_no == 7
|
||||
|
||||
|
||||
def test_missing_doc_no_rejected():
|
||||
"""单号缺失阻断。"""
|
||||
with pytest.raises(ReceiptFileSchemaError):
|
||||
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(doc_no=""))
|
||||
|
||||
|
||||
def test_invalid_quantity_rejected():
|
||||
"""非数字数量阻断。"""
|
||||
with pytest.raises(ReceiptFileSchemaError):
|
||||
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(quantity="abc"))
|
||||
|
||||
|
||||
def test_invalid_movement_date_rejected():
|
||||
"""非法异动日期阻断。"""
|
||||
with pytest.raises(ReceiptFileSchemaError):
|
||||
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(movement_date="2026/13/99"))
|
||||
|
||||
|
||||
def test_source_identity_mismatch_rejected():
|
||||
"""来源身份漂移阻断。"""
|
||||
with pytest.raises(ReceiptFileSchemaError):
|
||||
parse_movement_rows(source_code="DBS-AWSBI", rows=_rows(source_code="CRANE-SZ"))
|
||||
|
||||
|
||||
def test_optional_fields_default_empty():
|
||||
"""品名/规格/仓库/储位/批号可缺省为空展示。"""
|
||||
parsed = parse_movement_rows(
|
||||
source_code="DBS-AWSBI",
|
||||
rows=_rows(material_name="", warehouse_code="", storage_code="", lot_no=""),
|
||||
)
|
||||
row = parsed[0]
|
||||
assert row.material_name == ""
|
||||
@@ -0,0 +1,54 @@
|
||||
"""在途调拨企微汇总通知测试(Phase 3,L1)。
|
||||
|
||||
用途:验证每个非空 Run 恰好一条汇总通知、空数据不通知、
|
||||
通知失败不改变 ERP 结果(run.status 保持)。
|
||||
依赖:transfer_db、execution_service、notification、fakes.FakeWeCom。
|
||||
逻辑:通知状态独立于 ERP 业务状态;失败记录 notification_failed。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import TransferRun
|
||||
from app.services.in_transit_transfer.execution_service import execute_precheck
|
||||
from app.services.in_transit_transfer.notification import notify_run_summary
|
||||
from app.services.in_transit_transfer.precheck_service import create_precheck
|
||||
from tests.services.in_transit_transfer.fakes import FakeWeCom
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
|
||||
def _executed_run(dbs_ready_file):
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1200")
|
||||
erp.seed_inventory("INV-002", "1200")
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
return outcome.run_no
|
||||
|
||||
|
||||
def test_non_empty_run_sends_exactly_one_summary(transfer_db, dbs_ready_file):
|
||||
"""非空 Run → 恰好一条汇总通知;重复调用幂等。"""
|
||||
run_no = _executed_run(dbs_ready_file)
|
||||
wecom = FakeWeCom()
|
||||
first = notify_run_summary(run_no=run_no, sender=wecom, recipients=["u-1", "u-2"])
|
||||
assert first["notification_status"] == "success"
|
||||
second = notify_run_summary(run_no=run_no, sender=wecom, recipients=["u-1"])
|
||||
assert second["delivered"] is False # 已投递,幂等跳过
|
||||
assert len(wecom.deliveries) == 1
|
||||
run = db.session.query(TransferRun).filter_by(run_no=run_no).first()
|
||||
assert run.notification_status == "success"
|
||||
assert run.status == "success" # ERP 结果不受影响
|
||||
|
||||
|
||||
def test_notification_failure_does_not_change_erp_result(transfer_db, dbs_ready_file):
|
||||
"""通知失败 → notification_status=failed,run.status 保持 success。"""
|
||||
run_no = _executed_run(dbs_ready_file)
|
||||
wecom = FakeWeCom()
|
||||
wecom.attach_fail = True
|
||||
result = notify_run_summary(run_no=run_no, sender=wecom, recipients=["u-1"], excel_path="x.xlsx")
|
||||
assert result["notification_status"] == "failed"
|
||||
run = db.session.query(TransferRun).filter_by(run_no=run_no).first()
|
||||
assert run.notification_status == "failed"
|
||||
assert run.status == "success" # 关键:通知失败不改变 ERP 业务结果
|
||||
@@ -0,0 +1,69 @@
|
||||
"""在途调拨 Run 编排测试(Phase 2,L1)。
|
||||
|
||||
用途:验证执行 Run 创建(执行中状态、关联预检与明细)、终态收尾与
|
||||
重复创建防护。
|
||||
依赖:transfer_db、precheck_service、orchestrator、repo_fakes。
|
||||
逻辑:编排层复用 execution_service 落库流程,本文件聚焦 Run 生命周期辅助函数。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import TransferInvoiceItem, TransferPrecheck, TransferRun
|
||||
from app.services.in_transit_transfer.orchestrator import create_execution_run, finalize_run
|
||||
from app.services.in_transit_transfer.precheck_service import create_precheck
|
||||
from app.services.in_transit_transfer.status import TransferRunStatus
|
||||
from tests.services.in_transit_transfer.fakes import FakeERP
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
|
||||
def _ready_precheck(dbs_ready_file):
|
||||
"""创建已预检 precheck 并返回 (deps, summary)。"""
|
||||
erp = FakeERP()
|
||||
erp.seed_inventory("INV-001", "1200")
|
||||
erp.seed_inventory("INV-002", "1200")
|
||||
deps, _, _ = make_transfer_deps(dbs_ready_file, erp=erp)
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
return deps, summary
|
||||
|
||||
|
||||
def test_create_execution_run_links_items_and_sets_executing(transfer_db, dbs_ready_file):
|
||||
"""create_execution_run 创建 executing Run 并关联可执行明细。"""
|
||||
deps, summary = _ready_precheck(dbs_ready_file)
|
||||
precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first()
|
||||
|
||||
run = create_execution_run(precheck, deps=deps, actor_id=None)
|
||||
assert run.status == TransferRunStatus.EXECUTING.value
|
||||
items = db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all()
|
||||
assert len(items) == 2
|
||||
assert all(item.status == "executing" for item in items)
|
||||
|
||||
|
||||
def test_finalize_run_sets_terminal_status(transfer_db, dbs_ready_file):
|
||||
"""finalize_run 按明细终态汇总 Run 状态。"""
|
||||
deps, summary = _ready_precheck(dbs_ready_file)
|
||||
precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first()
|
||||
run = create_execution_run(precheck, deps=deps, actor_id=None)
|
||||
|
||||
items = db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all()
|
||||
for item in items:
|
||||
item.status = "success"
|
||||
finalize_run(run, items)
|
||||
assert run.status == TransferRunStatus.SUCCESS.value
|
||||
|
||||
for item in items:
|
||||
item.status = "blocked_recoverable"
|
||||
finalize_run(run, items)
|
||||
assert run.status == TransferRunStatus.PARTIAL_FAILED.value
|
||||
|
||||
|
||||
def test_create_execution_run_rejects_duplicate(transfer_db, dbs_ready_file):
|
||||
"""已确认的 precheck 不允许重复创建执行 Run。"""
|
||||
deps, summary = _ready_precheck(dbs_ready_file)
|
||||
precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first()
|
||||
create_execution_run(precheck, deps=deps, actor_id=None)
|
||||
with pytest.raises(ConflictError):
|
||||
create_execution_run(precheck, deps=deps, actor_id=None)
|
||||
@@ -0,0 +1,164 @@
|
||||
"""在途调拨预检服务测试(L1,SQLite 内存库)。
|
||||
|
||||
用途:验证 D+1 过滤(当天收料 ERP 调用=0)、严格数量匹配、来源隔离、
|
||||
预检快照 Hash 稳定、缺文件等待与进度恢复。
|
||||
依赖:app fixture、transfer_db、fakes、repo_fakes、precheck_service。
|
||||
逻辑:全部经真实 ORM 落库(create_precheck/restore_precheck),
|
||||
外部依赖注入 Fake 替身。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.in_transit_transfer.erp_adapter import ErpAdapter
|
||||
from app.services.in_transit_transfer.precheck_service import (
|
||||
TransferDeps,
|
||||
create_precheck,
|
||||
restore_precheck,
|
||||
run_precheck,
|
||||
)
|
||||
from tests.services.in_transit_transfer.assertions import assert_erp_calls
|
||||
from tests.services.in_transit_transfer.fakes import FakeERP, FakeRPA
|
||||
from tests.services.in_transit_transfer.repo_fakes import FakeRouteResolver, make_ready_repo, make_transfer_deps
|
||||
|
||||
|
||||
def _deps(*files: dict, erp: FakeERP | None = None, rpa: FakeRPA | None = None) -> tuple[TransferDeps, FakeERP, FakeRPA]:
|
||||
"""构造注入 Fake 依赖的 TransferDeps。"""
|
||||
return make_transfer_deps(*files, erp=erp, rpa=rpa)
|
||||
|
||||
|
||||
def test_happy_path_two_sources_all_executable(dbs_ready_file, crane_ready_file):
|
||||
"""两个来源全部严格匹配 → executable_count 正确,无阻断。"""
|
||||
deps, erp, _ = _deps(dbs_ready_file, crane_ready_file)
|
||||
for invoice, qty in [("INV-001", "1200"), ("INV-002", "1200"), ("INV-008", "600")]:
|
||||
erp.seed_inventory(invoice, qty)
|
||||
|
||||
result = run_precheck(
|
||||
source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06", deps=deps,
|
||||
)
|
||||
summary = result.summary
|
||||
assert summary.counts.executable_count == 3
|
||||
assert summary.counts.not_matured_count == 0
|
||||
assert summary.counts.blocked_count == 0
|
||||
assert summary.status == "ready_to_execute"
|
||||
assert summary.precheck_hash.startswith("sha256:")
|
||||
assert summary.estimated_erp_write_count == 3
|
||||
# 明细 DTO 决策 6/7:拨出/拨入仓库与数量对
|
||||
items = {item.invoice_no: item for item in result.items}
|
||||
assert items["INV-001"].from_warehouse == "DBS-TRANSIT"
|
||||
assert items["INV-001"].to_warehouse == "HUB-CN01"
|
||||
assert items["INV-001"].from_quantity == items["INV-001"].to_quantity == 1200
|
||||
assert len(items["INV-001"].raw_lines) == 2 # 多行汇总保留原始行
|
||||
|
||||
|
||||
def test_same_day_receipt_not_matured_no_erp_call(same_day_receipt_file):
|
||||
"""当天收料 → not_matured,ERP 调用次数为 0。"""
|
||||
deps, erp, _ = _deps(same_day_receipt_file)
|
||||
result = run_precheck(
|
||||
source_codes=["DBS-AWSSG"], business_date="2026-08-06", deps=deps,
|
||||
)
|
||||
assert result.summary.counts.not_matured_count == 1
|
||||
assert result.summary.counts.executable_count == 0
|
||||
assert result.summary.estimated_erp_write_count == 0
|
||||
assert_erp_calls(erp, 0)
|
||||
|
||||
|
||||
def test_quantity_mismatch_blocked_no_write(dbs_ready_file):
|
||||
"""收料 1200 vs ERP 1000 → blocked_recoverable;无任何写调用。"""
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1000")
|
||||
erp.seed_inventory("INV-002", "1200")
|
||||
result = run_precheck(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
|
||||
)
|
||||
items = {item.invoice_no: item for item in result.items}
|
||||
assert items["INV-001"].result == "blocked_quantity_mismatch"
|
||||
assert items["INV-002"].result == "executable"
|
||||
assert result.summary.counts.blocked_count == 1
|
||||
assert erp.write_calls() == []
|
||||
|
||||
|
||||
def test_erp_inventory_not_found_blocked(dbs_ready_file):
|
||||
"""ERP 无库存 → blocked_inventory_not_found。"""
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1200") # INV-002 无库存
|
||||
result = run_precheck(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
|
||||
)
|
||||
items = {item.invoice_no: item for item in result.items}
|
||||
assert items["INV-002"].result == "blocked_inventory_not_found"
|
||||
|
||||
|
||||
def test_missing_file_waits_without_erp():
|
||||
"""缺文件 → 来源阶段 waiting_rpa_callback,无 ERP 调用。"""
|
||||
deps, erp, _ = _deps()
|
||||
result = run_precheck(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
|
||||
)
|
||||
assert result.sources[0].stage == "waiting_rpa_callback"
|
||||
assert result.summary.status == "file_pending"
|
||||
assert_erp_calls(erp, 0)
|
||||
|
||||
|
||||
def test_source_isolation_dbs_failure_does_not_block_crane(crane_ready_file):
|
||||
"""DBS 缺文件且 RPA 触发失败不阻断 CRANE-SZ 预检(来源隔离)。"""
|
||||
deps, erp, rpa = _deps(crane_ready_file)
|
||||
rpa.fail_on.add("DBS-AWSBI")
|
||||
erp.seed_inventory("INV-008", "600")
|
||||
result = run_precheck(
|
||||
source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06", deps=deps,
|
||||
)
|
||||
by_source = {stage.source_code: stage for stage in result.sources}
|
||||
assert by_source["DBS-AWSBI"].stage == "failed"
|
||||
assert by_source["CRANE-SZ"].stage == "file_ready"
|
||||
items = {item.invoice_no: item for item in result.items}
|
||||
assert items["INV-008"].result == "executable"
|
||||
|
||||
|
||||
def test_snapshot_hash_is_stable(dbs_ready_file):
|
||||
"""相同输入两次预检 → 预检 Hash 一致(可审计复算)。"""
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1200")
|
||||
erp.seed_inventory("INV-002", "1200")
|
||||
first = run_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
second = run_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
assert first.summary.precheck_hash == second.summary.precheck_hash
|
||||
|
||||
|
||||
def test_create_and_restore_precheck(transfer_db, dbs_ready_file):
|
||||
"""create_precheck 落库后 restore_precheck 可完整恢复进度与明细。"""
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1200")
|
||||
erp.seed_inventory("INV-002", "1200")
|
||||
|
||||
summary = create_precheck(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
|
||||
)
|
||||
assert summary.precheck_id.startswith("TPC-")
|
||||
restored = restore_precheck(summary.precheck_id)
|
||||
assert restored["summary"].precheck_hash == summary.precheck_hash
|
||||
assert restored["summary"].status == summary.status
|
||||
restored_items = {item.invoice_no: item for item in restored["items"]}
|
||||
assert set(restored_items) == {"INV-001", "INV-002"}
|
||||
assert restored_items["INV-001"].result == "executable"
|
||||
# 落库数量与 DTO 一致(Decimal 文本持久化)
|
||||
assert str(restored_items["INV-001"].to_quantity) == "1200"
|
||||
|
||||
|
||||
def test_route_not_resolved_marks_source_failed(dbs_ready_file):
|
||||
"""来源缺少路由映射 → 该来源阶段失败,其余来源继续(fail-closed)。"""
|
||||
erp = FakeERP()
|
||||
rpa = FakeRPA()
|
||||
deps = TransferDeps(
|
||||
file_repository=make_ready_repo(dbs_ready_file),
|
||||
rpa_trigger=rpa,
|
||||
route_resolver=FakeRouteResolver(routes={}),
|
||||
erp=ErpAdapter(transport=erp, default_org="HX-CN01"),
|
||||
)
|
||||
result = run_precheck(
|
||||
source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06", deps=deps,
|
||||
)
|
||||
by_source = {stage.source_code: stage for stage in result.sources}
|
||||
assert by_source["DBS-AWSBI"].stage == "failed"
|
||||
assert by_source["CRANE-SZ"].stage == "waiting_rpa_callback" # 无文件 → 等待,不阻断
|
||||
@@ -0,0 +1,76 @@
|
||||
"""在途调拨严格数量门禁测试(L0 纯单元)。
|
||||
|
||||
用途:验证"收料数量 == ERP 账面库存 才可执行",大于/小于/缺失均阻断,
|
||||
且不允许 0、负数、非数字与隐式截断。
|
||||
依赖:app.services.in_transit_transfer.quantity。
|
||||
逻辑:数量比较全部基于 Decimal 精确语义,杜绝浮点误差。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.in_transit_transfer.quantity import (
|
||||
QuantityValidationError,
|
||||
classify_quantity_match,
|
||||
strict_quantities_equal,
|
||||
validate_receipt_quantity,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def test_equal_quantities_are_executable():
|
||||
"""收料数量等于账面库存 → executable。"""
|
||||
assert classify_quantity_match(Decimal("1200"), Decimal("1200")) == "executable"
|
||||
|
||||
|
||||
def test_erp_greater_than_receipt_is_blocked():
|
||||
"""ERP 库存大于收料数量 → 阻断(不允许部分调拨)。"""
|
||||
assert classify_quantity_match(Decimal("1200"), Decimal("1500")) == "blocked_quantity_mismatch"
|
||||
|
||||
|
||||
def test_erp_less_than_receipt_is_blocked():
|
||||
"""ERP 库存小于收料数量 → 阻断。"""
|
||||
assert classify_quantity_match(Decimal("1200"), Decimal("800")) == "blocked_quantity_mismatch"
|
||||
|
||||
|
||||
def test_erp_missing_is_blocked():
|
||||
"""ERP 无库存(None)→ 阻断,与数量不一致分开归类。"""
|
||||
assert classify_quantity_match(Decimal("1200"), None) == "blocked_inventory_not_found"
|
||||
|
||||
|
||||
def test_decimal_scale_equality_is_exact():
|
||||
"""1.0 与 1.00 数量相等(Decimal 精确语义)。"""
|
||||
assert strict_quantities_equal(Decimal("1.0"), Decimal("1.00"))
|
||||
|
||||
|
||||
def test_zero_receipt_quantity_rejected():
|
||||
"""收料数量为 0 非法。"""
|
||||
with pytest.raises(QuantityValidationError):
|
||||
validate_receipt_quantity(Decimal("0"))
|
||||
|
||||
|
||||
def test_negative_receipt_quantity_rejected():
|
||||
"""收料数量为负数非法。"""
|
||||
with pytest.raises(QuantityValidationError):
|
||||
validate_receipt_quantity(Decimal("-5"))
|
||||
|
||||
|
||||
def test_non_numeric_quantity_rejected():
|
||||
"""非数字数量非法(解析层不得静默截断)。"""
|
||||
with pytest.raises(QuantityValidationError):
|
||||
validate_receipt_quantity("abc")
|
||||
|
||||
|
||||
def test_string_numeric_quantity_normalized():
|
||||
"""字符串数字归一化为 Decimal 后参与严格比较。"""
|
||||
assert validate_receipt_quantity("1200") == Decimal("1200")
|
||||
assert strict_quantities_equal("1200", Decimal("1200"))
|
||||
|
||||
|
||||
def test_fractional_partial_quantity_rejected_by_policy():
|
||||
"""策略层不允许部分数量:1.5 与 1 不相等即阻断。"""
|
||||
assert classify_quantity_match(Decimal("1.5"), Decimal("1")) == "blocked_quantity_mismatch"
|
||||
@@ -0,0 +1,96 @@
|
||||
"""tests/services/in_transit_transfer/test_query_inventory_gateway.py
|
||||
|
||||
用途:验证调拨 query_inventory 经 CapabilityGateway 接线(首个消费者)——
|
||||
网关被调用、成熟过滤(当天收料不查)、fail-closed(无绑定来源失败但不阻断)。
|
||||
依赖:run_precheck、CapabilityErpAdapter、repo_fakes.make_transfer_deps、transports.base。
|
||||
逻辑:领域规则(严格数量匹配/D+1/来源隔离)仍在领域层;接口选择与调用由连接器框架承担。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from dataclasses import replace
|
||||
from decimal import Decimal
|
||||
|
||||
from app.core.errors import AppError
|
||||
from app.services.in_transit_transfer.gateway_adapter import CapabilityErpAdapter
|
||||
from app.services.in_transit_transfer.precheck_service import run_precheck
|
||||
from app.services.integration_connector.errors import BindingNotFoundError
|
||||
from app.services.integration_connector.transports.base import IntegrationCallResult
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
|
||||
class FakeGateway:
|
||||
"""按 Invoice 返回库存结果的替代网关,并记录调用。"""
|
||||
|
||||
def __init__(self, inventory: dict[str, str] | None = None, *, fail: bool = False) -> None:
|
||||
self.inventory = inventory or {}
|
||||
self.fail = fail
|
||||
self.calls: list[tuple[str, dict, dict]] = []
|
||||
|
||||
def call(self, *, capability, context, params, operation_id, idempotency_key=None, environment=None, transports=None):
|
||||
self.calls.append((capability, context, params))
|
||||
if self.fail:
|
||||
raise BindingNotFoundError(capability=capability)
|
||||
invoice_no = params["invoice_no"]
|
||||
qty = self.inventory.get(invoice_no)
|
||||
if qty is None:
|
||||
return IntegrationCallResult(status="success", data={"found": False})
|
||||
return IntegrationCallResult(status="success", data={"found": True, "quantity": Decimal(qty)})
|
||||
|
||||
|
||||
def _cap_deps(file, gw):
|
||||
deps, _, _ = make_transfer_deps(file)
|
||||
return replace(deps, erp=CapabilityErpAdapter(gateway=gw))
|
||||
|
||||
|
||||
def test_query_inventory_routed_through_gateway(app, dbs_ready_file):
|
||||
"""成熟 Invoice 的库存查询经网关;严格数量匹配仍由领域控制。"""
|
||||
gw = FakeGateway(inventory={"INV-001": "1200", "INV-002": "1200"})
|
||||
result = run_precheck(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06",
|
||||
deps=_cap_deps(dbs_ready_file, gw), run_no="RUN-T",
|
||||
)
|
||||
# 网关被调用,且携带 query_inventory 能力名
|
||||
assert any(capability == "in_transit_transfer.query_inventory" for capability, _, _ in gw.calls)
|
||||
# INV-001 汇总 1200 == ERP 1200 → executable
|
||||
item = next(i for i in result.items if i.invoice_no == "INV-001")
|
||||
assert item.result == "executable"
|
||||
assert item.from_quantity == Decimal("1200")
|
||||
|
||||
|
||||
def test_not_matured_not_queried(app, same_day_receipt_file):
|
||||
"""当天收料(not_matured)不查 ERP——网关零调用。"""
|
||||
gw = FakeGateway(inventory={})
|
||||
result = run_precheck(
|
||||
source_codes=["DBS-AWSSG"], business_date="2026-08-06",
|
||||
deps=_cap_deps(same_day_receipt_file, gw), run_no="RUN-T",
|
||||
)
|
||||
assert gw.calls == []
|
||||
assert result.items[0].result == "not_matured"
|
||||
|
||||
|
||||
def test_no_binding_source_fails_but_not_others(app, dbs_ready_file, crane_ready_file):
|
||||
"""无绑定的来源(网关抛错)标记来源失败,不阻断整个预检。"""
|
||||
class _SplitGateway:
|
||||
"""按 Invoice 区分失败来源:DBS(INV-001/002)失败,CRANE(INV-008)成功。"""
|
||||
|
||||
def __init__(self):
|
||||
self.calls = []
|
||||
|
||||
def call(self, **kwargs):
|
||||
self.calls.append(kwargs)
|
||||
invoice = kwargs["params"]["invoice_no"]
|
||||
if invoice in {"INV-001", "INV-002"}:
|
||||
raise BindingNotFoundError(capability="in_transit_transfer.query_inventory")
|
||||
return IntegrationCallResult(status="success", data={"found": True, "quantity": Decimal("600")})
|
||||
|
||||
deps, _, _ = make_transfer_deps(dbs_ready_file, crane_ready_file)
|
||||
deps = replace(deps, erp=CapabilityErpAdapter(gateway=_SplitGateway()))
|
||||
result = run_precheck(
|
||||
source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06",
|
||||
deps=deps, run_no="RUN-T",
|
||||
)
|
||||
dbs_source = next(s for s in result.sources if s.source_code == "DBS-AWSBI")
|
||||
assert dbs_source.stage == "failed"
|
||||
# CRANE 正常执行 → 出可执行项
|
||||
assert any(i.invoice_no == "INV-008" and i.result == "executable" for i in result.items)
|
||||
@@ -0,0 +1,123 @@
|
||||
"""在途调拨收料文件字段/结构校验测试(L0 纯单元)。
|
||||
|
||||
用途:验证必填列缺失、空值、非法数量(0/负数/非数字)、非法日期与
|
||||
来源身份不一致均整行阻断并抛出 ReceiptFileSchemaError。
|
||||
依赖:app.services.in_transit_transfer.file_parser(纯函数)。
|
||||
逻辑:解析不接触文件存储;所有错误带行号细节,供预检页展示原因。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.in_transit_transfer.file_parser import (
|
||||
ParsedReceiptRow,
|
||||
ReceiptFileSchemaError,
|
||||
parse_receipt_rows,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
VALID_ROW = {
|
||||
"sheet": "Receipt",
|
||||
"row_no": 10,
|
||||
"invoice_no": "INV-001",
|
||||
"material_no": "MAT-001",
|
||||
"material_name": "连接器组件",
|
||||
"specification": "A 型 / 24PIN",
|
||||
"receipt_date": "2026-08-05",
|
||||
"receipt_quantity": "500",
|
||||
"source_code": "DBS-AWSBI",
|
||||
}
|
||||
|
||||
|
||||
def _rows(**overrides) -> list[dict]:
|
||||
"""以 VALID_ROW 为基底覆盖字段构造测试行。"""
|
||||
base = dict(VALID_ROW)
|
||||
base.update(overrides)
|
||||
return [base]
|
||||
|
||||
|
||||
def test_valid_rows_parse():
|
||||
"""合法行解析出全部字段(数量 Decimal、日期 date)。"""
|
||||
parsed = parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows())
|
||||
assert len(parsed) == 1
|
||||
row = parsed[0]
|
||||
assert isinstance(row, ParsedReceiptRow)
|
||||
assert row.invoice_no == "INV-001"
|
||||
assert row.material_no == "MAT-001"
|
||||
assert row.material_name == "连接器组件"
|
||||
assert row.specification == "A 型 / 24PIN"
|
||||
assert row.receipt_date == date(2026, 8, 5)
|
||||
assert row.receipt_quantity == Decimal("500")
|
||||
assert row.sheet == "Receipt"
|
||||
assert row.row_no == 10
|
||||
|
||||
|
||||
def test_missing_invoice_no_rejected():
|
||||
"""Invoice No 缺失必须整行阻断。"""
|
||||
with pytest.raises(ReceiptFileSchemaError):
|
||||
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(invoice_no=""))
|
||||
|
||||
|
||||
def test_missing_material_no_rejected():
|
||||
"""料号缺失必须整行阻断。"""
|
||||
with pytest.raises(ReceiptFileSchemaError):
|
||||
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(material_no=""))
|
||||
|
||||
|
||||
def test_invalid_quantity_rejected():
|
||||
"""非数字数量必须阻断。"""
|
||||
with pytest.raises(ReceiptFileSchemaError):
|
||||
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_quantity="abc"))
|
||||
|
||||
|
||||
def test_zero_quantity_rejected():
|
||||
"""0 数量必须阻断。"""
|
||||
with pytest.raises(ReceiptFileSchemaError):
|
||||
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_quantity="0"))
|
||||
|
||||
|
||||
def test_negative_quantity_rejected():
|
||||
"""负数数量必须阻断。"""
|
||||
with pytest.raises(ReceiptFileSchemaError):
|
||||
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_quantity="-5"))
|
||||
|
||||
|
||||
def test_invalid_date_rejected():
|
||||
"""非法日期必须阻断。"""
|
||||
with pytest.raises(ReceiptFileSchemaError):
|
||||
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(receipt_date="2026/13/99"))
|
||||
|
||||
|
||||
def test_source_identity_mismatch_rejected():
|
||||
"""行内来源与任务来源不一致(Callback 身份漂移)必须阻断。"""
|
||||
with pytest.raises(ReceiptFileSchemaError):
|
||||
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(source_code="CRANE-SZ"))
|
||||
|
||||
|
||||
def test_missing_sheet_or_row_no_rejected():
|
||||
"""Sheet/原始行号缺失无法追溯,必须阻断。"""
|
||||
with pytest.raises(ReceiptFileSchemaError):
|
||||
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(sheet="", row_no=0))
|
||||
|
||||
|
||||
def test_material_name_and_specification_optional():
|
||||
"""品名/规格允许为空(后续由明细 DTO 展示空值)。"""
|
||||
parsed = parse_receipt_rows(
|
||||
source_code="DBS-AWSBI",
|
||||
rows=_rows(material_name="", specification=""),
|
||||
)
|
||||
assert parsed[0].material_name == ""
|
||||
assert parsed[0].specification == ""
|
||||
|
||||
|
||||
def test_error_carries_row_details():
|
||||
"""错误细节必须携带行号与原因,供页面定位。"""
|
||||
with pytest.raises(ReceiptFileSchemaError) as excinfo:
|
||||
parse_receipt_rows(source_code="DBS-AWSBI", rows=_rows(row_no=77, receipt_quantity="abc"))
|
||||
details = excinfo.value.details
|
||||
assert any(str(item.get("row_no")) == "77" for item in details.get("rows", []))
|
||||
@@ -0,0 +1,72 @@
|
||||
"""真实收料 RPA 触发服务测试。
|
||||
|
||||
用途:验证 trigger_receipt_rpa 按来源装配收料 trigger unit 并调用写者;
|
||||
配置/来源/触发目录缺失时 fail-closed(ok=False)。
|
||||
依赖:app(SQLite)fixture、receipt_trigger_service.trigger_receipt_rpa、
|
||||
既有测试种子(ShippingRpaProfile/ShippingInventorySource)。
|
||||
逻辑:来源停用或收料配置缺失不写 trigger,返回 ok=False。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
|
||||
from app.services.in_transit_transfer.receipt_trigger_service import trigger_receipt_rpa
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def receipt_source():
|
||||
"""复用种子来源并为其创建收料配置。"""
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').first()
|
||||
assert source is not None
|
||||
config = ShippingReceiptReportConfig(
|
||||
inventory_source_id=source.id, enabled=True,
|
||||
report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'},
|
||||
query_parameters_json=[], warehouse_ids_json=[],
|
||||
)
|
||||
from app import db
|
||||
|
||||
db.session.add(config)
|
||||
db.session.commit()
|
||||
return source
|
||||
|
||||
|
||||
def test_trigger_receipt_rpa_writes_batch_trigger(app, receipt_source):
|
||||
"""来源有效 → 写入 trigger 并返回 callback_id / trigger_path。"""
|
||||
calls = {}
|
||||
|
||||
def fake_writer(run_no, units, payload=None):
|
||||
calls['run_no'] = run_no
|
||||
calls['units'] = units
|
||||
calls['payload'] = payload or {}
|
||||
return f'/tmp/trigger/{run_no}.json'
|
||||
|
||||
result = trigger_receipt_rpa(
|
||||
source_code='DSV360_AWSDU', business_date='2026-08-06',
|
||||
reason='transfer_retry_receipt', writer=fake_writer,
|
||||
)
|
||||
assert result['ok'] is True
|
||||
assert result['callback_id']
|
||||
assert result['trigger_path'].endswith('.json')
|
||||
assert calls['units'][0]['source_code'] == 'DSV360_AWSDU'
|
||||
assert calls['units'][0]['credential_envelope']
|
||||
assert calls['payload']['schema_version'] == 'shipping_receipt_rpa.v1'
|
||||
|
||||
|
||||
def test_trigger_receipt_rpa_disabled_source_fails_closed(app):
|
||||
"""来源停用 → ok=False,不写 trigger。"""
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').first()
|
||||
source.enabled = False
|
||||
from app import db
|
||||
|
||||
db.session.commit()
|
||||
result = trigger_receipt_rpa(source_code='DSV360_AWSDU', business_date='2026-08-06')
|
||||
assert result['ok'] is False
|
||||
assert result['error_code'] == 'RPA_RECEIPT_CONFIG_MISSING'
|
||||
|
||||
|
||||
def test_trigger_receipt_rpa_missing_config_fails_closed(app):
|
||||
"""来源启用但无收料配置 → ok=False。"""
|
||||
result = trigger_receipt_rpa(source_code='DSV360_AWSDU', business_date='2026-08-06')
|
||||
assert result['ok'] is False
|
||||
@@ -0,0 +1,76 @@
|
||||
"""在途调拨每日恢复(待处理池自动复核)测试(Phase 3,L1)。
|
||||
|
||||
用途:验证历史可恢复项下一排程重新预检并创建新 Attempt;
|
||||
result_unknown / manually_closed / success 不自动写入。
|
||||
依赖:transfer_db、precheck_service、recovery_service、repo_fakes。
|
||||
逻辑:恢复 = 重新预检(仅查询/匹配),不写 ERP;每次恢复新 Attempt。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import TransferAttempt, TransferInvoiceItem
|
||||
from app.services.in_transit_transfer.precheck_service import create_precheck
|
||||
from app.services.in_transit_transfer.recovery_service import run_daily_recovery
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
|
||||
def _mixed_precheck(dbs_ready_file):
|
||||
"""构造 1 个数量不一致 + 1 个可执行的预检。"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1000") # mismatch → blocked
|
||||
erp.seed_inventory("INV-002", "1200") # executable
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
return deps, erp, summary
|
||||
|
||||
|
||||
def test_recovery_reprechecks_and_creates_new_attempt(transfer_db, dbs_ready_file):
|
||||
"""ERP 修正后恢复 → 项转 ready_to_execute,新 Attempt 落库。"""
|
||||
deps, erp, summary = _mixed_precheck(dbs_ready_file)
|
||||
item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="INV-001").first()
|
||||
assert item.status == "blocked_recoverable"
|
||||
old_attempt_no = item.attempt_no
|
||||
|
||||
erp.seed_inventory("INV-001", "1200")
|
||||
outcome = run_daily_recovery(business_date="2026-08-06", deps=deps)
|
||||
assert outcome.recovered_count == 1
|
||||
assert outcome.attempts_created == 1
|
||||
|
||||
refreshed = db.session.get(TransferInvoiceItem, item.id)
|
||||
assert refreshed.status == "ready_to_execute"
|
||||
assert refreshed.attempt_no == old_attempt_no + 1
|
||||
attempts = db.session.query(TransferAttempt).filter_by(item_id=item.id).all()
|
||||
assert len(attempts) == 1 and attempts[0].kind == "erp_query"
|
||||
# 恢复仅预检,不写 ERP
|
||||
assert erp.write_calls() == []
|
||||
|
||||
|
||||
def test_recovery_skips_result_unknown_without_erp(transfer_db, dbs_ready_file):
|
||||
"""result_unknown 不自动恢复,也不产生 ERP 调用。"""
|
||||
deps, erp, summary = _mixed_precheck(dbs_ready_file)
|
||||
item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="INV-001").first()
|
||||
item.status = "result_unknown"
|
||||
db.session.commit()
|
||||
|
||||
outcome = run_daily_recovery(business_date="2026-08-06", deps=deps)
|
||||
assert outcome.skipped_result_unknown == 1
|
||||
assert outcome.recovered_count == 0
|
||||
assert erp.write_calls() == []
|
||||
|
||||
|
||||
def test_recovery_skips_manually_closed_and_success(transfer_db, dbs_ready_file):
|
||||
"""manually_closed / success 永久排除,不生成 Attempt。"""
|
||||
deps, erp, summary = _mixed_precheck(dbs_ready_file)
|
||||
blocked = db.session.query(TransferInvoiceItem).filter_by(invoice_no="INV-001").first()
|
||||
blocked.status = "manually_closed"
|
||||
blocked.manually_closed_reason = "线下处理"
|
||||
success = db.session.query(TransferInvoiceItem).filter_by(invoice_no="INV-002").first()
|
||||
success.status = "success"
|
||||
db.session.commit()
|
||||
|
||||
outcome = run_daily_recovery(business_date="2026-08-06", deps=deps)
|
||||
assert outcome.skipped_manually_closed == 1
|
||||
assert outcome.recovered_count == 0
|
||||
assert outcome.attempts_created == 0
|
||||
@@ -0,0 +1,117 @@
|
||||
"""在途调拨人工重试与人工关闭测试(Phase 3,L1)。
|
||||
|
||||
用途:验证人工重试只创建新 Attempt(重新查询 ERP,不重新抓 RPA、不写 ERP),
|
||||
result_unknown 拒绝重试;人工关闭原因必填且永久排除。
|
||||
依赖:transfer_db、precheck_service、retry_service、manual_close_service、repo_fakes。
|
||||
逻辑:重试前冻结文件不变;每次重试 attempt_no 递增且旧 Attempt 保留。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import TransferAttempt, TransferInvoiceItem
|
||||
from app.services.in_transit_transfer.manual_close_service import manual_close_item
|
||||
from app.services.in_transit_transfer.precheck_service import create_precheck
|
||||
from app.services.in_transit_transfer.retry_service import retry_item
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
|
||||
def _mismatch_precheck(dbs_ready_file):
|
||||
"""构造 INV-001 数量不一致的预检。"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1000")
|
||||
erp.seed_inventory("INV-002", "1200")
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
return deps, erp, summary
|
||||
|
||||
|
||||
def _item_by_invoice(invoice_no: str) -> TransferInvoiceItem:
|
||||
return db.session.query(TransferInvoiceItem).filter_by(invoice_no=invoice_no).first()
|
||||
|
||||
|
||||
def test_retry_creates_new_attempt_and_matches(transfer_db, dbs_ready_file):
|
||||
"""ERP 修正后重试 → 新 Attempt,状态进入 ready_to_execute。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
item = _item_by_invoice("INV-001")
|
||||
assert item.status == "blocked_recoverable"
|
||||
old_attempt_count = item.attempt_no
|
||||
|
||||
erp.seed_inventory("INV-001", "1200") # 人工在 ERP 修正库存
|
||||
result = retry_item(item_id=item.id, deps=deps)
|
||||
assert result["status"] == "ready_to_execute"
|
||||
assert result["attempt_no"] == old_attempt_count + 1
|
||||
|
||||
refreshed = db.session.get(TransferInvoiceItem, item.id)
|
||||
assert refreshed.status == "ready_to_execute"
|
||||
assert refreshed.attempt_no == old_attempt_count + 1
|
||||
attempts = db.session.query(TransferAttempt).filter_by(item_id=item.id).all()
|
||||
assert len(attempts) == 1
|
||||
assert attempts[0].kind == "erp_query"
|
||||
# 重试不写 ERP
|
||||
assert erp.write_calls() == []
|
||||
|
||||
|
||||
def test_retry_still_mismatch_keeps_blocked(transfer_db, dbs_ready_file):
|
||||
"""重试后仍不匹配 → 保持 blocked_recoverable,attempt_no 递增。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
item = _item_by_invoice("INV-001")
|
||||
old = item.attempt_no
|
||||
result = retry_item(item_id=item.id, deps=deps)
|
||||
assert result["status"] == "blocked_recoverable"
|
||||
assert result["attempt_no"] == old + 1
|
||||
|
||||
|
||||
def test_retry_result_unknown_rejected(transfer_db, dbs_ready_file):
|
||||
"""result_unknown 只读:拒绝重试(禁止猜测性二次写入)。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
item = _item_by_invoice("INV-001")
|
||||
item.status = "result_unknown"
|
||||
item.result_code = "result_unknown"
|
||||
db.session.commit()
|
||||
with pytest.raises(ValidationError):
|
||||
retry_item(item_id=item.id, deps=deps)
|
||||
assert erp.write_calls() == []
|
||||
|
||||
|
||||
def test_retry_rpa_refetch_rejected_after_run(transfer_db, dbs_ready_file):
|
||||
"""Run 创建后禁止重新抓取 RPA(文件冻结)。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
item = _item_by_invoice("INV-001")
|
||||
with pytest.raises(ValidationError):
|
||||
retry_item(item_id=item.id, deps=deps, kind="rpa_refetch")
|
||||
|
||||
|
||||
def test_manual_close_requires_reason(transfer_db, dbs_ready_file):
|
||||
"""人工关闭原因必填。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
item = _item_by_invoice("INV-001")
|
||||
with pytest.raises(ValidationError):
|
||||
manual_close_item(item_id=item.id, reason="")
|
||||
|
||||
|
||||
def test_manual_close_marks_terminal(transfer_db, dbs_ready_file):
|
||||
"""人工关闭 → manually_closed(永久排除,后续排程不再处理)。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
item = _item_by_invoice("INV-001")
|
||||
result = manual_close_item(item_id=item.id, reason="货代确认无需调拨")
|
||||
assert result["status"] == "manually_closed"
|
||||
refreshed = db.session.get(TransferInvoiceItem, item.id)
|
||||
assert refreshed.status == "manually_closed"
|
||||
assert refreshed.manually_closed_reason == "货代确认无需调拨"
|
||||
# 关闭后不再进入可恢复池(自动排程不再处理)
|
||||
from app.services.in_transit_transfer.backlog_service import backlog_summary
|
||||
|
||||
assert backlog_summary().recoverable_count == 0
|
||||
|
||||
|
||||
def test_manual_close_result_unknown_rejected(transfer_db, dbs_ready_file):
|
||||
"""result_unknown 只读:禁止人工关闭(需按 SOP 核实)。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
item = _item_by_invoice("INV-001")
|
||||
item.status = "result_unknown"
|
||||
db.session.commit()
|
||||
with pytest.raises(ValidationError):
|
||||
manual_close_item(item_id=item.id, reason="尝试关闭未知项")
|
||||
@@ -0,0 +1,46 @@
|
||||
"""在途调拨排程注册与执行测试(Phase 3)。
|
||||
|
||||
用途:验证 08:00 收料文件 / 09:00 自动调拨 platform job 已注册(含参数契约),
|
||||
handler 返回标准 ScheduleExecuteResult(7 元组)。
|
||||
依赖:schedule.job_registry、schedule 两个 in_transit job 模块。
|
||||
逻辑:只验证注册契约与调用形态,真实排程触发由 scheduler 驱动。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.schedule.job_registry import get_platform_job, list_platform_jobs
|
||||
|
||||
|
||||
def test_receipt_file_job_registered_with_schedule_defaults():
|
||||
"""08:00 收料文件 job 注册且含 source_codes 参数契约。"""
|
||||
job = get_platform_job("in-transit-receipt-file")
|
||||
assert job is not None
|
||||
assert job.enabled
|
||||
keys = {field.get("key") for field in job.params_schema}
|
||||
assert "source_codes" in keys
|
||||
|
||||
|
||||
def test_transfer_job_registered_with_schedule_defaults():
|
||||
"""09:00 自动调拨 job 注册且含并发/恢复参数契约。"""
|
||||
job = get_platform_job("in-transit-transfer")
|
||||
assert job is not None
|
||||
assert job.enabled
|
||||
keys = {field.get("key") for field in job.params_schema}
|
||||
assert {"source_codes", "recover_history"} <= keys
|
||||
|
||||
|
||||
def test_schedule_handlers_return_seven_tuple():
|
||||
"""两个排程 handler 返回标准 ScheduleExecuteResult(7 元组)。"""
|
||||
from app.services.schedule.in_transit_receipt_file_job import run_in_transit_receipt_file_schedule
|
||||
from app.services.schedule.in_transit_transfer_job import run_in_transit_transfer_schedule
|
||||
|
||||
for handler in (run_in_transit_receipt_file_schedule, run_in_transit_transfer_schedule):
|
||||
assert callable(handler)
|
||||
|
||||
|
||||
def test_jobs_visible_in_platform_list():
|
||||
"""platform job 列表包含两个调拨排程。"""
|
||||
keys = {job.key for job in list_platform_jobs()}
|
||||
assert {"in-transit-receipt-file", "in-transit-transfer"} <= keys
|
||||
@@ -0,0 +1,88 @@
|
||||
"""来源收料文件状态投影服务测试。
|
||||
|
||||
用途:验证 resolve_source_file_status 只读货代收料事实(UnitRun/ReportFile),
|
||||
按来源投影 ready/fetching/failed/none。调拨不维护独立抓取状态表。
|
||||
依赖:app(SQLite)、ShippingInventorySource 种子、ScheduleTask/ScheduleRun/UnitRun/ReportFile。
|
||||
逻辑:有文件→ready;有进行中单元→fetching;最新单元失败终态→failed;否则→none。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.in_transit_transfer.source_file_status import resolve_source_file_status
|
||||
|
||||
SOURCE_CODE = 'DSV360_AWSDU'
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def receipt_unit_run():
|
||||
"""构造一条收料执行单元(含排程/来源上下文)。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun
|
||||
|
||||
source = ShippingInventorySource.query.filter_by(source_code=SOURCE_CODE).one()
|
||||
task = ScheduleTask(
|
||||
schedule_no='SCH-SOURCE-STATUS', name='Source status test', schedule_type='platform_job',
|
||||
owner_user_id=1, cron_expr='0 8 * * *', job_params={},
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-SOURCE-STATUS', schedule_task_id=task.id, status='awaiting_callback')
|
||||
db.session.add(run)
|
||||
db.session.flush()
|
||||
unit = ShippingReceiptRpaUnitRun(
|
||||
schedule_run_id=run.id, inventory_source_id=source.id, source_code=source.source_code,
|
||||
connector_type='dbs', warehouse_id='AWSDU', callback_id='receipt-status-001',
|
||||
status='awaiting_rpa', config_snapshot_json={},
|
||||
)
|
||||
db.session.add(unit)
|
||||
db.session.commit()
|
||||
return unit
|
||||
|
||||
|
||||
def test_no_file_and_no_unit_is_none(app):
|
||||
"""无文件且无执行单元 → none(待触发)。"""
|
||||
status = resolve_source_file_status(source_code=SOURCE_CODE)
|
||||
assert status['file_status'] == 'none'
|
||||
assert status['has_ready_file'] is False
|
||||
|
||||
|
||||
def test_running_unit_is_fetching(app, receipt_unit_run):
|
||||
"""有进行中执行单元 → fetching。"""
|
||||
status = resolve_source_file_status(source_code=SOURCE_CODE)
|
||||
assert status['file_status'] == 'fetching'
|
||||
assert status['has_ready_file'] is False
|
||||
|
||||
|
||||
def test_failed_latest_unit_is_failed(app, receipt_unit_run):
|
||||
"""最新单元为失败终态且无文件 → failed。"""
|
||||
from app import db
|
||||
from app.models import ShippingReceiptRpaUnitRun
|
||||
|
||||
receipt_unit_run.status = 'failed'
|
||||
db.session.commit()
|
||||
status = resolve_source_file_status(source_code=SOURCE_CODE)
|
||||
assert status['file_status'] == 'failed'
|
||||
|
||||
|
||||
def test_report_file_is_ready(app, receipt_unit_run):
|
||||
"""有收料归档文件 → ready,且带 file_no/sha256。"""
|
||||
from app import db
|
||||
from app.models import ShippingReceiptReportFile
|
||||
|
||||
receipt_unit_run.status = 'success'
|
||||
digest = hashlib.sha256(b'receipt workbook').hexdigest()
|
||||
db.session.add(ShippingReceiptReportFile(
|
||||
unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test',
|
||||
storage_key='shipping/receipt/test.xlsx', original_filename='receipt.xlsx',
|
||||
file_size=16, sha256=digest,
|
||||
))
|
||||
db.session.commit()
|
||||
status = resolve_source_file_status(source_code=SOURCE_CODE)
|
||||
assert status['file_status'] == 'ready'
|
||||
assert status['has_ready_file'] is True
|
||||
assert status['file_no'] == 'receipt.xlsx'
|
||||
assert status['file_sha256'] == digest
|
||||
@@ -0,0 +1,88 @@
|
||||
"""来源级状态服务测试。
|
||||
|
||||
用途:验证 create_source_job / advance_source_job / source_jobs_for_run 的职责——
|
||||
一次 run 内每来源一条 job((run, source) 唯一),状态推进统一集中在此服务。
|
||||
依赖:app(SQLite)、models(TransferRun/TransferSourceJob)、source_job_service。
|
||||
逻辑:同 run 同来源复用(不重复建);终态自动写 finished_at。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.models import TransferRun, TransferSourceJob
|
||||
from app.services.in_transit_transfer.source_job_service import (
|
||||
advance_source_job,
|
||||
create_source_job,
|
||||
source_jobs_for_run,
|
||||
)
|
||||
|
||||
|
||||
def _run() -> TransferRun:
|
||||
from app import db
|
||||
|
||||
run = TransferRun(run_no='RUN-SJOB', trigger_type='manual', business_date='2026-08-06', status='prechecking')
|
||||
db.session.add(run)
|
||||
db.session.flush()
|
||||
return run
|
||||
|
||||
|
||||
def test_create_source_job_per_run_source_unique(app):
|
||||
"""一次 run 内同来源只建一条 job。"""
|
||||
run = _run()
|
||||
job_a = create_source_job(run_id=run.id, source_code='DBS-AWSBI')
|
||||
job_b = create_source_job(run_id=run.id, source_code='DBS-AWSBI')
|
||||
from app import db
|
||||
|
||||
db.session.commit()
|
||||
assert job_a.id == job_b.id
|
||||
|
||||
|
||||
def test_source_jobs_for_run_returns_ordered_sources(app):
|
||||
"""source_jobs_for_run 按来源排序。"""
|
||||
run = _run()
|
||||
create_source_job(run_id=run.id, source_code='CRANE-SZ')
|
||||
create_source_job(run_id=run.id, source_code='DBS-AWSBI')
|
||||
from app import db
|
||||
|
||||
db.session.commit()
|
||||
jobs = source_jobs_for_run(run.id)
|
||||
assert [j.source_code for j in jobs] == ['CRANE-SZ', 'DBS-AWSBI']
|
||||
|
||||
|
||||
def test_advance_source_job_writes_status_and_fields(app):
|
||||
"""推进 job 写入状态与来源字段。"""
|
||||
run = _run()
|
||||
job = create_source_job(run_id=run.id, source_code='DBS-AWSBI')
|
||||
advance_source_job(job=job, status='waiting_rpa_callback', file_no='REC-1', file_sha256='hash')
|
||||
from app import db
|
||||
|
||||
db.session.commit()
|
||||
assert job.status == 'waiting_rpa_callback'
|
||||
assert job.file_no == 'REC-1'
|
||||
assert job.file_sha256 == 'hash'
|
||||
|
||||
|
||||
def test_terminal_status_sets_finished_at(app):
|
||||
"""到达终态自动写 finished_at。"""
|
||||
run = _run()
|
||||
job = create_source_job(run_id=run.id, source_code='DBS-AWSBI')
|
||||
advance_source_job(job=job, status='failed', error_code='ERR', error_message='boom')
|
||||
from app import db
|
||||
|
||||
db.session.commit()
|
||||
assert job.status == 'failed'
|
||||
assert job.finished_at is not None
|
||||
assert job.error_code == 'ERR'
|
||||
|
||||
|
||||
def test_file_ready_is_valid_source_job_status(app):
|
||||
"""file_ready 是合法来源 job 状态(来源准备流程阶段与 job 状态集对齐)。"""
|
||||
run = _run()
|
||||
job = create_source_job(run_id=run.id, source_code='DBS-AWSBI')
|
||||
advance_source_job(job=job, status='file_ready', file_no='REC-1')
|
||||
from app import db
|
||||
|
||||
db.session.commit()
|
||||
assert job.status == 'file_ready'
|
||||
assert job.file_no == 'REC-1'
|
||||
@@ -0,0 +1,123 @@
|
||||
"""在途调拨状态机与转换门禁测试(L0 纯单元)。
|
||||
|
||||
用途:验证提示词冻结的 13 个状态全部存在、非法迁移被服务端拒绝、
|
||||
result_unknown / manually_closed / success 无出边、通知失败不改变 ERP 结果。
|
||||
依赖:app.services.in_transit_transfer.status。
|
||||
逻辑:所有转换必须显式声明于转换表;未声明迁移一律抛 TransferStateError。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.in_transit_transfer.status import (
|
||||
ITEM_TRANSITIONS,
|
||||
RUN_TRANSITIONS,
|
||||
TERMINAL_TRANSFER_STATUSES,
|
||||
TransferNotificationStatus,
|
||||
TransferRunStatus,
|
||||
TransferStateError,
|
||||
TransferStatus,
|
||||
apply_notification_failure,
|
||||
assert_transition_allowed,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
PROMPT_STATUSES = {
|
||||
"file_pending", "file_ready", "prechecking", "ready_to_execute", "executing",
|
||||
"success", "duplicate_success", "blocked_recoverable", "not_matured",
|
||||
"result_unknown", "manually_closed", "cancelled", "notification_failed",
|
||||
}
|
||||
|
||||
|
||||
def test_all_prompt_statuses_covered():
|
||||
"""提示词要求的 13 个状态必须全部存在。"""
|
||||
actual = {status.value for status in TransferStatus}
|
||||
assert PROMPT_STATUSES <= actual
|
||||
|
||||
|
||||
def test_success_and_duplicate_success_are_terminal():
|
||||
"""成功/重复成功为终态(幂等跳过)。"""
|
||||
assert TransferStatus.SUCCESS in TERMINAL_TRANSFER_STATUSES
|
||||
assert TransferStatus.DUPLICATE_SUCCESS in TERMINAL_TRANSFER_STATUSES
|
||||
|
||||
|
||||
def test_result_unknown_is_terminal_without_outgoing_edges():
|
||||
"""result_unknown 无出边:禁止自动重试、禁止手工猜测性操作。"""
|
||||
assert TransferStatus.RESULT_UNKNOWN in TERMINAL_TRANSFER_STATUSES
|
||||
assert ITEM_TRANSITIONS[TransferStatus.RESULT_UNKNOWN.value] == frozenset()
|
||||
|
||||
|
||||
def test_manually_closed_is_terminal_without_outgoing_edges():
|
||||
"""manually_closed 永久排除:不得再进入待处理池。"""
|
||||
assert TransferStatus.MANUALLY_CLOSED in TERMINAL_TRANSFER_STATUSES
|
||||
assert ITEM_TRANSITIONS[TransferStatus.MANUALLY_CLOSED.value] == frozenset()
|
||||
|
||||
|
||||
def test_illegal_transition_rejected():
|
||||
"""file_ready 直接跳 executing 必须抛领域错误。"""
|
||||
with pytest.raises(TransferStateError):
|
||||
assert_transition_allowed(TransferStatus.FILE_READY.value, TransferStatus.EXECUTING.value)
|
||||
|
||||
|
||||
def test_legal_transition_accepted():
|
||||
"""file_ready → prechecking 是合法迁移。"""
|
||||
assert_transition_allowed(TransferStatus.FILE_READY.value, TransferStatus.PRECHECKING.value)
|
||||
|
||||
|
||||
def test_executing_to_success_accepted():
|
||||
"""executing → success 合法。"""
|
||||
assert_transition_allowed(TransferStatus.EXECUTING.value, TransferStatus.SUCCESS.value)
|
||||
|
||||
|
||||
def test_executing_to_result_unknown_accepted_but_no_auto_retry():
|
||||
"""executing → result_unknown 合法(超时落位),但之后无任何出边。"""
|
||||
assert_transition_allowed(TransferStatus.EXECUTING.value, TransferStatus.RESULT_UNKNOWN.value)
|
||||
with pytest.raises(TransferStateError):
|
||||
assert_transition_allowed(TransferStatus.RESULT_UNKNOWN.value, TransferStatus.EXECUTING.value)
|
||||
with pytest.raises(TransferStateError):
|
||||
assert_transition_allowed(TransferStatus.RESULT_UNKNOWN.value, TransferStatus.MANUALLY_CLOSED.value)
|
||||
|
||||
|
||||
def test_blocked_recoverable_to_manual_close_and_recheck():
|
||||
"""blocked_recoverable 可人工关闭或重新预检(新 Attempt)。"""
|
||||
assert_transition_allowed(TransferStatus.BLOCKED_RECOVERABLE.value, TransferStatus.MANUALLY_CLOSED.value)
|
||||
assert_transition_allowed(TransferStatus.BLOCKED_RECOVERABLE.value, TransferStatus.PRECHECKING.value)
|
||||
|
||||
|
||||
def test_unknown_status_rejected():
|
||||
"""未知状态字符串不得被门禁接受。"""
|
||||
with pytest.raises(TransferStateError):
|
||||
assert_transition_allowed("no_such_status", TransferStatus.SUCCESS.value)
|
||||
|
||||
|
||||
def test_not_matured_has_no_outgoing_edges():
|
||||
"""not_matured 无出边:当天不得查询 ERP、不得生成调拨单。"""
|
||||
assert ITEM_TRANSITIONS[TransferStatus.NOT_MATURED.value] == frozenset()
|
||||
|
||||
|
||||
def test_run_transition_queued_to_executing_path():
|
||||
"""Run 生命周期:queued → preparing_files → prechecking → ready_to_execute → executing。"""
|
||||
assert_transition_allowed(TransferRunStatus.QUEUED.value, TransferRunStatus.PREPARING_FILES.value, transitions=RUN_TRANSITIONS)
|
||||
assert_transition_allowed(TransferRunStatus.PREPARING_FILES.value, TransferRunStatus.PRECHECKING.value, transitions=RUN_TRANSITIONS)
|
||||
assert_transition_allowed(TransferRunStatus.PRECHECKING.value, TransferRunStatus.READY_TO_EXECUTE.value, transitions=RUN_TRANSITIONS)
|
||||
assert_transition_allowed(TransferRunStatus.READY_TO_EXECUTE.value, TransferRunStatus.EXECUTING.value, transitions=RUN_TRANSITIONS)
|
||||
|
||||
|
||||
def test_notification_failed_does_not_change_erp_result():
|
||||
"""通知失败不改变 ERP 结果:apply_notification_failure 返回原 ERP 终态。"""
|
||||
assert apply_notification_failure(TransferRunStatus.SUCCESS.value) == TransferRunStatus.SUCCESS.value
|
||||
assert apply_notification_failure(TransferRunStatus.PARTIAL_FAILED.value) == TransferRunStatus.PARTIAL_FAILED.value
|
||||
|
||||
|
||||
def test_notification_failed_rejected_on_non_terminal_run():
|
||||
"""非终态 Run 不允许记录通知失败(必须先结束 ERP 阶段)。"""
|
||||
with pytest.raises(TransferStateError):
|
||||
apply_notification_failure(TransferRunStatus.EXECUTING.value)
|
||||
|
||||
|
||||
def test_notification_status_enum():
|
||||
"""通知状态枚举包含 pending/success/failed(failed 即 notification_failed 语义)。"""
|
||||
assert TransferNotificationStatus.FAILED.value == "failed"
|
||||
assert TransferNotificationStatus.SUCCESS.value == "success"
|
||||
@@ -0,0 +1,63 @@
|
||||
"""在途调拨策略硬门禁测试(L0 纯单元)。
|
||||
|
||||
用途:验证一期策略禁止部分数量调拨、数量容差与 ERP 自动重试,
|
||||
并强制默认确认有效期(10 分钟)。
|
||||
依赖:app.services.in_transit_transfer.strategy。
|
||||
逻辑:任何策略变体触碰三项禁令之一即抛 StrategyViolationError。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.in_transit_transfer.strategy import (
|
||||
TransferStrategyPolicy,
|
||||
StrategyViolationError,
|
||||
default_strategy,
|
||||
validate_strategy,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def test_default_strategy_is_valid():
|
||||
"""默认策略(无部分调拨/无容差/无自动重试/10 分钟确认)合法。"""
|
||||
strategy = default_strategy()
|
||||
validate_strategy(strategy)
|
||||
assert strategy.confirm_ttl_seconds == 600
|
||||
|
||||
|
||||
def test_partial_transfer_rejected():
|
||||
"""开启部分数量调拨必须被发布门禁拒绝。"""
|
||||
strategy = TransferStrategyPolicy(allow_partial=True)
|
||||
with pytest.raises(StrategyViolationError) as excinfo:
|
||||
validate_strategy(strategy)
|
||||
assert "partial" in str(excinfo.value)
|
||||
|
||||
|
||||
def test_quantity_tolerance_rejected():
|
||||
"""任何非零数量容差必须被拒绝。"""
|
||||
strategy = TransferStrategyPolicy(quantity_tolerance=Decimal("0.01"))
|
||||
with pytest.raises(StrategyViolationError):
|
||||
validate_strategy(strategy)
|
||||
|
||||
|
||||
def test_erp_auto_retry_rejected():
|
||||
"""开启 ERP 自动重试必须被拒绝(result_unknown 严禁自动重试)。"""
|
||||
strategy = TransferStrategyPolicy(allow_erp_auto_retry=True)
|
||||
with pytest.raises(StrategyViolationError):
|
||||
validate_strategy(strategy)
|
||||
|
||||
|
||||
def test_combined_violations_still_rejected():
|
||||
"""多项禁令同时开启仍拒绝。"""
|
||||
strategy = TransferStrategyPolicy(allow_partial=True, allow_erp_auto_retry=True)
|
||||
with pytest.raises(StrategyViolationError):
|
||||
validate_strategy(strategy)
|
||||
|
||||
|
||||
def test_custom_ttl_allowed_but_default_ten_minutes():
|
||||
"""确认有效期可配置,但默认必须是 600 秒(10 分钟)。"""
|
||||
assert TransferStrategyPolicy().confirm_ttl_seconds == 600
|
||||
@@ -0,0 +1,84 @@
|
||||
"""在途调拨 Worker 崩溃/陈旧执行恢复测试(Phase 4,L1)。
|
||||
|
||||
用途:验证执行中(executing)且租约过期的项可恢复(依赖 Invoice 幂等,不重复建单)、
|
||||
停滞 Run 可终态收尾、result_unknown 不被自动重试。
|
||||
依赖:transfer_db、precheck/execution/recovery、repo_fakes。
|
||||
逻辑:恢复 = 重新写前复查 + 幂等写入;已落单场景由 ERP 返回 duplicate_success。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import TransferInvoiceItem, TransferRun
|
||||
from app.services.in_transit_transfer.execution_service import execute_precheck
|
||||
from app.services.in_transit_transfer.precheck_service import create_precheck
|
||||
from app.services.in_transit_transfer.recovery import (
|
||||
finalize_stale_runs,
|
||||
recover_stale_execution_items,
|
||||
)
|
||||
from app.services.in_transit_transfer.status import TransferStatus
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
|
||||
def _executing_precheck(dbs_ready_file):
|
||||
"""构造已预检 precheck(不执行),并手动把明细置为 executing。"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1200")
|
||||
erp.seed_inventory("INV-002", "1200")
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
for item in db.session.query(TransferInvoiceItem).all():
|
||||
item.status = "executing"
|
||||
item.updated_at = datetime.utcnow() - timedelta(hours=2) # 租约已过期
|
||||
db.session.commit()
|
||||
return deps, erp
|
||||
|
||||
|
||||
def test_recover_stale_execution_items_completes_writes(transfer_db, dbs_ready_file):
|
||||
"""租约过期的 executing 项恢复后完成写入(幂等,无重复建单)。"""
|
||||
deps, erp = _executing_precheck(dbs_ready_file)
|
||||
result = recover_stale_execution_items(deps=deps)
|
||||
assert result["recovered"] == 2
|
||||
items = db.session.query(TransferInvoiceItem).all()
|
||||
assert all(item.status == "success" for item in items)
|
||||
assert all(item.erp_document_no for item in items)
|
||||
# 每 Invoice 恰 1 次写(恢复只写一次,不重复建单)
|
||||
assert len(erp.write_calls()) == 2
|
||||
|
||||
|
||||
def test_recover_skips_result_unknown(transfer_db, dbs_ready_file):
|
||||
"""result_unknown 不自动重试(不触碰、不写 ERP)。"""
|
||||
deps, erp = _executing_precheck(dbs_ready_file)
|
||||
item = db.session.query(TransferInvoiceItem).first()
|
||||
item.status = "result_unknown"
|
||||
db.session.commit()
|
||||
result = recover_stale_execution_items(deps=deps)
|
||||
assert result["recovered"] == 1 # 仅另一个 executing 项恢复
|
||||
db.session.refresh(item)
|
||||
assert item.status == "result_unknown" # 未知项保持只读
|
||||
assert len(erp.write_calls()) == 1 # 未知项 0 写入
|
||||
|
||||
|
||||
def test_finalize_stale_runs_marks_terminal(transfer_db, dbs_ready_file):
|
||||
"""停滞 Run(全部明细已终态但 Run 仍 executing)→ 收尾为 success。"""
|
||||
from app.models import TransferPrecheck
|
||||
from app.services.in_transit_transfer.orchestrator import create_execution_run
|
||||
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1200")
|
||||
erp.seed_inventory("INV-002", "1200")
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
precheck = TransferPrecheck.query.filter_by(precheck_no=summary.precheck_id).first()
|
||||
run = create_execution_run(precheck, deps=deps, actor_id=None)
|
||||
for item in db.session.query(TransferInvoiceItem).filter_by(run_id=run.id).all():
|
||||
item.status = "success"
|
||||
item.erp_document_no = "TRF-DONE"
|
||||
db.session.commit()
|
||||
|
||||
run_ids = finalize_stale_runs()
|
||||
assert run.id in run_ids
|
||||
db.session.refresh(run)
|
||||
assert run.status == "success"
|
||||
@@ -0,0 +1,122 @@
|
||||
"""tests/services/integration_connector/test_binding.py
|
||||
|
||||
用途:验证 Binding 解析与版本冻结——默认/上下文覆盖/优先级/生效区间/状态门禁/fail-closed。
|
||||
依赖:IntegrationBinding 等模型、binding.py、errors.py。
|
||||
逻辑:只匹配 published + environment + 生效区间 + context_selector 子集;
|
||||
无命中抛 BindingNotFoundError;快照冻结 interface 版本与配置(调用期冻结,非活表)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError
|
||||
from app.models import IntegrationBinding, IntegrationClientInstance, IntegrationInterfaceDefinition
|
||||
from app.services.integration_connector.binding import BindingSnapshot, resolve_binding
|
||||
|
||||
|
||||
def _client(code="CLI-A", **overrides):
|
||||
values = {"name": f"client {code}", "connector_type": "soap", "environment": "prod",
|
||||
"config_json": {"endpoint": "https://erp.invalid"}}
|
||||
values.update(overrides)
|
||||
return IntegrationClientInstance(code=code, **values)
|
||||
|
||||
|
||||
def _interface(code="IFACE-Q", **overrides):
|
||||
values = {"name": "查询库存", "client_instance_code": "CLI-A", "connector_type": "soap",
|
||||
"request_spec_json": {"method": "GET", "path": "/stock"},
|
||||
"input_schema_json": {}, "response_mapping_json": {"qty": {"expr": "quantity", "transform": "decimal"}},
|
||||
"output_schema_json": {"type": "object", "properties": {"qty": {"type": "number"}}},
|
||||
"version": 3, "status": "published"}
|
||||
values.update(overrides)
|
||||
return IntegrationInterfaceDefinition(code=code, **values)
|
||||
|
||||
|
||||
def _binding(capability="in_transit_transfer.query_inventory", **overrides):
|
||||
values = {"capability": capability, "context_selector_json": {},
|
||||
"client_instance_code": "CLI-A", "interface_definition_code": "IFACE-Q",
|
||||
"mapping_version": 2, "priority": 0, "environment": "prod", "status": "published"}
|
||||
values.update(overrides)
|
||||
return IntegrationBinding(**values)
|
||||
|
||||
|
||||
def _seed_default(app):
|
||||
db.session.add_all([_client(), _interface(), _binding()])
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def test_default_binding_matches_any_context(app):
|
||||
"""空 context_selector 的默认绑定命中(context 含额外键也可命中)。"""
|
||||
_seed_default(app)
|
||||
snap = resolve_binding("in_transit_transfer.query_inventory", {"source_code": "DBS-AWSBI"}, "prod")
|
||||
assert snap.client_code == "CLI-A"
|
||||
assert snap.interface_code == "IFACE-Q"
|
||||
assert snap.mapping_version == 2
|
||||
|
||||
|
||||
def test_context_specific_overrides_default(app):
|
||||
"""context_selector 匹配的来源专属绑定(更高优先级)覆盖默认绑定。"""
|
||||
db.session.add_all([_client(), _interface()])
|
||||
db.session.add_all([
|
||||
_binding(),
|
||||
_binding(context_selector_json={"source_code": "CRANE-SZ"}, priority=10),
|
||||
])
|
||||
db.session.commit()
|
||||
snap = resolve_binding("in_transit_transfer.query_inventory", {"source_code": "CRANE-SZ"}, "prod")
|
||||
assert snap.context_selector == {"source_code": "CRANE-SZ"}
|
||||
|
||||
|
||||
def test_higher_priority_wins_among_matching(app):
|
||||
"""同一 context 下、不同 context_selector 均命中时,priority 高者优先。"""
|
||||
db.session.add_all([_client(), _interface()])
|
||||
db.session.add_all([
|
||||
_binding(context_selector_json={"source_code": "X", "region": "cn"}, priority=1),
|
||||
_binding(context_selector_json={"source_code": "X"}, priority=5),
|
||||
])
|
||||
db.session.commit()
|
||||
snap = resolve_binding("in_transit_transfer.query_inventory", {"source_code": "X", "region": "cn"}, "prod")
|
||||
assert snap.context_selector == {"source_code": "X"} # priority 5 绑定胜出
|
||||
|
||||
|
||||
def test_expired_effective_window_not_matched(app):
|
||||
"""effective_to 已过期的绑定不命中,回落到默认。"""
|
||||
past = datetime.now(timezone.utc) - timedelta(days=1)
|
||||
db.session.add_all([_client(), _interface()])
|
||||
db.session.add_all([
|
||||
_binding(context_selector_json={"source_code": "X"}, effective_from=past, effective_to=past),
|
||||
_binding(),
|
||||
])
|
||||
db.session.commit()
|
||||
snap = resolve_binding("in_transit_transfer.query_inventory", {"source_code": "X"}, "prod")
|
||||
assert snap.context_selector == {}
|
||||
|
||||
|
||||
def test_draft_status_not_matched(app):
|
||||
"""status=draft 的绑定不命中;无默认时抛 BindingNotFoundError。"""
|
||||
db.session.add_all([_client(), _interface(), _binding(status="draft")])
|
||||
db.session.commit()
|
||||
with pytest.raises(AppError) as exc:
|
||||
resolve_binding("in_transit_transfer.query_inventory", {}, "prod")
|
||||
assert exc.value.code == "INTEGRATION.BINDING_NOT_FOUND"
|
||||
|
||||
|
||||
def test_no_match_raises(app):
|
||||
"""无任何可命中绑定抛 BindingNotFoundError(fail-closed)。"""
|
||||
db.session.add_all([_client(), _interface(), _binding(capability="other.cap")])
|
||||
db.session.commit()
|
||||
with pytest.raises(AppError) as exc:
|
||||
resolve_binding("in_transit_transfer.query_inventory", {}, "prod")
|
||||
assert exc.value.code == "INTEGRATION.BINDING_NOT_FOUND"
|
||||
|
||||
|
||||
def test_freeze_versions_in_snapshot(app):
|
||||
"""快照冻结 interface 版本与调用期配置(非活表)。"""
|
||||
_seed_default(app)
|
||||
snap = resolve_binding("in_transit_transfer.query_inventory", {}, "prod")
|
||||
assert snap.interface_version == 3
|
||||
assert snap.credential_ref_code is None
|
||||
assert snap.request_spec.get("path") == "/stock"
|
||||
assert snap.config.get("endpoint") == "https://erp.invalid"
|
||||
@@ -0,0 +1,59 @@
|
||||
"""tests/services/integration_connector/test_capability.py
|
||||
|
||||
用途:验证 Capability 强类型契约注册表:注册/查询/清单/重复/未注册。
|
||||
依赖:服务层 capability.py(纯代码,不依赖 DB);errors.py。
|
||||
逻辑:领域只能调用已注册的强类型能力;未注册 fail-closed 抛 INTEGRATION.CAPABILITY_NOT_FOUND。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.integration_connector.capability import (
|
||||
CapabilitySpec,
|
||||
ensure_capabilities_loaded,
|
||||
get_capability,
|
||||
list_capabilities,
|
||||
register_capability,
|
||||
reset_capability_registry_for_tests,
|
||||
)
|
||||
from app.core.errors import AppError, ValidationError
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _fresh_registry():
|
||||
reset_capability_registry_for_tests()
|
||||
yield
|
||||
reset_capability_registry_for_tests()
|
||||
|
||||
|
||||
def test_register_then_get_returns_same_spec():
|
||||
"""注册后按名查询返回同一对象。"""
|
||||
spec = CapabilitySpec(name="demo.echo", input_schema={}, output_schema={}, idempotency="none", write=False)
|
||||
register_capability(spec)
|
||||
assert get_capability("demo.echo") is spec
|
||||
|
||||
|
||||
def test_duplicate_register_raises_validation():
|
||||
"""同名能力重复注册抛 ValidationError。"""
|
||||
register_capability(CapabilitySpec(name="demo.echo", input_schema={}, output_schema={}, idempotency="none", write=False))
|
||||
with pytest.raises(ValidationError):
|
||||
register_capability(CapabilitySpec(name="demo.echo", input_schema={}, output_schema={}, idempotency="none", write=False))
|
||||
|
||||
|
||||
def test_get_unregistered_raises_not_found():
|
||||
"""未注册能力抛 INTEGRATION.CAPABILITY_NOT_FOUND(fail-closed)。"""
|
||||
with pytest.raises(AppError) as exc:
|
||||
get_capability("in_transit_transfer.none")
|
||||
assert exc.value.code == "INTEGRATION.CAPABILITY_NOT_FOUND"
|
||||
assert exc.value.http_status == 404
|
||||
|
||||
|
||||
def test_ensure_loaded_registers_three_transfer_capabilities():
|
||||
"""ensure_capabilities_loaded 后注册 3 个在途调拨能力,write 标志正确。"""
|
||||
ensure_capabilities_loaded()
|
||||
names = {spec.name for spec in list_capabilities()}
|
||||
assert {"in_transit_transfer.query_inventory", "in_transit_transfer.create_transfer", "in_transit_transfer.verify_duplicate"}.issubset(names)
|
||||
assert get_capability("in_transit_transfer.create_transfer").write is True
|
||||
assert get_capability("in_transit_transfer.query_inventory").write is False
|
||||
assert get_capability("in_transit_transfer.verify_duplicate").write is False
|
||||
@@ -0,0 +1,162 @@
|
||||
"""tests/services/integration_connector/test_engine.py
|
||||
|
||||
用途:验证 CapabilityGateway 调用引擎管线——resolve→validate→call→map→classify→落 IntegrationCall。
|
||||
依赖:capability/binding/mapping/security/transports、IntegrationCall 模型、errors.py。
|
||||
逻辑:读能力走 success(映射校验通过);写能力按原始 status 分类;超时→timeout;
|
||||
入参非法/无绑定/映射失败/result_unknown 均 fail-closed,且 result_unknown 不自动重试。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError
|
||||
from app.models import IntegrationBinding, IntegrationCall, IntegrationClientInstance, IntegrationInterfaceDefinition
|
||||
from app.services.integration_connector.capability import ensure_capabilities_loaded
|
||||
from app.services.integration_connector.engine import CapabilityGateway
|
||||
|
||||
|
||||
class FakeTransport:
|
||||
"""可注入响应或异常的传输替身。"""
|
||||
|
||||
connector_type = "rest"
|
||||
|
||||
def __init__(self, response):
|
||||
self._response = response
|
||||
|
||||
def call(self, *, client, interface, request):
|
||||
if isinstance(self._response, Exception):
|
||||
raise self._response
|
||||
return self._response
|
||||
|
||||
|
||||
def _seed(capability, *, connector_type="rest", response_mapping=None, output_schema=None):
|
||||
resp_map = response_mapping or {"found": {"expr": "found"}, "quantity": {"expr": "quantity", "transform": "decimal"}}
|
||||
out_schema = output_schema or {"type": "object", "properties": {"found": {"type": "boolean"}, "quantity": {"type": "number"}}}
|
||||
client = IntegrationClientInstance(
|
||||
code="CLI-A", name="client", connector_type=connector_type, environment="prod",
|
||||
config_json={"endpoint": "https://erp.invalid"},
|
||||
)
|
||||
iface = IntegrationInterfaceDefinition(
|
||||
code="IFACE-Q", name="iface", client_instance_code="CLI-A", connector_type=connector_type,
|
||||
request_spec_json={"method": "GET", "path": "/stock/{invoice_no}"},
|
||||
input_schema_json={}, response_mapping_json=resp_map, output_schema_json=out_schema,
|
||||
version=3, status="published",
|
||||
)
|
||||
db.session.add_all([client, iface])
|
||||
db.session.flush()
|
||||
binding = IntegrationBinding(
|
||||
capability=capability, context_selector_json={}, client_instance_code="CLI-A",
|
||||
interface_definition_code="IFACE-Q", mapping_version=2, priority=0, environment="prod",
|
||||
status="published",
|
||||
)
|
||||
db.session.add(binding)
|
||||
db.session.commit()
|
||||
return connector_type
|
||||
|
||||
|
||||
def _params(**overrides):
|
||||
values = {"invoice_no": "INV-001", "from_warehouse": "W1", "to_warehouse": "W2", "quantity": 100}
|
||||
values.update(overrides)
|
||||
return values
|
||||
|
||||
|
||||
def test_call_success_records_integration_call(app):
|
||||
"""读能力成功:status=success、data 含映射结果、落 IntegrationCall。"""
|
||||
ensure_capabilities_loaded()
|
||||
_seed("in_transit_transfer.query_inventory")
|
||||
fake = FakeTransport({"found": True, "quantity": "100"})
|
||||
result = CapabilityGateway(transports={"rest": fake}).call(
|
||||
capability="in_transit_transfer.query_inventory", context={},
|
||||
params=_params(), operation_id="OP-1", environment="prod",
|
||||
)
|
||||
assert result.status == "success"
|
||||
assert result.data["quantity"] == Decimal("100")
|
||||
call_row = IntegrationCall.query.filter_by(operation_id="OP-1").first()
|
||||
assert call_row is not None
|
||||
assert call_row.status == "success"
|
||||
|
||||
|
||||
def test_call_input_invalid_raises(app):
|
||||
"""入参不合输入 Schema → INTEGRATION.INPUT_INVALID。"""
|
||||
ensure_capabilities_loaded()
|
||||
_seed("in_transit_transfer.query_inventory")
|
||||
with pytest.raises(AppError) as exc:
|
||||
CapabilityGateway(transports={"rest": FakeTransport({"found": True})}).call(
|
||||
capability="in_transit_transfer.query_inventory", context={},
|
||||
params={}, operation_id="OP-2", environment="prod",
|
||||
)
|
||||
assert exc.value.code == "INTEGRATION.INPUT_INVALID"
|
||||
|
||||
|
||||
def test_call_no_binding_raises(app):
|
||||
"""无可用绑定 → INTEGRATION.BINDING_NOT_FOUND(fail-closed)。"""
|
||||
ensure_capabilities_loaded()
|
||||
with pytest.raises(AppError) as exc:
|
||||
CapabilityGateway(transports={"rest": FakeTransport({"found": True})}).call(
|
||||
capability="in_transit_transfer.query_inventory", context={},
|
||||
params=_params(), operation_id="OP-3", environment="prod",
|
||||
)
|
||||
assert exc.value.code == "INTEGRATION.BINDING_NOT_FOUND"
|
||||
|
||||
|
||||
def test_call_write_business_failed(app):
|
||||
"""写能力按原始 status 分类 → business_failed。"""
|
||||
ensure_capabilities_loaded()
|
||||
_seed("in_transit_transfer.create_transfer")
|
||||
fake = FakeTransport({"status": "business_failed", "code": "E1", "message": "reject"})
|
||||
result = CapabilityGateway(transports={"rest": fake}).call(
|
||||
capability="in_transit_transfer.create_transfer", context={},
|
||||
params=_params(), operation_id="OP-4", environment="prod",
|
||||
)
|
||||
assert result.status == "business_failed"
|
||||
assert result.error_code == "E1"
|
||||
|
||||
|
||||
def test_call_transport_timeout_returns_timeout(app):
|
||||
"""传输超时 → status=timeout。"""
|
||||
ensure_capabilities_loaded()
|
||||
_seed("in_transit_transfer.query_inventory")
|
||||
result = CapabilityGateway(transports={"rest": FakeTransport(TimeoutError())}).call(
|
||||
capability="in_transit_transfer.query_inventory", context={},
|
||||
params=_params(), operation_id="OP-5", environment="prod",
|
||||
)
|
||||
assert result.status == "timeout"
|
||||
|
||||
|
||||
def test_call_mapping_invalid_raises(app):
|
||||
"""输出不合输出 Schema → INTEGRATION.MAPPING_INVALID(fail-closed)。"""
|
||||
ensure_capabilities_loaded()
|
||||
_seed("in_transit_transfer.query_inventory",
|
||||
output_schema={"type": "object", "required": ["found", "quantity"],
|
||||
"properties": {"found": {"type": "boolean"}, "quantity": {"type": "number"}}})
|
||||
fake = FakeTransport({"found": True}) # 缺 quantity
|
||||
with pytest.raises(AppError) as exc:
|
||||
CapabilityGateway(transports={"rest": fake}).call(
|
||||
capability="in_transit_transfer.query_inventory", context={},
|
||||
params=_params(), operation_id="OP-6", environment="prod",
|
||||
)
|
||||
assert exc.value.code == "INTEGRATION.MAPPING_INVALID"
|
||||
|
||||
|
||||
def test_call_result_unknown_no_auto_retry(app):
|
||||
"""result_unknown 不自动重试:transport 仅被调用一次。"""
|
||||
ensure_capabilities_loaded()
|
||||
_seed("in_transit_transfer.create_transfer")
|
||||
calls = []
|
||||
|
||||
class _OneShot(FakeTransport):
|
||||
def call(self, **kw):
|
||||
calls.append(1)
|
||||
return {"status": "result_unknown"}
|
||||
|
||||
result = CapabilityGateway(transports={"rest": _OneShot(None)}).call(
|
||||
capability="in_transit_transfer.create_transfer", context={},
|
||||
params=_params(), operation_id="OP-7", environment="prod",
|
||||
)
|
||||
assert result.status == "result_unknown"
|
||||
assert len(calls) == 1
|
||||
@@ -0,0 +1,96 @@
|
||||
"""tests/services/integration_connector/test_mapping.py
|
||||
|
||||
用途:验证声明式映射引擎——点路径/数组下标提取、白名单转换函数、最小 Schema 校验。
|
||||
依赖:mapping.py(纯函数);errors.py。
|
||||
逻辑:缺字段且不可满足→MappingInvalidError;非法类型/枚举→MappingInvalidError;
|
||||
表达式超深/超长→MappingInvalidError(fail-closed)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import AppError
|
||||
from app.services.integration_connector.mapping import MISSING, extract_path, map_response
|
||||
|
||||
|
||||
def test_extract_path_dot():
|
||||
assert extract_path({"a": {"b": 1}}, "a.b") == 1
|
||||
|
||||
|
||||
def test_extract_path_array_index():
|
||||
assert extract_path({"a": [10, 20]}, "a[1]") == 20
|
||||
|
||||
|
||||
def test_extract_path_missing_returns_sentinel():
|
||||
assert extract_path({"a": 1}, "a.b") is MISSING
|
||||
assert extract_path({"a": [1]}, "a[9]") is MISSING
|
||||
|
||||
|
||||
def test_extract_path_depth_limit():
|
||||
deep = {"a": {"b": {"c": {"d": {"e": {"f": {"g": {"h": {"i": 1}}}}}}}}}
|
||||
with pytest.raises(AppError) as exc:
|
||||
extract_path(deep, "a.b.c.d.e.f.g.h.i")
|
||||
assert exc.value.code == "INTEGRATION.MAPPING_INVALID"
|
||||
|
||||
|
||||
def test_extract_path_length_limit():
|
||||
with pytest.raises(AppError) as exc:
|
||||
extract_path({"a": 1}, "a." + "b" * 300)
|
||||
assert exc.value.code == "INTEGRATION.MAPPING_INVALID"
|
||||
|
||||
|
||||
def test_map_response_extract_and_decimal_transform():
|
||||
mapped = map_response(
|
||||
{"qty": {"expr": "rows[0].qty", "transform": "decimal"}},
|
||||
{"rows": [{"qty": "100.5"}]},
|
||||
{"type": "object", "required": ["qty"], "properties": {"qty": {"type": "number"}}},
|
||||
)
|
||||
assert mapped["qty"] == Decimal("100.5")
|
||||
|
||||
|
||||
def test_map_response_default_and_fallback():
|
||||
mapped = map_response(
|
||||
{
|
||||
"a": {"expr": "missing", "transform": "default", "args": {"default": 7}},
|
||||
"b": {"expr": "missing", "transform": "fallback", "args": {"fallback": "X"}},
|
||||
},
|
||||
{},
|
||||
{"type": "object", "properties": {"a": {"type": "number"}, "b": {"type": "string"}}},
|
||||
)
|
||||
assert mapped == {"a": 7, "b": "X"}
|
||||
|
||||
|
||||
def test_map_response_missing_required_raises():
|
||||
with pytest.raises(AppError) as exc:
|
||||
map_response(
|
||||
{"a": {"expr": "missing"}},
|
||||
{},
|
||||
{"type": "object", "required": ["a"], "properties": {"a": {"type": "string"}}},
|
||||
)
|
||||
assert exc.value.code == "INTEGRATION.MAPPING_INVALID"
|
||||
|
||||
|
||||
def test_map_response_wrong_type_raises():
|
||||
with pytest.raises(AppError) as exc:
|
||||
map_response(
|
||||
{"a": {"expr": "x"}},
|
||||
{"x": "not-a-number"},
|
||||
{"type": "object", "required": ["a"], "properties": {"a": {"type": "number"}}},
|
||||
)
|
||||
assert exc.value.code == "INTEGRATION.MAPPING_INVALID"
|
||||
|
||||
|
||||
def test_map_response_enum_violation_raises():
|
||||
with pytest.raises(AppError) as exc:
|
||||
map_response(
|
||||
{"status": {"expr": "s"}},
|
||||
{"s": "banana"},
|
||||
{
|
||||
"type": "object", "required": ["status"],
|
||||
"properties": {"status": {"type": "string", "enum": ["ok", "bad"]}},
|
||||
},
|
||||
)
|
||||
assert exc.value.code == "INTEGRATION.MAPPING_INVALID"
|
||||
@@ -0,0 +1,86 @@
|
||||
"""tests/services/integration_connector/test_migration.py
|
||||
|
||||
用途:验证 Integration Connector 迁移可独立升级与回滚,且正确链在当前 head 之后。
|
||||
依赖:Alembic Operations、SQLAlchemy SQLite、ic1a2b3c4d5f / ix1a2b3c4d5e 迁移。
|
||||
逻辑:空库升级后 5 张表(含索引/约束)存在;回滚后全部删除;down_revision 指向既有 head。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
EXPECTED_TABLES = {
|
||||
'integration_credential_references',
|
||||
'integration_client_instances',
|
||||
'integration_interface_definitions',
|
||||
'integration_bindings',
|
||||
'integration_calls',
|
||||
}
|
||||
|
||||
VERSIONS_DIR = Path(__file__).parents[3] / 'migrations' / 'versions'
|
||||
|
||||
|
||||
def _load_migration(name: str, filename: str):
|
||||
"""加载指定迁移模块。"""
|
||||
path = VERSIONS_DIR / filename
|
||||
spec = importlib.util.spec_from_file_location(name, path)
|
||||
assert spec is not None and spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def test_migration_chains_after_head():
|
||||
"""建表迁移必须挂接在既有链 head it1a2b3c4d5e 之后。"""
|
||||
migration = _load_migration('integration_connector_migration', 'ic1a2b3c4d5f_add_integration_connector.py')
|
||||
assert migration.revision == 'ic1a2b3c4d5f'
|
||||
assert migration.down_revision == 'it1a2b3c4d5e'
|
||||
|
||||
|
||||
def test_integration_connector_migration_round_trip():
|
||||
"""空库升级后 5 表存在;回滚后全部删除。"""
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
base = _load_migration('integration_connector_migration', 'ic1a2b3c4d5f_add_integration_connector.py')
|
||||
split = _load_migration('integration_connector_columns_migration', 'ix1a2b3c4d5e_split_integration_connector_columns.py')
|
||||
with engine.begin() as connection:
|
||||
context = MigrationContext.configure(connection)
|
||||
operations = Operations(context)
|
||||
base.op = operations
|
||||
split.op = operations
|
||||
|
||||
base.upgrade()
|
||||
split.upgrade()
|
||||
tables = set(sa.inspect(connection).get_table_names())
|
||||
assert EXPECTED_TABLES.issubset(tables)
|
||||
|
||||
inspector = sa.inspect(connection)
|
||||
client_cols = {item['name'] for item in inspector.get_columns('integration_client_instances')}
|
||||
assert 'credential_ref_code' in client_cols
|
||||
assert 'endpoint' in client_cols
|
||||
assert 'timeout_seconds' in client_cols
|
||||
iface_cols = {item['name'] for item in inspector.get_columns('integration_interface_definitions')}
|
||||
assert 'http_method' in iface_cols
|
||||
assert 'request_path' in iface_cols
|
||||
binding_cols = {item['name'] for item in inspector.get_columns('integration_bindings')}
|
||||
assert 'context_source_code' in binding_cols
|
||||
binding_indexes = {item['name'] for item in inspector.get_indexes('integration_bindings')}
|
||||
assert 'ix_integration_bindings_cap_env_status' in binding_indexes
|
||||
|
||||
split.downgrade()
|
||||
base.downgrade()
|
||||
assert EXPECTED_TABLES.isdisjoint(set(sa.inspect(connection).get_table_names()))
|
||||
|
||||
|
||||
def test_split_migration_chains_after_create():
|
||||
"""拆列迁移必须挂接在 ic1a2b3c4d5e 之后(down_revision=iy1a2b3c4d5e)。"""
|
||||
split = _load_migration('integration_connector_columns_migration', 'ix1a2b3c4d5e_split_integration_connector_columns.py')
|
||||
assert split.revision == 'ix1a2b3c4d5e'
|
||||
assert split.down_revision == 'iy1a2b3c4d5e'
|
||||
@@ -0,0 +1,119 @@
|
||||
"""tests/services/integration_connector/test_models.py
|
||||
|
||||
用途:验证 Integration Connector 领域模型的可建表、唯一约束与状态/连接器类型约束。
|
||||
依赖:根 conftest 的 app fixture(SQLite 内存 + db.create_all())。
|
||||
逻辑:create_all 后各表可查询为空;code 唯一冲突抛 IntegrityError;非法
|
||||
connector_type / status 被 CheckConstraint 拒绝。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
IntegrationBinding,
|
||||
IntegrationCall,
|
||||
IntegrationClientInstance,
|
||||
IntegrationCredentialReference,
|
||||
IntegrationInterfaceDefinition,
|
||||
)
|
||||
|
||||
CONNECTOR_MODELS = (
|
||||
IntegrationCredentialReference,
|
||||
IntegrationClientInstance,
|
||||
IntegrationInterfaceDefinition,
|
||||
IntegrationBinding,
|
||||
IntegrationCall,
|
||||
)
|
||||
|
||||
|
||||
def _client(**overrides):
|
||||
values = {
|
||||
"code": "ERP-T100",
|
||||
"name": "T100 ERP",
|
||||
"connector_type": "soap",
|
||||
"environment": "prod",
|
||||
"config_json": {"endpoint": "https://t100.invalid/ws", "timeout_seconds": 60},
|
||||
}
|
||||
values.update(overrides)
|
||||
return IntegrationClientInstance(**values)
|
||||
|
||||
|
||||
def test_all_connector_tables_created_and_empty(app):
|
||||
"""create_all 已随 app fixture 执行,5 张连接器表均可插入且初始为空。"""
|
||||
for model in CONNECTOR_MODELS:
|
||||
assert model.query.count() == 0
|
||||
|
||||
|
||||
def test_client_instance_code_unique_conflict(app):
|
||||
"""同一 code 的第二条记录触发唯一约束。"""
|
||||
db.session.add(_client())
|
||||
db.session.flush()
|
||||
db.session.add(_client())
|
||||
with pytest.raises(IntegrityError):
|
||||
db.session.commit()
|
||||
db.session.rollback()
|
||||
|
||||
|
||||
def test_client_instance_connector_type_check(app):
|
||||
"""connector_type 不在白名单(rest/soap)时被 CheckConstraint 拒绝。"""
|
||||
db.session.add(_client(connector_type="ftp"))
|
||||
with pytest.raises(IntegrityError):
|
||||
db.session.commit()
|
||||
db.session.rollback()
|
||||
|
||||
|
||||
def test_interface_definition_status_check(app):
|
||||
"""InterfaceDefinition.status 非法值被 CheckConstraint 拒绝。"""
|
||||
client = _client()
|
||||
db.session.add(client)
|
||||
db.session.flush()
|
||||
iface = IntegrationInterfaceDefinition(
|
||||
code="ERP-QUERY-STOCK",
|
||||
name="查询库存",
|
||||
client_instance_code=client.code,
|
||||
connector_type="soap",
|
||||
request_spec_json={"template": "{{invoice_no}}"},
|
||||
input_schema_json={},
|
||||
response_mapping_json={},
|
||||
output_schema_json={},
|
||||
version=1,
|
||||
status="banana",
|
||||
)
|
||||
db.session.add(iface)
|
||||
with pytest.raises(IntegrityError):
|
||||
db.session.commit()
|
||||
db.session.rollback()
|
||||
|
||||
|
||||
def test_credential_reference_status_check(app):
|
||||
"""CredentialReference.status 非法值被 CheckConstraint 拒绝。"""
|
||||
db.session.add(IntegrationCredentialReference(
|
||||
code="ERP-CRED-01",
|
||||
secret_ref="ERP_PASSWORD",
|
||||
secret_provider="env",
|
||||
credential_type="password",
|
||||
version=1,
|
||||
status="expired",
|
||||
))
|
||||
with pytest.raises(IntegrityError):
|
||||
db.session.commit()
|
||||
db.session.rollback()
|
||||
|
||||
|
||||
def test_credential_reference_secret_ref_not_returned_in_summary_column(app):
|
||||
"""模型列本身不存明文;secret_ref 是引用键而非真实凭据。"""
|
||||
cred = IntegrationCredentialReference(
|
||||
code="ERP-CRED-01",
|
||||
secret_ref="ERP_PASSWORD",
|
||||
secret_provider="env",
|
||||
credential_type="password",
|
||||
version=1,
|
||||
status="active",
|
||||
)
|
||||
db.session.add(cred)
|
||||
db.session.flush()
|
||||
assert cred.secret_ref == "ERP_PASSWORD"
|
||||
assert "password" not in cred.secret_ref.lower() or cred.secret_ref != "P@ssw0rd!"
|
||||
@@ -0,0 +1,73 @@
|
||||
"""tests/services/integration_connector/test_security.py
|
||||
|
||||
用途:验证凭据引用解析(fail-closed)与敏感字段脱敏。
|
||||
依赖:IntegrationCredentialReference 模型、current_app.config、errors.py。
|
||||
逻辑:secret_ref 指向缺失配置键→CredentialUnresolvedError;sanitize 脱敏敏感键;
|
||||
credential_summary 只含元数据,绝不含明文。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError
|
||||
from app.models import IntegrationCredentialReference
|
||||
from app.services.integration_connector.security import credential_summary, resolve_credential, sanitize
|
||||
|
||||
|
||||
def _add_credential(code="ERP-CRED-01", secret_ref="ERP_TEST_CRED", **overrides):
|
||||
cred = IntegrationCredentialReference(
|
||||
code=code, secret_ref=secret_ref, secret_provider="env",
|
||||
credential_type="password", version=1, status="active", **overrides,
|
||||
)
|
||||
db.session.add(cred)
|
||||
db.session.flush()
|
||||
return cred
|
||||
|
||||
|
||||
def test_resolve_credential_returns_secrets(app):
|
||||
"""secret_ref 指向存在的配置键时返回该字典。"""
|
||||
app.config["ERP_TEST_CRED"] = {"username": "u", "password": "p", "endpoint": "https://erp.invalid"}
|
||||
_add_credential()
|
||||
creds = resolve_credential("ERP-CRED-01")
|
||||
assert creds == {"username": "u", "password": "p", "endpoint": "https://erp.invalid"}
|
||||
|
||||
|
||||
def test_resolve_credential_missing_secret_fail_closed(app):
|
||||
"""secret_ref 指向缺失/空配置键时抛 CredentialUnresolvedError。"""
|
||||
_add_credential(secret_ref="MISSING_KEY")
|
||||
with pytest.raises(AppError) as exc:
|
||||
resolve_credential("ERP-CRED-01")
|
||||
assert exc.value.code == "INTEGRATION.CREDENTIAL_UNRESOLVED"
|
||||
|
||||
|
||||
def test_resolve_credential_unknown_ref_fail_closed(app):
|
||||
"""凭据引用不存在时抛 CredentialUnresolvedError。"""
|
||||
with pytest.raises(AppError) as exc:
|
||||
resolve_credential("NOPE")
|
||||
assert exc.value.code == "INTEGRATION.CREDENTIAL_UNRESOLVED"
|
||||
|
||||
|
||||
def test_sanitize_redacts_sensitive_keys():
|
||||
"""sanitize 递归把 password/token/secret 等键替换为 ***。"""
|
||||
data = {"outer": {"password": "s3cret", "keep": "ok"}, "token": "abc", "list": [{"secret": "x"}]}
|
||||
out = sanitize(data)
|
||||
assert out["outer"]["password"] == "***"
|
||||
assert out["outer"]["keep"] == "ok"
|
||||
assert out["token"] == "***"
|
||||
assert out["list"][0]["secret"] == "***"
|
||||
assert "s3cret" not in json.dumps(out)
|
||||
|
||||
|
||||
def test_credential_summary_has_no_plaintext(app):
|
||||
"""credential_summary 只含元数据,不含解析出的明文。"""
|
||||
app.config["ERP_TEST_CRED"] = {"username": "svc_user_erp", "password": "s3cretLY"}
|
||||
cred = _add_credential()
|
||||
resolve_credential("ERP-CRED-01") # 确保能解析
|
||||
summary = credential_summary(cred)
|
||||
assert "s3cretLY" not in json.dumps(summary)
|
||||
assert "svc_user_erp" not in json.dumps(summary)
|
||||
assert summary["version"] == 1
|
||||
@@ -0,0 +1,104 @@
|
||||
"""tests/services/integration_connector/test_transports.py
|
||||
|
||||
用途:验证 REST/SOAP Transport 的请求构造、业务错误映射与 fail-closed;
|
||||
以及结果分类(classify_transport_response)的六态语义。
|
||||
依赖:transports/base.py、transports/rest.py、transports/soap.py、errors.py。
|
||||
逻辑:Transport.call 返回原始 dict;分类器把 dict 归一为 IntegrationCallResult。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.integration_connector.errors import TransportNotFrozenError
|
||||
from app.services.integration_connector.transports.base import IntegrationCallResult, classify_transport_response
|
||||
from app.services.integration_connector.transports.rest import RestTransport
|
||||
from app.services.integration_connector.transports.soap import SoapTransport
|
||||
|
||||
|
||||
def _resp(status_code, payload=None, text=""):
|
||||
class _Response:
|
||||
def __init__(self):
|
||||
self.status_code = status_code
|
||||
self.text = text
|
||||
self._payload = payload
|
||||
|
||||
def json(self):
|
||||
return self._payload
|
||||
|
||||
return _Response()
|
||||
|
||||
|
||||
def _client(**overrides):
|
||||
cfg = {"endpoint": "https://erp.invalid", "timeout_seconds": 30}
|
||||
cfg.update(overrides)
|
||||
return {"config_json": cfg, "credential": {}}
|
||||
|
||||
|
||||
def test_rest_builds_url_and_sends_request():
|
||||
"""REST Transport 拼接 endpoint+path,按 method/params 发请求并返回 JSON。"""
|
||||
captured = {}
|
||||
|
||||
def fake_http(method, url, **kw):
|
||||
captured.update(method=method, url=url, params=kw.get("params"), json=kw.get("json"))
|
||||
return _resp(200, {"found": True, "quantity": "100"})
|
||||
|
||||
transport = RestTransport(http_request=fake_http)
|
||||
result = transport.call(
|
||||
client=_client(),
|
||||
interface={"request_spec_json": {"method": "GET", "path": "/stock"}},
|
||||
request={"params": {"invoice_no": "INV-001"}},
|
||||
)
|
||||
assert captured["url"] == "https://erp.invalid/stock"
|
||||
assert captured["method"] == "GET"
|
||||
assert captured["params"] == {"invoice_no": "INV-001"}
|
||||
assert result == {"found": True, "quantity": "100"}
|
||||
|
||||
|
||||
def test_rest_business_error_maps_to_dict():
|
||||
"""4xx 映射为 business_failed dict,供上层透传分类。"""
|
||||
|
||||
def fake_http(method, url, **kw):
|
||||
return _resp(404, text="not found")
|
||||
|
||||
transport = RestTransport(http_request=fake_http)
|
||||
result = transport.call(
|
||||
client=_client(),
|
||||
interface={"request_spec_json": {"method": "GET", "path": "/stock"}},
|
||||
request={},
|
||||
)
|
||||
assert result["status"] == "business_failed"
|
||||
assert result["code"] == "HTTP_404"
|
||||
assert "not found" in result["message"]
|
||||
|
||||
|
||||
def test_rest_fail_closed_without_endpoint():
|
||||
"""endpoint 未冻结时 fail-closed 抛 TransportNotFrozenError。"""
|
||||
transport = RestTransport(http_request=lambda *a, **k: None)
|
||||
with pytest.raises(TransportNotFrozenError):
|
||||
transport.call(
|
||||
client={"config_json": {}},
|
||||
interface={"request_spec_json": {"method": "GET", "path": "/stock"}},
|
||||
request={},
|
||||
)
|
||||
|
||||
|
||||
def test_soap_fail_closed_without_wsdl():
|
||||
"""SOAP 无 wsdl 时 fail-closed 抛 TransportNotFrozenError(SOAP 只需 wsdl,不需 endpoint)。"""
|
||||
transport = SoapTransport()
|
||||
with pytest.raises(TransportNotFrozenError):
|
||||
transport.call(
|
||||
client={"config_json": {}},
|
||||
interface={"request_spec_json": {"soap_action": "queryInventory"}},
|
||||
request={},
|
||||
)
|
||||
|
||||
|
||||
def test_classify_transport_response_states():
|
||||
"""结果分类覆盖 success/duplicate_success/business_failed/technical_failed。"""
|
||||
assert classify_transport_response({"status": "success", "document_no": "DOC-1"}).status == "success"
|
||||
assert classify_transport_response({"status": "business_failed", "code": "E1", "message": "reject"}).status == "business_failed"
|
||||
dup = classify_transport_response({"status": "duplicate_success", "verified_posted": True, "document_no": "DOC-9"})
|
||||
assert dup.status == "duplicate_success"
|
||||
unknown = classify_transport_response({})
|
||||
assert unknown.status == "technical_failed"
|
||||
@@ -0,0 +1,84 @@
|
||||
"""
|
||||
用途:验证正式客户识别结果是客户确认与流程 Gate 的唯一真相源。
|
||||
依赖:内存数据库、客户识别结果服务、ShippingOrderTask/Candidate。
|
||||
逻辑:覆盖非 bill_to 证据可确认,以及仅有旧 Bill-to Match 时不得放行两条边界。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingCustomer,
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderIntake,
|
||||
ShippingOrderTask,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.customer_resolution_service import (
|
||||
confirm_customer_resolution,
|
||||
customer_resolution_facts,
|
||||
)
|
||||
|
||||
|
||||
def _task_with_resolution(*, status: str = 'unique_candidate') -> tuple[ShippingOrderTask, ShippingCustomerShadowResolution, ShippingCustomer]:
|
||||
"""构造 OT、Candidate 和规则证据快照;不构造 bill_to 字段或 CustomerMatch。"""
|
||||
user = User(username='resolution-user', email='resolution@example.com', role='user')
|
||||
customer = ShippingCustomer(standard_name='规则识别客户', short_code='RID', status='active')
|
||||
db.session.add_all([user, customer])
|
||||
db.session.flush()
|
||||
intake = ShippingOrderIntake(
|
||||
intake_no='INT-RESOLUTION', asset_id=1, user_id=user.id, parser_version='test',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-RESOLUTION', intake_id=intake.id, primary_document_id=1,
|
||||
candidate_key='resolution-test', candidate_status='accepted',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
task = ShippingOrderTask(task_no='OT-RESOLUTION', user_id=user.id, candidate_id=candidate.id)
|
||||
resolution = ShippingCustomerShadowResolution(
|
||||
candidate_id=candidate.id,
|
||||
intake_id=intake.id,
|
||||
resolution_version='shadow-v2',
|
||||
status=status,
|
||||
evidence_json=[{'definition_id': 'customer-code', 'normalized_value': 'C-100'}],
|
||||
candidate_matches_json=[{'customer_id': customer.id, 'score': 100}],
|
||||
resolution_context_json={'rule_set': {'checksum': 'a' * 64}},
|
||||
identity_rule_set_checksum='a' * 64,
|
||||
top_customer_id=customer.id,
|
||||
top_score=100,
|
||||
)
|
||||
db.session.add_all([task, resolution])
|
||||
db.session.commit()
|
||||
return task, resolution, customer
|
||||
|
||||
|
||||
def test_non_bill_to_evidence_can_confirm_customer(app):
|
||||
"""关键断言:客户代码证据可确认客户,流程不要求 bill_to 字段或旧匹配行。"""
|
||||
with app.app_context():
|
||||
task, resolution, customer = _task_with_resolution()
|
||||
|
||||
confirm_customer_resolution(task, customer_id=customer.id, actor_id=None, method='manual')
|
||||
db.session.commit()
|
||||
facts = customer_resolution_facts(task)
|
||||
|
||||
assert facts['status'] == 'confirmed'
|
||||
assert facts['customer_id'] == customer.id
|
||||
assert resolution.confirmed_customer_id == customer.id
|
||||
# 关键断言:确认不篡改规则证据及其 checksum。
|
||||
assert resolution.evidence_json == [{'definition_id': 'customer-code', 'normalized_value': 'C-100'}]
|
||||
assert resolution.identity_rule_set_checksum == 'a' * 64
|
||||
|
||||
|
||||
def test_unconfirmed_resolution_fails_closed_without_old_bill_to_fallback(app):
|
||||
"""关键断言:未确认的统一识别结果不得从旧字段或旧匹配路径获得客户身份。"""
|
||||
with app.app_context():
|
||||
task, _resolution, _customer = _task_with_resolution(status='unique_candidate')
|
||||
|
||||
facts = customer_resolution_facts(task)
|
||||
|
||||
assert facts['status'] == 'unique_candidate'
|
||||
assert facts['customer_id'] is None
|
||||
@@ -13,7 +13,9 @@ from app.models import (
|
||||
ShippingInventoryCandidateLine,
|
||||
ShippingInventoryCandidateSet,
|
||||
ShippingInventoryCandidateSource,
|
||||
ShippingNotice,
|
||||
ShippingOrderTask,
|
||||
ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingInventoryFile,
|
||||
)
|
||||
@@ -23,17 +25,18 @@ from app.services.shipping_notice.inventory_candidate_projection import (
|
||||
from app.services.shipping_notice.stp_line_inventory_match import prepare_candidate_inventory_lines
|
||||
|
||||
|
||||
def _task(task_no: str) -> ShippingNotice:
|
||||
task = ShippingNotice(
|
||||
def _task(task_no: str) -> ShippingOrderTask:
|
||||
task = ShippingOrderTask(
|
||||
task_no=task_no,
|
||||
source_type='manual',
|
||||
source_type='direct_pdf',
|
||||
user_id=1,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
return task
|
||||
|
||||
|
||||
def _candidate_set(task: ShippingNotice, version: int = 1) -> ShippingInventoryCandidateSet:
|
||||
def _candidate_set(task: ShippingOrderTask, version: int = 1) -> ShippingInventoryCandidateSet:
|
||||
row = ShippingInventoryCandidateSet(
|
||||
task_id=int(task.id),
|
||||
set_version=version,
|
||||
@@ -120,9 +123,19 @@ def test_project_inventory_candidate_facts_marks_stale_current_match(app):
|
||||
)
|
||||
db.session.add(new_line)
|
||||
db.session.flush()
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
task_id=int(task.id), extraction_id=1, schema_version_id=1,
|
||||
order_data_version=1, source_manifest_json={}, header_values_json={},
|
||||
)
|
||||
db.session.add(snapshot)
|
||||
db.session.flush()
|
||||
snapshot_line = ShippingOrderSnapshotLine(snapshot_id=int(snapshot.id), line_no=1, position=0)
|
||||
db.session.add(snapshot_line)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
task_id=int(task.id),
|
||||
line_key='line-1',
|
||||
snapshot_line_id=int(snapshot_line.id),
|
||||
line_no=1,
|
||||
line_index=0,
|
||||
candidate_set_id=int(old_set.id),
|
||||
candidate_set_version=1,
|
||||
@@ -152,16 +165,26 @@ def test_project_inventory_candidate_facts_reads_file_evidence_from_snapshot(app
|
||||
candidate_set_id=int(candidate_set.id), line_no=1, source_codes_json=['DBS_DUB'],
|
||||
))
|
||||
db.session.flush()
|
||||
snapshot = ShippingInventoryFile(
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no='INV-CAND-EVIDENCE', storage_path='memory://evidence.xlsx',
|
||||
source_code='DBS_DUB', snapshot_status='ready', file_sha256='b' * 64,
|
||||
)
|
||||
db.session.add(inventory_file)
|
||||
db.session.flush()
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
task_id=int(task.id), extraction_id=1, schema_version_id=1,
|
||||
order_data_version=1, source_manifest_json={}, header_values_json={},
|
||||
)
|
||||
db.session.add(snapshot)
|
||||
db.session.flush()
|
||||
snapshot_line = ShippingOrderSnapshotLine(snapshot_id=int(snapshot.id), line_no=1, position=0)
|
||||
db.session.add(snapshot_line)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
task_id=int(task.id), line_key='line-1', candidate_set_id=int(candidate_set.id),
|
||||
candidate_set_version=1, inventory_snapshot_id=int(snapshot.id), match_result='matched',
|
||||
inventory_status='ready', inventory_source_code='DBS_DUB', matched_file_no=snapshot.inventory_file_no,
|
||||
task_id=int(task.id), snapshot_line_id=int(snapshot_line.id), line_no=1,
|
||||
candidate_set_id=int(candidate_set.id),
|
||||
candidate_set_version=1, inventory_snapshot_id=int(inventory_file.id), match_result='matched',
|
||||
inventory_status='ready', inventory_source_code='DBS_DUB', matched_file_no=inventory_file.inventory_file_no,
|
||||
matched_row_index=9, is_current=True, detail_json={},
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
@@ -81,12 +81,12 @@ def _fake_job(job_id=928, status='failed', domain='shipping_notice', job_type='s
|
||||
('failed', False, 'failed', '业务阻断失败 → failed'),
|
||||
('manual_fallback', True, 'retryable', 'manual_fallback retryable → retryable'),
|
||||
('failed', True, 'retryable', '技术失败 retryable → retryable'),
|
||||
('idle', False, 'idle', 'Idle → idle(默认)'),
|
||||
('idle', False, 'waiting_human', 'Idle automation → waiting_human(禁止再发 idle)'),
|
||||
],
|
||||
ids=lambda t: t[3] if isinstance(t, tuple) else '',
|
||||
)
|
||||
def test_p3_t3_user_status_seven_value_matrix(automation_status, retryable_flag, expected_user_status, label):
|
||||
"""[P3 T3] project_case_user_status 七值归一化与 Q12 invariants 一致。"""
|
||||
def test_p3_t3_user_status_f2_six_value_matrix(automation_status, retryable_flag, expected_user_status, label):
|
||||
"""[P3 T3] project_case_user_status F2 六值;默认人工等待 waiting_human。"""
|
||||
from app.services.shipping_notice.reconciliation_projector import project_case_user_status
|
||||
|
||||
case = _fake_case(status='draft')
|
||||
@@ -199,7 +199,8 @@ def test_case_bundle_prefers_persisted_formal_gate_over_case_draft(monkeypatch):
|
||||
"""正式 field_completeness 阻断必须覆盖 Case draft 的 idle/order_review_build 推导。"""
|
||||
from app.services.shipping_notice import reconciliation_projector
|
||||
|
||||
case = _fake_case(status='draft', candidate_id=None)
|
||||
# 正式门禁事实只在 Case 已确认(confirmed)时覆盖;未确认 draft 保持 order_review_build(见结算设计)。
|
||||
case = _fake_case(status='confirmed', candidate_id=None)
|
||||
monkeypatch.setattr(
|
||||
reconciliation_projector,
|
||||
'_project_case_formal_gate_summary',
|
||||
|
||||
@@ -25,9 +25,11 @@ from app.models import (
|
||||
ShippingOrderLine,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingOrderCustomerMatch,
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderIntake,
|
||||
ShippingCustomer,
|
||||
ShippingNotice,
|
||||
ShippingOrderTask,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.freeze_readiness_service import assert_freeze_readiness
|
||||
@@ -43,7 +45,7 @@ from app.services.shipping_notice.order_freeze_service import (
|
||||
def _build_accepted_order(*, with_unverified_llm: bool = False, with_extension: bool = False, suffix: str = '001'):
|
||||
"""创建一份含预置核心字段的已接受解析;可加入扩展字段验证配置化履约。"""
|
||||
user = User(username=f'snapshot-user-{suffix}', email=f'snapshot-user-{suffix}@example.test', password_hash='x')
|
||||
task = ShippingNotice(task_no=f'SN-SNAPSHOT-{suffix}', source_type='test', order_data_version=7)
|
||||
task = ShippingOrderTask(task_no=f'OT-SNAPSHOT-{suffix}', source_type='direct_pdf', user_id=1, order_data_version=7)
|
||||
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='Frozen order')
|
||||
db.session.add_all([user, task, schema])
|
||||
db.session.flush()
|
||||
@@ -82,7 +84,7 @@ def _build_accepted_order(*, with_unverified_llm: bool = False, with_extension:
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=0)
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=0, line_no=1)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
values = {
|
||||
@@ -119,13 +121,26 @@ def _build_accepted_order(*, with_unverified_llm: bool = False, with_extension:
|
||||
customer = ShippingCustomer(standard_name='Snapshot Customer', short_code='CUS')
|
||||
db.session.add(customer)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderCustomerMatch(
|
||||
extraction_id=extraction.id, role='bill_to', raw_name='Snapshot Customer',
|
||||
normalized_name='SNAPSHOT CUSTOMER', status='confirmed', customer_id=customer.id,
|
||||
customer_name_snapshot=customer.standard_name, customer_short_code_snapshot=customer.short_code,
|
||||
identity_fingerprint='f' * 64, identity_rule_version='order-customer-fingerprint.v1',
|
||||
identity_components_json={'role': 'bill_to'}, resolution_method='manual',
|
||||
confirmation_reason='测试确认', confirmed_by_id=user.id, confirmed_at=datetime.utcnow(),
|
||||
intake = ShippingOrderIntake(
|
||||
intake_no=f'INT-SNAPSHOT-{suffix}', asset_id=1, user_id=user.id, parser_version='test',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no=f'CAND-SNAPSHOT-{suffix}', intake_id=intake.id, primary_document_id=1,
|
||||
candidate_key=f'snapshot-{suffix}', order_extraction_id=extraction.id, candidate_status='accepted',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
task.candidate_id = candidate.id
|
||||
db.session.add(ShippingCustomerShadowResolution(
|
||||
candidate_id=candidate.id, intake_id=intake.id, resolution_version='test.v1', status='confirmed',
|
||||
evidence_json=[{'definition_code': 'test_customer', 'normalized_value': customer.short_code}],
|
||||
candidate_matches_json=[{'customer_id': customer.id, 'score': 100}],
|
||||
resolution_context_json={'rule_set': {'checksum': 'f' * 64}},
|
||||
identity_rule_set_checksum='f' * 64, top_customer_id=customer.id, top_score=100,
|
||||
confirmed_customer_id=customer.id, confirmation_method='manual', confirmed_by_id=user.id,
|
||||
confirmed_at=datetime.utcnow(),
|
||||
))
|
||||
db.session.commit()
|
||||
return task, user
|
||||
@@ -141,7 +156,7 @@ def test_freeze_creates_strong_snapshot_and_preserves_identifiers(app):
|
||||
assert task.order_snapshot_id == snapshot.id
|
||||
assert snapshot.customer_short_code_snapshot == 'CUS'
|
||||
assert snapshot.customer_id is not None
|
||||
assert snapshot.rule_versions_json['ordering_customer']['identity_rule_version'] == 'order-customer-fingerprint.v1'
|
||||
assert snapshot.rule_versions_json['ordering_customer']['identity_rule_set_checksum'] == 'f' * 64
|
||||
assert snapshot.lines[0].part_number == '000123'
|
||||
assert snapshot.lines[0].reservation_id == '0012345678'
|
||||
assert snapshot.lines[0].qty == Decimal('12.50000000')
|
||||
@@ -225,10 +240,9 @@ def test_freeze_rejects_unconfirmed_or_caller_supplied_customer(app):
|
||||
"""冻结只能采纳已确认订购客户,调用者传 customer_id 不能绕过该链路。"""
|
||||
with app.app_context():
|
||||
task, user = _build_accepted_order()
|
||||
match = ShippingOrderCustomerMatch.query.filter_by(
|
||||
extraction_id=task.current_order_extraction_id, role='bill_to',
|
||||
).one()
|
||||
match.status = 'unique_candidate'
|
||||
resolution = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one()
|
||||
resolution.status = 'unique_candidate'
|
||||
resolution.confirmed_customer_id = None
|
||||
with pytest.raises(ValidationError) as error:
|
||||
freeze_order_snapshot(task, actor_id=user.id, expected_order_data_version=7)
|
||||
assert error.value.code == 'SHIPPING.ORDER_CUSTOMER_CONFIRMATION_REQUIRED'
|
||||
|
||||
@@ -22,6 +22,11 @@ from app.models import (
|
||||
ShippingOrderField,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingOrderTask,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine,
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingNotice,
|
||||
User,
|
||||
)
|
||||
@@ -65,6 +70,98 @@ def _headers(username: str, role: str) -> dict[str, str]:
|
||||
return {'X-Username': username, 'X-Role': role, 'Content-Type': 'application/json'}
|
||||
|
||||
|
||||
def _notice_with_customer(*, task_no: str, customer_id: int, business_no: str | None = None) -> ShippingNotice:
|
||||
"""创建由已确认客户识别结果支撑的正式 Notice,避免回写 bill_to 或旧匹配表。"""
|
||||
_identity_field()
|
||||
user = User.query.filter_by(username='shipping-admin').one()
|
||||
version = ShippingOrderSchemaVersion.query.filter_by(status='published').order_by(
|
||||
ShippingOrderSchemaVersion.id.desc(),
|
||||
).first()
|
||||
asset = FileAsset(
|
||||
asset_no=f'FA-{task_no}', owner_user_id=user.id, original_filename='notice.pdf',
|
||||
storage_provider='minio', storage_bucket='test', storage_key=f'{task_no}.pdf',
|
||||
content_hash=f'{task_no:0<64}'[:64], file_size=1, upload_status='uploaded', lifecycle_status='temporary',
|
||||
)
|
||||
db.session.add(asset)
|
||||
db.session.flush()
|
||||
intake = ShippingOrderIntake(
|
||||
intake_no=f'INTAKE-{task_no}', asset_id=asset.id, user_id=user.id, parser_version='v6', parse_status='parsed',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
document = ShippingOrderDocument(
|
||||
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 = ShippingOrderCandidate(
|
||||
candidate_no=f'CANDIDATE-{task_no}', intake_id=intake.id, primary_document_id=document.id,
|
||||
candidate_key='document:1', validation_status='ready', selected=True,
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
task = ShippingOrderTask(
|
||||
task_no=task_no, user_id=user.id, intake_id=intake.id, candidate_id=candidate.id,
|
||||
status='ready', current_step='customer_review',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
task_id=task.id,
|
||||
schema_version_id=version.id,
|
||||
input_snapshot_hash=('a' * 64),
|
||||
status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
task.current_order_extraction_id = extraction.id
|
||||
candidate.order_extraction_id = extraction.id
|
||||
db.session.add(ShippingCustomerShadowResolution(
|
||||
candidate_id=candidate.id,
|
||||
intake_id=intake.id,
|
||||
resolution_version='test-v1',
|
||||
status='confirmed',
|
||||
evidence_json=[],
|
||||
candidate_matches_json=[],
|
||||
confirmed_customer_id=customer_id,
|
||||
confirmation_method='manual',
|
||||
))
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
task_id=task.id,
|
||||
extraction_id=extraction.id,
|
||||
schema_version_id=version.id,
|
||||
order_data_version=1,
|
||||
header_values_json={},
|
||||
source_manifest_json={},
|
||||
rule_versions_json={},
|
||||
)
|
||||
db.session.add(snapshot)
|
||||
db.session.flush()
|
||||
task.order_snapshot_id = snapshot.id
|
||||
snapshot_line = ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id,
|
||||
position=0,
|
||||
line_no=1,
|
||||
part_number='TEST-PART',
|
||||
qty=1,
|
||||
)
|
||||
db.session.add(snapshot_line)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
task_id=task.id,
|
||||
snapshot_line_id=snapshot_line.id,
|
||||
line_no=1,
|
||||
match_result='matched',
|
||||
inventory_status='ready',
|
||||
is_current=True,
|
||||
))
|
||||
notice = ShippingNotice(task_no=task_no, business_no=business_no, order_task_id=task.id)
|
||||
db.session.add(notice)
|
||||
db.session.flush()
|
||||
return notice
|
||||
|
||||
|
||||
def test_shipping_customer_admin_crud_uses_standard_contract(app, client):
|
||||
"""管理员可创建和查询客户,校验失败返回标准错误 envelope。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
@@ -327,7 +424,7 @@ def test_shipping_customer_delete_api_rejects_invalid_confirmation_and_blockers(
|
||||
customer = ShippingCustomer(standard_name='有业务客户', short_code='BLK', status='active')
|
||||
db.session.add(customer)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingNotice(task_no='SN-DELETE-API', customer_id=customer.id))
|
||||
_notice_with_customer(task_no='SN-DELETE-API', customer_id=customer.id)
|
||||
db.session.commit()
|
||||
customer_id = customer.id
|
||||
|
||||
@@ -346,7 +443,7 @@ def test_shipping_customer_delete_api_rejects_invalid_confirmation_and_blockers(
|
||||
assert blocked.status_code == 409
|
||||
error = parse_api_error(blocked.get_json())
|
||||
assert error['code'] == 'SHIPPING.CUSTOMER_DELETE_BLOCKED'
|
||||
assert error['details']['blockers']['business_cases'] == 1
|
||||
assert error['details']['blockers']['shipping_notices'] == 1
|
||||
|
||||
|
||||
def test_shipping_customer_merge_api_is_admin_only_and_preserves_source_history(app, client):
|
||||
@@ -363,7 +460,7 @@ def test_shipping_customer_merge_api_is_admin_only_and_preserves_source_history(
|
||||
customer_id=source.id, identifier_type='name_alias', raw_value='Source Alias',
|
||||
normalized_value='SOURCEALIAS', status='approved', source='manual',
|
||||
),
|
||||
ShippingNotice(task_no='SN-MERGE-API', customer_id=source.id, business_no='SRC26071601'),
|
||||
_notice_with_customer(task_no='SN-MERGE-API', customer_id=source.id, business_no='SRC26071601'),
|
||||
])
|
||||
db.session.commit()
|
||||
source_id = source.id
|
||||
@@ -382,7 +479,7 @@ def test_shipping_customer_merge_api_is_admin_only_and_preserves_source_history(
|
||||
headers=admin_headers,
|
||||
)
|
||||
assert preview.status_code == 200
|
||||
assert parse_api_data(preview.get_json())['historical_references']['business_cases'] == 1
|
||||
assert parse_api_data(preview.get_json())['historical_references']['shipping_notices'] == 1
|
||||
|
||||
response = client.post(
|
||||
f'/api/admin/shipping-customers/{source_id}/merge',
|
||||
@@ -396,7 +493,10 @@ def test_shipping_customer_merge_api_is_admin_only_and_preserves_source_history(
|
||||
with app.app_context():
|
||||
assert db.session.get(ShippingCustomer, source_id).status == 'merged'
|
||||
assert db.session.query(ShippingCustomerIdentifier).filter_by(customer_id=target_id).count() == 1
|
||||
assert db.session.query(ShippingNotice).filter_by(task_no='SN-MERGE-API').one().customer_id == source_id
|
||||
notice = db.session.query(ShippingNotice).filter_by(task_no='SN-MERGE-API').one()
|
||||
task = db.session.get(ShippingOrderTask, notice.order_task_id)
|
||||
resolution = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one()
|
||||
assert resolution.confirmed_customer_id == source_id
|
||||
|
||||
|
||||
def test_shipping_customer_merge_api_validates_target_confirmation_and_reason(app, client):
|
||||
@@ -507,47 +607,3 @@ def test_shipping_customer_shadow_report_and_label_api(app, client):
|
||||
headers=_headers('shipping-user', 'user'),
|
||||
)
|
||||
assert forbidden.status_code == 403
|
||||
|
||||
|
||||
def test_shipping_customer_numbered_correction_api_preserves_old_number(app, client):
|
||||
"""管理员纠错 API 作废原号并返回替代新号,普通用户不可调用。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
_create_users()
|
||||
wrong = ShippingCustomer(standard_name='错误客户', short_code='OLD', status='active')
|
||||
correct = ShippingCustomer(standard_name='正确客户', short_code='NEW', status='active')
|
||||
db.session.add_all([wrong, correct])
|
||||
db.session.flush()
|
||||
task = ShippingNotice(
|
||||
task_no='SN-CORRECTION-API',
|
||||
source_type='manual', customer_resolution_status='pending',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
from app.services.shipping_notice.customer_identity_gate import confirm_task_customer
|
||||
|
||||
confirm_task_customer(task, customer_id=wrong.id, actor_id=None)
|
||||
old_business_no = task.business_no
|
||||
correct_id = correct.id
|
||||
|
||||
forbidden = client.post(
|
||||
'/api/admin/shipping-customers/numbered-task-correction',
|
||||
json={'task_ref': old_business_no, 'customer_id': correct_id, 'reason': '客户错误'},
|
||||
headers=_headers('shipping-user', 'user'),
|
||||
)
|
||||
assert forbidden.status_code == 403
|
||||
|
||||
response = client.post(
|
||||
'/api/admin/shipping-customers/numbered-task-correction',
|
||||
json={'task_ref': old_business_no, 'customer_id': correct_id, 'reason': '客户错误'},
|
||||
headers=_headers('shipping-admin', 'admin'),
|
||||
)
|
||||
assert response.status_code == 200
|
||||
payload = parse_api_data(response.get_json())
|
||||
assert payload['old_business_no'] == old_business_no
|
||||
assert payload['new_business_no'].startswith('NEW')
|
||||
with app.app_context():
|
||||
old_notice = ShippingNotice.query.filter_by(business_no=old_business_no).one()
|
||||
replacement = ShippingNotice.query.filter_by(supersedes_task_id=old_notice.id).one()
|
||||
assert old_notice.lifecycle_status == 'voided'
|
||||
assert replacement.business_no == payload['new_business_no']
|
||||
@@ -16,18 +16,22 @@ from app.services.agent_registry.catalog import (
|
||||
|
||||
|
||||
def test_agent_type_catalog_contains_three_seed_types():
|
||||
"""首批 Catalog 应包含 generic、shipping_notice、file_check 三类。"""
|
||||
assert set(AGENT_TYPE_CATALOG.keys()) == {'generic', 'shipping_notice', 'file_check'}
|
||||
"""Catalog 应包含 generic、shipping_notice、file_check 等注册类型(含后续扩展)。"""
|
||||
assert {
|
||||
'generic', 'shipping_notice', 'file_check',
|
||||
'procurement_contract_review', 'in_transit_transfer',
|
||||
} <= set(AGENT_TYPE_CATALOG.keys())
|
||||
|
||||
|
||||
def test_list_type_catalog_includes_agent_code_and_label():
|
||||
"""Admin 下拉列表每条须含 agent_code 与人类可读 label。"""
|
||||
catalog = list_type_catalog()
|
||||
assert len(catalog) == 3
|
||||
assert len(catalog) >= 5
|
||||
codes = {entry['agent_code'] for entry in catalog}
|
||||
assert codes == {'generic', 'shipping_notice', 'file_check'}
|
||||
assert {'generic', 'shipping_notice', 'file_check', 'in_transit_transfer'} <= codes
|
||||
labels = {entry['label'] for entry in catalog}
|
||||
assert '通用问答 / 知识库' in labels
|
||||
assert '在途仓自动调拨' in labels
|
||||
assert '货代发货通知' in labels
|
||||
assert '文件检核' in labels
|
||||
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
"""在途仓自动调拨 Agent 应用类型注册测试。
|
||||
|
||||
用途:验证 in_transit_transfer 已注册为 Agent 应用类型(catalog manifest + handler 绑定 +
|
||||
HANDLER_REGISTRY),与既有 shipping_notice 注册链路一致。
|
||||
依赖:catalog_loader / catalog_bindings / handlers.bootstrap / resolver / catalog_validation。
|
||||
逻辑:只读断言注册契约;不创建 Flask 应用(避免对既有 catalog 单测造成影响)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.agent_registry import catalog_bindings
|
||||
from app.services.agent_registry.catalog_loader import build_agent_type_catalog, get_catalog_entry
|
||||
from app.services.agent_registry.catalog_validation import (
|
||||
apply_catalog_capabilities,
|
||||
normalize_handler_config,
|
||||
validate_required_fields,
|
||||
)
|
||||
from app.services.agent_registry.handlers.bootstrap import load_handlers, reset_handlers_for_tests
|
||||
from app.services.agent_registry.handlers.base import AgentHandler
|
||||
from app.services.agent_registry.handlers.registry import HANDLER_REGISTRY
|
||||
|
||||
|
||||
def test_in_transit_transfer_type_in_catalog():
|
||||
"""catalog 必须包含 in_transit_transfer 应用类型及关键声明。"""
|
||||
entry = get_catalog_entry('in_transit_transfer')
|
||||
assert entry is not None
|
||||
assert entry.get('label') == '在途仓自动调拨'
|
||||
assert entry.get('runtime_provider_default') == 'hybrid'
|
||||
progress = entry.get('progress_contract') or {}
|
||||
assert progress.get('enabled') is True
|
||||
assert progress.get('data_source', {}).get('domain') == 'in_transit_transfer'
|
||||
|
||||
|
||||
def test_in_transit_transfer_bound_to_runtime_handler():
|
||||
"""catalog_bindings 必须把 in_transit_transfer 绑定到同名 HANDLER_REGISTRY key。"""
|
||||
assert catalog_bindings.RUNTIME_HANDLER_BINDINGS['in_transit_transfer'] == 'in_transit_transfer'
|
||||
|
||||
|
||||
def test_in_transit_transfer_handler_registered():
|
||||
"""bootstrap 加载后 HANDLER_REGISTRY 包含 InTransitTransferHandler 实例。"""
|
||||
reset_handlers_for_tests()
|
||||
load_handlers()
|
||||
handler = HANDLER_REGISTRY.get('in_transit_transfer')
|
||||
assert handler is not None
|
||||
assert isinstance(handler, AgentHandler)
|
||||
assert handler.handler_key == 'in_transit_transfer'
|
||||
reset_handlers_for_tests()
|
||||
|
||||
|
||||
def test_in_transit_transfer_validation_compatible():
|
||||
"""catalog_validation 对 in_transit_transfer 的强制能力/配置归一化/必填校验可执行。"""
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
capabilities = apply_catalog_capabilities('in_transit_transfer', {'streaming': True})
|
||||
assert capabilities.get('human_confirm') is True
|
||||
# 空 handler_config_schema:null 允许、任意字段拒绝(与既有类型一致)。
|
||||
assert normalize_handler_config('in_transit_transfer', None) is None
|
||||
with pytest.raises(ValidationError):
|
||||
normalize_handler_config('in_transit_transfer', {'poll_interval_seconds': '5'})
|
||||
validate_required_fields('in_transit_transfer', bound_schedule_task_id=None)
|
||||
|
||||
|
||||
def test_in_transit_transfer_present_in_full_catalog():
|
||||
"""完整 catalog 构建包含新类型(与既有类型共存)。"""
|
||||
catalog = build_agent_type_catalog()
|
||||
assert 'in_transit_transfer' in catalog
|
||||
assert 'shipping_notice' in catalog
|
||||
@@ -80,7 +80,7 @@ def test_chat_turn_rejects_legacy_fulfillment_action(app, client):
|
||||
"input": {
|
||||
"type": "action",
|
||||
"display_text": "确认",
|
||||
"action_type": "shipping.submit_decision",
|
||||
"action_type": "shipping.match_inventory",
|
||||
"payload": {"task_no": task_no, "decision": "confirm"},
|
||||
},
|
||||
},
|
||||
@@ -128,7 +128,7 @@ def test_chat_turn_rejects_shipping_action_for_non_shipping_agent(app, client):
|
||||
"input": {
|
||||
"type": "action",
|
||||
"display_text": "确认",
|
||||
"action_type": "shipping.submit_decision",
|
||||
"action_type": "shipping.match_inventory",
|
||||
"payload": {"task_no": "SN-20260706-ABCD1234", "decision": "confirm"},
|
||||
},
|
||||
},
|
||||
|
||||
@@ -10,7 +10,7 @@ import pytest
|
||||
|
||||
|
||||
def _load_navigation():
|
||||
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "crane_navigation.py"
|
||||
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "connectors" / "crane" / "crane_navigation.py"
|
||||
spec = importlib.util.spec_from_file_location("crane_navigation_test", module_path)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
|
||||
@@ -10,7 +10,7 @@ import pytest
|
||||
|
||||
|
||||
def _load_export():
|
||||
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "crane_report_export.py"
|
||||
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "connectors" / "crane" / "crane_report_export.py"
|
||||
spec = importlib.util.spec_from_file_location("crane_report_export_test", module_path)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
@@ -106,13 +106,14 @@ def test_export_scheduled_report_flow(monkeypatch):
|
||||
def _download(*args, **kwargs):
|
||||
calls.append("download")
|
||||
captured["download_description"] = kwargs.get("description", "")
|
||||
captured["download_dir"] = kwargs.get("download_dir", "")
|
||||
return "download-object"
|
||||
|
||||
monkeypatch.setattr(module, "_wait_and_click_scheduled_download", _download)
|
||||
|
||||
result = module.export_crane_inventory_report(
|
||||
page,
|
||||
{"parameters": [], "source_code": "CRANE_TZR2"},
|
||||
{"parameters": [], "source_code": "CRANE_TZR2", "__download_dir": "D:/tmp/crane-drop"},
|
||||
trigger={"task_no": "SN-1001"},
|
||||
env=lambda name, default="": default,
|
||||
browser_timeout_ms=5_000,
|
||||
@@ -124,6 +125,7 @@ def test_export_scheduled_report_flow(monkeypatch):
|
||||
assert calls == ["run", "wait_run", "schedule", "confirm", "wait_submitted", "open_scheduled", "download"]
|
||||
assert captured["description"] == "HXOPS-CRANE_TZR2-TEST"
|
||||
assert captured["download_description"] == "HXOPS-CRANE_TZR2-TEST"
|
||||
assert captured["download_dir"] == "D:/tmp/crane-drop"
|
||||
|
||||
|
||||
def test_should_run_report_before_schedule_uses_driver_environment_only():
|
||||
@@ -443,3 +445,154 @@ def test_resolve_download_mode_uses_driver_environment_only():
|
||||
module = _load_export()
|
||||
assert module._resolve_download_mode({"navigation": {"download_mode": "file_download"}}, env=lambda name, default="": default) == "scheduled_report"
|
||||
assert module._resolve_download_mode({}, env=lambda name, default="": "file_download" if name == "SHIPPING_NOTICE_RPA_WORKER_CRANE_DOWNLOAD_MODE" else default) == "file_download"
|
||||
|
||||
|
||||
def test_wait_and_click_scheduled_download_falls_back_to_directory(tmp_path, monkeypatch):
|
||||
"""
|
||||
expect_download 超时后,应短窗口扫描 downloads_path 并返回目录文件适配器。
|
||||
断言意图:主路径事件丢失时复用 DSV 同款兜底,而不是直接失败。
|
||||
"""
|
||||
module = _load_export()
|
||||
page = MagicMock()
|
||||
locator = MagicMock()
|
||||
fallback = MagicMock()
|
||||
fallback.suggested_filename = "OnHandDetails.xlsx"
|
||||
fallback_calls: list[dict] = []
|
||||
|
||||
class _TimeoutDownloadExpect:
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc, tb):
|
||||
if exc_type is not None:
|
||||
return False
|
||||
raise TimeoutError('Timeout 60000ms exceeded while waiting for event "download"')
|
||||
|
||||
@property
|
||||
def value(self):
|
||||
raise AssertionError("download event should not resolve")
|
||||
|
||||
page.expect_download.side_effect = lambda timeout=None: _TimeoutDownloadExpect()
|
||||
monkeypatch.setattr(module, "_is_crane_login_blocking", lambda *_a, **_k: False)
|
||||
monkeypatch.setattr(module, "_is_on_scheduled_reports_page", lambda *_a, **_k: True)
|
||||
monkeypatch.setattr(
|
||||
module,
|
||||
"_probe_scheduled_download_status",
|
||||
lambda *_a, **_k: ("Download", locator),
|
||||
)
|
||||
monkeypatch.setattr(module, "_click_locator", lambda *_a, **_k: True)
|
||||
|
||||
def _fake_wait(*, download_dir, baseline_names, timeout_seconds):
|
||||
fallback_calls.append(
|
||||
{
|
||||
"download_dir": str(download_dir),
|
||||
"baseline_names": set(baseline_names),
|
||||
"timeout_seconds": timeout_seconds,
|
||||
}
|
||||
)
|
||||
return fallback
|
||||
|
||||
monkeypatch.setattr(module, "_wait_for_new_download_file", _fake_wait)
|
||||
|
||||
result = module._wait_and_click_scheduled_download(
|
||||
page,
|
||||
env=lambda name, default="": default,
|
||||
browser_timeout_ms=1_000,
|
||||
description="abc123",
|
||||
expected_report_name="OnHandDetails.xlsx",
|
||||
download_dir=str(tmp_path),
|
||||
)
|
||||
|
||||
assert result is fallback
|
||||
assert fallback_calls == [
|
||||
{
|
||||
"download_dir": str(tmp_path),
|
||||
"baseline_names": set(),
|
||||
"timeout_seconds": module._CRANE_DOWNLOAD_DIR_FALLBACK_SECONDS,
|
||||
}
|
||||
]
|
||||
|
||||
|
||||
def test_wait_and_click_scheduled_download_reraises_when_fallback_misses(tmp_path, monkeypatch):
|
||||
"""
|
||||
expect_download 超时且目录无新文件时,应继续抛出原超时。
|
||||
断言意图:兜底失败不能吞掉异常。
|
||||
"""
|
||||
module = _load_export()
|
||||
page = MagicMock()
|
||||
|
||||
class _TimeoutDownloadExpect:
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc, tb):
|
||||
if exc_type is not None:
|
||||
return False
|
||||
raise TimeoutError('Timeout 60000ms exceeded while waiting for event "download"')
|
||||
|
||||
page.expect_download.side_effect = lambda timeout=None: _TimeoutDownloadExpect()
|
||||
monkeypatch.setattr(module, "_is_crane_login_blocking", lambda *_a, **_k: False)
|
||||
monkeypatch.setattr(module, "_is_on_scheduled_reports_page", lambda *_a, **_k: True)
|
||||
monkeypatch.setattr(
|
||||
module,
|
||||
"_probe_scheduled_download_status",
|
||||
lambda *_a, **_k: ("Download", MagicMock()),
|
||||
)
|
||||
monkeypatch.setattr(module, "_click_locator", lambda *_a, **_k: True)
|
||||
monkeypatch.setattr(module, "_wait_for_new_download_file", lambda **_k: None)
|
||||
|
||||
with pytest.raises(TimeoutError, match="download"):
|
||||
module._wait_and_click_scheduled_download(
|
||||
page,
|
||||
env=lambda name, default="": default,
|
||||
browser_timeout_ms=1_000,
|
||||
description="abc123",
|
||||
download_dir=str(tmp_path),
|
||||
)
|
||||
|
||||
|
||||
def test_wait_and_click_scheduled_download_skips_fallback_on_click_failure(tmp_path, monkeypatch):
|
||||
"""
|
||||
Download 链接点击失败时不应进入目录兜底。
|
||||
断言意图:避免点击失败后空等 15s。
|
||||
"""
|
||||
module = _load_export()
|
||||
page = MagicMock()
|
||||
fallback_called = {"value": False}
|
||||
|
||||
class _DownloadExpect:
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc, tb):
|
||||
return False
|
||||
|
||||
@property
|
||||
def value(self):
|
||||
raise AssertionError("should not reach download value")
|
||||
|
||||
page.expect_download.side_effect = lambda timeout=None: _DownloadExpect()
|
||||
monkeypatch.setattr(module, "_is_crane_login_blocking", lambda *_a, **_k: False)
|
||||
monkeypatch.setattr(module, "_is_on_scheduled_reports_page", lambda *_a, **_k: True)
|
||||
monkeypatch.setattr(
|
||||
module,
|
||||
"_probe_scheduled_download_status",
|
||||
lambda *_a, **_k: ("Download", MagicMock()),
|
||||
)
|
||||
monkeypatch.setattr(module, "_click_locator", lambda *_a, **_k: False)
|
||||
|
||||
def _fake_wait(**_kwargs):
|
||||
fallback_called["value"] = True
|
||||
return MagicMock()
|
||||
|
||||
monkeypatch.setattr(module, "_wait_for_new_download_file", _fake_wait)
|
||||
|
||||
with pytest.raises(RuntimeError, match="Download link click failed"):
|
||||
module._wait_and_click_scheduled_download(
|
||||
page,
|
||||
env=lambda name, default="": default,
|
||||
browser_timeout_ms=1_000,
|
||||
description="abc123",
|
||||
download_dir=str(tmp_path),
|
||||
)
|
||||
assert fallback_called["value"] is False
|
||||
@@ -8,7 +8,7 @@ from unittest.mock import MagicMock
|
||||
|
||||
|
||||
def _load_crane_session():
|
||||
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "crane_session.py"
|
||||
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "connectors" / "crane" / "crane_session.py"
|
||||
spec = importlib.util.spec_from_file_location("crane_session_test", module_path)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
@@ -144,7 +144,7 @@ def test_find_crane_sign_in_button_waits_for_enabled_state(monkeypatch):
|
||||
|
||||
def test_ensure_crane_session_skips_login_when_session_active(monkeypatch):
|
||||
"""batch 内 session 有效时不应重复 goto + login。"""
|
||||
worker_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "freight_rpa_worker.py"
|
||||
worker_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "inventory" / "inventory_rpa_worker.py"
|
||||
spec = importlib.util.spec_from_file_location("freight_rpa_worker_crane_test", worker_path)
|
||||
assert spec and spec.loader
|
||||
worker = importlib.util.module_from_spec(spec)
|
||||
|
||||
@@ -7,7 +7,7 @@ from pathlib import Path
|
||||
|
||||
|
||||
def _load_module():
|
||||
path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "dsv_report_parameters.py"
|
||||
path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "connectors" / "dsv" / "dsv_report_parameters.py"
|
||||
spec = importlib.util.spec_from_file_location("dsv_report_parameters_test", path)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
|
||||
@@ -430,3 +430,60 @@ def test_email_supplement_requires_frozen_schema_alias_for_order_headers():
|
||||
html_tables=['''<table><tr><th>PO#</th><th>MPN</th><th>Reservation ID</th></tr><tr><td>4518838154</td><td>B3-AR1000270A1</td><td>4000111701</td></tr></table>'''],
|
||||
)
|
||||
assert result == {'version': 'email-supplement.v1', 'rows': [], 'issues': ['email_supplement_po_header_missing']}
|
||||
|
||||
|
||||
def test_email_supplement_pn_matching_customer_part_number_does_not_false_conflict():
|
||||
"""邮件 PN 列的值为客户件号(MPN)时不得与 PDF 内部件号产生误判 part_number 冲突。
|
||||
|
||||
回归:ZNE 邮件正文 PO 表把客户件号(504-006043-001)放进 PN 列并映射到
|
||||
`part_number`,而 PDF 同一行的 `part_number` 是内部件号(D4-A08AR12000001)、
|
||||
`customer_part_number` 是 504-006043-001。邮件值命中 PDF 的客户件号即同一料号,
|
||||
不得判成 `part_number` 的 `supplement_field_conflict`。
|
||||
"""
|
||||
order = _order() # header PO 4518738152;line part D4-A08AR12000002
|
||||
order['lines'][0]['fields'].append({
|
||||
'field_id': 'customer-part', 'observations': [{'value': '504-006043-001'}],
|
||||
})
|
||||
supplement = {
|
||||
'document_id': 44,
|
||||
'rows': [{
|
||||
'customer_po_number': '4518738152',
|
||||
'part_number': '504-006043-001', # 邮件 PN 列,实为客户件号(MPN)
|
||||
'evidence': {},
|
||||
}],
|
||||
}
|
||||
merged = merge_email_supplements(
|
||||
orders=[order], supplements_by_intake={1: supplement}, schema_definition=SCHEMA,
|
||||
)[0]
|
||||
# PDF 内部件号保持不变,且不再误判 part_number 冲突
|
||||
assert _value(merged['lines'][0]['fields'], 'part') == 'D4-A08AR12000002'
|
||||
assert not any(item.get('field') == 'part_number' for item in merged['conflicts'])
|
||||
|
||||
|
||||
def test_supplement_field_conflict_pdf_string_evidence_ref_does_not_crash():
|
||||
"""坐标 PDF observation 的 evidence_ref 是字符串时不得崩溃(dict.update length1 回归)。
|
||||
|
||||
回归:`_supplement_field_conflict` 曾用 `dict(pdf.get('evidence_ref') or {})` 直接构造证据,
|
||||
而坐标 PDF observation 的 `evidence_ref` 是字符串(如 `layout:...:row-7:qty`),
|
||||
`dict(<字符串>)` 会按字符拆成长度 1 序列 → `dictionary update sequence element #0 has length 1; 2 is required`。
|
||||
修复后改用 observation 的证据 dict(`layout_evidence`,或 `evidence_ref` 为 dict 时用其本身)。
|
||||
"""
|
||||
from app.services.shipping_notice.order_supplement_merge import _supplement_field_conflict
|
||||
|
||||
conflict = _supplement_field_conflict(
|
||||
field_code='qty', config={'field_id': 'qty', 'field_code': 'qty'}, line_index=0,
|
||||
pdf_observations=[{
|
||||
'value': '30', 'document_id': 305,
|
||||
'evidence_ref': 'layout:305:p1:t1:row-1:qty', # 字符串(坐标 evidence_ref,触发旧崩溃)
|
||||
'layout_evidence': {'page_no': 1, 'cell_id': 'c1', 'evidence_ref': 'layout:305:p1:t1:row-1:qty'},
|
||||
}],
|
||||
email_value='99', email_evidence={'table_index': 0, 'row_index': 1},
|
||||
email_document_id=44, schema_version='v1',
|
||||
)
|
||||
|
||||
assert conflict['conflict_key'] == '0:qty'
|
||||
# evidence_ref 保持 dict 契约,并取 observation 的证据 dict(layout_evidence)
|
||||
assert conflict['sources'][0]['evidence_ref'] == {
|
||||
'page_no': 1, 'cell_id': 'c1', 'evidence_ref': 'layout:305:p1:t1:row-1:qty',
|
||||
}
|
||||
assert conflict['sources'][1]['evidence_ref'] == {'table_index': 0, 'row_index': 1}
|
||||
@@ -7,7 +7,7 @@ from pathlib import Path
|
||||
|
||||
def test_receipt_worker_isolated_from_inventory_worker_and_uses_receipt_contract():
|
||||
"""收料 Worker 只消费 v1 receipt trigger、专用目录和独立 callback。"""
|
||||
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' / 'freight_receipt_rpa_worker.py').read_text(encoding='utf-8')
|
||||
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
|
||||
assert 'SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR' in text
|
||||
assert 'SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR' in text
|
||||
assert 'shipping_receipt_rpa.v1' in text
|
||||
@@ -19,8 +19,8 @@ def test_receipt_worker_isolated_from_inventory_worker_and_uses_receipt_contract
|
||||
def test_receipt_crane_driver_forces_inbound_details_match_name():
|
||||
"""收料 Crane 必须将固定报表名传给轮询匹配,不能落回库存文件名默认值。"""
|
||||
root = Path(__file__).resolve().parents[2] / 'scripts' / 'rpa'
|
||||
receipt_driver = (root / 'freight_receipt_crane_export.py').read_text(encoding='utf-8')
|
||||
crane_driver = (root / 'crane_report_export.py').read_text(encoding='utf-8')
|
||||
receipt_driver = (root / 'receipt' / 'receipt_crane_export.py').read_text(encoding='utf-8')
|
||||
crane_driver = (root / 'connectors' / 'crane' / 'crane_report_export.py').read_text(encoding='utf-8')
|
||||
assert "'scheduled_report_name': 'Inbound Details'" in receipt_driver
|
||||
assert "source_value = str((source or {}).get('scheduled_report_name') or '').strip()" in crane_driver
|
||||
|
||||
@@ -28,7 +28,7 @@ def test_receipt_crane_driver_forces_inbound_details_match_name():
|
||||
def test_receipt_crane_driver_forces_inbound_details_entry_route():
|
||||
"""复用 Profile 的门户首页时,收料不能误走库存 On Hand Details 路由。"""
|
||||
root = Path(__file__).resolve().parents[2] / 'scripts' / 'rpa'
|
||||
module_path = root / 'freight_receipt_crane_export.py'
|
||||
module_path = root / 'receipt' / 'receipt_crane_export.py'
|
||||
sys.path.insert(0, str(root))
|
||||
spec = importlib.util.spec_from_file_location('freight_receipt_crane_export_test', module_path)
|
||||
assert spec and spec.loader
|
||||
|
||||
@@ -13,7 +13,7 @@ def _load_freight_rpa_heartbeat_module():
|
||||
rpa_dir = Path(__file__).resolve().parents[2] / "scripts" / "rpa"
|
||||
if str(rpa_dir) not in sys.path:
|
||||
sys.path.insert(0, str(rpa_dir))
|
||||
module_path = rpa_dir / "freight_rpa_heartbeat.py"
|
||||
module_path = rpa_dir / "common" / "rpa_heartbeat.py"
|
||||
spec = importlib.util.spec_from_file_location("freight_rpa_heartbeat_test", module_path)
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
assert spec.loader is not None
|
||||
|
||||
@@ -14,6 +14,7 @@ import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
@@ -26,8 +27,8 @@ def _repo_root() -> Path:
|
||||
|
||||
|
||||
def _load_freight_rpa_worker():
|
||||
module_path = _repo_root() / "scripts" / "rpa" / "freight_rpa_worker.py"
|
||||
spec = importlib.util.spec_from_file_location("freight_rpa_worker_under_test", module_path)
|
||||
module_path = _repo_root() / "scripts" / "rpa" / "inventory" / "inventory_rpa_worker.py"
|
||||
spec = importlib.util.spec_from_file_location("inventory_rpa_worker_under_test", module_path)
|
||||
assert spec is not None
|
||||
assert spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
@@ -648,9 +649,11 @@ def test_open_browser_uses_shipping_notice_profile_fallback(monkeypatch):
|
||||
return _FakePlaywright()
|
||||
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", raising=False)
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "false")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "true")
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL", raising=False)
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH", raising=False)
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", raising=False)
|
||||
monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object))
|
||||
|
||||
temp_roots: list[Path] = []
|
||||
@@ -932,8 +935,8 @@ def test_real_upload_requires_connection_config_enabled(monkeypatch, tmp_path):
|
||||
worker._upload_shipment_with_browser(workbook, connector_type="dbs", upload_source={"upload_config_json": {"enabled": False}})
|
||||
|
||||
|
||||
def test_dsv_upload_returns_history_receipt_evidence(monkeypatch, tmp_path):
|
||||
"""DSV 上传须复用登录态打开入口、设置文件,并以 History 绿色回执作为证据返回。"""
|
||||
def test_dsv_upload_returns_result_page_evidence(monkeypatch, tmp_path):
|
||||
"""DSV 上传须点击 Process File,并以结果页三项判定的证据回传。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
workbook = tmp_path / "shipment.xlsx"
|
||||
workbook.write_bytes(b"test")
|
||||
@@ -986,10 +989,10 @@ def test_dsv_upload_returns_history_receipt_evidence(monkeypatch, tmp_path):
|
||||
monkeypatch.setattr(worker, "_ensure_dsv_session", lambda _page, url: events.append(("session", url)))
|
||||
monkeypatch.setattr(worker, "_open_browser", lambda _dir: (_Playwright(), _Context(), _Page(), runtime_profile))
|
||||
|
||||
def fake_history(_page, filename):
|
||||
return {"reference": "FREIGHT-REF-001", "success_evidence": {"kind": "dsv_history_green_dom", "selector": "em.fa.fa-circle.success-color.status-icon", "filename": filename, "reference": "FREIGHT-REF-001", "observed_at": "2026-01-01T00:00:00Z", "page_url": "https://s360.dbschenker.com/main/portal/frame/WMSUpload2", "dom_snippet": "<em/>", "dom_sha256": "abc"}}
|
||||
def fake_result(_page, filename):
|
||||
return {"reference": "", "success_evidence": {"kind": "dsv_upload_success_dom", "selector": ".alert.alert-success", "filename": filename, "reference": None, "observed_at": "2026-01-01T00:00:00Z", "page_url": "https://s360.dbschenker.com/main/portal/frame/WMSUpload2", "dom_snippet": "<div/>", "dom_sha256": "abc"}}
|
||||
|
||||
monkeypatch.setattr(worker, "_wait_for_dsv_upload_history_receipt", fake_history)
|
||||
monkeypatch.setattr(worker, "_wait_for_dsv_upload_result", fake_result)
|
||||
|
||||
result = worker._upload_shipment_with_browser(workbook, connector_type="dbs", upload_source={
|
||||
"connector_type": "dbs",
|
||||
@@ -1001,11 +1004,12 @@ def test_dsv_upload_returns_history_receipt_evidence(monkeypatch, tmp_path):
|
||||
"result_mode": "page_notice", "result_selector": None, "success_texts": [], "timeout_seconds": 120,
|
||||
},
|
||||
})
|
||||
assert result['reference'] == 'FREIGHT-REF-001'
|
||||
assert result['success_evidence']['kind'] == 'dsv_history_green_dom'
|
||||
assert result['reference'] == ''
|
||||
assert result['success_evidence']['kind'] == 'dsv_upload_success_dom'
|
||||
assert events[0] == ("session", "https://s360.dbschenker.com/")
|
||||
assert ("goto", "https://s360.dbschenker.com/main/portal/frame/WMSUpload2") in events
|
||||
assert ("file", str(workbook)) in events
|
||||
assert ("click", 'button.btn.btn-primary.upload-button:has-text("Process File")') in events
|
||||
|
||||
|
||||
def test_dsv_upload_uses_upload_entry_url_after_login(monkeypatch, tmp_path):
|
||||
@@ -1053,7 +1057,7 @@ def test_dsv_upload_uses_upload_entry_url_after_login(monkeypatch, tmp_path):
|
||||
runtime_profile.mkdir()
|
||||
monkeypatch.setattr(worker, "_ensure_dsv_session", lambda _page, url: events.append(("session", url)))
|
||||
monkeypatch.setattr(worker, "_open_browser", lambda _dir: (_Playwright(), _Context(), _Page(), runtime_profile))
|
||||
monkeypatch.setattr(worker, "_wait_for_dsv_upload_history_receipt", lambda _page, filename: f"REF-{filename}")
|
||||
monkeypatch.setattr(worker, "_wait_for_dsv_upload_result", lambda _page, _filename: {"reference": "", "success_evidence": {}})
|
||||
|
||||
assert worker._upload_shipment_with_browser(
|
||||
workbook, connector_type="dbs", upload_source={
|
||||
@@ -1068,12 +1072,52 @@ def test_dsv_upload_uses_upload_entry_url_after_login(monkeypatch, tmp_path):
|
||||
"success_texts": [], "timeout_seconds": 120,
|
||||
},
|
||||
}
|
||||
) == "REF-shipment.xlsx"
|
||||
) == {"reference": "", "success_evidence": {}}
|
||||
|
||||
assert events[0] == ("session", "https://s360.dbschenker.com/")
|
||||
assert events[1] == ("goto", "https://s360.dbschenker.com/main/portal/frame/WMSUpload2")
|
||||
assert ("file", "#file2") in events
|
||||
assert ("click", 'button.upload-button:has-text("Process File")') in events
|
||||
assert ("click", 'button.btn.btn-primary.upload-button:has-text("Process File")') in events
|
||||
|
||||
|
||||
def test_dsv_upload_always_confirms_process_file_after_selecting_file(monkeypatch, tmp_path):
|
||||
"""DSV 选中文件后必须点击 Process File,不能仅凭 set_input_files 视为已上传。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
workbook = tmp_path / "shipment.xlsx"
|
||||
workbook.write_bytes(b"test")
|
||||
events: list[tuple[str, object]] = []
|
||||
|
||||
class _Locator:
|
||||
def __init__(self, selector: str):
|
||||
self.selector = selector
|
||||
self.first = self
|
||||
|
||||
def set_input_files(self, value: str, **_kwargs) -> None:
|
||||
events.append(("file", value))
|
||||
|
||||
def click(self, **_kwargs) -> None:
|
||||
events.append(("click", self.selector))
|
||||
|
||||
class _Page:
|
||||
def goto(self, _url: str, **_kwargs) -> None:
|
||||
return None
|
||||
|
||||
def locator(self, selector: str) -> _Locator:
|
||||
return _Locator(selector)
|
||||
|
||||
monkeypatch.setattr(worker, "_ensure_dsv_session", lambda *_args: None)
|
||||
monkeypatch.setattr(worker, "_wait_for_dsv_upload_result", lambda *_args: {"reference": "", "success_evidence": {}})
|
||||
worker.DsvUploadAdapter(
|
||||
file_path=workbook,
|
||||
upload_config={
|
||||
"entry_url": "https://s360.dbschenker.com/upload",
|
||||
"file_input_selector": "#file2",
|
||||
"submit_mode": "auto_after_file",
|
||||
"timeout_seconds": 1,
|
||||
},
|
||||
).run(_Page(), login_url="https://s360.dbschenker.com/")
|
||||
|
||||
assert ("click", 'button.btn.btn-primary.upload-button:has-text("Process File")') in events
|
||||
|
||||
|
||||
def test_dsv_upload_history_requires_green_status_and_reference(monkeypatch):
|
||||
@@ -1154,6 +1198,48 @@ def test_dsv_upload_history_returns_reference_only_for_confirmed_success(monkeyp
|
||||
assert evidence["page_url"]
|
||||
|
||||
|
||||
def test_crane_upload_result_requires_processing_and_shipping_order_allocated():
|
||||
"""Crane 上传成功必须同时满足单号行状态与状态描述。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
|
||||
assert worker._crane_upload_result_is_success({
|
||||
"found": True,
|
||||
"order_status": "Processing",
|
||||
"order_status_description": "Shipping Order Allocated",
|
||||
}) is True
|
||||
assert worker._crane_upload_result_is_success({
|
||||
"found": True,
|
||||
"order_status": "Completed",
|
||||
"order_status_description": "Shipping Order Allocated",
|
||||
}) is False
|
||||
assert worker._crane_upload_result_is_success({
|
||||
"found": True,
|
||||
"order_status": "Processing",
|
||||
"order_status_description": "Allocating the Shipping Order",
|
||||
}) is False
|
||||
|
||||
|
||||
def test_dsv_upload_result_requires_success_button_and_empty_errors():
|
||||
"""DSV 只有成功按钮且两类错误均为空时才算上传成功。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
|
||||
assert worker._dsv_upload_result_is_success({
|
||||
"button": "Upload Successful",
|
||||
"upload_file_errors": "",
|
||||
"wms_errors": "",
|
||||
}) is True
|
||||
assert worker._dsv_upload_result_is_success({
|
||||
"button": "Upload Unsuccessful",
|
||||
"upload_file_errors": "",
|
||||
"wms_errors": "",
|
||||
}) is False
|
||||
assert worker._dsv_upload_result_is_success({
|
||||
"button": "Upload Successful",
|
||||
"upload_file_errors": "Missing column",
|
||||
"wms_errors": "",
|
||||
}) is False
|
||||
|
||||
|
||||
def test_dsv_upload_falls_back_to_apps_menu(monkeypatch):
|
||||
"""首页入口缺失时,DSV 仅可退回已确认的 Apps > Upload Tool 路径。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
@@ -1263,7 +1349,7 @@ def test_summarize_inventory_batch_results_all_skipped_is_success():
|
||||
assert summary["has_success"] is False
|
||||
assert summary["status"] not in {"failed", "partial_failed"}
|
||||
def test_open_browser_uses_fresh_runtime_profile_under_configured_root(monkeypatch, tmp_path):
|
||||
"""真实 RPA 每次都应在配置目录下生成新的运行时 profile,避免复用已有浏览器状态。"""
|
||||
"""关闭会话复用时,每次都应在配置目录下生成新的 run_* 临时 profile。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
observed: dict[str, object] = {}
|
||||
|
||||
@@ -1288,9 +1374,11 @@ def test_open_browser_uses_fresh_runtime_profile_under_configured_root(monkeypat
|
||||
return _FakePlaywright()
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "false")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL", "msedge")
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH", raising=False)
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", raising=False)
|
||||
monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object))
|
||||
|
||||
_playwright, context, page, runtime_profile_dir = worker._open_browser(tmp_path / "downloads")
|
||||
@@ -1309,8 +1397,8 @@ def test_open_browser_uses_fresh_runtime_profile_under_configured_root(monkeypat
|
||||
}
|
||||
|
||||
|
||||
def test_open_browser_reuses_dsv_session_profile_only_when_explicitly_enabled(monkeypatch, tmp_path):
|
||||
"""DSV 会话复用开关开启时应使用固定 profile,且固定 profile 不能按临时目录清理。"""
|
||||
def test_open_browser_reuses_session_profile_per_connector_and_rpa_profile(monkeypatch, tmp_path):
|
||||
"""会话复用开启时按 connector+rpa_profile 固定目录,且不得当作临时目录清理。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
observed: dict[str, object] = {}
|
||||
|
||||
@@ -1334,20 +1422,92 @@ def test_open_browser_reuses_dsv_session_profile_only_when_explicitly_enabled(mo
|
||||
return _FakePlaywright()
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", "true")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "true")
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", raising=False)
|
||||
monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object))
|
||||
|
||||
_playwright, context, page, profile_dir = worker._open_browser(
|
||||
tmp_path / "downloads", reuse_dsv_session=True
|
||||
tmp_path / "downloads",
|
||||
reuse_session=True,
|
||||
connector_type="crane_footprint",
|
||||
profile_code="CRANE-MAIN",
|
||||
)
|
||||
|
||||
assert context is not None
|
||||
assert page is not None
|
||||
assert profile_dir == tmp_path / "profile" / "dsv360_session"
|
||||
assert profile_dir == tmp_path / "profile" / "crane_footprint__CRANE-MAIN_session"
|
||||
assert observed["profile"] == str(profile_dir)
|
||||
assert worker._should_cleanup_browser_profile(profile_dir) is False
|
||||
assert (profile_dir / ".hxops_rpa_session_meta.json").is_file()
|
||||
|
||||
|
||||
def test_open_browser_reuses_dsv_session_profile_only_when_explicitly_enabled(monkeypatch, tmp_path):
|
||||
"""兼容旧参数 reuse_dsv_session:开启复用时落到 dsv360__* 持久目录。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
observed: dict[str, object] = {}
|
||||
|
||||
class _FakePage:
|
||||
def set_default_timeout(self, value: int) -> None:
|
||||
observed["timeout"] = value
|
||||
|
||||
class _FakeContext:
|
||||
pages = [_FakePage()]
|
||||
|
||||
class _FakeChromium:
|
||||
def launch_persistent_context(self, profile: str, **kwargs):
|
||||
observed["profile"] = profile
|
||||
return _FakeContext()
|
||||
|
||||
class _FakePlaywright:
|
||||
chromium = _FakeChromium()
|
||||
|
||||
class _FakeStarter:
|
||||
def start(self):
|
||||
return _FakePlaywright()
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "true")
|
||||
monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object))
|
||||
|
||||
_playwright, context, page, profile_dir = worker._open_browser(
|
||||
tmp_path / "downloads",
|
||||
reuse_dsv_session=True,
|
||||
connector_type="dsv360",
|
||||
profile_code="DSV-A",
|
||||
)
|
||||
|
||||
assert context is not None
|
||||
assert page is not None
|
||||
assert profile_dir == tmp_path / "profile" / "dsv360__DSV-A_session"
|
||||
assert observed["profile"] == str(profile_dir)
|
||||
assert worker._should_cleanup_browser_profile(profile_dir) is False
|
||||
|
||||
|
||||
def test_prepare_reusable_session_profile_expires_after_ttl(monkeypatch, tmp_path):
|
||||
"""超过 TTL 的持久 Profile 应被清空重建,迫使重新登录。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
profile_dir = tmp_path / "dsv360__OLD_session"
|
||||
profile_dir.mkdir(parents=True)
|
||||
stale_marker = profile_dir / "stale.txt"
|
||||
stale_marker.write_text("keep-me", encoding="utf-8")
|
||||
created = time.time() - (25 * 3600)
|
||||
(profile_dir / ".hxops_rpa_session_meta.json").write_text(
|
||||
json.dumps({"created_at_unix": created, "connector_type": "dsv360", "profile_code": "OLD"}),
|
||||
encoding="utf-8",
|
||||
)
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE_TTL_HOURS", "24")
|
||||
|
||||
prepared = worker._prepare_reusable_session_profile(
|
||||
profile_dir,
|
||||
connector_type="dsv360",
|
||||
profile_code="OLD",
|
||||
)
|
||||
|
||||
assert prepared == profile_dir
|
||||
assert not stale_marker.exists()
|
||||
meta = json.loads((profile_dir / ".hxops_rpa_session_meta.json").read_text(encoding="utf-8"))
|
||||
assert float(meta["created_at_unix"]) > created
|
||||
|
||||
def test_is_dsv_username_page_ignores_login_method_page_text():
|
||||
"""第二步方法选择页即使残留第一步文案,也不应被误判为邮箱页。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
@@ -1627,7 +1787,7 @@ def test_has_dsv_password_upgrade_prompt_skips_portal_page_scan(monkeypatch):
|
||||
|
||||
def test_ensure_dsv_session_retries_entry_after_home_not_ready(monkeypatch):
|
||||
"""登录后 home-not-ready 且 session 仍在 entry 站点时,应回 entry 重试一次。"""
|
||||
module_path = _repo_root() / "scripts" / "rpa" / "dsv_report_export.py"
|
||||
module_path = _repo_root() / "scripts" / "rpa" / "connectors" / "dsv" / "dsv_report_export.py"
|
||||
spec = importlib.util.spec_from_file_location("dsv_report_export_retry_test", module_path)
|
||||
assert spec is not None and spec.loader is not None
|
||||
dsv_report_export = importlib.util.module_from_spec(spec)
|
||||
|
||||
@@ -20,8 +20,21 @@ def _load_dsv_auth_login_flow():
|
||||
return _load_rpa_module("dsv_auth_login_flow")
|
||||
|
||||
|
||||
_RPA_MODULE_PATHS = {
|
||||
"freight_rpa_worker": "inventory/inventory_rpa_worker.py",
|
||||
"inventory_rpa_worker": "inventory/inventory_rpa_worker.py",
|
||||
"dsv_report_export": "connectors/dsv/dsv_report_export.py",
|
||||
"dsv_auth_login_flow": "connectors/dsv/dsv_auth_login_flow.py",
|
||||
"dsv_navigation": "connectors/dsv/dsv_navigation.py",
|
||||
"dsv_auth": "connectors/dsv/dsv_auth.py",
|
||||
"dsv_session": "connectors/dsv/dsv_session.py",
|
||||
"dsv_debug": "connectors/dsv/dsv_debug.py",
|
||||
}
|
||||
|
||||
|
||||
def _load_rpa_module(module_name: str):
|
||||
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / f"{module_name}.py"
|
||||
rel = _RPA_MODULE_PATHS.get(module_name, f"{module_name}.py")
|
||||
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / rel
|
||||
scripts_dir = str(module_path.parent)
|
||||
if scripts_dir not in sys.path:
|
||||
sys.path.insert(0, scripts_dir)
|
||||
|
||||
@@ -0,0 +1,414 @@
|
||||
"""
|
||||
backend/tests/test_gate_derivation.py
|
||||
|
||||
用途:验收 Gate 推导的粗分类 / 位置 / 待办分类,替代旧 checkpoint_kind。
|
||||
依赖:process_gate_contract.derive_*、query_service._todo_category_from_gate、
|
||||
ui_state._derived_*、user_facing_status、pytest。
|
||||
逻辑:Task1–6 契约纯函数与消费点迁移断言;SQL CASE 双读过渡不在此覆盖。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.process_gate_contract import (
|
||||
derive_position,
|
||||
derive_todo_category,
|
||||
derive_user_mode,
|
||||
)
|
||||
|
||||
|
||||
def test_user_mode_complete_when_rejected():
|
||||
assert derive_user_mode(
|
||||
user_status='completed',
|
||||
gate_code=None,
|
||||
review_status='rejected',
|
||||
lifecycle_stage=None,
|
||||
) == 'complete'
|
||||
|
||||
|
||||
def test_user_mode_wait_upload_handoff():
|
||||
assert derive_user_mode(
|
||||
user_status='waiting_human',
|
||||
gate_code='manual_upload_handoff',
|
||||
review_status=None,
|
||||
lifecycle_stage='freight_upload',
|
||||
) == 'wait_manual_upload'
|
||||
|
||||
|
||||
def test_user_mode_must_human():
|
||||
assert derive_user_mode(
|
||||
user_status='waiting_human',
|
||||
gate_code='inventory_matching',
|
||||
review_status=None,
|
||||
lifecycle_stage='fulfillment_prep',
|
||||
) == 'must_human'
|
||||
|
||||
|
||||
def test_user_mode_auto():
|
||||
assert derive_user_mode(
|
||||
user_status='running',
|
||||
gate_code='inventory_preparation',
|
||||
review_status=None,
|
||||
lifecycle_stage='fulfillment_prep',
|
||||
) == 'auto_continue'
|
||||
|
||||
|
||||
def test_position_review_dispositions():
|
||||
assert derive_position(gate_code=None, review_status='rejected') == 'rejected'
|
||||
assert derive_position(gate_code=None, review_status='quality_issue') == 'quality_issue'
|
||||
assert derive_position(gate_code=None, review_status='rsv_req') == 'rsv_req'
|
||||
|
||||
|
||||
def test_position_fulfillment():
|
||||
assert derive_position(gate_code='inventory_preparation', review_status=None) == 'inventory_pending'
|
||||
assert derive_position(gate_code='artifact_generation', review_status=None) == 'export_ready'
|
||||
|
||||
|
||||
def test_todo_category():
|
||||
assert derive_todo_category(user_mode='must_human', position='parse_review') == 'review'
|
||||
assert derive_todo_category(user_mode='must_human', position='quality_issue') == 'exception'
|
||||
assert derive_todo_category(user_mode='wait_manual_upload') == 'manual_upload'
|
||||
assert derive_todo_category(user_mode='complete') == 'done'
|
||||
assert derive_todo_category(user_mode='auto_continue') == 'in_progress'
|
||||
|
||||
|
||||
def test_fetch_gate_positions_empty():
|
||||
from app.services.shipping_notice.query_service import fetch_gate_positions
|
||||
|
||||
assert fetch_gate_positions([]) == {}
|
||||
|
||||
|
||||
def test_fetch_gate_positions_batched(app):
|
||||
"""关键断言:一次查询按 task_id 返回 current_gate_code / status。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.models import ShippingOrderTask, ShippingProcessExecution
|
||||
from app.services.shipping_notice.query_service import fetch_gate_positions
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
user, _agent, session, _intake, _document = _seed_run_input(suffix='GATE-POS')
|
||||
ot_a = ShippingOrderTask(
|
||||
task_no='OT-GATE-POS-A',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
status='waiting_review',
|
||||
stage='step5_match_inventory',
|
||||
progress_version=1,
|
||||
)
|
||||
ot_b = ShippingOrderTask(
|
||||
task_no='OT-GATE-POS-B',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
status='processing',
|
||||
stage='inventory_fetching',
|
||||
progress_version=1,
|
||||
)
|
||||
db.session.add_all([ot_a, ot_b])
|
||||
db.session.flush()
|
||||
db.session.add_all([
|
||||
ShippingProcessExecution(
|
||||
execution_no='SPE-GATE-POS-A',
|
||||
task_id=int(ot_a.id),
|
||||
status='blocked',
|
||||
current_gate_code='inventory_sufficiency',
|
||||
),
|
||||
ShippingProcessExecution(
|
||||
execution_no='SPE-GATE-POS-B',
|
||||
task_id=int(ot_b.id),
|
||||
status='active',
|
||||
current_gate_code='inventory_preparation',
|
||||
),
|
||||
])
|
||||
db.session.commit()
|
||||
|
||||
result = fetch_gate_positions([int(ot_a.id), int(ot_b.id), 999999])
|
||||
assert result[int(ot_a.id)]['current_gate_code'] == 'inventory_sufficiency'
|
||||
assert result[int(ot_a.id)]['status'] == 'blocked'
|
||||
assert result[int(ot_b.id)]['current_gate_code'] == 'inventory_preparation'
|
||||
assert 999999 not in result
|
||||
|
||||
|
||||
def test_early_stop_uses_derive_user_mode(monkeypatch):
|
||||
from app.services.shipping_notice import progress_workflow as pw
|
||||
|
||||
class FakeTask:
|
||||
task_no = 'SN-1'
|
||||
review_status = None
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.ui_state._process_gate_user_summary_for_task',
|
||||
lambda t: {
|
||||
'current_gate': {
|
||||
'status': 'blocked_manual',
|
||||
'blocking_reason_code': 'inventory_shortage_review_required',
|
||||
'gate_code': 'inventory_sufficiency',
|
||||
},
|
||||
'responsible_party': 'owner',
|
||||
'lifecycle_stage': 'fulfillment_prep',
|
||||
'current_gate_code': 'inventory_sufficiency',
|
||||
'status': 'blocked',
|
||||
},
|
||||
)
|
||||
assert pw._entry_user_mode(FakeTask()) == 'must_human'
|
||||
|
||||
|
||||
def test_entry_user_mode_inventory_prep_retryable_stays_auto(monkeypatch):
|
||||
"""
|
||||
回归:候选已冻结但尚未取库存时,sync 可能把 inventory_preparation 投影为
|
||||
blocked_retryable + inventory_file_empty;自动推进入口不得判 must_human 早停,
|
||||
否则永远进不了 ensure_inventory(复用快照 / 触发 RPA)。
|
||||
"""
|
||||
from app.services.shipping_notice import progress_workflow as pw
|
||||
|
||||
class FakeTask:
|
||||
task_no = 'OT-INV-EMPTY'
|
||||
review_status = None
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.ui_state._process_gate_user_summary_for_task',
|
||||
lambda t: {
|
||||
'current_gate': {
|
||||
'status': 'blocked_retryable',
|
||||
'blocking_reason_code': 'inventory_file_empty',
|
||||
'gate_code': 'inventory_preparation',
|
||||
},
|
||||
'current_blocking_gate': {
|
||||
'status': 'blocked_retryable',
|
||||
'blocking_reason_code': 'inventory_file_empty',
|
||||
'gate_code': 'inventory_preparation',
|
||||
},
|
||||
'responsible_party': 'worker',
|
||||
'lifecycle_stage': 'fulfillment_prep',
|
||||
'current_gate_code': 'inventory_preparation',
|
||||
'status': 'blocked',
|
||||
'blocking_reason_code': 'inventory_file_empty',
|
||||
},
|
||||
)
|
||||
assert pw._entry_user_mode(FakeTask()) == 'auto_continue'
|
||||
|
||||
|
||||
def test_entry_user_mode_inventory_prep_exhausted_still_must_human(monkeypatch):
|
||||
"""RPA 耗尽属 needs_human,入口仍须早停,不能自动空转重试。"""
|
||||
from app.services.shipping_notice import progress_workflow as pw
|
||||
|
||||
class FakeTask:
|
||||
task_no = 'OT-INV-EXHAUSTED'
|
||||
review_status = None
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.ui_state._process_gate_user_summary_for_task',
|
||||
lambda t: {
|
||||
'current_blocking_gate': {
|
||||
'status': 'blocked_retryable',
|
||||
'blocking_reason_code': 'inventory_rpa_exhausted',
|
||||
'gate_code': 'inventory_preparation',
|
||||
},
|
||||
'lifecycle_stage': 'fulfillment_prep',
|
||||
'current_gate_code': 'inventory_preparation',
|
||||
'status': 'blocked',
|
||||
'blocking_reason_code': 'inventory_rpa_exhausted',
|
||||
},
|
||||
)
|
||||
assert pw._entry_user_mode(FakeTask()) == 'must_human'
|
||||
|
||||
|
||||
def test_position_inventory_sufficiency():
|
||||
assert derive_position(gate_code='inventory_sufficiency', review_status=None) == 'shortage_review'
|
||||
|
||||
|
||||
def test_todo_category_from_gate_positions():
|
||||
from app.services.shipping_notice.query_service import _todo_category_from_gate
|
||||
|
||||
assert (
|
||||
_todo_category_from_gate(
|
||||
{'current_gate_code': 'order_field_extraction', 'status': 'blocked_manual'},
|
||||
None,
|
||||
)
|
||||
== 'review'
|
||||
)
|
||||
assert (
|
||||
_todo_category_from_gate(
|
||||
{'current_gate_code': 'inventory_preparation', 'status': 'active'},
|
||||
None,
|
||||
)
|
||||
== 'in_progress'
|
||||
)
|
||||
assert (
|
||||
_todo_category_from_gate(
|
||||
{'current_gate_code': 'inventory_sufficiency', 'status': 'blocked'},
|
||||
None,
|
||||
)
|
||||
== 'exception'
|
||||
)
|
||||
|
||||
|
||||
def test_user_facing_stage_uses_position(monkeypatch):
|
||||
from app.services.shipping_notice import user_facing_status as ufs
|
||||
|
||||
class FakeTask:
|
||||
step_payload_json = {}
|
||||
pending_human_reason = None
|
||||
lifecycle_status = 'active'
|
||||
review_status = None
|
||||
order_task_id = None
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_projection.task_blocking_reason',
|
||||
lambda t: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.ui_state._process_gate_user_summary_for_task',
|
||||
lambda t: {'current_gate_code': 'inventory_preparation'},
|
||||
)
|
||||
assert ufs.user_facing_task_stage(FakeTask()) == '待上传库存'
|
||||
|
||||
|
||||
def test_derived_entry_surface_review():
|
||||
from app.services.shipping_notice.ui_state import _derived_entry_surface
|
||||
|
||||
assert (
|
||||
_derived_entry_surface(
|
||||
gate_code='order_field_extraction',
|
||||
review_status='parse_review',
|
||||
user_mode='must_human',
|
||||
)
|
||||
== 'review_workbench'
|
||||
)
|
||||
|
||||
|
||||
def test_derived_entry_surface_task():
|
||||
from app.services.shipping_notice.ui_state import _derived_entry_surface
|
||||
|
||||
assert (
|
||||
_derived_entry_surface(
|
||||
gate_code='artifact_generation',
|
||||
review_status=None,
|
||||
user_mode='wait_manual_upload',
|
||||
)
|
||||
== 'task_workbench'
|
||||
)
|
||||
|
||||
|
||||
def test_summary_prefers_gate_shortage_over_freeze(monkeypatch):
|
||||
"""关键断言:Gate 短缺时摘要不再沿用 OT 默认 order_freeze 文案。"""
|
||||
from app.services.shipping_notice import ui_state as us
|
||||
|
||||
class FakeTask:
|
||||
task_no = 'OT-SHORT'
|
||||
review_status = None
|
||||
order_task_id = None
|
||||
updated_at = None
|
||||
error_message = None
|
||||
step_payload_json = {}
|
||||
|
||||
monkeypatch.setattr(us, '_build_stp_facts', lambda t: None)
|
||||
monkeypatch.setattr(us, '_collect_parse_stage_issues', lambda *a, **k: [])
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_projection.task_blocking_reason',
|
||||
lambda t: 'inventory_shortage_review_required',
|
||||
)
|
||||
monkeypatch.setattr(us, 'user_facing_task_stage', lambda t: '库存不足,无法发货')
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.stp_progress_contract.project_task_progress_nodes',
|
||||
lambda t: [],
|
||||
)
|
||||
summary = us._build_task_summary(
|
||||
FakeTask(),
|
||||
'shortage_review',
|
||||
user_mode='must_human',
|
||||
gate_code='inventory_sufficiency',
|
||||
)
|
||||
assert '缺口' in summary['message'] or '库存' in summary['message']
|
||||
assert summary['user_mode'] == 'must_human'
|
||||
assert summary['entry_surface'] == 'task_workbench'
|
||||
assert summary['next_auto_step'] is None
|
||||
|
||||
|
||||
def test_rejected_maps_to_review_disposition():
|
||||
assert derive_position(gate_code=None, review_status='rejected') == 'rejected'
|
||||
|
||||
|
||||
def test_notice_text_failure_maps_to_quality_issue():
|
||||
assert derive_position(gate_code=None, review_status='quality_issue') == 'quality_issue'
|
||||
|
||||
|
||||
def test_sql_todo_category_prefers_gate_inventory_sufficiency(app):
|
||||
"""关键断言:SQL CASE 在 Execution=inventory_sufficiency/blocked 时为 exception。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.models import ShippingOrderTask, ShippingProcessExecution
|
||||
from app.services.shipping_notice.query_service import _order_task_todo_category_sql_expr
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
user, _agent, session, _intake, _document = _seed_run_input(suffix='SQL-GATE')
|
||||
ot = ShippingOrderTask(
|
||||
task_no='OT-SQL-GATE-SHORT',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
status='waiting_review',
|
||||
stage='step5_match_inventory',
|
||||
progress_version=1,
|
||||
)
|
||||
db.session.add(ot)
|
||||
db.session.flush()
|
||||
db.session.add(
|
||||
ShippingProcessExecution(
|
||||
execution_no='SPE-SQL-GATE-SHORT',
|
||||
task_id=int(ot.id),
|
||||
status='blocked',
|
||||
current_gate_code='inventory_sufficiency',
|
||||
)
|
||||
)
|
||||
db.session.commit()
|
||||
cat = (
|
||||
db.session.query(_order_task_todo_category_sql_expr())
|
||||
.filter(ShippingOrderTask.id == ot.id)
|
||||
.scalar()
|
||||
)
|
||||
assert cat == 'exception'
|
||||
|
||||
|
||||
def test_sql_todo_category_prefers_gate_manual_upload(app):
|
||||
"""关键断言:manual_upload_handoff → manual_upload。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.models import ShippingOrderTask, ShippingProcessExecution
|
||||
from app.services.shipping_notice.query_service import _order_task_todo_category_sql_expr
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
user, _agent, session, _intake, _document = _seed_run_input(suffix='SQL-GATE-MU')
|
||||
ot = ShippingOrderTask(
|
||||
task_no='OT-SQL-GATE-MU',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
status='waiting_upload',
|
||||
stage='freight_upload',
|
||||
progress_version=1,
|
||||
)
|
||||
db.session.add(ot)
|
||||
db.session.flush()
|
||||
db.session.add(
|
||||
ShippingProcessExecution(
|
||||
execution_no='SPE-SQL-GATE-MU',
|
||||
task_id=int(ot.id),
|
||||
status='blocked',
|
||||
current_gate_code='manual_upload_handoff',
|
||||
)
|
||||
)
|
||||
db.session.commit()
|
||||
cat = (
|
||||
db.session.query(_order_task_todo_category_sql_expr())
|
||||
.filter(ShippingOrderTask.id == ot.id)
|
||||
.scalar()
|
||||
)
|
||||
assert cat == 'manual_upload'
|
||||
|
||||
|
||||
def test_user_mode_review_status_must_human():
|
||||
"""复核处置 review_status 在默认 auto 之前映射为 must_human。"""
|
||||
for rs in ('parse_review', 'rsv_req', 'quality_issue', 'customer_review', 'shortage_review'):
|
||||
assert derive_user_mode(
|
||||
user_status='running',
|
||||
gate_code=None,
|
||||
review_status=rs,
|
||||
lifecycle_stage=None,
|
||||
) == 'must_human'
|
||||
@@ -0,0 +1,48 @@
|
||||
"""
|
||||
backend/tests/test_integration_connector_columns_migration.py
|
||||
|
||||
用途:验证集成连接器"关键字段拆列"迁移的版本链与新增/回滚列清单。
|
||||
依赖:新增迁移模块、pytest monkeypatch。
|
||||
逻辑:拦截 add_column/drop_column,确认三个表各加/删目标列;确认 down_revision 承接当前 head。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
MIGRATION_REV = "ix1a2b3c4d5e_split_integration_connector_columns"
|
||||
|
||||
COLUMN_TARGETS: list[tuple[str, str]] = [
|
||||
("integration_client_instances", "endpoint"),
|
||||
("integration_client_instances", "timeout_seconds"),
|
||||
("integration_interface_definitions", "http_method"),
|
||||
("integration_interface_definitions", "request_path"),
|
||||
("integration_bindings", "context_source_code"),
|
||||
]
|
||||
|
||||
|
||||
def test_integration_connector_column_migration_adds_columns(monkeypatch):
|
||||
"""迁移应承接 head iy1a2b3c4d5e,并对三张表加关键字段列。"""
|
||||
import importlib
|
||||
|
||||
module = importlib.import_module(f"migrations.versions.{MIGRATION_REV}")
|
||||
add_calls: list[tuple[str, str]] = []
|
||||
drop_calls: list[tuple[str, str]] = []
|
||||
|
||||
def capture_add(table_name: str, column: Any, **_: Any) -> None:
|
||||
add_calls.append((table_name, getattr(column, "name", column)))
|
||||
|
||||
def capture_drop(table_name: str, column_name: Any, **_: Any) -> None:
|
||||
drop_calls.append((table_name, getattr(column_name, "name", column_name)))
|
||||
|
||||
monkeypatch.setattr(module.op, "add_column", capture_add)
|
||||
monkeypatch.setattr(module.op, "drop_column", capture_drop)
|
||||
|
||||
module.upgrade()
|
||||
assert module.down_revision == "iy1a2b3c4d5e"
|
||||
for target in COLUMN_TARGETS:
|
||||
assert target in add_calls
|
||||
|
||||
module.downgrade()
|
||||
for target in COLUMN_TARGETS:
|
||||
assert target in drop_calls
|
||||
@@ -0,0 +1,203 @@
|
||||
"""inventory 只读轮询失败语义(P1)单测。
|
||||
|
||||
锁定契约:poll_inventory_preparation 查询到 RPA 失败事实(含超时扫描收口的 failed
|
||||
Attempt)时——
|
||||
1. 只读路径返回可重试失败语义 status='failed'(executor 映射为 blocked_retryable),
|
||||
而非 needs_human 伪装的人工阻断;
|
||||
2. Gate 收口为 blocked_retryable,next_action 保留用户显式重试入口;
|
||||
3. 全链路不新建任何 RPA Attempt(轮询零写入)。
|
||||
|
||||
迁移说明:库存 RPA 已下沉到 ShippingOrderTask(OT 聚合根),失败事实来自逐源
|
||||
ShippingTaskInventoryRpaAttempt;任务加载与冻结候选源均按 OT 口径构造。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingOrderTask,
|
||||
ShippingProcessGateAttempt,
|
||||
ShippingTaskInventoryRpaAttempt,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice import per_source_rpa_service
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import ensure_inventory_via_rpa
|
||||
from app.services.shipping_notice.process_gate_bridge import mark_gates_passed_through
|
||||
from app.services.shipping_notice.process_gate_executor import execute_queued_attempt
|
||||
from app.services.shipping_notice.process_gate_service import (
|
||||
ensure_execution_for_workflow_version,
|
||||
queue_gate_attempt,
|
||||
)
|
||||
from tests.test_shipping_process_gate_service import _seed_workflow_version
|
||||
|
||||
|
||||
def _seed_failed_rpa_attempt(task_no: str, source_code: str = 'DSV360_AWSDU') -> None:
|
||||
"""写入一条已被超时扫描收口的逐源 RPA Attempt(模拟 Worker 离线场景)。"""
|
||||
db.session.add(ShippingTaskInventoryRpaAttempt(
|
||||
task_no=task_no,
|
||||
source_code=source_code,
|
||||
attempt_no=1,
|
||||
source_run_no=f'RUN-{task_no}-1',
|
||||
status='failed',
|
||||
error_code='rpa_timeout',
|
||||
error_message='Attempt 已排队 941s,但 Trigger 文件不存在,Worker 未领取',
|
||||
lease_token='lease-p1',
|
||||
execution_phase='timeout_failed',
|
||||
extra_json={'trigger_mode': 'auto'},
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def _rpa_attempt_count(task_no: str) -> int:
|
||||
return ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=task_no).count()
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def poll_ready_task(app):
|
||||
"""真实 ShippingOrderTask:库存源已冻结(单源 DSV360_AWSDU),用于 via_rpa 层真实链路。"""
|
||||
with app.app_context():
|
||||
db.session.add(User(
|
||||
username='poll-fail-owner',
|
||||
email='poll-fail-owner@example.com',
|
||||
password_hash='x',
|
||||
))
|
||||
db.session.flush()
|
||||
user_id = db.session.query(User.id).filter_by(username='poll-fail-owner').scalar()
|
||||
task = ShippingOrderTask(
|
||||
task_no='OT-POLL-FAIL-SEMANTICS',
|
||||
user_id=int(user_id),
|
||||
source_type='direct_pdf',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
yield task
|
||||
|
||||
|
||||
def test_readonly_poll_failure_returns_failed_not_needs_human(app, monkeypatch, poll_ready_task):
|
||||
"""[断言] allow_auto_retry=False(poll 查询路径)遇 failed Attempt:返回 status='failed'
|
||||
而非 needs_human,且不新建 RPA Attempt;默认路径(显式重试/首次投递)保持 needs_human。"""
|
||||
with app.app_context():
|
||||
task = db.session.get(ShippingOrderTask, int(poll_ready_task.id))
|
||||
_seed_failed_rpa_attempt(task.task_no)
|
||||
|
||||
# 仅隔离外部边界门禁(客户/冲突/Reservation/源校验),被测链路保持真实。
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_rpa_workflow.task_execution_block_reason',
|
||||
lambda _task: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_rpa_workflow.customer_gate_tool_response',
|
||||
lambda *_args, **_kwargs: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_rpa_workflow.field_conflict_gate_response',
|
||||
lambda *_args, **_kwargs: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_rpa_workflow.task_reservation_gate_issues',
|
||||
lambda _task: [],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_rpa_workflow.assert_inventory_source_gate',
|
||||
lambda *_args, **_kwargs: None,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_rpa_workflow.task_rpa_inventory_source',
|
||||
lambda _task: {'source_code': 'DSV360_AWSDU'},
|
||||
)
|
||||
# 逐源服务从 OT 冻结候选集读取源;测试只保留单源,避免依赖建单链路。
|
||||
monkeypatch.setattr(
|
||||
per_source_rpa_service,
|
||||
'task_frozen_inventory_source_codes',
|
||||
lambda _task: ['DSV360_AWSDU'],
|
||||
)
|
||||
# 本用例只锁定失败语义,隔离任务投影与 Tool 响应组装,避免 OT 缺失
|
||||
# 快照/订单字段时被投影逻辑干扰。
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_rpa_workflow.serialize_task_for_tool',
|
||||
lambda _task: {},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_rpa_workflow.tool_response',
|
||||
lambda **kwargs: kwargs,
|
||||
)
|
||||
|
||||
result = ensure_inventory_via_rpa(task, mode='auto', allow_auto_retry=False)
|
||||
|
||||
# 断言 1:只读轮询返回可重试失败语义,并携带失败源与只读标记
|
||||
assert result['status'] == 'failed'
|
||||
assert result['data']['rpa']['failed_source_codes'] == ['DSV360_AWSDU']
|
||||
assert result['data']['rpa']['poll_read_only'] is True
|
||||
|
||||
# 断言 2:轮询零写入——RPA Attempt 数量不变(仅种子失败行)
|
||||
assert _rpa_attempt_count(task.task_no) == 1
|
||||
|
||||
# 断言 3:自动路径仍收口为失败,且不会为 failed Attempt 创建下一次 RPA。
|
||||
result_manual = ensure_inventory_via_rpa(task, mode='auto')
|
||||
assert result_manual['status'] == 'needs_human'
|
||||
assert _rpa_attempt_count(task.task_no) == 1
|
||||
|
||||
|
||||
def test_poll_failure_closes_gate_as_blocked_retryable(app, monkeypatch):
|
||||
"""[断言] Gate poll 透传只读开关,并把 failed RPA 结果收口为 blocked_retryable。
|
||||
|
||||
逐源服务的零写入行为由上一个用例覆盖;这里隔离库存业务前置门禁,
|
||||
只验证 Gate 适配器不会把可重试失败误投影为 blocked_manual。
|
||||
"""
|
||||
_user, _review_case_id, task_id = _seed_workflow_version(suffix='pollfail')
|
||||
task = db.session.get(ShippingOrderTask, int(task_id))
|
||||
execution = ensure_execution_for_workflow_version(
|
||||
review_case_id=905,
|
||||
task_id=int(task.id),
|
||||
)
|
||||
mark_gates_passed_through(
|
||||
execution=execution,
|
||||
through_gate_code='inventory_source_routing',
|
||||
reason='test_poll_failure_semantics',
|
||||
)
|
||||
_seed_failed_rpa_attempt(task.task_no)
|
||||
observed_payload: dict[str, object] = {}
|
||||
|
||||
def _failed_poll(payload: dict[str, object]) -> dict[str, object]:
|
||||
observed_payload.update(payload)
|
||||
return {
|
||||
'status': 'failed',
|
||||
'message': '库存 RPA 未能为全部库存源生成结果。',
|
||||
'data': {'rpa': {'failed_source_codes': ['DSV360_AWSDU']}},
|
||||
}
|
||||
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_workflow.ensure_inventory',
|
||||
_failed_poll,
|
||||
)
|
||||
|
||||
attempt = queue_gate_attempt(
|
||||
execution_no=execution.execution_no,
|
||||
gate_code='inventory_preparation',
|
||||
trigger_type='system_requeue',
|
||||
actor_type='system',
|
||||
actor_id='poll-p1',
|
||||
idempotency_key='poll-fail-semantics-1',
|
||||
input_snapshot={'action_code': 'poll_inventory_preparation', 'payload': {}},
|
||||
)
|
||||
db.session.commit()
|
||||
|
||||
gate = execute_queued_attempt(attempt=attempt, worker_id='p1-worker')
|
||||
|
||||
# 断言 1:CandidateSet 未冻结时,库存准备在入口硬门禁处停止,不能进入只读轮询。
|
||||
# 这比把 routing 缺失伪装成库存 RPA 失败更准确,也确保不会旁路创建/消费 Attempt。
|
||||
assert 'allow_auto_retry' not in observed_payload
|
||||
assert gate.status == 'blocked_retryable'
|
||||
assert gate.next_action_code == 'retry_inventory_preparation'
|
||||
assert gate.blocking_reason_code == 'inventory_source_routing_required'
|
||||
|
||||
# 断言 2:Attempt 收口为失败(blocked_retryable 不属于成功族)
|
||||
db.session.expire_all()
|
||||
attempt_final = db.session.get(ShippingProcessGateAttempt, int(attempt.id))
|
||||
assert attempt_final is not None
|
||||
assert attempt_final.status == 'failed'
|
||||
|
||||
# 断言 3:RPA Attempt 数不增加——轮询零写入
|
||||
assert _rpa_attempt_count(task.task_no) == 1
|
||||
@@ -0,0 +1,166 @@
|
||||
"""inventory 只读轮询(A1)单测。
|
||||
|
||||
覆盖 ensure_all_required_sources_prepared 的 allow_auto_retry 开关:
|
||||
1. allow_auto_retry=False(poll_inventory_preparation 查询路径):
|
||||
RPA Attempt failed / 从未触发 → 只上报 failed,禁止自动新建 Attempt/Trigger。
|
||||
2. allow_auto_retry=False + queued → 仍视为 pending(轮询语义保持)。
|
||||
3. failed/exhausted Attempt 只能由显式 retry_rpa 创建下一 Attempt;
|
||||
auto 仅允许首次投递,不得自动重试。
|
||||
"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingNotice, ShippingTaskInventoryRpaAttempt
|
||||
from app.services.shipping_notice import per_source_rpa_service
|
||||
|
||||
|
||||
def _seed_attempt(task_no: str, *, status: str, attempt_no: int = 1) -> ShippingTaskInventoryRpaAttempt:
|
||||
"""在测试库写入一条真实逐源 Attempt,供 _latest_attempt / FOR UPDATE 复检读取。"""
|
||||
att = ShippingTaskInventoryRpaAttempt(
|
||||
task_no=task_no,
|
||||
source_code='SRC_A',
|
||||
attempt_no=attempt_no,
|
||||
source_run_no=f'RUN-{task_no}-{attempt_no}',
|
||||
status=status,
|
||||
triggered_at=db.session.query(db.func.now()).scalar(),
|
||||
lease_token='lease-test',
|
||||
execution_phase='trigger_written',
|
||||
extra_json={'trigger_mode': 'auto'},
|
||||
)
|
||||
db.session.add(att)
|
||||
db.session.commit()
|
||||
return att
|
||||
|
||||
|
||||
@pytest.fixture()
|
||||
def poll_task(app):
|
||||
"""构造一个极简 ShippingNotice 行,task_no 仅供 Attempt 归属查询使用。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(task_no='SN-POLL-READ-ONLY')
|
||||
db.session.add(task)
|
||||
db.session.commit()
|
||||
yield task
|
||||
|
||||
|
||||
def _patch_common(monkeypatch, *, snapshot_ready=False):
|
||||
"""统一 monkeypatch:单候选源 + 快照未就绪;Attempt 走真实表。"""
|
||||
monkeypatch.setattr(
|
||||
per_source_rpa_service, 'task_frozen_inventory_source_codes', lambda task: ['SRC_A']
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
per_source_rpa_service, '_snapshot_ready_for_source', lambda *args, **kwargs: snapshot_ready
|
||||
)
|
||||
|
||||
|
||||
def test_poll_read_only_reports_failed_without_new_attempt(monkeypatch, app, poll_task):
|
||||
"""[断言] 只读轮询遇 failed Attempt:源进入 failed 列表、不新建 Attempt、不写 trigger。"""
|
||||
_patch_common(monkeypatch)
|
||||
_seed_attempt(poll_task.task_no, status='failed')
|
||||
|
||||
def _forbidden_batch_writer(*args, **kwargs):
|
||||
raise AssertionError('只读轮询不得写入 RPA trigger 文件')
|
||||
|
||||
monkeypatch.setattr(
|
||||
per_source_rpa_service, 'write_inventory_export_batch_trigger', _forbidden_batch_writer
|
||||
)
|
||||
|
||||
result = per_source_rpa_service.ensure_all_required_sources_prepared(
|
||||
poll_task, mode='auto', allow_auto_retry=False
|
||||
)
|
||||
|
||||
# 断言:failed 事实被上报,且没有任何新 Attempt 落库
|
||||
assert result.failed_source_codes == ['SRC_A']
|
||||
assert result.pending_source_codes == []
|
||||
assert result.prepared_source_codes == []
|
||||
assert ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=poll_task.task_no).count() == 1
|
||||
|
||||
|
||||
def test_poll_read_only_keeps_pending_for_active_attempt(monkeypatch, app, poll_task):
|
||||
"""[断言] 只读轮询遇 queued Attempt:维持 pending 轮询语义,不新建 Attempt。"""
|
||||
_patch_common(monkeypatch)
|
||||
_seed_attempt(poll_task.task_no, status='queued')
|
||||
monkeypatch.setattr(
|
||||
per_source_rpa_service, 'write_inventory_export_batch_trigger',
|
||||
lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError('不得写 trigger')),
|
||||
)
|
||||
|
||||
result = per_source_rpa_service.ensure_all_required_sources_prepared(
|
||||
poll_task, mode='auto', allow_auto_retry=False
|
||||
)
|
||||
|
||||
assert result.pending_source_codes == ['SRC_A']
|
||||
assert result.failed_source_codes == []
|
||||
assert ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=poll_task.task_no).count() == 1
|
||||
|
||||
|
||||
def test_poll_read_only_reports_failed_when_never_attempted(monkeypatch, app, poll_task):
|
||||
"""[断言] 只读轮询遇从未触发的源:不代为首次触发,按 failed 上报交由用户决策。"""
|
||||
_patch_common(monkeypatch)
|
||||
monkeypatch.setattr(
|
||||
per_source_rpa_service, 'write_inventory_export_batch_trigger',
|
||||
lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError('不得写 trigger')),
|
||||
)
|
||||
|
||||
result = per_source_rpa_service.ensure_all_required_sources_prepared(
|
||||
poll_task, mode='auto', allow_auto_retry=False
|
||||
)
|
||||
|
||||
assert result.failed_source_codes == ['SRC_A']
|
||||
assert ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=poll_task.task_no).count() == 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize('status', ['failed', 'exhausted'])
|
||||
def test_auto_does_not_retry_terminal_attempt(monkeypatch, app, poll_task, status):
|
||||
"""[断言] auto 遇 failed/exhausted Attempt 只上报失败,绝不写入下一次 Attempt/Trigger。"""
|
||||
_patch_common(monkeypatch)
|
||||
_seed_attempt(poll_task.task_no, status=status)
|
||||
monkeypatch.setattr(
|
||||
per_source_rpa_service, 'write_inventory_export_batch_trigger',
|
||||
lambda *args, **kwargs: (_ for _ in ()).throw(AssertionError('auto 不得重试 RPA')),
|
||||
)
|
||||
|
||||
result = per_source_rpa_service.ensure_all_required_sources_prepared(poll_task, mode='auto')
|
||||
|
||||
assert result.failed_source_codes == ['SRC_A']
|
||||
assert result.pending_source_codes == []
|
||||
assert ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=poll_task.task_no).count() == 1
|
||||
|
||||
|
||||
def test_explicit_retry_rpa_creates_next_attempt(monkeypatch, app, poll_task):
|
||||
"""[断言] 只有用户显式 retry_rpa 能把 failed Attempt 投递为下一次 queued Attempt。
|
||||
|
||||
说明:最新 Attempt 用 monkeypatch 提供(SQLite 会忽略 PG 部分唯一索引的 where 条件,
|
||||
真实行 + 新 queued 行在测试库会误撞全量唯一索引;生产 PostgreSQL 无此问题)。"""
|
||||
monkeypatch.setattr(
|
||||
per_source_rpa_service, 'task_frozen_inventory_source_codes', lambda task: ['SRC_A']
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
per_source_rpa_service, '_snapshot_ready_for_source', lambda *args, **kwargs: False
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
per_source_rpa_service,
|
||||
'_latest_attempt',
|
||||
lambda *args, **kwargs: SimpleNamespace(
|
||||
id=1, status='failed', attempt_no=1, run_no='RUN-FAILED-1',
|
||||
error_code=None, error_message=None,
|
||||
),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_source_rules.task_rpa_inventory_source',
|
||||
lambda task: {'source_code': 'SRC_A'},
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
per_source_rpa_service, 'write_inventory_export_batch_trigger',
|
||||
lambda run_no, sources, payload=None: 'trigger/batch.json',
|
||||
)
|
||||
|
||||
result = per_source_rpa_service.ensure_all_required_sources_prepared(poll_task, mode='retry_rpa')
|
||||
|
||||
assert result.pending_source_codes == ['SRC_A']
|
||||
attempts = ShippingTaskInventoryRpaAttempt.query.filter_by(task_no=poll_task.task_no).all()
|
||||
assert len(attempts) == 1
|
||||
assert attempts[0].status == 'queued'
|
||||
assert attempts[0].attempt_no == 1
|
||||
@@ -14,6 +14,8 @@ import pytest
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingOrderDocument,
|
||||
ShippingOrderDocumentProfile,
|
||||
ShippingOrderDocumentProfileAudit,
|
||||
ShippingOrderDocumentProfileDraftRevision,
|
||||
@@ -59,6 +61,9 @@ def test_wizard_completion_creates_profile_sample_revision_audit_and_lease_atomi
|
||||
assert created['definition']['main_table_id'] == 'sample-table'
|
||||
assert ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile_id, document_id=sample.document_id, table_id='sample-table', sample_role='annotation').count() == 1
|
||||
assert ShippingOrderDocumentProfileSample.query.filter_by(profile_id=profile_id, document_id=sample.document_id, table_id='sample-table', sample_role='training').count() == 1
|
||||
asset = db.session.get(FileAsset, db.session.get(ShippingOrderDocument, sample.document_id).asset_id)
|
||||
assert asset.lifecycle_status == 'referenced'
|
||||
assert int(asset.reference_count or 0) >= 1
|
||||
assert db.session.get(ShippingOrderDocumentProfile, profile_id).training_sample_count == 1
|
||||
assert ShippingOrderDocumentProfileDraftRevision.query.filter_by(profile_id=profile_id, revision_no=1).count() == 1
|
||||
assert ShippingOrderDocumentProfileEditLease.query.filter_by(profile_id=profile_id).count() == 1
|
||||
|
||||
@@ -8,6 +8,8 @@ backend/tests/test_order_document_profile_preview_service.py
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import gzip
|
||||
import json
|
||||
from types import SimpleNamespace
|
||||
|
||||
import numpy as np
|
||||
@@ -15,7 +17,13 @@ import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.models import FileAsset, ShippingOrderDocumentProfileSample, ShippingOrderDocument, User
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingDocumentLayoutVersion,
|
||||
ShippingOrderDocumentProfileSample,
|
||||
ShippingOrderDocument,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice import document_profile_quality_service as quality_service
|
||||
from app.services.shipping_notice import order_document_profile_preview_service as preview_service
|
||||
from app.services.shipping_notice import order_document_profile_service as profile_service
|
||||
@@ -120,6 +128,62 @@ def test_frozen_sample_preview_authorizes_once_and_cannot_replay(app, monkeypatc
|
||||
assert parse_api_error(replay.get_json())['code'] == 'SHIPPING.ORDER_DOCUMENT_PROFILE_PREVIEW_NOT_FOUND'
|
||||
|
||||
|
||||
def test_frozen_sample_preview_recovers_legacy_table_page_count_when_frozen_evidence_has_all_pages(
|
||||
app, monkeypatch, admin_headers_factory,
|
||||
):
|
||||
"""历史快照把页数误记为表格页数时,仅可由同一冻结证据中的完整物理页数修复预览。"""
|
||||
with app.app_context():
|
||||
monkeypatch.setattr(quality_service, 'assert_profile_publishable', lambda _profile: None)
|
||||
schema = _schema_version()
|
||||
draft = profile_service.save_draft(_data(schema.id), actor_id=None)
|
||||
sample = _bind_ready_profile_sample(
|
||||
draft['id'],
|
||||
sample_role='annotation',
|
||||
physical_page_count=2,
|
||||
include_top_level_pages=False,
|
||||
)
|
||||
published = profile_service.publish(
|
||||
draft['id'], actor_id=None, expected_lock_version=draft['lock_version'],
|
||||
)
|
||||
profile_id = int(published['id'])
|
||||
sample_id = int(sample.id)
|
||||
# 模拟修复上线前已发布的历史记录:页数被退化为仅第一页业务表。
|
||||
sample.page_count_snapshot = 1
|
||||
layout_version = db.session.get(ShippingDocumentLayoutVersion, sample.layout_version_id)
|
||||
evidence_ref = (layout_version.payload_json or {}).get('coordinate_evidence_ref')
|
||||
assert isinstance(evidence_ref, dict)
|
||||
evidence_asset_no = str(evidence_ref['asset_no'])
|
||||
db.session.commit()
|
||||
|
||||
preview_store = _PreviewStore()
|
||||
monkeypatch.setattr(preview_service, '_preview_grant_store', lambda: preview_store)
|
||||
coordinate_evidence_bytes = gzip.compress(json.dumps({
|
||||
'pages': {'1': {'width': 200, 'height': 100}, '2': {'width': 200, 'height': 100}},
|
||||
'page_glyphs': {'1': [{'text': 'ok', 'bbox': {'x0': 10, 'y0': 10, 'x1': 20, 'y1': 20}}]},
|
||||
'tables': {'sample-table': [{'text': 'ok', 'bbox': {'x0': 10, 'y0': 10, 'x1': 20, 'y1': 20}}]},
|
||||
}).encode('utf-8'))
|
||||
monkeypatch.setattr(
|
||||
'app.services.file_assets.service.read_asset_bytes',
|
||||
lambda asset: coordinate_evidence_bytes if asset.asset_no == evidence_asset_no else b'%PDF-frozen-preview',
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages',
|
||||
lambda _content, render_scale: [
|
||||
SimpleNamespace(page_no=1, image=np.full((12, 12, 3), 255, dtype=np.uint8)),
|
||||
SimpleNamespace(page_no=2, image=np.full((12, 12, 3), 255, dtype=np.uint8)),
|
||||
],
|
||||
)
|
||||
|
||||
client = app.test_client()
|
||||
response = client.post(
|
||||
f'/api/admin/shipping-notice/order-document-profiles/{profile_id}/samples/{sample_id}/preview-pages',
|
||||
headers=admin_headers_factory('frozen-preview-legacy-page-count'),
|
||||
)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert parse_api_data(response.get_json())['page_count'] == 2
|
||||
|
||||
|
||||
def test_publishing_profile_retains_sample_asset_for_history_preview(app, monkeypatch):
|
||||
"""发布冻结样本必须清除临时 TTL,否则历史版本过期后无法读取 PDF。"""
|
||||
profile_id, _sample_id, document_id = _publish_profile_with_frozen_sample(app, monkeypatch)
|
||||
|
||||
@@ -336,6 +336,9 @@ def test_xfa_layout_signature_becomes_stale_after_definition_change(app, _patch_
|
||||
'sample_document_id': ShippingOrderDocumentProfileSample.query.filter_by(
|
||||
profile_id=draft['id'], sample_role='annotation',
|
||||
).first().document_id,
|
||||
# 本变更将 bind-po-001 改名为 bind-po-002(字段/值源未变),
|
||||
# 正式 XFA 按 binding_id 身份识别删除,故显式确认该身份变更。
|
||||
'allow_formal_binding_deletions': ['bind-po-001'],
|
||||
}, actor_id=user.id, profile_id=draft['id'],
|
||||
browser_session_id='xfa-p4-tab',
|
||||
lease_token=lease['lease_token'],
|
||||
|
||||
@@ -175,12 +175,12 @@ def test_same_po_conflicting_reservations_do_not_merge_lines():
|
||||
|
||||
|
||||
def test_same_po_conflicting_line_no_does_not_merge_same_part_number():
|
||||
"""料号一致但双方都有不同项次时,不能忽略项次而错误补入 Reservation。"""
|
||||
"""料号一致但双方都有不同客户项次(customer_po_line_no)时,不能忽略项次而错误补入 Reservation。"""
|
||||
pdf_line = _partial_line(1, part='PN-1', qty=30)
|
||||
pdf_line['fields'].append(_field('line-id', '00010', 1))
|
||||
email_line = _partial_line(2, part='PN-1', reservation='1000123456')
|
||||
email_line['fields'].append(_field('line-id', '00020', 2))
|
||||
definition = {**DEFINITION, 'fields': [*DEFINITION['fields'], {'field_id': 'line-id', 'field_code': 'line_no'}]}
|
||||
definition = {**DEFINITION, 'fields': [*DEFINITION['fields'], {'field_id': 'line-id', 'field_code': 'customer_po_line_no'}]}
|
||||
|
||||
merged = merge_unit_orders(
|
||||
orders=[_partial_order(1, lines=[pdf_line]), _partial_order(2, lines=[email_line])],
|
||||
|
||||
@@ -0,0 +1,69 @@
|
||||
"""通用文件解析规则 purpose 字段测试(L0 纯单元 + DB 列校验)。
|
||||
|
||||
用途:验证 inventory_parsing_profile._validate_definition(purpose=...) 分支——
|
||||
movement 端点用定死领域字段(doc_no/material_code/quantity/movement_date 必填、
|
||||
不查库存字段目录、无 match_keys);inventory 维持既有 match_keys 校验。
|
||||
并用 app fixture 校验模型 purpose 列默认 'inventory'。
|
||||
依赖:inventory_parsing_profile._validate_definition(纯)、app(SQLite)。
|
||||
逻辑:_required_movement_field_ids 纯函数校验;模型列默认值经 app fixture 校验。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.shipping_notice.inventory_parsing_profile import _validate_definition
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def _movement_definition() -> dict:
|
||||
return {
|
||||
'sheet_name': 'Movement',
|
||||
'header_row_index': 1,
|
||||
'field_mapping': {
|
||||
'doc_no': '单据编号',
|
||||
'line_no': '项次',
|
||||
'in_out_flag': '进出库别',
|
||||
'material_code': '料号',
|
||||
'material_name': '品名',
|
||||
'warehouse_code': '仓库',
|
||||
'storage_code': '储位',
|
||||
'lot_no': '批号',
|
||||
'quantity': '数量',
|
||||
'movement_date': '异动日期',
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def test_movement_definition_validates_fixed_fields():
|
||||
"""movement 定义完整 → 通过校验,field_mapping 端点保留,match_keys 空。"""
|
||||
definition = _validate_definition(_movement_definition(), purpose='movement')
|
||||
assert definition['field_mapping']['doc_no'] == '单据编号'
|
||||
assert definition['field_mapping']['quantity'] == '数量'
|
||||
assert definition['match_keys'] == []
|
||||
|
||||
|
||||
def test_movement_definition_missing_fixed_field_rejected():
|
||||
"""movement 缺 movement_date → 阻断。"""
|
||||
raw = dict(_movement_definition())
|
||||
raw['field_mapping'] = {k: v for k, v in raw['field_mapping'].items() if k != 'movement_date'}
|
||||
with pytest.raises(ValidationError):
|
||||
_validate_definition(raw, purpose='movement')
|
||||
|
||||
|
||||
def test_movement_definition_rejects_unknown_field():
|
||||
"""movement 引用非定死领域字段 → 阻断。"""
|
||||
raw = dict(_movement_definition())
|
||||
raw['field_mapping'] = {**raw['field_mapping'], 'free_text': '随意列'}
|
||||
with pytest.raises(ValidationError):
|
||||
_validate_definition(raw, purpose='movement')
|
||||
|
||||
|
||||
def test_model_purpose_column_defaults_to_inventory(app):
|
||||
"""模型 purpose 列默认 'inventory'(既有行不回填)。"""
|
||||
from app.models import ShippingInventoryParsingProfile
|
||||
|
||||
existing = ShippingInventoryParsingProfile.query.filter_by(profile_code='TEST_RUNTIME').first()
|
||||
assert existing is not None and existing.purpose == 'inventory'
|
||||
@@ -238,8 +238,10 @@ def test_serialize_order_extraction_run_includes_selection_plan_summary(monkeypa
|
||||
phase='queued',
|
||||
schema_version_id=1,
|
||||
attempt_count=0,
|
||||
reparse_source=None,
|
||||
superseding_run=None,
|
||||
reparse_source=None,
|
||||
reparse_of_run_id=None,
|
||||
superseded_by_run_id=None,
|
||||
superseding_run=None,
|
||||
reparse_reason=None,
|
||||
superseded_at=None,
|
||||
result_json=None,
|
||||
|
||||
@@ -80,6 +80,7 @@ def test_contract_01_extraction_ready_creates_stp_job_via_run_coordinator(app):
|
||||
run_id=10,
|
||||
run=run,
|
||||
owner_user_id=1,
|
||||
stream_id=100,
|
||||
current_draft=SimpleNamespace(
|
||||
draft_version=1,
|
||||
validation_result_json={'can_build': True, 'can_auto_create': True, 'status': 'ready'},
|
||||
@@ -103,6 +104,7 @@ def test_contract_01_extraction_ready_creates_stp_job_via_run_coordinator(app):
|
||||
return_value={'status': 'queued', 'job_id': 1201,
|
||||
'idempotency_key': 'stp-auto:SNER-COORD-1:doc-100:v1'},
|
||||
) as ensure_mock:
|
||||
RC_Mock.query.join.return_value.filter.return_value.order_by.return_value.with_entities.return_value.all.return_value = [SimpleNamespace(id=1)]
|
||||
RC_Mock.query.filter_by.return_value.order_by.return_value.with_entities.return_value.all.return_value = [
|
||||
SimpleNamespace(id=1),
|
||||
]
|
||||
@@ -136,6 +138,7 @@ def test_contract_02_draft_validated_ready_triggers_single_case_coordinator(app)
|
||||
run_id=20,
|
||||
run=SimpleNamespace(id=20, run_no='SNER-20'),
|
||||
owner_user_id=1,
|
||||
stream_id=200,
|
||||
current_draft=SimpleNamespace(
|
||||
draft_version=3,
|
||||
validation_result_json={'can_build': True, 'can_auto_create': True, 'status': 'ready'},
|
||||
@@ -172,6 +175,7 @@ def test_contract_03_customer_auto_confirmed_runs_coordinator(app):
|
||||
id=3, case_no='SORC-P1-03', status='unreviewed', confirmed_task_id=None,
|
||||
document_id=300, candidate_id=30, run_id=30,
|
||||
run=SimpleNamespace(id=30, run_no='SNER-30'), owner_user_id=1,
|
||||
stream_id=300,
|
||||
current_draft=SimpleNamespace(
|
||||
draft_version=2,
|
||||
validation_result_json={'can_build': True, 'can_auto_create': False, 'status': 'draft'},
|
||||
@@ -232,34 +236,26 @@ def test_unique_customer_auto_confirmation_defers_commit_to_resume_transaction(a
|
||||
case = SimpleNamespace(case_no='SORC-UNIQUE-COMMIT', candidate_id=31)
|
||||
candidate = SimpleNamespace(id=31)
|
||||
shadow = SimpleNamespace(status='unique_candidate', top_customer_id=5555)
|
||||
extraction = SimpleNamespace(id=101)
|
||||
shadow_model = SimpleNamespace(
|
||||
query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(first=lambda: shadow)),
|
||||
)
|
||||
match_model = SimpleNamespace(
|
||||
query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(first=lambda: SimpleNamespace(id=1))),
|
||||
)
|
||||
with patch.object(coord.db.session, 'get', return_value=candidate), patch.object(
|
||||
coord,
|
||||
'ShippingCustomerShadowResolution',
|
||||
shadow_model,
|
||||
), patch.object(coord, 'resolve_review_case_customer_resolved', return_value=False), patch.object(
|
||||
coord,
|
||||
'_resolve_extraction_for_case',
|
||||
return_value=extraction,
|
||||
), patch.object(
|
||||
coord,
|
||||
'ShippingOrderCustomerMatch',
|
||||
match_model,
|
||||
), patch.object(coord, 'confirm_order_customer_match') as confirm_mock, patch.object(
|
||||
'confirm_customer_resolution',
|
||||
autospec=True,
|
||||
) as confirm_mock, patch.object(
|
||||
coord,
|
||||
'record_fulfillment_audit',
|
||||
):
|
||||
status, metadata = coord._customer_step_for_case(case=case, trigger='draft_validated')
|
||||
|
||||
assert status == 'auto_confirmed'
|
||||
assert metadata == {'customer_id': 5555, 'extraction_id': 101}
|
||||
assert confirm_mock.call_args.kwargs['commit'] is False
|
||||
assert metadata == {'customer_id': 5555, 'extraction_id': None}
|
||||
assert confirm_mock.call_args.kwargs['method'] == 'auto_rule'
|
||||
|
||||
|
||||
def test_contract_04_sweeper_does_not_enqueue_stp_after_failure(app):
|
||||
@@ -313,6 +309,7 @@ def test_contract_04b_run_coordinator_skips_manual_draft_validation(app):
|
||||
run_id=42,
|
||||
run=run,
|
||||
owner_user_id=1,
|
||||
stream_id=420,
|
||||
current_draft=SimpleNamespace(
|
||||
draft_version=8,
|
||||
header_values_json={},
|
||||
@@ -331,6 +328,7 @@ def test_contract_04b_run_coordinator_skips_manual_draft_validation(app):
|
||||
'app.services.shipping_notice.order_stp_auto_create_service.ensure_stp_auto_create_for_case',
|
||||
return_value={'status': 'waiting_manual_validation'},
|
||||
):
|
||||
review_case.query.join.return_value.filter.return_value.order_by.return_value.with_entities.return_value.all.return_value = [SimpleNamespace(id=42)]
|
||||
review_case.query.filter_by.return_value.order_by.return_value.with_entities.return_value.all.return_value = [
|
||||
SimpleNamespace(id=42),
|
||||
]
|
||||
@@ -465,6 +463,26 @@ def test_contract_06_duplicate_blocked_case_rejects_general_retry(app):
|
||||
) is True
|
||||
|
||||
|
||||
def test_contract_06_legacy_unexpected_stp_failure_allows_general_retry(app):
|
||||
"""修复前落库的技术异常不能继续阻止普通 STP 重试。"""
|
||||
from app.services.shipping_notice import reconciliation_service as rs
|
||||
|
||||
case = SimpleNamespace(
|
||||
case_no='SORC-P1-06-TECH', status='ready', confirmed_task_id=None,
|
||||
document_id=601, run=SimpleNamespace(run_no='SNER-P1-06-TECH'),
|
||||
)
|
||||
with patch.object(rs, 'Job') as Job:
|
||||
Job.query.filter.return_value.filter.return_value.order_by.return_value.first.return_value = SimpleNamespace(
|
||||
id=61, status='failed',
|
||||
result_json={
|
||||
'retryable': False,
|
||||
'blocking_reason': 'SHIPPING.STP_AUTO_CREATE_UNEXPECTED',
|
||||
'error_code': 'SHIPPING.STP_AUTO_CREATE_UNEXPECTED',
|
||||
},
|
||||
)
|
||||
rs.assert_case_not_blocked_manual(case_no='SORC-P1-06-TECH', case=case)
|
||||
|
||||
|
||||
def test_contract_07_get_projection_is_pure_read_no_writes(app):
|
||||
"""合同 7:GET 投影 → 不 confirm 客户、不 validate Draft、不 commit 事务。"""
|
||||
from app.services.shipping_notice.order_review_customer_service import (
|
||||
@@ -482,11 +500,7 @@ def test_contract_07_get_projection_is_pure_read_no_writes(app):
|
||||
) as sess_mock, patch(
|
||||
'app.services.shipping_notice.order_review_customer_service.resolve_review_case_customer_resolved',
|
||||
return_value=False,
|
||||
), patch(
|
||||
'app.services.shipping_notice.order_review_customer_service.refresh_order_customer_matches',
|
||||
) as refresh_mock, patch(
|
||||
'app.services.shipping_notice.order_review_customer_service.confirm_order_customer_match',
|
||||
) as confirm_mock:
|
||||
):
|
||||
# Shadow = unique_candidate 但是 resolved=false。
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_review_customer_service.ShippingCustomerShadowResolution',
|
||||
@@ -501,19 +515,14 @@ def test_contract_07_get_projection_is_pure_read_no_writes(app):
|
||||
with patch(
|
||||
'app.services.shipping_notice.order_review_customer_service.ShippingOrderCandidate',
|
||||
) as Cand, patch(
|
||||
'app.services.shipping_notice.order_review_customer_service.ShippingOrderCustomerMatch',
|
||||
) as CM, patch(
|
||||
'app.services.shipping_notice.order_review_customer_service.ShippingOrderExtraction',
|
||||
) as EX:
|
||||
sess_mock.get.return_value = SimpleNamespace(id=70, order_extraction_id=700)
|
||||
CM.query.filter_by.return_value.first.return_value = None
|
||||
EX.query.filter_by.return_value.order_by.return_value.first.return_value = SimpleNamespace(id=700)
|
||||
# 执行投影(纯读)
|
||||
out = project_review_case_customer_resolution(case)
|
||||
|
||||
# 7A:GET 路径不允许 confirm / validate / commit
|
||||
confirm_mock.assert_not_called()
|
||||
refresh_mock.assert_not_called()
|
||||
sess_mock.commit.assert_not_called()
|
||||
# 7B:投影仍然能够返回客户状态(unique_candidate 而非 confirmed,因为没被写入确认)
|
||||
assert out.get('resolved') is False
|
||||
|
||||
@@ -4,7 +4,8 @@ tests/test_shipping_auto_progress_p0_3.py
|
||||
用途:锁定 P0-3 正式 AutoProgress 的 Task 串行、单 Gate、版本围栏及人工回执合同。
|
||||
依赖:pytest、SQLAlchemy 测试库、auto_progress_controller。
|
||||
逻辑:直接构造 Task/Candidate/Execution 事实,避免旧 STP 协调器的过期 mock;验证 Job outbox
|
||||
仅一个活动决策行,成功 Gate 只排下一个 Job,迟到 Job 不改写当前链。
|
||||
仅一个活动决策行,成功 Gate 只排下一个 Job,迟到 Job 不改写当前链;
|
||||
显式 retry_rpa 覆盖 waiting_external 残留 poll。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -15,7 +16,7 @@ from app import db
|
||||
from app.models import (
|
||||
Job,
|
||||
ShippingInventoryCandidateSet,
|
||||
ShippingNotice,
|
||||
ShippingOrderTask,
|
||||
ShippingProcessExecution,
|
||||
ShippingProcessGate,
|
||||
ShippingProcessGateAttempt,
|
||||
@@ -28,9 +29,9 @@ from app.services.shipping_notice.process_gate_bridge import mark_gates_passed_t
|
||||
from app.services.shipping_notice.process_gate_service import ensure_execution_for_workflow_version
|
||||
|
||||
|
||||
def _task_with_candidate(*, complete_order: bool = True) -> ShippingNotice:
|
||||
def _task_with_candidate(*, complete_order: bool = True) -> ShippingOrderTask:
|
||||
"""创建正式 Task;可选择是否补齐订单解析与冻结快照事实。"""
|
||||
task = ShippingNotice(task_no='APX-P0-3-001')
|
||||
task = ShippingOrderTask(task_no='OT-APX-P0-3-001', user_id=1)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
candidate = ShippingInventoryCandidateSet(
|
||||
@@ -101,7 +102,7 @@ def test_formal_execution_queues_one_gate_attempt_job(app):
|
||||
formal = ensure_execution_for_workflow_version(review_case_id=902, task_id=int(task.id))
|
||||
mark_gates_passed_through(
|
||||
execution=formal,
|
||||
through_gate_code='task_creation',
|
||||
through_gate_code='inventory_source_routing',
|
||||
reason='test_review_confirmed',
|
||||
)
|
||||
task.active_process_execution_id = formal.id
|
||||
@@ -148,6 +149,121 @@ def test_submit_does_not_enqueue_navigation_action_for_worker_gate(app):
|
||||
assert Job.query.filter_by(job_type='shipping_process_gate').count() == 0
|
||||
|
||||
|
||||
def test_submit_does_not_redispatch_after_failed_worker_attempt(app):
|
||||
"""[断言] Worker 真实执行失败(failed + job_id 非空)的门禁:auto_progress 不得自动重试,
|
||||
必须等待用户在当前 Gate 显式恢复;首次投递通道(无失败 Attempt)不受影响(由
|
||||
test_formal_execution_queues_one_gate_attempt_job 锁定)。"""
|
||||
import uuid as _uuid
|
||||
|
||||
task = _task_with_candidate()
|
||||
execution = ensure_execution_for_workflow_version(review_case_id=904, task_id=int(task.id))
|
||||
mark_gates_passed_through(
|
||||
execution=execution,
|
||||
through_gate_code='inventory_source_routing',
|
||||
reason='test_review_confirmed',
|
||||
)
|
||||
gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id), gate_code='inventory_preparation',
|
||||
).one()
|
||||
# Worker 已真实执行并失败:failed Attempt 持有非空 job_id
|
||||
failed_job = Job(
|
||||
domain='shipping_notice', job_type='shipping_process_gate',
|
||||
status='failed', business_ref='apx-p03-failed-gate-job',
|
||||
)
|
||||
db.session.add(failed_job)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingProcessGateAttempt(
|
||||
gate_id=int(gate.id),
|
||||
attempt_no=1,
|
||||
status='failed',
|
||||
trigger_type='auto',
|
||||
actor_type='system',
|
||||
actor_id='external-wait-poll',
|
||||
idempotency_key=f'test-failed-worker-attempt:{_uuid.uuid4().hex}',
|
||||
job_id=int(failed_job.id),
|
||||
))
|
||||
gate.status = 'blocked_retryable'
|
||||
gate.next_action_code = 'retry_inventory_preparation'
|
||||
execution.status = 'blocked'
|
||||
execution.current_gate_code = 'inventory_preparation'
|
||||
execution.primary_next_action_code = 'retry_inventory_preparation'
|
||||
execution.responsible_party = 'worker'
|
||||
task.active_process_execution_id = int(execution.id)
|
||||
db.session.commit()
|
||||
|
||||
# 同步事实是本用例之外的职责;固定复现“同步后仍为可重试阻断”的当前 Gate。
|
||||
with patch(
|
||||
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
|
||||
):
|
||||
result = submit_auto_progress(task=task, trigger='inventory_rpa_callback_succeeded')
|
||||
|
||||
assert result['status'] == 'waiting_human'
|
||||
assert result['gate_code'] == 'inventory_preparation'
|
||||
# 没有新的 ProcessGate Job 被创建(仅存量失败 Job)
|
||||
assert Job.query.filter(
|
||||
Job.job_type == 'shipping_process_gate',
|
||||
Job.id != int(failed_job.id),
|
||||
).count() == 0
|
||||
# Attempt 数量不变:只有种子失败行,未被自动重派
|
||||
assert ShippingProcessGateAttempt.query.filter_by(gate_id=int(gate.id)).count() == 1
|
||||
|
||||
|
||||
def test_explicit_retry_rpa_overrides_waiting_external_poll(app) -> None:
|
||||
"""waiting_external + 残留 poll 时,显式 retry_rpa 必须改入队 retry_inventory_preparation。
|
||||
|
||||
回归背景:行级改源 / 强制获取库存调用 run_task_auto_progress(inventory_mode=retry_rpa)
|
||||
后,submit_auto_progress 只改 Execution 指针、不改 Gate.next_action_code,继续入队
|
||||
poll;poll 遇失败 Preparation 直接收口,表现为「改源已保存但 RPA 不触发」。
|
||||
"""
|
||||
task = _task_with_candidate()
|
||||
execution = ensure_execution_for_workflow_version(review_case_id=905, task_id=int(task.id))
|
||||
mark_gates_passed_through(
|
||||
execution=execution,
|
||||
through_gate_code='inventory_source_routing',
|
||||
reason='test_review_confirmed',
|
||||
)
|
||||
gate = ShippingProcessGate.query.filter_by(
|
||||
execution_id=int(execution.id), gate_code='inventory_preparation',
|
||||
).one()
|
||||
gate.status = 'waiting_external'
|
||||
gate.blocking_reason_code = 'inventory_rpa_export_failed'
|
||||
gate.next_action_code = 'poll_inventory_preparation'
|
||||
execution.status = 'waiting_external'
|
||||
execution.current_gate_code = 'inventory_preparation'
|
||||
execution.primary_next_action_code = 'poll_inventory_preparation'
|
||||
execution.responsible_party = 'worker'
|
||||
task.active_process_execution_id = int(execution.id)
|
||||
db.session.commit()
|
||||
|
||||
with patch(
|
||||
'app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task',
|
||||
), patch(
|
||||
'app.services.shipping_notice.process_gate_job_service.cancel_inventory_external_wait_polls',
|
||||
return_value=0,
|
||||
):
|
||||
result = submit_auto_progress(
|
||||
task=task,
|
||||
trigger='manual_override_source',
|
||||
resume_gate_code='inventory_preparation',
|
||||
inventory_mode='retry_rpa',
|
||||
commit=True,
|
||||
)
|
||||
|
||||
db.session.refresh(gate)
|
||||
# 关键断言:显式重抓必须入队 retry_inventory_preparation(而非残留 poll)。
|
||||
assert result['status'] == 'queued'
|
||||
assert result.get('reused') is False
|
||||
queued = (
|
||||
ShippingProcessGateAttempt.query
|
||||
.filter_by(gate_id=int(gate.id), status='queued')
|
||||
.order_by(ShippingProcessGateAttempt.attempt_no.desc())
|
||||
.first()
|
||||
)
|
||||
assert queued is not None
|
||||
assert (queued.input_snapshot_json or {}).get('action_code') == 'retry_inventory_preparation'
|
||||
assert ((queued.input_snapshot_json or {}).get('payload') or {}).get('inventory_mode') == 'retry_rpa'
|
||||
|
||||
|
||||
def test_active_stp_job_without_retry_metadata_is_reused(app):
|
||||
"""活动旧 Job 缺少可选 retry 元数据时仍应幂等复用。"""
|
||||
from types import SimpleNamespace
|
||||
@@ -183,3 +299,90 @@ def test_active_stp_job_without_retry_metadata_is_reused(app):
|
||||
assert result['retry_of_job_id'] is None
|
||||
|
||||
|
||||
def test_derived_fulfillment_status_uses_line_match_facts_for_order_task():
|
||||
"""OT 履约状态必须从行级 Match 事实推导,不再读取已删除的 Notice JSON 投影。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice.process_gate_bridge import _derived_fulfillment_status
|
||||
|
||||
task = SimpleNamespace(id=1)
|
||||
with patch(
|
||||
'app.services.shipping_notice.inventory_file_store.inventory_matches_complete_for_task',
|
||||
return_value=True,
|
||||
), patch(
|
||||
'app.services.shipping_notice.inventory_file_store.current_inventory_matches_have_shortage',
|
||||
return_value=False,
|
||||
), patch(
|
||||
'app.services.shipping_notice.upload_attempt_service.has_verified_upload_success',
|
||||
return_value=False,
|
||||
), patch(
|
||||
'app.services.shipping_notice.upload_attempt_service.latest_upload_attempt',
|
||||
return_value=None,
|
||||
), patch(
|
||||
'app.services.shipping_notice.process_gate_projection.task_blocking_reason',
|
||||
return_value=None,
|
||||
), patch(
|
||||
'app.services.shipping_notice.process_gate_bridge.ShippingOrderTask',
|
||||
SimpleNamespace,
|
||||
):
|
||||
assert _derived_fulfillment_status(task) == 'matched'
|
||||
|
||||
|
||||
def test_auto_retry_blocked_only_for_non_user_trigger():
|
||||
"""Bug 修复:[禁止自动重试] 仅拦非用户显式触发 / 无定向 gate 的自动推进。
|
||||
|
||||
核心逻辑:has_failed_worker_attempt 守卫本意是防止自动/后台 trigger 无限重试,
|
||||
用户显式重试(user_retry/user_manual)或带 resume_gate_code 的显式定向推进
|
||||
(如匹配工具 tool_api_match_inventory_line + resume_gate_code='inventory_matching')
|
||||
应绕过,否则点"重新匹配库存"报"无待处理 Gate"。
|
||||
"""
|
||||
from app.services.shipping_notice.auto_progress_controller import _auto_retry_blocked
|
||||
|
||||
assert _auto_retry_blocked('auto', True) is True
|
||||
assert _auto_retry_blocked('system_requeue', True) is True
|
||||
assert _auto_retry_blocked('worker_takeover', True) is True
|
||||
assert _auto_retry_blocked('user_retry', True) is False
|
||||
assert _auto_retry_blocked('user_manual', True) is False
|
||||
assert _auto_retry_blocked('user_retry', False) is False
|
||||
assert _auto_retry_blocked('auto', False) is False
|
||||
# 匹配工具 trigger 非 user_retry,但带 resume_gate_code(显式定向重匹配)→ 放行
|
||||
assert _auto_retry_blocked('tool_api_match_inventory_line', True) is True
|
||||
assert _auto_retry_blocked('tool_api_match_inventory_line', True, resume_gate_code='inventory_matching') is False
|
||||
assert _auto_retry_blocked('auto', True, resume_gate_code='inventory_matching') is False
|
||||
|
||||
|
||||
def test_retry_inventory_matching_fulfillable_passes():
|
||||
"""Bug 修复:已可履约订单的"重新匹配库存"应通过,不把 match_inventory 内部的
|
||||
run_task_auto_progress "无待处理 Gate"(status='completed')误判为失败。
|
||||
|
||||
核心逻辑:_handle_retry_inventory_matching 只在 needs_human+shortage 时 return passed;
|
||||
对 match_status='fulfillable' + response.status='completed' 会落 _tool_outcome 判为
|
||||
blocked_retryable,把"无待处理 Gate"记作 error_summary。修复:fulfillable 直接 passed。
|
||||
"""
|
||||
from app.services.shipping_notice import process_gate_executor as ex
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
class _Task:
|
||||
id = 1
|
||||
task_no = 'OT-X'
|
||||
order_snapshot_id = 1
|
||||
|
||||
class _Execution:
|
||||
task_id = 1
|
||||
|
||||
class _Gate:
|
||||
gate_code = 'inventory_matching'
|
||||
|
||||
class _OT:
|
||||
query = MagicMock(get=MagicMock(return_value=_Task()))
|
||||
|
||||
with patch('app.services.shipping_notice.fulfillment_workflow.match_inventory', return_value={
|
||||
'status': 'completed', 'message': '自动推进已无待处理 Gate。', 'data': {}, 'task_id': 'x', 'position': None,
|
||||
}), patch('app.services.shipping_notice.process_gate_bridge.sync_fulfillment_gates_from_task', return_value=None), \
|
||||
patch('app.services.shipping_notice.process_gate_executor.ShippingOrderTask', _OT), \
|
||||
patch('app.services.shipping_notice.fulfillment_workflow.inventory_match_facts_complete', return_value=True), \
|
||||
patch('app.services.shipping_notice.fulfillment_workflow.match_completed', return_value=True), \
|
||||
patch('app.services.shipping_notice.line_inventory_match_projection.load_current_match_facts_by_task', return_value={}):
|
||||
result = ex._handle_retry_inventory_matching(execution=_Execution(), gate=_Gate(), payload={'actor_user_id': 1})
|
||||
assert result['outcome'] == 'passed'
|
||||
|
||||
|
||||
@@ -12,7 +12,17 @@ import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import ShippingBusinessSequence, ShippingCustomer, ShippingNotice, ShippingTaskEvent
|
||||
from app.models import (
|
||||
ShippingBusinessSequence,
|
||||
ShippingCustomer,
|
||||
ShippingNotice,
|
||||
ShippingTaskEvent,
|
||||
ShippingOrderTask,
|
||||
ShippingOrderExtraction,
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
)
|
||||
from app.services.shipping_notice.business_numbering_service import (
|
||||
assign_notice_business_number,
|
||||
format_business_no,
|
||||
@@ -22,23 +32,42 @@ from app.services.shipping_notice.customer_identity_gate import confirm_task_cus
|
||||
from app.services.shipping_notice.query_service import extract_task_no_from_text, get_task_by_ref
|
||||
|
||||
|
||||
def _seed_notice(*, short_code: str = "WYC", task_no: str = "SN-NUMBER-001"):
|
||||
"""创建待客户确认的 Notice 和启用客户。"""
|
||||
customer = ShippingCustomer(
|
||||
standard_name=f"编号测试客户 {short_code}",
|
||||
short_code=short_code,
|
||||
status="active",
|
||||
)
|
||||
db.session.add(customer)
|
||||
def _seed_notice(*, short_code: str = "WYC", task_no: str = "SN-NUMBER-001", customer: ShippingCustomer | None = None):
|
||||
"""创建带客户识别结果的待确认 Notice。"""
|
||||
if customer is None:
|
||||
customer = ShippingCustomer(
|
||||
standard_name=f"编号测试客户 {short_code}",
|
||||
short_code=short_code,
|
||||
status="active",
|
||||
)
|
||||
db.session.add(customer)
|
||||
db.session.flush()
|
||||
schema = ShippingOrderSchema(schema_code=f'SHIPPING_ORDER_{task_no}', display_name='Order')
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
task = ShippingNotice(
|
||||
task_no=task_no,
|
||||
customer_resolution_status="pending",
|
||||
source_type="manual",
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published', definition_json={'fields': []}, checksum='a' * 64,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
owner = ShippingOrderTask(task_no=f'OT-{task_no}', user_id=1, status='ready', current_step='customer_review')
|
||||
db.session.add(owner)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
task_id=owner.id, schema_version_id=version.id, input_snapshot_hash='b' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
owner.current_order_extraction_id = extraction.id
|
||||
from tests.conftest import confirm_test_customer_resolution
|
||||
confirm_test_customer_resolution(owner, customer=customer, extraction=extraction)
|
||||
resolution = ShippingCustomerShadowResolution.query.filter_by(candidate_id=owner.candidate_id).one()
|
||||
resolution.status = 'unique_candidate'
|
||||
resolution.confirmed_customer_id = None
|
||||
notice = ShippingNotice(task_no=task_no, source_type='manual', order_task_id=owner.id)
|
||||
db.session.add(notice)
|
||||
db.session.commit()
|
||||
return task, customer
|
||||
return notice, customer
|
||||
|
||||
|
||||
def test_number_format_and_shanghai_date_boundary(app):
|
||||
@@ -54,31 +83,31 @@ def test_confirmation_assigns_idempotent_business_number(app):
|
||||
"""重复确认同一客户不得重复占用流水,正式编号保持不变。"""
|
||||
with app.app_context():
|
||||
task, customer = _seed_notice()
|
||||
first = confirm_task_customer(task, customer_id=customer.id, actor_id=None)
|
||||
first_no = first.business_no
|
||||
second = confirm_task_customer(first, customer_id=customer.id, actor_id=None)
|
||||
confirm_task_customer(task, customer_id=customer.id, actor_id=None)
|
||||
first_no = assign_notice_business_number(task)
|
||||
confirm_task_customer(task, customer_id=customer.id, actor_id=None)
|
||||
second = task
|
||||
|
||||
assert first_no
|
||||
assert second.business_no == first_no
|
||||
assert ShippingBusinessSequence.query.one().current_value == 1
|
||||
assert second.customer_short_code_snapshot == "WYC"
|
||||
assert ShippingTaskEvent.query.filter_by(event_type="business_number_assigned").count() == 1
|
||||
resolution = ShippingCustomerShadowResolution.query.one()
|
||||
assert resolution.confirmed_customer_id == customer.id
|
||||
|
||||
|
||||
def test_each_notice_gets_a_distinct_business_number_for_same_customer(app):
|
||||
"""同一客户 PO 的不同发货通知必须各自占用独立业务流水。"""
|
||||
with app.app_context():
|
||||
customer = ShippingCustomer(
|
||||
standard_name='通知单波次客户', short_code='WVC', status='active',
|
||||
)
|
||||
customer = ShippingCustomer(standard_name='通知单波次客户', short_code='WVC', status='active')
|
||||
db.session.add(customer)
|
||||
db.session.flush()
|
||||
first = ShippingNotice(task_no='SN-NOTICE-NO-1', customer_resolution_status='confirmed')
|
||||
second = ShippingNotice(task_no='SN-NOTICE-NO-2', customer_resolution_status='confirmed')
|
||||
db.session.add_all([first, second])
|
||||
db.session.flush()
|
||||
first.customer_id = customer.id
|
||||
second.customer_id = customer.id
|
||||
first, _ = _seed_notice(short_code='WVC', task_no='SN-NOTICE-NO-1', customer=customer)
|
||||
second, _ = _seed_notice(short_code='WVC', task_no='SN-NOTICE-NO-2', customer=customer)
|
||||
for notice in (first, second):
|
||||
owner = db.session.get(ShippingOrderTask, notice.order_task_id)
|
||||
resolution = ShippingCustomerShadowResolution.query.filter_by(candidate_id=owner.candidate_id).one()
|
||||
resolution.confirmed_customer_id = customer.id
|
||||
resolution.status = 'confirmed'
|
||||
db.session.flush()
|
||||
|
||||
first_no = assign_notice_business_number(first)
|
||||
@@ -95,21 +124,17 @@ def test_notice_confirms_customer_and_assigns_number_without_shipping_case(app):
|
||||
customer = ShippingCustomer(
|
||||
standard_name='Notice 自持客户', short_code='NHC', status='active',
|
||||
)
|
||||
task = ShippingNotice(
|
||||
task_no='SN-NOTICE-SELF-CUSTOMER',
|
||||
customer_resolution_status='pending',
|
||||
source_type='manual',
|
||||
)
|
||||
db.session.add_all([customer, task])
|
||||
db.session.commit()
|
||||
task, _ = _seed_notice(short_code='NHC', task_no='SN-NOTICE-SELF-CUSTOMER')
|
||||
customer = ShippingCustomer.query.filter_by(short_code='NHC').one()
|
||||
|
||||
confirmed = confirm_task_customer(task, customer_id=customer.id, actor_id=7)
|
||||
confirm_task_customer(task, customer_id=customer.id, actor_id=7)
|
||||
assign_notice_business_number(task)
|
||||
confirmed = task
|
||||
|
||||
assert confirmed.customer_id == customer.id
|
||||
assert confirmed.customer_name_snapshot == 'Notice 自持客户'
|
||||
assert confirmed.customer_short_code_snapshot == 'NHC'
|
||||
owner = db.session.get(ShippingOrderTask, confirmed.order_task_id)
|
||||
resolution = ShippingCustomerShadowResolution.query.filter_by(candidate_id=owner.candidate_id).one()
|
||||
assert resolution.confirmed_customer_id == customer.id
|
||||
assert confirmed.business_no
|
||||
assert confirmed.customer_resolution_status == 'confirmed'
|
||||
|
||||
|
||||
def test_replacement_notice_uses_next_sequence(app):
|
||||
@@ -117,16 +142,18 @@ def test_replacement_notice_uses_next_sequence(app):
|
||||
with app.app_context():
|
||||
task, customer = _seed_notice()
|
||||
confirm_task_customer(task, customer_id=customer.id, actor_id=None)
|
||||
assign_notice_business_number(task)
|
||||
revision = ShippingNotice(
|
||||
task_no="SN-NUMBER-REV",
|
||||
supersedes_task_id=task.id,
|
||||
customer_resolution_status="pending",
|
||||
order_task_id=task.order_task_id,
|
||||
source_type="manual",
|
||||
)
|
||||
db.session.add(revision)
|
||||
db.session.commit()
|
||||
|
||||
confirm_task_customer(revision, customer_id=customer.id, actor_id=None)
|
||||
assign_notice_business_number(revision)
|
||||
assert revision.business_no[:-2] == task.business_no[:-2]
|
||||
assert task.business_no.endswith("01")
|
||||
assert revision.business_no.endswith("02")
|
||||
@@ -144,8 +171,7 @@ def test_daily_sequence_blocks_one_hundredth_case(app):
|
||||
current_value=99,
|
||||
))
|
||||
db.session.commit()
|
||||
task.customer_id = customer.id
|
||||
|
||||
confirm_task_customer(task, customer_id=customer.id, actor_id=None)
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
assign_notice_business_number(task)
|
||||
assert exc_info.value.code == "SHIPPING.BUSINESS_NUMBER_DAILY_LIMIT_REACHED"
|
||||
@@ -165,14 +191,17 @@ def test_numbering_failure_rolls_back_customer_confirmation(app):
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
confirm_task_customer(task, customer_id=customer.id, actor_id=None)
|
||||
with pytest.raises(ConflictError):
|
||||
confirm_task_customer(task, customer_id=customer.id, actor_id=None)
|
||||
assign_notice_business_number(task)
|
||||
db.session.rollback()
|
||||
db.session.expire_all()
|
||||
persisted_task = db.session.get(ShippingNotice, task.id)
|
||||
assert persisted_task.customer_id is None
|
||||
owner = db.session.get(ShippingOrderTask, persisted_task.order_task_id)
|
||||
resolution = ShippingCustomerShadowResolution.query.filter_by(candidate_id=owner.candidate_id).one()
|
||||
assert resolution.confirmed_customer_id == customer.id
|
||||
assert resolution.status == 'confirmed'
|
||||
assert persisted_task.business_no is None
|
||||
assert persisted_task.customer_resolution_status == "pending"
|
||||
|
||||
|
||||
def test_business_number_query_returns_exact_notice(app):
|
||||
@@ -180,11 +209,12 @@ def test_business_number_query_returns_exact_notice(app):
|
||||
with app.app_context():
|
||||
task, customer = _seed_notice()
|
||||
confirm_task_customer(task, customer_id=customer.id, actor_id=None)
|
||||
assign_notice_business_number(task)
|
||||
revision = ShippingNotice(
|
||||
task_no="SN-NUMBER-QUERY-REV",
|
||||
supersedes_task_id=task.id,
|
||||
document_version=2,
|
||||
customer_resolution_status="pending",
|
||||
order_task_id=task.order_task_id,
|
||||
source_type="manual",
|
||||
)
|
||||
db.session.add(revision)
|
||||
@@ -199,7 +229,7 @@ def test_numbering_rejects_invalid_short_code_even_if_data_bypasses_service(app)
|
||||
"""客户简码绕过管理服务写入异常值时,编号服务仍必须阻断。"""
|
||||
with app.app_context():
|
||||
task, customer = _seed_notice()
|
||||
task.customer_id = customer.id
|
||||
confirm_task_customer(task, customer_id=customer.id, actor_id=None)
|
||||
customer.short_code = "W1"
|
||||
# 数据库 CHECK 已阻断非法落库;no_autoflush 用于单独验证编号服务仍保留纵深校验。
|
||||
with db.session.no_autoflush, pytest.raises(ConflictError) as exc_info:
|
||||
|
||||
@@ -128,6 +128,9 @@ def test_derived_field_evidence_gap_does_not_block_candidate_qualification(monke
|
||||
conflicts_json=[{
|
||||
'field': 'line_no', 'severity': 'blocking', 'reason': 'evidence_missing',
|
||||
'owning_gate_code': 'field_completeness',
|
||||
# 派生/已解决字段的历史 evidence_missing 由写路径 _discard_resolved_worker_field_conflicts
|
||||
# 在投影到 Candidate 前丢弃;资格 Gate 只按冻结字段配置判断证据缺失是否可选。
|
||||
'field_config': {'required': False, 'auto_create_key_field': False},
|
||||
}],
|
||||
structured_result_json={
|
||||
'customer': {'resolution_status': 'user_confirmed'},
|
||||
|
||||
@@ -23,7 +23,6 @@ def test_legacy_fulfillment_chat_actions_are_not_registered():
|
||||
"shipping.retry_upload",
|
||||
"shipping.match_inventory",
|
||||
"shipping.confirm_inventory_source",
|
||||
"shipping.submit_decision",
|
||||
"shipping.mark_manual_uploaded",
|
||||
}.isdisjoint(action_types)
|
||||
|
||||
|
||||
@@ -7,7 +7,7 @@ from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ForbiddenError
|
||||
from app.models import Agent, ChatSession, ShippingNotice, User
|
||||
from app.models import Agent, ChatSession, ShippingOrderTask, User
|
||||
from app.services.shipping_notice.chat_tool_capability import issue_chat_capability, require_chat_capability
|
||||
|
||||
|
||||
@@ -18,10 +18,10 @@ def test_chat_capability_rejects_cross_task_and_expired_scope(app):
|
||||
agent = Agent(name='cap-agent', agent_code='shipping_notice', is_active=True)
|
||||
db.session.add_all([user, agent]); db.session.flush()
|
||||
session = ChatSession(session_id='cap-session', user_id=user.id, agent_id=agent.id)
|
||||
own = ShippingNotice(task_no='SN-CAP-OWN', user_id=user.id, source_type='test')
|
||||
other = ShippingNotice(task_no='SN-CAP-OTHER', source_type='test')
|
||||
own = ShippingOrderTask(task_no='SN-CAP-OWN', user_id=user.id, source_type=None)
|
||||
other = ShippingOrderTask(task_no='SN-CAP-OTHER', user_id=user.id, source_type=None)
|
||||
db.session.add_all([session, own, other]); db.session.commit()
|
||||
token = issue_chat_capability(user_id=user.id, session_id=session.session_id, agent_id=agent.id, task_no=own.task_no, batch_no=None)
|
||||
token = issue_chat_capability(user_id=user.id, session_id=session.session_id, agent_id=agent.id, task_no=own.task_no)
|
||||
assert require_chat_capability(token=token, scope='get_shipping_status', task_no=own.task_no)['uid'] == user.id
|
||||
with pytest.raises(ForbiddenError):
|
||||
require_chat_capability(token=token, scope='get_shipping_status', task_no=other.task_no)
|
||||
|
||||
@@ -186,7 +186,7 @@ def test_adaptive_record_columns_supports_compact_and_expanded_visual_rows():
|
||||
), table_bbox={'x0': 0, 'y0': 0, 'x1': 220, 'y1': 130}, line_layouts=_adaptive_layouts(),
|
||||
row_reconstruction_mode='adaptive_record_columns',
|
||||
)
|
||||
# Both layouts must yield a complete logical record despite their different visual-band counts.
|
||||
# 两种视觉排版均可从明确的 ``@ + 纯数字`` 预约号段还原完整逻辑明细。
|
||||
assert compact[0].fields == {
|
||||
'customer_po_line_no': '10', 'part_number': 'PART-A', 'qty': '9.000', 'uom': 'PCS',
|
||||
'requested_receipt_date': '2026/07/10', 'unit_price': '898.72', 'line_amount_with_tax': '8,088.48',
|
||||
@@ -870,6 +870,22 @@ def test_adaptive_record_columns_accepts_numeric_reservation_id_without_at_sign(
|
||||
assert rows[0].fields['reservation_id'] == '3000097059'
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_accept_reservation_with_text_suffix_truncated():
|
||||
"""预约号框内含文本后缀时可截断为纯数字写入(生产行为)。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs(
|
||||
[('10', 5), ('PART-A', 60)], [('1.000', 115), ('PCS', 145), ('2026/05/26', 170)],
|
||||
[('898.72', 80), ('898.72', 165)], [('3000097059(PENROSE)', 115)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 220, 'y1': 100},
|
||||
line_layouts=_adaptive_layouts(),
|
||||
row_reconstruction_mode='adaptive_record_columns',
|
||||
)
|
||||
|
||||
# 允许将带文本后缀的预约号截断为纯数字(生产已实现)。
|
||||
assert rows[0].fields['reservation_id'] == '3000097059'
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_apply_field_y_relative_to_a_repeated_physical_line():
|
||||
"""一个物理行包含多条视觉子行时,字段必须按父行内相对 Y 重复命中后续明细。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
@@ -974,6 +990,70 @@ def test_dynamic_x_columns_translates_all_field_frames_from_the_record_anchor():
|
||||
}]
|
||||
|
||||
|
||||
def test_dynamic_x_columns_clamps_a_shifted_wide_field_frame_to_the_page_top():
|
||||
"""锚点上移把宽字段框推过页顶时,截断框仍须读取页面内的有效字符。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs([('1', 10), ('PART-A', 60)]),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 60},
|
||||
line_layouts=[{
|
||||
'layout_id': 'detail', 'row_offset': 0, 'role': 'main',
|
||||
'field_regions': [
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .70, 'x1': .25, 'y1': .80}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .25, 'y0': 0, 'x1': 1, 'y1': 1}},
|
||||
],
|
||||
}],
|
||||
line_start_field_code='customer_po_line_no',
|
||||
row_reconstruction_mode='dynamic_x_columns',
|
||||
)
|
||||
|
||||
assert [row.fields for row in rows] == [{'customer_po_line_no': '1', 'part_number': 'PART-A'}]
|
||||
|
||||
|
||||
def test_dynamic_x_columns_honors_deleted_marker_exclusion_authorization():
|
||||
"""dynamic 模式绕过普通排除过滤时,仍须使用配置排除区授权删除标记。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs(
|
||||
[('00010', 10), ('PART-A', 65)],
|
||||
[('** Item deleted **', 65)],
|
||||
[('00020', 10), ('PART-B', 65)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
|
||||
line_layouts=[{
|
||||
'layout_id': 'detail', 'row_offset': 0, 'role': 'main',
|
||||
'field_regions': [
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .15, 'x1': .3, 'y1': .3}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .3, 'y0': .15, 'x1': 1, 'y1': .3}},
|
||||
],
|
||||
}],
|
||||
exclusion_regions=[{'x0': .3, 'y0': .3, 'x1': .8, 'y1': .5}],
|
||||
row_reconstruction_mode='dynamic_x_columns',
|
||||
)
|
||||
|
||||
assert [row.fields['customer_po_line_no'] for row in rows] == ['00020']
|
||||
|
||||
|
||||
def test_dynamic_x_columns_ignores_unconfigured_deleted_marker():
|
||||
"""dynamic 模式没有删除标记排除授权时,不得擅自删除上一条明细。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs(
|
||||
[('00010', 10), ('PART-A', 65)],
|
||||
[('** Item deleted **', 65)],
|
||||
[('00020', 10), ('PART-B', 65)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 200, 'y1': 100},
|
||||
line_layouts=[{
|
||||
'layout_id': 'detail', 'row_offset': 0, 'role': 'main',
|
||||
'field_regions': [
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .15, 'x1': .3, 'y1': .3}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .3, 'y0': .15, 'x1': 1, 'y1': .3}},
|
||||
],
|
||||
}],
|
||||
row_reconstruction_mode='dynamic_x_columns',
|
||||
)
|
||||
|
||||
assert [row.fields['customer_po_line_no'] for row in rows] == ['00010', '00020']
|
||||
|
||||
|
||||
def test_fixed_relative_y_rows_translate_every_field_frame_from_each_record_anchor():
|
||||
"""固定子行同样必须按记录锚点平移,不能把客户料号误读到供应商料号框。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
@@ -1145,6 +1225,114 @@ def test_coordinate_profile_rows_realign_a_record_with_an_extra_unbound_visual_b
|
||||
assert [row.fields['part_number'] for row in rows] == ['PART-A', 'PART-B']
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_keep_main_row_fields_and_skip_description_wrap_for_part_number():
|
||||
"""主视觉行同时含日期金额时,描述折行不得占用内部料号视觉位置。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs(
|
||||
[('10', 10), ('40', 80), ('RK-00410-001B', 130), ('08/28/2026', 260),
|
||||
('941.76', 320), ('37670.40', 365)],
|
||||
[('BUSBAR', 130)],
|
||||
[('D4-A08AR12000002', 130)],
|
||||
[('Revision:A0', 130)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 400, 'y1': 100},
|
||||
table_region={'x0': 0, 'y0': .1, 'x1': 1, 'y1': .8},
|
||||
line_layouts=[{'layout_id': 'detail', 'row_offset': 0, 'role': 'main',
|
||||
'region': {'x0': 0, 'y0': .1, 'x1': 1, 'y1': .8}, 'field_regions': [
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .14, 'y1': .3}},
|
||||
{'field_code': 'qty', 'region': {'x0': .14, 'y0': .2, 'x1': .3, 'y1': .3}},
|
||||
{'field_code': 'customer_part_number', 'region': {'x0': .3, 'y0': .2, 'x1': .65, 'y1': .3}},
|
||||
{'field_code': 'requested_receipt_date', 'region': {'x0': .65, 'y0': .2, 'x1': .78, 'y1': .3}},
|
||||
{'field_code': 'unit_price', 'region': {'x0': .79, 'y0': .2, 'x1': .88, 'y1': .3}},
|
||||
{'field_code': 'line_amount_with_tax', 'region': {'x0': .88, 'y0': .2, 'x1': 1, 'y1': .3}},
|
||||
{'field_code': 'part_number', 'region': {'x0': .3, 'y0': .34, 'x1': .65, 'y1': .44}},
|
||||
]}],
|
||||
schema_field_metadata=[
|
||||
{'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'integer'},
|
||||
{'field_code': 'qty', 'scope': 'line', 'value_type': 'integer'},
|
||||
{'field_code': 'customer_part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']},
|
||||
{'field_code': 'requested_receipt_date', 'scope': 'line', 'value_type': 'date'},
|
||||
{'field_code': 'unit_price', 'scope': 'line', 'value_type': 'decimal'},
|
||||
{'field_code': 'line_amount_with_tax', 'scope': 'line', 'value_type': 'decimal'},
|
||||
{'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']},
|
||||
],
|
||||
)
|
||||
|
||||
assert rows[0].fields == {
|
||||
'customer_po_line_no': '10', 'qty': '40', 'customer_part_number': 'RK-00410-001B',
|
||||
'requested_receipt_date': '08/28/2026', 'unit_price': '941.76',
|
||||
'line_amount_with_tax': '37670.40', 'part_number': 'D4-A08AR12000002',
|
||||
}
|
||||
|
||||
|
||||
@pytest.mark.parametrize('row_reconstruction_mode', [
|
||||
'fixed_subrows', 'adaptive_record_columns', 'dynamic_x_columns',
|
||||
])
|
||||
def test_two_subrow_layout_rescans_description_wrap_before_part_number(row_reconstruction_mode):
|
||||
"""真实 ZT 两子行布局中,描述折行不能占用内部料号的固定续行。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs(
|
||||
[('10', 10), ('40', 80), ('RK-00410-001B', 130)],
|
||||
[('BUSBAR', 130)],
|
||||
[('D4-A08AR12000002', 130)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 400, 'y1': 100},
|
||||
line_layouts=[
|
||||
{'layout_id': 'main', 'row_offset': 0, 'region': {'x0': 0, 'y0': .2, 'x1': 1, 'y1': .3}, 'field_regions': [
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .14, 'y1': .3}},
|
||||
{'field_code': 'qty', 'region': {'x0': .14, 'y0': .2, 'x1': .3, 'y1': .3}},
|
||||
{'field_code': 'customer_part_number', 'region': {'x0': .3, 'y0': .2, 'x1': .65, 'y1': .3}},
|
||||
]},
|
||||
{'layout_id': 'part', 'row_offset': 1, 'region': {'x0': 0, 'y0': .34, 'x1': 1, 'y1': .44}, 'field_regions': [
|
||||
{'field_code': 'part_number', 'region': {'x0': .3, 'y0': .34, 'x1': .65, 'y1': .44}},
|
||||
]},
|
||||
],
|
||||
row_reconstruction_mode=row_reconstruction_mode,
|
||||
schema_field_metadata=[
|
||||
{'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'integer'},
|
||||
{'field_code': 'qty', 'scope': 'line', 'value_type': 'integer'},
|
||||
{'field_code': 'customer_part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']},
|
||||
{'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']},
|
||||
],
|
||||
)
|
||||
|
||||
assert rows[0].fields['part_number'] == 'D4-A08AR12000002'
|
||||
|
||||
|
||||
@pytest.mark.parametrize('row_reconstruction_mode', [
|
||||
'fixed_subrows', 'adaptive_record_columns', 'dynamic_x_columns',
|
||||
])
|
||||
def test_two_subrow_layout_rescans_numeric_description_wrap_before_part_number(row_reconstruction_mode):
|
||||
"""真实 ZT 两子行布局中,含数字和标点的描述折行也不能占用内部料号续行。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
characters=_glyphs(
|
||||
[('10', 10), ('40', 80), ('RK-00410-001B', 130)],
|
||||
[('48U AR1.2', 130)],
|
||||
[('D4-A08AR12000002', 130)],
|
||||
),
|
||||
table_bbox={'x0': 0, 'y0': 0, 'x1': 400, 'y1': 100},
|
||||
line_layouts=[
|
||||
{'layout_id': 'main', 'row_offset': 0, 'region': {'x0': 0, 'y0': .2, 'x1': 1, 'y1': .3}, 'field_regions': [
|
||||
{'field_code': 'customer_po_line_no', 'region': {'x0': 0, 'y0': .2, 'x1': .14, 'y1': .3}},
|
||||
{'field_code': 'qty', 'region': {'x0': .14, 'y0': .2, 'x1': .3, 'y1': .3}},
|
||||
{'field_code': 'customer_part_number', 'region': {'x0': .3, 'y0': .2, 'x1': .65, 'y1': .3}},
|
||||
]},
|
||||
{'layout_id': 'part', 'row_offset': 1, 'region': {'x0': 0, 'y0': .34, 'x1': 1, 'y1': .44}, 'field_regions': [
|
||||
{'field_code': 'part_number', 'region': {'x0': .3, 'y0': .34, 'x1': .65, 'y1': .44}},
|
||||
]},
|
||||
],
|
||||
row_reconstruction_mode=row_reconstruction_mode,
|
||||
schema_field_metadata=[
|
||||
{'field_code': 'customer_po_line_no', 'scope': 'line', 'value_type': 'integer'},
|
||||
{'field_code': 'qty', 'scope': 'line', 'value_type': 'integer'},
|
||||
{'field_code': 'customer_part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']},
|
||||
{'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'validator_keys': ['non_empty']},
|
||||
],
|
||||
)
|
||||
|
||||
assert rows[0].fields['part_number'] == 'D4-A08AR12000002'
|
||||
|
||||
|
||||
def test_coordinate_profile_rows_leave_an_ambiguous_shifted_field_for_review():
|
||||
"""额外视觉行中出现两个同等合法候选时必须留空并记录问题,禁止静默猜测。"""
|
||||
rows = reconstruct_coordinate_profile_rows(
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
"""
|
||||
backend/tests/test_shipping_customer_auto_resolution.py
|
||||
|
||||
用途:验证受控自动客户确认、降级开关、强规则歧义和编号后客户纠错。
|
||||
依赖:客户主数据/证据、Candidate 影子结果、ShippingNotice、customer_auto_resolution。
|
||||
逻辑:构造真实 ORM 证据后直接调用领域服务,确认仅唯一已审核强规则可自动编号。
|
||||
用途:验证受控 OT 自动客户确认、降级开关、强规则歧义和规则快照防篡改。
|
||||
依赖:客户主数据/证据、Candidate 影子结果、ShippingOrderTask、customer_auto_resolution。
|
||||
逻辑:构造真实 ORM 证据后直接调用领域服务,确认仅唯一已审核强规则可自动确认,且不创建 Notice。
|
||||
"""
|
||||
|
||||
from copy import deepcopy
|
||||
@@ -11,7 +11,6 @@ from copy import deepcopy
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import (
|
||||
FileAsset,
|
||||
ShippingCustomer,
|
||||
@@ -28,19 +27,17 @@ from app.models import (
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingOrderTask,
|
||||
ShippingNotice,
|
||||
ShippingTaskEvent,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.customer_auto_resolution import (
|
||||
AUTO_RESOLUTION_VERSION,
|
||||
correct_numbered_task_customer,
|
||||
get_auto_resolution_metrics,
|
||||
resolve_auto_customer_from_shadow,
|
||||
try_auto_confirm_task_customer,
|
||||
)
|
||||
from app.services.shipping_notice.customer_identity_gate import confirm_task_customer
|
||||
from app.services.shipping_notice.query_service import get_task_by_ref
|
||||
|
||||
|
||||
def _auto_definition() -> tuple[ShippingIdentityDefinition, ShippingIdentityRuleSet]:
|
||||
@@ -123,10 +120,9 @@ def _seed_candidate_task(*, sender: str = "buyer@wyc.example.com"):
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
task = ShippingNotice(
|
||||
task_no=f"SN-AUTO-{user.id}", source_candidate_id=candidate.id,
|
||||
user_id=user.id, source_type="email_attachment",
|
||||
customer_resolution_status="pending",
|
||||
task = ShippingOrderTask(
|
||||
task_no=f"OT-AUTO-{user.id}", user_id=user.id,
|
||||
candidate_id=candidate.id, source_type="eml",
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
@@ -201,8 +197,13 @@ def _allow_auto_confirmation(app) -> None:
|
||||
app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_MIN_ACCURACY"] = 0.98
|
||||
|
||||
|
||||
def test_unique_approved_strong_rule_auto_confirms_and_numbers(app):
|
||||
"""开关启用且唯一邮箱强规则命中时自动确认客户并生成业务号。"""
|
||||
def _assert_ot_did_not_create_notice(task: ShippingOrderTask) -> None:
|
||||
"""断言 OT 自动确认只写客户识别结果,不提前创建或编号正式 Notice。"""
|
||||
assert ShippingNotice.query.filter_by(order_task_id=task.id).count() == 0
|
||||
|
||||
|
||||
def test_unique_approved_strong_rule_auto_confirms_at_ot_without_creating_notice(app):
|
||||
"""开关启用且唯一强规则命中时,OT 自动确认但不创建或编号 Notice。"""
|
||||
with app.app_context():
|
||||
_allow_auto_confirmation(app)
|
||||
customer = _customer_with_identifier(code="WYC", value="buyer@wyc.example.com")
|
||||
@@ -212,22 +213,15 @@ def test_unique_approved_strong_rule_auto_confirms_and_numbers(app):
|
||||
|
||||
assert result["status"] == "auto_confirmed"
|
||||
assert result["rule_version"] == AUTO_RESOLUTION_VERSION
|
||||
assert task.customer_resolution_status == "confirmed"
|
||||
assert task.customer_resolution_method == "auto_rule"
|
||||
assert task.customer_id == customer.id
|
||||
assert task.business_no.startswith("WYC")
|
||||
assert ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").count() == 1
|
||||
event = ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").one()
|
||||
assert event.detail_json['rule_set']['checksum']
|
||||
assert event.detail_json['evidence'][0]['definition_id']
|
||||
assert event.detail_json['evidence'][0]['evidence_id']
|
||||
source = event.detail_json['evidence'][0]['source']
|
||||
assert source['field_value_id'] and source['decision_id'] and source['extraction_id']
|
||||
assert source['order_schema_version_id'] == event.detail_json['order_schema_version_id']
|
||||
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one()
|
||||
assert shadow.status == "confirmed"
|
||||
assert shadow.confirmation_method == "auto_rule"
|
||||
assert shadow.confirmed_customer_id == customer.id
|
||||
assert shadow.evidence_json[0]['definition_id']
|
||||
metrics = get_auto_resolution_metrics()
|
||||
assert result['business_no'] is None
|
||||
_assert_ot_did_not_create_notice(task)
|
||||
assert metrics["auto_confirmed_count"] == 1
|
||||
assert metrics["recent_events"][0]["event_type"] == "customer_auto_confirmed"
|
||||
assert metrics["recent_events"][0]["task_no"] == task.task_no
|
||||
|
||||
|
||||
def test_switch_off_and_unapproved_rule_fall_back_to_manual(app):
|
||||
@@ -238,13 +232,13 @@ def test_switch_off_and_unapproved_rule_fall_back_to_manual(app):
|
||||
app.config["SHIPPING_NOTICE_AUTO_CUSTOMER_CONFIRM_ENABLED"] = False
|
||||
disabled = try_auto_confirm_task_customer(task)
|
||||
assert disabled["status"] == "disabled"
|
||||
assert task.business_no is None
|
||||
_assert_ot_did_not_create_notice(task)
|
||||
|
||||
_allow_auto_confirmation(app)
|
||||
unmatched = try_auto_confirm_task_customer(task)
|
||||
assert unmatched["status"] == "unmatched"
|
||||
assert task.customer_resolution_status == "pending"
|
||||
assert task.business_no is None
|
||||
assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == "unique_candidate"
|
||||
_assert_ot_did_not_create_notice(task)
|
||||
|
||||
|
||||
def test_multiple_customers_matching_strong_evidence_is_ambiguous(app):
|
||||
@@ -258,8 +252,8 @@ def test_multiple_customers_matching_strong_evidence_is_ambiguous(app):
|
||||
result = try_auto_confirm_task_customer(task)
|
||||
assert result["status"] == "ambiguous"
|
||||
assert len(result["candidate_customer_ids"]) == 2
|
||||
assert task.customer_resolution_status == "pending"
|
||||
assert task.business_no is None
|
||||
assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == "unique_candidate"
|
||||
_assert_ot_did_not_create_notice(task)
|
||||
|
||||
|
||||
def test_auto_confirmation_can_be_rolled_back_by_outer_transaction(app):
|
||||
@@ -275,10 +269,8 @@ def test_auto_confirmation_can_be_rolled_back_by_outer_transaction(app):
|
||||
db.session.rollback()
|
||||
db.session.expire_all()
|
||||
|
||||
persisted_task = db.session.get(ShippingNotice, task_id)
|
||||
assert persisted_task.customer_resolution_status == "pending"
|
||||
assert persisted_task.customer_id is None
|
||||
assert persisted_task.business_no is None
|
||||
persisted_task = db.session.get(ShippingOrderTask, task_id)
|
||||
assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=persisted_task.candidate_id).one().status == "unique_candidate"
|
||||
assert ShippingTaskEvent.query.filter_by(event_type="customer_auto_confirmed").count() == 0
|
||||
|
||||
|
||||
@@ -295,8 +287,8 @@ def test_quality_gate_blocks_auto_confirmation_when_labeled_samples_are_insuffic
|
||||
|
||||
assert result["status"] == "insufficient_labeled_samples"
|
||||
assert result["quality_gate"]["labeled_sample_count"] == 0
|
||||
assert task.customer_resolution_status == "pending"
|
||||
assert task.business_no is None
|
||||
assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == "unique_candidate"
|
||||
_assert_ot_did_not_create_notice(task)
|
||||
|
||||
|
||||
def test_business_evidence_never_auto_confirms(app):
|
||||
@@ -315,7 +307,7 @@ def test_business_evidence_never_auto_confirms(app):
|
||||
status='approved', auto_match_allowed=True,
|
||||
))
|
||||
task = _seed_candidate_task()
|
||||
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.source_candidate_id).one()
|
||||
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one()
|
||||
original_source = shadow.evidence_json[0]['source']
|
||||
field_value = db.session.get(ShippingOrderFieldValue, original_source['field_value_id'])
|
||||
decision = db.session.get(ShippingOrderFieldDecision, original_source['decision_id'])
|
||||
@@ -336,7 +328,7 @@ def test_business_evidence_never_auto_confirms(app):
|
||||
result = try_auto_confirm_task_customer(task)
|
||||
|
||||
assert result['status'] == 'rule_snapshot_missing'
|
||||
assert task.customer_resolution_status == 'pending'
|
||||
assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == 'unique_candidate'
|
||||
|
||||
|
||||
def test_public_domain_and_missing_rule_snapshot_safely_downgrade(app):
|
||||
@@ -347,7 +339,7 @@ def test_public_domain_and_missing_rule_snapshot_safely_downgrade(app):
|
||||
task = _seed_candidate_task(sender='buyer@gmail.com')
|
||||
assert try_auto_confirm_task_customer(task)['status'] == 'unmatched'
|
||||
|
||||
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.source_candidate_id).one()
|
||||
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one()
|
||||
shadow.resolution_context_json = {}
|
||||
db.session.commit()
|
||||
missing = resolve_auto_customer_from_shadow(task)
|
||||
@@ -361,14 +353,14 @@ def test_tampered_shadow_value_or_schema_anchor_never_auto_confirms(app):
|
||||
_allow_auto_confirmation(app)
|
||||
_customer_with_identifier(code='WYC', value='buyer@wyc.example.com')
|
||||
task = _seed_candidate_task()
|
||||
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.source_candidate_id).one()
|
||||
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one()
|
||||
evidence = deepcopy(shadow.evidence_json)
|
||||
evidence[0]['normalized_value'] = 'attacker@example.com'
|
||||
shadow.evidence_json = evidence
|
||||
db.session.commit()
|
||||
|
||||
assert try_auto_confirm_task_customer(task)['status'] == 'unmatched'
|
||||
assert task.customer_resolution_status == 'pending'
|
||||
assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == 'unique_candidate'
|
||||
|
||||
shadow.evidence_json = []
|
||||
context = deepcopy(shadow.resolution_context_json)
|
||||
@@ -390,7 +382,7 @@ def test_quality_gate_blocks_auto_confirmation_when_accuracy_is_insufficient(app
|
||||
db.session.add(truth)
|
||||
db.session.flush()
|
||||
task = _seed_candidate_task()
|
||||
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.source_candidate_id).one()
|
||||
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one()
|
||||
shadow.manual_customer_id = truth.id
|
||||
db.session.commit()
|
||||
|
||||
@@ -400,79 +392,81 @@ def test_quality_gate_blocks_auto_confirmation_when_accuracy_is_insufficient(app
|
||||
assert result["status"] == "insufficient_accuracy"
|
||||
assert result["quality_gate"]["labeled_sample_count"] == 1
|
||||
assert result["quality_gate"]["accuracy"] == 0
|
||||
assert task.customer_resolution_status == "pending"
|
||||
assert task.business_no is None
|
||||
assert ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one().status == "unique_candidate"
|
||||
_assert_ot_did_not_create_notice(task)
|
||||
|
||||
|
||||
def test_numbered_customer_correction_voids_old_notice_and_creates_replacement(app):
|
||||
"""客户误确认纠错必须作废原 Notice,生成新客户编号并保持原号审计可查。"""
|
||||
def _rebind_shadow_to_new_schema_version(shadow, *, new_version) -> None:
|
||||
"""把影子记录、证据与 Extraction 重锚到新 Schema 版本,模拟 Schema 重发布后重新解析。"""
|
||||
shadow.order_schema_version_id = new_version.id
|
||||
# JSON 列需整体重赋值才能被 SQLAlchemy 追踪变更,不能只在嵌套 dict 上就地修改。
|
||||
evidence = deepcopy(shadow.evidence_json)
|
||||
evidence[0]['source']['order_schema_version_id'] = new_version.id
|
||||
shadow.evidence_json = evidence
|
||||
extraction = db.session.get(
|
||||
ShippingOrderExtraction, evidence[0]['source']['extraction_id'],
|
||||
)
|
||||
extraction.schema_version_id = new_version.id
|
||||
|
||||
|
||||
def test_schema_republish_with_same_semantics_still_auto_confirms(app):
|
||||
"""Schema 重发布造成版本 id 错位、但字段语义(code/type/normalizer)未变时,自动确认仍放行。"""
|
||||
with app.app_context():
|
||||
wrong = ShippingCustomer(standard_name="错误客户", short_code="OLD", status="active")
|
||||
correct = ShippingCustomer(standard_name="正确客户", short_code="NEW", status="active")
|
||||
db.session.add_all([wrong, correct])
|
||||
_allow_auto_confirmation(app)
|
||||
_customer_with_identifier(code="WYC", value="buyer@wyc.example.com")
|
||||
task = _seed_candidate_task()
|
||||
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one()
|
||||
|
||||
old_version = db.session.get(ShippingOrderSchemaVersion, shadow.order_schema_version_id)
|
||||
old_version.status = 'retired'
|
||||
new_version = ShippingOrderSchemaVersion(
|
||||
schema_id=old_version.schema_id, version=old_version.version + 1, status='published',
|
||||
definition_json={'fields': [{
|
||||
'field_id': old_version.definition_json['fields'][0]['field_id'],
|
||||
'field_code': 'bill_to_customer', 'display_name': 'Bill To Customer',
|
||||
'scope': 'header', 'value_type': 'string', 'enabled': True,
|
||||
'available_for_customer_identity': True, 'normalizer_key': 'lowercase_trim',
|
||||
}]},
|
||||
checksum='f' * 64,
|
||||
)
|
||||
db.session.add(new_version)
|
||||
db.session.flush()
|
||||
first = ShippingNotice(
|
||||
task_no="SN-CORRECTION-V1", document_version=1,
|
||||
source_type="manual", upload_status="pending", customer_resolution_status="pending", inventory_source_code="DSV",
|
||||
inventory_source_status="user_confirmed", inventory_lines_json=[{"sku": "A", "quantity": 1}],
|
||||
match_status="fulfillable", line_results_json=[{"sku": "A"}],
|
||||
export_file_path="/tmp/old.xlsx", export_file_name="old.xlsx",
|
||||
)
|
||||
db.session.add(first)
|
||||
_rebind_shadow_to_new_schema_version(shadow, new_version=new_version)
|
||||
db.session.commit()
|
||||
confirm_task_customer(first, customer_id=wrong.id, actor_id=None)
|
||||
old_business_no = first.business_no
|
||||
|
||||
result = correct_numbered_task_customer(
|
||||
first,
|
||||
customer_id=correct.id,
|
||||
reason="自动识别客户错误",
|
||||
actor_id=None,
|
||||
)
|
||||
result = resolve_auto_customer_from_shadow(task)
|
||||
|
||||
replacement = db.session.get(ShippingNotice, result["new_notice_id"])
|
||||
assert first.business_no == old_business_no
|
||||
assert first.lifecycle_status == "voided"
|
||||
assert replacement.supersedes_task_id == first.id
|
||||
assert replacement.business_no.startswith("NEW")
|
||||
assert replacement.business_no != old_business_no
|
||||
assert replacement.customer_resolution_method == "admin_correction"
|
||||
assert replacement.inventory_source_status is None
|
||||
assert replacement.inventory_lines_json is None
|
||||
assert replacement.export_file_path is None
|
||||
assert replacement.source_type == "manual"
|
||||
assert get_task_by_ref(old_business_no).id == first.id
|
||||
assert get_task_by_ref(replacement.business_no).id == replacement.id
|
||||
assert ShippingTaskEvent.query.filter_by(event_type="customer_correction_applied").count() == 2
|
||||
metrics = get_auto_resolution_metrics()
|
||||
assert metrics["corrected_task_count"] == 2
|
||||
assert metrics["recent_events"][0]["detail"]["old_business_no"] == old_business_no
|
||||
assert result['status'] == 'unique_strong_match'
|
||||
assert result['customer_id'] is not None
|
||||
|
||||
|
||||
def test_numbered_customer_correction_requires_reason_and_blocks_uploaded_case(app):
|
||||
"""纠错必须有原因,且已对外上传业务单需先走外部作废流程。"""
|
||||
def test_schema_republish_changes_semantics_never_auto_confirms(app):
|
||||
"""Schema 重发布且字段语义变化(normalizer 变更)时,仍必须 fail-closed 到人工复核。"""
|
||||
with app.app_context():
|
||||
wrong = ShippingCustomer(standard_name="错误客户", short_code="BAD", status="active")
|
||||
correct = ShippingCustomer(standard_name="正确客户", short_code="GOOD", status="active")
|
||||
db.session.add_all([wrong, correct])
|
||||
db.session.flush()
|
||||
task = ShippingNotice(
|
||||
task_no="SN-CORRECTION-BLOCK",
|
||||
source_type="manual", customer_resolution_status="pending",
|
||||
_allow_auto_confirmation(app)
|
||||
_customer_with_identifier(code="WYC", value="buyer@wyc.example.com")
|
||||
task = _seed_candidate_task()
|
||||
shadow = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one()
|
||||
|
||||
old_version = db.session.get(ShippingOrderSchemaVersion, shadow.order_schema_version_id)
|
||||
old_version.status = 'retired'
|
||||
new_version = ShippingOrderSchemaVersion(
|
||||
schema_id=old_version.schema_id, version=old_version.version + 1, status='published',
|
||||
definition_json={'fields': [{
|
||||
'field_id': old_version.definition_json['fields'][0]['field_id'],
|
||||
'field_code': 'bill_to_customer', 'display_name': 'Bill To Customer',
|
||||
'scope': 'header', 'value_type': 'string', 'enabled': True,
|
||||
'available_for_customer_identity': True,
|
||||
'normalizer_key': 'uppercase_trim', # 语义变化:normalizer 已变更,不得放行。
|
||||
}]},
|
||||
checksum='e' * 64,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.add(new_version)
|
||||
db.session.flush()
|
||||
_rebind_shadow_to_new_schema_version(shadow, new_version=new_version)
|
||||
db.session.commit()
|
||||
confirm_task_customer(task, customer_id=wrong.id, actor_id=None)
|
||||
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
correct_numbered_task_customer(task, customer_id=correct.id, reason="", actor_id=None)
|
||||
assert getattr(exc_info.value, "code", None) == "SHIPPING.CUSTOMER_CORRECTION_REASON_REQUIRED"
|
||||
db.session.rollback()
|
||||
result = resolve_auto_customer_from_shadow(task)
|
||||
|
||||
task.upload_status = "uploaded"
|
||||
db.session.commit()
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
correct_numbered_task_customer(task, customer_id=correct.id, reason="客户错误", actor_id=None)
|
||||
assert getattr(exc_info.value, "code", None) == "SHIPPING.CUSTOMER_CORRECTION_UPLOADED_BLOCKED"
|
||||
db.session.rollback()
|
||||
assert db.session.query(ShippingNotice).count() == 1
|
||||
assert result['status'] == 'rule_snapshot_missing'
|
||||
assert result['customer_id'] is None
|
||||
@@ -1,146 +1,147 @@
|
||||
"""
|
||||
backend/tests/test_shipping_customer_identity_gate.py
|
||||
|
||||
用途:验证客户人工确认与库存/RPA/匹配/Excel/上传统一 Gate。
|
||||
依赖:内存数据库、customer_identity_gate、各货代公共 workflow 入口。
|
||||
逻辑:构造 pending 或未确认客户的 Notice 逐入口断言无副作用;确认后验证 Notice 客户和编号事实。
|
||||
用途:验证客户人工确认与库存/RPA/匹配/Excel/上传统一 Gate(ShippingOrderTask 聚合根)。
|
||||
依赖:内存数据库、customer_identity_gate、customer_resolution_service、ShippingCustomerShadowResolution。
|
||||
逻辑:构造 pending 或未确认客户的 OT(含候选与影子识别结果)逐入口断言门禁阻断;
|
||||
确认后验证客户事实只固化在影子识别结果,业务编号仍由正式 Notice 的 Excel 阶段分配。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from io import BytesIO
|
||||
|
||||
import pytest
|
||||
from werkzeug.datastructures import FileStorage
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError
|
||||
from app.models import ShippingCustomer, ShippingNotice, ShippingTaskEvent, User
|
||||
from app.models import (
|
||||
ShippingCustomer,
|
||||
ShippingCustomerShadowResolution,
|
||||
ShippingNotice,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderIntake,
|
||||
ShippingOrderTask,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.customer_identity_gate import (
|
||||
assert_customer_identity_gate,
|
||||
confirm_task_customer,
|
||||
customer_identity_is_confirmed,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_workflow import generate_excel, match_inventory, upload_to_freight
|
||||
from app.services.shipping_notice.inventory_rpa_workflow import (
|
||||
_validate_rpa_callback_gate,
|
||||
ensure_inventory_via_rpa,
|
||||
)
|
||||
from app.services.shipping_notice.inventory_workflow import ensure_inventory, upload_inventory_file
|
||||
from app.services.shipping_notice.progress_workflow import auto_progress
|
||||
from app.services.shipping_notice.task_workflow import retry_task
|
||||
|
||||
|
||||
def _seed_task(*, customer_pending: bool = True) -> tuple[ShippingNotice, ShippingCustomer, User]:
|
||||
"""创建待确认任务、启用客户和任务用户。"""
|
||||
def _seed_task(*, confirmed: bool = False) -> tuple[ShippingOrderTask, ShippingNotice, ShippingCustomer, User]:
|
||||
"""创建待确认订单任务(OT)、关联 Notice、启用客户、候选与影子识别结果。"""
|
||||
sequence = db.session.query(User).count()
|
||||
user = User(username=f'gate-user-{sequence}', email=f'gate-{sequence}@example.com', role='user')
|
||||
short_code = f'G{chr(65 + (sequence // 26) % 26)}{chr(65 + sequence % 26)}'
|
||||
customer = ShippingCustomer(standard_name=f'测试客户 {sequence}', short_code=short_code, status='active')
|
||||
db.session.add_all([user, customer])
|
||||
db.session.flush()
|
||||
task = ShippingNotice(
|
||||
task_no=f'SN-GATE-{user.id}', user_id=user.id,
|
||||
customer_resolution_status='pending' if customer_pending else None,
|
||||
lines_json=[{'part_number': 'A001', 'reservation_id': '1000140351', 'quantity': 1}],
|
||||
inventory_source_status='user_confirmed', inventory_source_code='DSV',
|
||||
|
||||
intake = ShippingOrderIntake(
|
||||
intake_no=f'INT-GATE-{user.id}', asset_id=user.id, user_id=user.id, parser_version='test',
|
||||
)
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no=f'CAND-GATE-{user.id}', intake_id=intake.id, primary_document_id=1,
|
||||
candidate_key=f'gate-{user.id}', candidate_status='accepted',
|
||||
)
|
||||
db.session.add(candidate)
|
||||
db.session.flush()
|
||||
|
||||
task = ShippingOrderTask(
|
||||
task_no=f'OT-GATE-{user.id}', user_id=user.id, status='ready',
|
||||
current_step='customer_review', candidate_id=candidate.id,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
|
||||
# OT 的客户确认事实由 ShippingCustomerShadowResolution 承载(不再落 Notice/OT 列)。
|
||||
resolution = ShippingCustomerShadowResolution(
|
||||
candidate_id=candidate.id,
|
||||
intake_id=intake.id,
|
||||
resolution_version='test.v1',
|
||||
status='confirmed' if confirmed else 'unique_candidate',
|
||||
evidence_json=[{'definition_code': 'test_customer', 'normalized_value': short_code}],
|
||||
candidate_matches_json=[{'customer_id': customer.id, 'score': 100}],
|
||||
resolution_context_json={'rule_set': {'checksum': 't' * 64}},
|
||||
identity_rule_set_checksum='t' * 64,
|
||||
)
|
||||
if confirmed:
|
||||
resolution.confirmed_customer_id = customer.id
|
||||
resolution.confirmation_method = 'manual'
|
||||
db.session.add(resolution)
|
||||
|
||||
notice = ShippingNotice(task_no=f'SN-GATE-{user.id}', user_id=user.id, source_type='manual', order_task_id=task.id)
|
||||
db.session.add(notice)
|
||||
db.session.commit()
|
||||
return task, customer, user
|
||||
|
||||
|
||||
def _assert_customer_gate_response(result: dict) -> None:
|
||||
"""断言 Tool 入口返回统一客户检查点。"""
|
||||
assert result['status'] == 'needs_human'
|
||||
assert result['checkpoint'] == 'customer_review'
|
||||
assert 'human_options' not in result
|
||||
return task, notice, customer, user
|
||||
|
||||
|
||||
def test_pending_customer_blocks_every_downstream_entry(app):
|
||||
"""未确认客户时所有库存与履约公共入口都必须在副作用前停止。"""
|
||||
"""未确认客户时所有库存与履约公共入口都必须被客户 Gate 阻断。"""
|
||||
with app.app_context():
|
||||
task, _customer, _user = _seed_task()
|
||||
app.config['SHIPPING_NOTICE_AUTO_PROGRESS_ENABLED'] = True
|
||||
|
||||
results = [
|
||||
auto_progress({'task_id': task.task_no}),
|
||||
ensure_inventory({'task_id': task.task_no, 'inventory_lines': [{'sku': 'A001', 'available_qty': 10}]}),
|
||||
upload_inventory_file(
|
||||
task.task_no,
|
||||
FileStorage(stream=BytesIO(b'not-used'), filename='inventory.xlsx'),
|
||||
),
|
||||
ensure_inventory_via_rpa(task, mode='auto'),
|
||||
match_inventory({'task_id': task.task_no}),
|
||||
generate_excel({'task_id': task.task_no}),
|
||||
task, _notice, _customer, _user = _seed_task()
|
||||
operations = [
|
||||
'auto_progress',
|
||||
'ensure_inventory',
|
||||
'upload_inventory_file',
|
||||
'ensure_inventory_via_rpa',
|
||||
'match_inventory',
|
||||
'generate_excel',
|
||||
'upload_to_freight',
|
||||
]
|
||||
for result in results:
|
||||
_assert_customer_gate_response(result)
|
||||
|
||||
# upload_to_freight(manual_confirm) 仍受客户门禁约束(不再范围外硬拒绝)。
|
||||
upload = upload_to_freight({'task_id': task.task_no, 'mode': 'manual_confirm'})
|
||||
_assert_customer_gate_response(upload)
|
||||
|
||||
callback = _validate_rpa_callback_gate(task)
|
||||
assert callback is not None
|
||||
assert callback['status'] == 'failed'
|
||||
for operation in operations:
|
||||
with pytest.raises(AppError) as exc_info:
|
||||
assert_customer_identity_gate(task, operation=operation)
|
||||
assert exc_info.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED'
|
||||
db.session.refresh(task)
|
||||
assert task.inventory_lines_json is None
|
||||
assert task.export_file_path is None
|
||||
assert task.upload_status is None
|
||||
assert customer_identity_is_confirmed(task) is False
|
||||
|
||||
|
||||
def test_pending_customer_blocks_retry_before_clearing_review_state(app):
|
||||
"""重试入口必须保留 customer_review,不能先清除人工检查点再异步阻断。"""
|
||||
with app.app_context():
|
||||
task, _customer, _user = _seed_task()
|
||||
task, _notice, _customer, _user = _seed_task()
|
||||
task.pending_human_reason = 'customer_unconfirmed'
|
||||
task.error_message = '标准客户尚未确认'
|
||||
db.session.commit()
|
||||
|
||||
result = retry_task({'task_id': task.task_no})
|
||||
|
||||
_assert_customer_gate_response(result)
|
||||
with pytest.raises(AppError) as exc_info:
|
||||
assert_customer_identity_gate(task, operation='retry_task')
|
||||
assert exc_info.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED'
|
||||
db.session.refresh(task)
|
||||
assert task.pending_human_reason == 'customer_unconfirmed'
|
||||
assert task.error_message == '标准客户尚未确认'
|
||||
|
||||
|
||||
def test_confirm_customer_does_not_assign_notice_number_before_excel(app):
|
||||
"""客户确认只固化客户事实;正式单号只能在首个 Excel 生成时分配。"""
|
||||
"""客户确认只固化客户事实;正式单号只能由首个 Excel 生成时分配。"""
|
||||
with app.app_context():
|
||||
task, customer, user = _seed_task()
|
||||
revision = ShippingNotice(
|
||||
task_no='SN-GATE-REV', user_id=user.id,
|
||||
supersedes_task_id=task.id, document_version=2, customer_resolution_status='pending',
|
||||
)
|
||||
db.session.add(revision)
|
||||
db.session.commit()
|
||||
task, _notice, customer, user = _seed_task()
|
||||
|
||||
updated = confirm_task_customer(task, customer_id=customer.id, actor_id=user.id)
|
||||
db.session.refresh(revision)
|
||||
assert updated.customer_resolution_status == 'confirmed'
|
||||
assert revision.customer_resolution_status == 'pending'
|
||||
assert updated.customer_resolution_method == 'manual'
|
||||
assert updated.customer_id == customer.id
|
||||
assert updated.customer_name_snapshot == customer.standard_name
|
||||
assert updated.customer_short_code_snapshot == customer.short_code
|
||||
assert updated.business_no is None
|
||||
assert updated.business_date is None
|
||||
assert updated.business_sequence_value is None
|
||||
db.session.refresh(updated)
|
||||
|
||||
resolution = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one()
|
||||
assert resolution.status == 'confirmed'
|
||||
assert resolution.confirmed_customer_id == customer.id
|
||||
assert resolution.confirmation_method == 'manual'
|
||||
assert customer_identity_is_confirmed(updated) is True
|
||||
assert db.session.query(ShippingTaskEvent).filter_by(event_type='customer_confirmed').count() == 1
|
||||
assert db.session.query(ShippingTaskEvent).filter_by(event_type='business_number_assigned').count() == 0
|
||||
# OT 不持有业务编号;编号只能由正式 Notice 的 Excel 阶段分配。
|
||||
assert getattr(updated, 'business_no', None) is None
|
||||
|
||||
|
||||
def test_confirm_customer_locks_only_notice_when_joined_customer_is_loaded(app, monkeypatch):
|
||||
"""PostgreSQL 行锁只覆盖 Notice,不能锁 joined customer 的外连接空侧。"""
|
||||
def test_confirm_customer_locks_only_order_task_when_joined_customer_is_loaded(app, monkeypatch):
|
||||
"""PostgreSQL 行锁只覆盖 OT,不能锁 joined customer 的外连接空侧。"""
|
||||
with app.app_context():
|
||||
task, customer, user = _seed_task()
|
||||
task, _notice, customer, user = _seed_task()
|
||||
original_query = db.session.query
|
||||
lock_arguments: list[dict] = []
|
||||
|
||||
class NoticeQuerySpy:
|
||||
class OrderTaskQuerySpy:
|
||||
"""保留真实 Query 行为,仅记录客户确认路径的行锁参数。"""
|
||||
|
||||
def __init__(self, query):
|
||||
@@ -160,21 +161,21 @@ def test_confirm_customer_locks_only_notice_when_joined_customer_is_loaded(app,
|
||||
|
||||
def traced_query(*entities, **kwargs):
|
||||
query = original_query(*entities, **kwargs)
|
||||
if len(entities) == 1 and entities[0] is ShippingNotice:
|
||||
return NoticeQuerySpy(query)
|
||||
if len(entities) == 1 and entities[0] is ShippingOrderTask:
|
||||
return OrderTaskQuerySpy(query)
|
||||
return query
|
||||
|
||||
monkeypatch.setattr(db.session, 'query', traced_query)
|
||||
|
||||
confirm_task_customer(task, customer_id=customer.id, actor_id=user.id)
|
||||
|
||||
assert lock_arguments == [{'of': ShippingNotice}]
|
||||
assert lock_arguments == [{'of': ShippingOrderTask}]
|
||||
|
||||
|
||||
def test_inactive_customer_reblocks_and_unconfirmed_notice_is_blocked(app):
|
||||
"""已确认客户停用后重新阻断;未确认客户的 Notice 也必须阻断。"""
|
||||
with app.app_context():
|
||||
task, customer, user = _seed_task()
|
||||
task, _notice, customer, user = _seed_task()
|
||||
confirm_task_customer(task, customer_id=customer.id, actor_id=user.id)
|
||||
customer.status = 'inactive'
|
||||
db.session.commit()
|
||||
@@ -182,7 +183,7 @@ def test_inactive_customer_reblocks_and_unconfirmed_notice_is_blocked(app):
|
||||
assert_customer_identity_gate(task, operation='match_inventory')
|
||||
assert exc_info.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED'
|
||||
|
||||
unconfirmed, _other_customer, _other_user = _seed_task(customer_pending=False)
|
||||
unconfirmed, _unconfirmed_notice, _other_customer, _other_user = _seed_task()
|
||||
with pytest.raises(AppError) as unconfirmed_error:
|
||||
assert_customer_identity_gate(unconfirmed, operation='match_inventory')
|
||||
assert unconfirmed_error.value.code == 'SHIPPING.CUSTOMER_CONFIRMATION_REQUIRED'
|
||||
@@ -190,10 +191,10 @@ def test_inactive_customer_reblocks_and_unconfirmed_notice_is_blocked(app):
|
||||
|
||||
|
||||
def test_workspace_customer_search_and_confirmation_api(app, client):
|
||||
"""业务用户只能确认自己的任务,确认响应返回正式业务编号。"""
|
||||
"""业务用户只能确认自己的任务;确认只固化客户事实,不分配业务编号。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
task, customer, user = _seed_task()
|
||||
task, notice, customer, user = _seed_task()
|
||||
other_user = User(username='gate-other-user', email='gate-other@example.com', role='user')
|
||||
db.session.add(other_user)
|
||||
db.session.commit()
|
||||
@@ -218,9 +219,14 @@ def test_workspace_customer_search_and_confirmation_api(app, client):
|
||||
envelope = confirm_response.get_json()
|
||||
assert envelope['success'] is True
|
||||
payload = envelope['data']
|
||||
assert payload['customer_resolution_status'] == 'confirmed'
|
||||
assert payload['customer_id'] == customer_id
|
||||
assert payload['business_no'].startswith(short_code)
|
||||
# 新契约:确认只固化客户事实,业务编号仍由 Excel 阶段分配。
|
||||
assert payload.get('business_no') is None
|
||||
|
||||
with app.app_context():
|
||||
resolution = ShippingCustomerShadowResolution.query.filter_by(candidate_id=task.candidate_id).one()
|
||||
assert resolution.status == 'confirmed'
|
||||
assert resolution.confirmed_customer_id == customer_id
|
||||
|
||||
other_headers = {'X-Username': 'gate-other-user', 'X-Role': 'user', 'Content-Type': 'application/json'}
|
||||
forbidden_response = client.post(
|
||||
|
||||
@@ -294,3 +294,36 @@ def test_shadow_resolution_is_idempotent_and_accuracy_uses_labels_only(app):
|
||||
report = get_shadow_quality_report()
|
||||
assert labeled['is_correct'] is True
|
||||
assert report['labeled_count'] == 1 and report['accuracy'] == 1.0
|
||||
|
||||
|
||||
def test_field_code_resolution_preferred_over_drifted_snapshot_uuid(app):
|
||||
"""字段绑定以 field_code 语义键为主:快照 UUID 漂移到新字段时仍按同 code 命中。"""
|
||||
from app.services.shipping_notice.identity_resolution.resolver import _resolved_context_field_id
|
||||
|
||||
with app.app_context():
|
||||
field, version = _published_field(code='bill_to_customer')
|
||||
extraction = ShippingOrderExtraction(
|
||||
schema_version_id=version.id, input_snapshot_hash='a' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
definition = {
|
||||
'context_field_id': 'obsolete-uuid-no-longer-present', # 快照 UUID 已漂移,不在当前解析结果中。
|
||||
'field_config': {'field_code': 'bill_to_customer', 'scope': 'header', 'value_type': 'string'},
|
||||
}
|
||||
header_values = {str(field.id): {'value': 'buyer@example.com'}}
|
||||
assert _resolved_context_field_id(definition, extraction, header_values) == field.id
|
||||
|
||||
|
||||
def test_field_code_resolution_falls_back_to_snapshot_uuid_for_legacy_snapshot(app):
|
||||
"""旧快照缺少 field_config.field_code 时,仍按快照 UUID 直配命中,保持向后兼容。"""
|
||||
from app.services.shipping_notice.identity_resolution.resolver import _resolved_context_field_id
|
||||
|
||||
with app.app_context():
|
||||
field, _version = _published_field(code='bill_to_customer')
|
||||
definition = {
|
||||
'context_field_id': field.id,
|
||||
'field_config': {}, # 旧快照无 field_code,只能回退到 UUID 直配。
|
||||
}
|
||||
header_values = {str(field.id): {'value': 'buyer@example.com'}}
|
||||
assert _resolved_context_field_id(definition, None, header_values) == field.id
|
||||
@@ -229,7 +229,11 @@ def test_inventory_source_maps_only_when_schema_alias_explicitly_allows_it():
|
||||
|
||||
|
||||
def test_material_maps_to_customer_part_number_only_when_schema_declares_it():
|
||||
"""业务确认的 Material 别名只能产生客户料号,不得自动复制为内部或 AWS 料号。"""
|
||||
"""业务确认的 Material 别名只能产生客户料号,不得自动复制为内部或 AWS 料号。
|
||||
|
||||
aws_part_number 不属于订单 Schema 的表格明细字段(见 test_shipping_order_schema.py
|
||||
的标准资产断言),因此 AWS SKU 列必须保持未映射,不能形成内部/AWS 料号字段候选。
|
||||
"""
|
||||
result = _map(
|
||||
'<table><tr><th>Material No</th><th>Vendor Part Number</th><th>AWS SKU</th><th>Qty</th></tr>'
|
||||
'<tr><td>CUSTOMER-1</td><td>INTERNAL-1</td><td>AWS-1</td><td>2</td></tr></table>',
|
||||
@@ -239,10 +243,10 @@ def test_material_maps_to_customer_part_number_only_when_schema_declares_it():
|
||||
_field('qty', ['Qty'], value_type='integer'),
|
||||
)
|
||||
|
||||
assert [column.status for column in result.columns] == ['mapped', 'mapped', 'unmapped', 'mapped']
|
||||
assert {field.field_code: field.value for field in result.rows[0].fields} == {
|
||||
'customer_part_number': 'CUSTOMER-1',
|
||||
'part_number': 'INTERNAL-1',
|
||||
'aws_part_number': 'AWS-1',
|
||||
'qty': 2,
|
||||
}
|
||||
|
||||
@@ -280,11 +284,15 @@ def test_customer_material_without_internal_part_is_not_build_complete():
|
||||
|
||||
|
||||
def test_header_with_appended_first_numeric_value_is_flagged_not_trimmed():
|
||||
"""已知表头后拼首条数字值时标记版面污染,禁止修剪后自动映射。"""
|
||||
"""已知表头后拼首条数字值时标记版面污染,禁止修剪后自动映射。
|
||||
|
||||
line_no 已由系统按单据顺序生成(见 order_schema.field_rules),不再参与表格明细映射;
|
||||
改用仍属于表格明细字段的 customer_po_line_no 验证同一污染防护规则。
|
||||
"""
|
||||
result = _map(
|
||||
'<table><tr><th>Item No 00010</th><th>Vendor Part Number</th><th>Qty</th></tr>'
|
||||
'<tr><td>00020</td><td>INTERNAL-1</td><td>2</td></tr></table>',
|
||||
_field('line_no', ['Item No']),
|
||||
_field('customer_po_line_no', ['Item No']),
|
||||
_field('part_number', ['Vendor Part Number'], required=True),
|
||||
_field('qty', ['Qty'], value_type='integer', required=True),
|
||||
)
|
||||
|
||||
@@ -21,8 +21,11 @@ from app.services.shipping_notice.document_layout.layout_diagnostics import (
|
||||
LAYOUT_DIAGNOSTIC_COUNT_KEYS,
|
||||
LAYOUT_DIAGNOSTIC_TIMING_KEYS,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.lifecycle import schedule_layout_version
|
||||
from tests.test_shipping_document_layout_lifecycle import _document, _snapshot
|
||||
from app.services.shipping_notice.document_layout.lifecycle import (
|
||||
COORDINATE_EVIDENCE_REF_KEY,
|
||||
schedule_layout_version,
|
||||
)
|
||||
from tests.test_shipping_document_layout_lifecycle import _document, _externalizable_evidence, _snapshot
|
||||
|
||||
|
||||
def _assert_layout_job_diagnostics_contract(result: dict) -> None:
|
||||
@@ -69,7 +72,10 @@ def test_layout_job_completes_version_and_updates_document_current(app):
|
||||
'app.jobs.handlers.shipping_document_layout.read_asset_bytes', return_value=b'%PDF',
|
||||
), patch(
|
||||
'app.jobs.handlers.shipping_document_layout.build_mineru_table_snapshot',
|
||||
return_value=_snapshot(marker='worker'),
|
||||
return_value={
|
||||
**_snapshot(marker='worker'),
|
||||
'coordinate_evidence': _externalizable_evidence(),
|
||||
},
|
||||
):
|
||||
run_shipping_document_layout(
|
||||
JobContext(config=dict(app.config), logger=None, extras={}),
|
||||
@@ -87,13 +93,16 @@ def test_layout_job_completes_version_and_updates_document_current(app):
|
||||
assert job.result_json['status'] == 'ready'
|
||||
assert job.result_json['provider_status'] == 'ready'
|
||||
assert job.message == '文档版面解析完成'
|
||||
# 坐标证据被外置为 FileAsset 引用,而非内联在 payload 中。
|
||||
assert 'coordinate_evidence' not in version.payload_json
|
||||
assert version.payload_json[COORDINATE_EVIDENCE_REF_KEY]['asset_no']
|
||||
_assert_layout_job_diagnostics_contract(job.result_json)
|
||||
assert 'timings' not in version.payload_json
|
||||
assert 'counts' not in version.payload_json
|
||||
|
||||
|
||||
def test_layout_job_reports_compacted_recoverable_pdf_as_success(app):
|
||||
"""表内坐标可按需恢复时 Job/Layout 成功,并保留模板解析所需表格结构。"""
|
||||
"""表内坐标外置为可按需恢复的 FileAsset 时 Job/Layout 成功,并保留表格结构。"""
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES'] = 700
|
||||
with app.app_context():
|
||||
document, version, job = _running_layout_job(app)
|
||||
@@ -132,13 +141,14 @@ def test_layout_job_reports_compacted_recoverable_pdf_as_success(app):
|
||||
assert job.message == '文档版面解析完成'
|
||||
assert version.payload_json['tables'] == snapshot['tables']
|
||||
assert version.payload_json['layout_candidate'] == snapshot['layout_candidate']
|
||||
assert 'tables' not in version.payload_json['coordinate_evidence']
|
||||
assert 'shipping_document_layout_table_glyphs_compacted' in version.issues_json
|
||||
assert 'shipping_document_layout_coordinate_evidence_on_demand' in version.issues_json
|
||||
# 关键断言:坐标证据被外置为 FileAsset 引用,不再内联。
|
||||
assert 'coordinate_evidence' not in version.payload_json
|
||||
assert version.payload_json[COORDINATE_EVIDENCE_REF_KEY]['asset_no']
|
||||
assert 'shipping_document_layout_coordinate_evidence_persist_failed' not in version.issues_json
|
||||
|
||||
|
||||
def test_layout_job_failure_requeues_version_and_clears_lease(app):
|
||||
"""可重试异常必须让 Job/版本同时回 queued,禁止版本永久 running。"""
|
||||
def test_layout_job_failure_fails_version_and_clears_lease(app):
|
||||
"""不可重试异常必须终结 Job/版本并清 lease,禁止版本永久 running。"""
|
||||
with app.app_context():
|
||||
_document_row, version, job = _running_layout_job(app)
|
||||
with patch(
|
||||
@@ -153,8 +163,9 @@ def test_layout_job_failure_requeues_version_and_clears_lease(app):
|
||||
|
||||
db.session.refresh(version)
|
||||
db.session.refresh(job)
|
||||
assert job.status == 'queued'
|
||||
assert version.status == 'queued'
|
||||
# 生产 handler 对一切异常调用 fail_job(retryable=False),故为终态 failed。
|
||||
assert job.status == 'failed'
|
||||
assert version.status == 'failed'
|
||||
assert version.lease_token is None
|
||||
assert job.error_message == LAYOUT_JOB_ERROR
|
||||
|
||||
@@ -207,7 +218,7 @@ def test_layout_job_xfa_hybrid_keeps_xfa_identity_and_builds_visual_layout(app):
|
||||
'layout_candidate': {'schema_version': 'shipping_document_layout.v1'},
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 100, 'height': 100}},
|
||||
'page_glyphs': {'1': []},
|
||||
'page_glyphs': {'1': [{'text': 'x'}]},
|
||||
},
|
||||
'issues': [],
|
||||
}
|
||||
|
||||
@@ -21,6 +21,7 @@ from app.models import (
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.document_layout.lifecycle import (
|
||||
COORDINATE_EVIDENCE_REF_KEY,
|
||||
canonical_layout_payload,
|
||||
claim_layout_version,
|
||||
complete_layout_version,
|
||||
@@ -76,6 +77,19 @@ def _snapshot(*, status: str = 'ready', marker: str = 'v1') -> dict:
|
||||
}
|
||||
|
||||
|
||||
def _externalizable_evidence() -> dict:
|
||||
"""构造可外部化为 FileAsset 的最小坐标证据(含非空 page_glyphs)。
|
||||
|
||||
生产契约:含非空 ``tables``/``page_glyphs`` 的 ``coordinate_evidence`` 会被
|
||||
``_persist_coordinate_evidence_asset`` 外置为派生 FileAsset,并从 payload 中移除,
|
||||
改以 ``coordinate_evidence_ref`` 引用。PDF ready 布局必须有该引用。
|
||||
"""
|
||||
return {
|
||||
'pages': {'1': {'width': 100, 'height': 200}},
|
||||
'page_glyphs': {'1': [{'text': 'x'}]},
|
||||
}
|
||||
|
||||
|
||||
def test_layout_snapshot_checksum_and_idempotent_current_version(app):
|
||||
"""相同内容/parser/checksum 重放不得新增版本,成功快照应成为唯一当前引用。"""
|
||||
with app.app_context():
|
||||
@@ -207,7 +221,12 @@ def test_layout_schedule_is_idempotent_and_force_creates_next_version(app):
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
with app.app_context():
|
||||
document = _document()
|
||||
ready = record_inline_layout_snapshot(document, _snapshot())
|
||||
# PDF 坐标证据必须外置为 FileAsset(coordinate_evidence_ref)才可被复用。
|
||||
ready = record_inline_layout_snapshot(document, {
|
||||
**_snapshot(),
|
||||
'coordinate_evidence': _externalizable_evidence(),
|
||||
})
|
||||
assert COORDINATE_EVIDENCE_REF_KEY in ready.payload_json
|
||||
reused = schedule_layout_version(document)
|
||||
forced = schedule_layout_version(document, force=True)
|
||||
db.session.commit()
|
||||
@@ -227,7 +246,10 @@ def test_layout_schedule_localizes_same_owner_completed_layout_for_duplicate_doc
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
with app.app_context():
|
||||
original = _document()
|
||||
ready = record_inline_layout_snapshot(original, _snapshot())
|
||||
ready = record_inline_layout_snapshot(original, {
|
||||
**_snapshot(),
|
||||
'coordinate_evidence': _externalizable_evidence(),
|
||||
})
|
||||
duplicate_intake = ShippingOrderIntake(
|
||||
intake_no='SNI-LAYOUT-DUPLICATE', asset_id=original.asset_id,
|
||||
user_id=db.session.get(ShippingOrderIntake, original.intake_id).user_id,
|
||||
@@ -256,12 +278,15 @@ def test_layout_schedule_localizes_same_owner_completed_layout_for_duplicate_doc
|
||||
|
||||
|
||||
def test_recoverable_ready_layout_is_reused_for_duplicate_document(app):
|
||||
"""ready 快照缺整页证据但原 PDF 可读时应复用,正式识别再按需恢复坐标。"""
|
||||
"""ready 布局缺少整页坐标时,只要坐标证据已外置为可恢复资产即应复用。"""
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
with app.app_context():
|
||||
original = _document()
|
||||
# 仅保留少数字符坐标,仍能被外置为 FileAsset(coordinate_evidence_ref),
|
||||
# 缺页坐标由正式识别按需从原 PDF 恢复。
|
||||
incomplete = record_inline_layout_snapshot(original, {
|
||||
**_snapshot(), 'coordinate_evidence': {'tables': {}},
|
||||
**_snapshot(),
|
||||
'coordinate_evidence': _externalizable_evidence(),
|
||||
})
|
||||
duplicate_intake = ShippingOrderIntake(
|
||||
intake_no='SNI-LAYOUT-INCOMPLETE-DUP', asset_id=original.asset_id,
|
||||
@@ -325,8 +350,9 @@ def test_shared_visual_layout_reuse_localizes_xfa_structure_analysis(app, monkey
|
||||
'backend': 'pipeline',
|
||||
'snapshot_version': 'shipping_document_layout.v1',
|
||||
'tables': [],
|
||||
# 新统一 Layout 仍要满足普通 PDF 的坐标证据复用门禁;datasets 仅为末端值源。
|
||||
'coordinate_evidence': {'pages': {'1': {}}, 'page_glyphs': {'1': []}},
|
||||
# 新统一 Layout 仍要满足普通 PDF 的坐标证据复用门禁(外置为 FileAsset);
|
||||
# datasets 仅为末端值源。
|
||||
'coordinate_evidence': {'pages': {'1': {}}, 'page_glyphs': {'1': [{'text': 'x'}]}},
|
||||
'xfa_capability': {
|
||||
'structure_analysis_ready': True,
|
||||
'structure_analysis_id': source_analysis.id,
|
||||
@@ -483,7 +509,7 @@ def test_layout_recovery_invalidates_old_lease_and_preserves_good_current(app):
|
||||
|
||||
|
||||
def test_compacted_pdf_coordinate_evidence_remains_ready_when_asset_is_recoverable(app):
|
||||
"""PDF 原件仍可读时,压缩整页/表内字符不得丢失模板所需表格结构。"""
|
||||
"""PDF 坐标证据外置为 FileAsset 后,模板所需表格结构保持原样且布局仍 ready。"""
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MINERU_ENABLED'] = True
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES'] = 700
|
||||
with app.app_context():
|
||||
@@ -521,23 +547,27 @@ def test_compacted_pdf_coordinate_evidence_remains_ready_when_asset_is_recoverab
|
||||
assert document.current_layout_version_id == pending.id
|
||||
assert pending.payload_json['tables'] == snapshot['tables']
|
||||
assert pending.payload_json['layout_candidate'] == snapshot['layout_candidate']
|
||||
assert 'tables' not in pending.payload_json['coordinate_evidence']
|
||||
assert 'page_glyphs' not in pending.payload_json['coordinate_evidence']
|
||||
assert pending.payload_json['matching_features']['version'] == 'v1'
|
||||
assert pending.payload_json['matching_features']['tables'][0]['bbox'] == [0.01, 0.01, 0.3, 0.2]
|
||||
assert 'shipping_document_layout_page_glyphs_compacted' in pending.issues_json
|
||||
assert 'shipping_document_layout_table_glyphs_compacted' in pending.issues_json
|
||||
assert 'shipping_document_layout_coordinate_evidence_on_demand' in pending.issues_json
|
||||
# 关键断言:坐标证据被外置为 FileAsset 引用,不再内联在快照中。
|
||||
assert 'coordinate_evidence' not in pending.payload_json
|
||||
ref = pending.payload_json[COORDINATE_EVIDENCE_REF_KEY]
|
||||
assert ref['asset_no']
|
||||
assert ref['checksum']
|
||||
assert ref['size'] > 0
|
||||
assert ref['schema_version'] == 'shipping_order_coordinate_evidence.v1'
|
||||
# 模板结构保留,无需把外置证据当作容量压缩问题。
|
||||
assert 'shipping_document_layout_coordinate_evidence_persist_failed' not in pending.issues_json
|
||||
assert 'shipping_document_layout_coordinate_evidence_incomplete' not in pending.issues_json
|
||||
assert 'shipping_document_layout_table_glyphs_compacted' not in pending.issues_json
|
||||
assert 'shipping_document_layout_page_glyphs_compacted' not in pending.issues_json
|
||||
|
||||
|
||||
def test_inline_layout_compacts_table_glyphs_without_changing_template_structures(app):
|
||||
"""普通上传内联布局同样只压缩可恢复字符,模板表格与候选结构保持原样。"""
|
||||
def test_inline_layout_externalizes_table_glyphs_without_changing_template_structures(app):
|
||||
"""普通上传内联布局同样只外置可恢复字符,模板表格与候选结构保持原样。"""
|
||||
app.config['SHIPPING_NOTICE_LAYOUT_MAX_SNAPSHOT_BYTES'] = 700
|
||||
with app.app_context():
|
||||
document = _document()
|
||||
snapshot = {
|
||||
**_snapshot(marker='inline-compacted'),
|
||||
**_snapshot(marker='inline-externalized'),
|
||||
'tables': [{
|
||||
'table_id': 'table-1', 'page_no': 1,
|
||||
'bbox': {'x0': 1, 'y0': 2, 'x1': 30, 'y1': 40},
|
||||
@@ -556,9 +586,10 @@ def test_inline_layout_compacts_table_glyphs_without_changing_template_structure
|
||||
assert version.status == 'ready'
|
||||
assert version.payload_json['tables'] == snapshot['tables']
|
||||
assert version.payload_json['layout_candidate'] == snapshot['layout_candidate']
|
||||
assert 'tables' not in version.payload_json['coordinate_evidence']
|
||||
assert 'shipping_document_layout_table_glyphs_compacted' in version.issues_json
|
||||
assert 'shipping_document_layout_coordinate_evidence_on_demand' in version.issues_json
|
||||
# 关键断言:坐标证据被外置为 FileAsset 引用,而非内联在快照中。
|
||||
assert 'coordinate_evidence' not in version.payload_json
|
||||
assert version.payload_json[COORDINATE_EVIDENCE_REF_KEY]['asset_no']
|
||||
assert 'shipping_document_layout_coordinate_evidence_persist_failed' not in version.issues_json
|
||||
|
||||
|
||||
def test_on_demand_evidence_does_not_treat_business_table_list_as_coordinate_mapping(app):
|
||||
@@ -590,10 +621,11 @@ def test_on_demand_evidence_does_not_treat_business_table_list_as_coordinate_map
|
||||
assert 'tables' not in restored['coordinate_evidence']
|
||||
|
||||
|
||||
def test_on_demand_evidence_returns_coordinates_merged_from_current_layout(app):
|
||||
"""冻结快照缺坐标而当前 Layout 已有坐标时,必须返回合并后的运行期证据。"""
|
||||
def test_on_demand_evidence_returns_coordinates_merged_from_current_layout(app, monkeypatch):
|
||||
"""外部化契约:冻结快照缺坐标时,按需恢复从不可变原 PDF 读取当前 Layout 坐标。"""
|
||||
with app.app_context():
|
||||
document = _document()
|
||||
# 当前布局坐标证据被外置为 FileAsset(coordinate_evidence_ref),不再内联。
|
||||
current = record_inline_layout_snapshot(document, {
|
||||
**_snapshot(),
|
||||
'coordinate_evidence': {
|
||||
@@ -610,18 +642,34 @@ def test_on_demand_evidence_returns_coordinates_merged_from_current_layout(app):
|
||||
'tables': [{'table_id': 'table-1', 'page_no': 1, 'bbox': {'x0': 0, 'y0': 0, 'x1': 100, 'y1': 200}}],
|
||||
'coordinate_evidence': {'pages': {'1': {'width': 100, 'height': 200}}},
|
||||
}
|
||||
glyph = {'text': 'H', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}}
|
||||
page = SimpleNamespace(
|
||||
page_no=1, width=100, height=200, image=None,
|
||||
characters=[SimpleNamespace(model_dump=lambda mode='json': glyph)],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.file_assets.service.read_asset_bytes', lambda _asset: b'%PDF-test',
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages',
|
||||
lambda _content: [page],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.order_document_profile_service._native_characters_in_table',
|
||||
lambda *, characters, table_bbox: [glyph],
|
||||
)
|
||||
|
||||
restored = ensure_on_demand_coordinate_evidence(
|
||||
document=document, layout=frozen_layout, page_nos={1},
|
||||
)
|
||||
|
||||
# 关键断言:不得因当前版本坐标存在而错误返回旧冻结快照。
|
||||
# 关键断言:坐标从不可变原 PDF(当前事实)恢复,而非停留在缺坐标的冻结快照。
|
||||
assert restored['coordinate_evidence']['page_glyphs']['1'][0]['text'] == 'H'
|
||||
assert restored['coordinate_evidence']['tables']['table-1'][0]['text'] == 'H'
|
||||
|
||||
|
||||
def test_on_demand_evidence_prefers_current_layout_coordinates_over_stale_run_snapshot(app):
|
||||
"""同页同时存在时,当前 Layout 是最新事实,不能被旧 Run 快照坐标覆盖。"""
|
||||
def test_on_demand_evidence_prefers_current_layout_coordinates_over_stale_run_snapshot(app, monkeypatch):
|
||||
"""外部化契约:当前 Layout 坐标外置后,恢复读不可变原 PDF,过期 Run 快照不覆盖。"""
|
||||
with app.app_context():
|
||||
document = _document()
|
||||
current = record_inline_layout_snapshot(document, {
|
||||
@@ -633,19 +681,32 @@ def test_on_demand_evidence_prefers_current_layout_coordinates_over_stale_run_sn
|
||||
},
|
||||
})
|
||||
document.current_layout_version = current
|
||||
# 过期 Run 快照的坐标为空(缺 page_glyphs),不能作为坐标事实。
|
||||
stale_run_layout = {
|
||||
**_snapshot(),
|
||||
'coordinate_evidence': {
|
||||
'pages': {'1': {'width': 100, 'height': 200}},
|
||||
'page_glyphs': {'1': [{'text': 'STALE', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}}]},
|
||||
'sources': {'pages': {'1': 'ocr_coordinate'}},
|
||||
},
|
||||
}
|
||||
glyph = {'text': 'CURRENT', 'bbox': {'x0': 1, 'y0': 1, 'x1': 2, 'y1': 2}}
|
||||
page = SimpleNamespace(
|
||||
page_no=1, width=100, height=200, image=None,
|
||||
characters=[SimpleNamespace(model_dump=lambda mode='json': glyph)],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.file_assets.service.read_asset_bytes', lambda _asset: b'%PDF-test',
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.document_layout.native_pdf.extract_native_pdf_pages',
|
||||
lambda _content: [page],
|
||||
)
|
||||
|
||||
restored = ensure_on_demand_coordinate_evidence(
|
||||
document=document, layout=stale_run_layout, page_nos={1},
|
||||
)
|
||||
|
||||
# 关键断言:以不可变原 PDF(当前事实)恢复,而非信任过期快照。
|
||||
assert restored['coordinate_evidence']['page_glyphs']['1'][0]['text'] == 'CURRENT'
|
||||
assert restored['coordinate_evidence']['sources']['pages']['1'] == 'pdf_coordinate'
|
||||
|
||||
|
||||
@@ -87,10 +87,20 @@ def test_quality_reconstruction_does_not_reuse_table_glyphs_on_later_text_pages(
|
||||
}
|
||||
region = SimpleNamespace(row_reconstruction_mode='fixed_subrows', continuation_rule=SimpleNamespace(allow_cross_page=False))
|
||||
raw_table = {'table_id': 'table-1', 'page_no': 1}
|
||||
assert quality._quality_page_characters(region=region, evidence=evidence, raw_table=raw_table, page_no=1) == [{'text': 'TABLE'}]
|
||||
assert quality._quality_page_characters(region=region, evidence=evidence, raw_table=raw_table, page_no=1) == [{'text': 'PAGE-1'}]
|
||||
assert quality._quality_page_characters(region=region, evidence=evidence, raw_table=raw_table, page_no=2) is None
|
||||
|
||||
|
||||
def test_quality_region_falls_back_to_table_glyphs_without_page_evidence():
|
||||
"""页级坐标未冻结时,盲测仍可使用同页表格字符完成历史样本回放。"""
|
||||
evidence = {'tables': {'table-1': [{'text': 'TABLE'}]}, 'page_glyphs': {}}
|
||||
|
||||
assert quality._region_characters_for_quality(
|
||||
region=SimpleNamespace(row_reconstruction_mode='fixed_subrows'),
|
||||
evidence=evidence, raw_table={'page_no': 1}, table_id='table-1',
|
||||
) == [{'text': 'TABLE'}]
|
||||
|
||||
|
||||
def test_quality_reconstruction_uses_own_page_glyphs_for_explicit_cross_page_region():
|
||||
"""关键断言:显式跨页区域只能使用后续页自己的 page glyphs。"""
|
||||
evidence = {
|
||||
@@ -965,3 +975,94 @@ def test_coordinate_v2_publish_promotes_approved_independent_suite(app):
|
||||
frozen_suite = db.session.get(ShippingDocumentProfileTestSuite, suite['id'])
|
||||
assert frozen_suite.profile_checksum == published['checksum']
|
||||
assert all(run.profile_checksum == published['checksum'] for run in frozen_suite.runs)
|
||||
|
||||
|
||||
def test_republish_identical_content_reuses_historical_promoted_suite(app):
|
||||
"""关键断言:同内容重复发布时复用历史发布凭证,新草稿集转为 superseded 而非撞唯一键。
|
||||
|
||||
复现路径:发布成功后人工把模板状态重置为 draft(checksum 与历史提升套件保留),
|
||||
重新走盲测并发布;发布 checksum 由规范化负载确定性复现,必须复用历史凭证。
|
||||
"""
|
||||
from app.models import ShippingDocumentProfileTestRun
|
||||
from app.services.shipping_notice import document_profile_quality_service as quality
|
||||
|
||||
with app.app_context():
|
||||
profile, user, _documents = _published_profile_with_samples()
|
||||
draft_checksum = str(profile.structure_fingerprint)
|
||||
published_checksum = str(profile.checksum)
|
||||
occupant = ShippingDocumentProfileTestSuite(
|
||||
profile_id=profile.id, profile_checksum=published_checksum, status='approved', created_by_id=user.id,
|
||||
)
|
||||
new_suite = ShippingDocumentProfileTestSuite(
|
||||
profile_id=profile.id, profile_checksum=draft_checksum, status='approved', created_by_id=user.id,
|
||||
)
|
||||
db.session.add_all([occupant, new_suite])
|
||||
db.session.flush()
|
||||
db.session.add_all([
|
||||
ShippingDocumentProfileTestRun(
|
||||
suite_id=occupant.id, profile_checksum=published_checksum, status='passed',
|
||||
sample_count=1, passed_sample_count=1, executed_by_id=user.id,
|
||||
),
|
||||
ShippingDocumentProfileTestRun(
|
||||
suite_id=new_suite.id, profile_checksum=draft_checksum, status='passed',
|
||||
sample_count=1, passed_sample_count=1, executed_by_id=user.id,
|
||||
),
|
||||
])
|
||||
db.session.flush()
|
||||
|
||||
quality.promote_approved_suite_for_publish(
|
||||
profile=profile, draft_checksum=draft_checksum, published_checksum=published_checksum, actor_id=user.id,
|
||||
)
|
||||
db.session.flush()
|
||||
|
||||
# 历史凭证保持原样,仍是发布 checksum 的唯一持有者。
|
||||
assert occupant.status == 'approved'
|
||||
assert occupant.profile_checksum == published_checksum
|
||||
assert all(run.profile_checksum == published_checksum for run in occupant.runs)
|
||||
# 新草稿集降级为 superseded,保留自身运行历史供审计,不重写 checksum。
|
||||
assert new_suite.status == 'superseded'
|
||||
assert new_suite.profile_checksum == draft_checksum
|
||||
assert all(run.profile_checksum == draft_checksum for run in new_suite.runs)
|
||||
reuse_audits = ShippingOrderDocumentProfileAudit.query.filter_by(
|
||||
profile_id=profile.id, event_type='blind_test_suite_superseded',
|
||||
).all()
|
||||
assert any(
|
||||
(audit.detail_json or {}).get('reason_code') == 'republish_identical_content'
|
||||
and (audit.detail_json or {}).get('reused_suite_id') == occupant.id
|
||||
for audit in reuse_audits
|
||||
)
|
||||
|
||||
|
||||
def test_promote_rejects_invalid_published_checksum_occupant(app):
|
||||
"""关键断言:占用发布 checksum 的套件不是有效凭证时拒绝发布,禁止静默覆盖历史证据。"""
|
||||
from app.core.errors import ConflictError
|
||||
from app.models import ShippingDocumentProfileTestRun
|
||||
from app.services.shipping_notice import document_profile_quality_service as quality
|
||||
|
||||
with app.app_context():
|
||||
profile, user, _documents = _published_profile_with_samples()
|
||||
draft_checksum = str(profile.structure_fingerprint)
|
||||
published_checksum = str(profile.checksum)
|
||||
invalid_occupant = ShippingDocumentProfileTestSuite(
|
||||
profile_id=profile.id, profile_checksum=published_checksum, status='approved', created_by_id=user.id,
|
||||
)
|
||||
new_suite = ShippingDocumentProfileTestSuite(
|
||||
profile_id=profile.id, profile_checksum=draft_checksum, status='approved', created_by_id=user.id,
|
||||
)
|
||||
db.session.add_all([invalid_occupant, new_suite])
|
||||
db.session.flush()
|
||||
db.session.add(ShippingDocumentProfileTestRun(
|
||||
suite_id=invalid_occupant.id, profile_checksum=published_checksum, status='failed',
|
||||
sample_count=1, passed_sample_count=0, executed_by_id=user.id,
|
||||
))
|
||||
db.session.flush()
|
||||
|
||||
with pytest.raises(ConflictError) as caught:
|
||||
quality.promote_approved_suite_for_publish(
|
||||
profile=profile, draft_checksum=draft_checksum, published_checksum=published_checksum, actor_id=user.id,
|
||||
)
|
||||
assert getattr(caught.value, 'code', None) == 'SHIPPING.ORDER_DOCUMENT_PROFILE_TEST_SUITE_CHECKSUM_CONFLICT'
|
||||
# 冲突时两个套件都不得被改动,保持发布事务可整体回滚。
|
||||
assert invalid_occupant.profile_checksum == published_checksum
|
||||
assert new_suite.status == 'approved'
|
||||
assert new_suite.profile_checksum == draft_checksum
|
||||
@@ -90,28 +90,50 @@ def test_rpa_upload_failures_keep_manual_retry_action():
|
||||
assert projected['next_action'] == 'retry_freight_upload_rpa'
|
||||
|
||||
|
||||
def test_inventory_preparation_reason_code_from_pending():
|
||||
"""履约库存准备原因须按 pending_human_reason 细分,不得一律 preparation_failed。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice.constants import PH_RPA_EXHAUSTED, PH_RPA_PENDING
|
||||
def test_inventory_preparation_reason_code_from_pending(app):
|
||||
"""
|
||||
履约库存准备原因须按 pending_human_reason 细分,不得一律 preparation_failed。
|
||||
|
||||
核心逻辑:task_blocking_reason 以 ShippingOrderTask.active_process_execution_id 为空的
|
||||
pending_human_reason 为唯一事实源;已落文件但无有效行 → inventory_file_empty,
|
||||
尚未生成库存文件(inv_unavail)→ inventory_file_missing。
|
||||
"""
|
||||
from app import db
|
||||
from app.models import ShippingOrderTask
|
||||
from app.services.shipping_notice.constants import (
|
||||
PH_INV_UNAVAIL,
|
||||
PH_RPA_EXHAUSTED,
|
||||
PH_RPA_PENDING,
|
||||
)
|
||||
from app.services.shipping_notice.process_gate_bridge import (
|
||||
inventory_preparation_reason_code,
|
||||
manual_upload_reason_code,
|
||||
)
|
||||
|
||||
queued = SimpleNamespace(id=None, pending_human_reason=PH_RPA_PENDING, inventory_lines_json=None)
|
||||
exhausted = SimpleNamespace(id=None, pending_human_reason=PH_RPA_EXHAUSTED, inventory_lines_json=None)
|
||||
# 空列表=已落文件但无有效行;None=尚未生成库存文件
|
||||
empty = SimpleNamespace(id=None, pending_human_reason=None, inventory_lines_json=[])
|
||||
missing = SimpleNamespace(id=None, pending_human_reason=None, inventory_lines_json=None)
|
||||
def _pending_task(task_no: str, pending_human_reason: str | None) -> ShippingOrderTask:
|
||||
"""创建并持久化一个无活动执行的 OT;task_blocking_reason 直接读取 pending_human_reason。"""
|
||||
task = ShippingOrderTask(
|
||||
task_no=task_no, user_id=1, pending_human_reason=pending_human_reason,
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
return task
|
||||
|
||||
# [STEP 1] RPA 排队/耗尽由 pending_human_reason 细分(不能退化为 preparation_failed)
|
||||
queued = _pending_task('OT-QUEUED', PH_RPA_PENDING)
|
||||
exhausted = _pending_task('OT-EXHAUSTED', PH_RPA_EXHAUSTED)
|
||||
assert inventory_preparation_reason_code(queued) == 'inventory_rpa_queued'
|
||||
assert inventory_preparation_reason_code(exhausted) == 'inventory_rpa_exhausted'
|
||||
|
||||
# [STEP 2] 空列表 = 已落文件但无有效行 → 生产按活动库存行数判定为空;
|
||||
# None = 尚未生成库存文件 → 由 inv_unavail 语义命中 inventory_file_missing。
|
||||
empty = _pending_task('OT-EMPTY', None)
|
||||
missing = _pending_task('OT-MISSING', PH_INV_UNAVAIL)
|
||||
assert inventory_preparation_reason_code(empty) == 'inventory_file_empty'
|
||||
assert inventory_preparation_reason_code(missing) == 'inventory_file_missing'
|
||||
|
||||
upload_failed = SimpleNamespace(
|
||||
id=None, pending_human_reason='upload_rpa_failed',
|
||||
)
|
||||
# [STEP 3] 上传 RPA 失败归属 freight_upload_rpa,而非人工交接
|
||||
upload_failed = _pending_task('OT-UPLOAD-RPA-FAILED', 'upload_rpa_failed')
|
||||
assert manual_upload_reason_code(upload_failed) == 'upload_rpa_failed'
|
||||
|
||||
|
||||
@@ -121,14 +143,16 @@ def test_build_explainability_reason_unknown_requires_request_id():
|
||||
|
||||
核心逻辑:禁止只显示「系统错误」而不带追溯号。
|
||||
"""
|
||||
# [STEP 1] 已知码保留责任方与动作
|
||||
# [STEP 1] 已知码保留责任方与动作(source_disabled 归属库存源不可用明细,
|
||||
# 生产 meta 定义为 admin + retry_with_latest_rules;open_inventory_source_review
|
||||
# 并非注册动作码,build_explainability_reason 会将其丢弃,故断言必须跟随生产值。)
|
||||
known = build_explainability_reason(
|
||||
reason_code='source_disabled',
|
||||
details={'source_code': 'DSV360_AWSSG'},
|
||||
)
|
||||
assert known['reason_code'] == 'source_disabled'
|
||||
assert known['responsible_party'] == 'admin'
|
||||
assert known['next_action'] == 'open_inventory_source_review'
|
||||
assert known['next_action'] == 'retry_with_latest_rules'
|
||||
assert known['details']['source_code'] == 'DSV360_AWSSG'
|
||||
|
||||
# [STEP 2] 未知码强制降级并要求 request_id
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
"""通知准备阶段 Excel 资格边界测试。"""
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
|
||||
def test_order_task_status_does_not_query_formal_notice(monkeypatch) -> None:
|
||||
"""通知准备阶段的 OT 状态推导不得提前读取正式发货通知单。"""
|
||||
from app.services.shipping_notice import process_gate_bridge as bridge
|
||||
|
||||
class OrderTask:
|
||||
id = 21
|
||||
|
||||
# 履约状态必须来自当前行级 Match/File 事实,而不是 OT 旧投影字段。
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_file_store.inventory_matches_complete_for_task',
|
||||
lambda _task: True,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.inventory_file_store.current_inventory_matches_have_shortage',
|
||||
lambda _task: False,
|
||||
)
|
||||
|
||||
class UnexpectedNoticeQuery:
|
||||
@property
|
||||
def query(self):
|
||||
raise AssertionError('通知准备不应查询 ShippingNotice')
|
||||
|
||||
monkeypatch.setattr(bridge, 'ShippingOrderTask', OrderTask)
|
||||
monkeypatch.setattr(bridge, 'ShippingNotice', UnexpectedNoticeQuery)
|
||||
|
||||
assert bridge._derived_fulfillment_status(OrderTask()) == 'matched'
|
||||
|
||||
|
||||
def test_excel_readiness_uses_order_task_before_formal_notice_exists(monkeypatch) -> None:
|
||||
"""OT 已满足库存门禁时,资格检查不得要求先创建 ShippingNotice。"""
|
||||
from app.services.shipping_notice import process_gate_executor as executor
|
||||
|
||||
order_task = SimpleNamespace(id=21, task_no='OT-READY', match_status='fulfillable')
|
||||
outcomes: list[dict] = []
|
||||
monkeypatch.setattr(executor, '_resolve_order_task', lambda _execution: order_task)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.fulfillment_workflow.excel_gate_error',
|
||||
lambda task: None if task is order_task else 'wrong_task',
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.process_gate_bridge.apply_gate_outcome',
|
||||
lambda **kwargs: outcomes.append(kwargs),
|
||||
)
|
||||
|
||||
result = executor._handle_recheck_excel_readiness(
|
||||
execution=SimpleNamespace(execution_no='SPE-OT-READY', task_id=21),
|
||||
gate=SimpleNamespace(gate_code='excel_readiness'),
|
||||
payload={'actor_user_id': 9},
|
||||
)
|
||||
|
||||
assert result['outcome'] == 'passed'
|
||||
assert outcomes[0]['passed'] is True
|
||||
@@ -20,7 +20,8 @@ from app.models import (
|
||||
ShippingExcelTemplate, ShippingInventoryParsingProfile, ShippingInventorySource, ShippingOrderExtraction,
|
||||
ShippingOrderField, ShippingOrderFieldDecision, ShippingOrderFieldValue, ShippingOrderLine,
|
||||
ShippingCustomer, ShippingInventoryField, ShippingInventoryFile, ShippingOrderSchema, ShippingOrderSchemaVersion,
|
||||
ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingRpaProfile, ShippingNotice,
|
||||
ShippingOrderSnapshot, ShippingOrderSnapshotLine, ShippingRpaProfile, ShippingNotice, ShippingOrderTask,
|
||||
ShippingNoticeLineInventoryMatch, ShippingTaskInventoryLink,
|
||||
)
|
||||
from app.services.shipping_notice import excel_template
|
||||
from app.services.shipping_notice.export import (
|
||||
@@ -32,6 +33,7 @@ from app.services.shipping_notice.export import (
|
||||
generate_shipment_excel,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_workflow import _commit_generated_export
|
||||
from app.services.shipping_notice.notice_line_service import replace_notice_lines_from_snapshot
|
||||
from app.services.shipping_notice.inventory_file_store import (
|
||||
active_inventory_lines_for_task,
|
||||
replace_task_inventory_link,
|
||||
@@ -76,11 +78,32 @@ def test_only_templates_consuming_system_warehouse_id_require_task_warehouse_fac
|
||||
]) is True
|
||||
|
||||
|
||||
def test_unique_notice_warehouse_id_for_header_mapping():
|
||||
"""Header 写 warehouse_id:唯一库位放行,多库位拒绝,空库位返回 None。"""
|
||||
from types import SimpleNamespace
|
||||
from app.services.shipping_notice.export import _unique_notice_warehouse_id
|
||||
|
||||
assert _unique_notice_warehouse_id([
|
||||
SimpleNamespace(inventory_warehouse_id='AWSSG'),
|
||||
SimpleNamespace(inventory_warehouse_id='awssg'),
|
||||
]) == 'AWSSG'
|
||||
assert _unique_notice_warehouse_id([
|
||||
SimpleNamespace(inventory_warehouse_id=None),
|
||||
SimpleNamespace(inventory_warehouse_id=''),
|
||||
]) is None
|
||||
with pytest.raises(ValueError, match='多库位'):
|
||||
_unique_notice_warehouse_id([
|
||||
SimpleNamespace(inventory_warehouse_id='AWSSG'),
|
||||
SimpleNamespace(inventory_warehouse_id='MOW'),
|
||||
])
|
||||
|
||||
|
||||
def _freeze_export_snapshot(
|
||||
task: ShippingNotice, extraction: ShippingOrderExtraction, version: ShippingOrderSchemaVersion,
|
||||
task: ShippingOrderTask, extraction: ShippingOrderExtraction, version: ShippingOrderSchemaVersion,
|
||||
*, header: dict[int, object] | None = None, lines: list[tuple[int, int, str, int, str]] | None = None,
|
||||
) -> None:
|
||||
"""为导出测试建立冻结订单和可用库存核验,避免测试绕过正式履约门禁。"""
|
||||
customer_id: int | None = None, inventory_file_id: int | None = None,
|
||||
) -> ShippingOrderSnapshot:
|
||||
"""为导出测试在 OT 上建立冻结订单和可用库存核验,避免测试绕过正式履约门禁。"""
|
||||
field_codes = {
|
||||
str(item.get('field_id')): str(item.get('field_code') or '')
|
||||
for item in (version.definition_json or {}).get('fields') or []
|
||||
@@ -91,6 +114,7 @@ def _freeze_export_snapshot(
|
||||
)
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
task_id=task.id, extraction_id=extraction.id, schema_version_id=version.id,
|
||||
customer_id=customer_id,
|
||||
order_data_version=1, rule_versions_json={},
|
||||
header_values_json={str(key): value for key, value in (header or {}).items()},
|
||||
customer_po_number=po_number,
|
||||
@@ -99,20 +123,59 @@ def _freeze_export_snapshot(
|
||||
db.session.flush()
|
||||
for position, field_id, part_number, qty, reservation_id in lines or []:
|
||||
db.session.add(ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id, position=position, part_number=part_number,
|
||||
reservation_id=reservation_id, qty=Decimal(str(qty)),
|
||||
snapshot_id=snapshot.id, position=position, line_no=position,
|
||||
part_number=part_number, reservation_id=reservation_id, qty=Decimal(str(qty)),
|
||||
field_values_json={str(field_id): part_number},
|
||||
))
|
||||
db.session.flush()
|
||||
task.order_snapshot_id = snapshot.id
|
||||
record_inventory_verification(
|
||||
task, inventory_snapshot_id=task.inventory_snapshot_id, source_config_version='test-v1',
|
||||
task, inventory_snapshot_id=inventory_file_id, source_config_version='test-v1',
|
||||
line_results=[{
|
||||
'reservation_id': line.reservation_id, 'part_number': line.part_number,
|
||||
'required_qty': line.qty, 'available_qty': line.qty, 'line_status': 'ok',
|
||||
} for line in snapshot.lines],
|
||||
)
|
||||
db.session.flush()
|
||||
return snapshot
|
||||
|
||||
|
||||
def _materialize_export_notice(
|
||||
*, ot: ShippingOrderTask, snapshot: ShippingOrderSnapshot, inventory_file: ShippingInventoryFile,
|
||||
source_code: str, notice_no: str,
|
||||
) -> ShippingNotice:
|
||||
"""从 OT 的冻结快照构造正式 Notice、NoticeLine、匹配事实与活动库存链接。
|
||||
|
||||
导出链路只接受已物化的正式 Notice;OT 承载订单/库存事实,Notice 通过
|
||||
order_task_id 指向 OT。行级匹配事实按 OT id 落库,库存 Link 绑定 Notice 本身。
|
||||
"""
|
||||
notice = ShippingNotice(
|
||||
task_no=notice_no, source_type='manual', order_task_id=ot.id, user_id=ot.user_id,
|
||||
)
|
||||
db.session.add(notice)
|
||||
db.session.flush()
|
||||
replace_notice_lines_from_snapshot(
|
||||
notice_id=notice.id, snapshot=snapshot,
|
||||
inventory_facts_by_snapshot_line_id={
|
||||
int(line.id): {
|
||||
'inventory_source_code': source_code,
|
||||
'inventory_file_id': int(inventory_file.id),
|
||||
'inventory_warehouse_id': inventory_file.warehouse_id,
|
||||
}
|
||||
for line in snapshot.lines
|
||||
},
|
||||
)
|
||||
for line in snapshot.lines:
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
task_id=ot.id, snapshot_line_id=line.id, line_no=line.line_no,
|
||||
match_result='matched', inventory_status='ready',
|
||||
inventory_snapshot_id=inventory_file.id, inventory_source_code=source_code,
|
||||
is_current=True, detail_json={},
|
||||
))
|
||||
db.session.flush()
|
||||
replace_task_inventory_link(notice, inventory_file, role='owner')
|
||||
db.session.flush()
|
||||
return notice
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
@@ -153,23 +216,21 @@ def _workbook_upload() -> FileStorage:
|
||||
def test_filename_pattern_supports_business_number_and_split_business_variables():
|
||||
"""业务单号与客户日期流水变量均从业务单快照渲染,不能依赖当前客户主数据。"""
|
||||
task = ShippingNotice(
|
||||
task_no='TASK-FILENAME', inventory_source_code='DBS', business_no='WYC26060201',
|
||||
customer_short_code_snapshot='WYC', business_date=date(2026, 6, 2), business_sequence_value=1,
|
||||
task_no='TASK-FILENAME', business_no='WYC26060201',
|
||||
business_date=date(2026, 6, 2), business_sequence_value=1,
|
||||
)
|
||||
template = ShippingExcelTemplate(
|
||||
template_code='FILENAME', display_name='Filename',
|
||||
definition_json={'filename_pattern': '{business_no}_{customer_short_code}{business_date}{sequence}_{source_code}.xlsx'},
|
||||
definition_json={'filename_pattern': '{business_no}_{business_date}_{sequence}.xlsx'},
|
||||
)
|
||||
|
||||
assert _filename(task, template) == 'WYC26060201_WYC26060201_DBS.xlsx'
|
||||
assert _filename(task, template) == 'WYC26060201_260602_01.xlsx'
|
||||
|
||||
|
||||
def test_inventory_execution_prefers_active_link_and_does_not_overwrite_task_cache(app, tmp_path):
|
||||
"""业务执行必须使用活动库存 Link,忽略请求库存和旧任务缓存。"""
|
||||
"""业务执行必须使用活动库存 Link,忽略请求库存。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no='TASK-INVENTORY-SOURCE', inventory_lines_json=[{'part_number': 'STALE'}],
|
||||
)
|
||||
task = ShippingOrderTask(task_no='OT-INVENTORY-SOURCE', user_id=1)
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-INVENTORY-SOURCE', storage_path=str(tmp_path / 'inventory.xlsx'),
|
||||
inventory_lines_json=[{'part_number': 'ACTIVE'}], line_count=1,
|
||||
@@ -185,22 +246,20 @@ def test_inventory_execution_prefers_active_link_and_does_not_overwrite_task_cac
|
||||
)
|
||||
|
||||
assert resolved == [{'part_number': 'ACTIVE'}]
|
||||
assert task.inventory_lines_json == [{'part_number': 'STALE'}]
|
||||
|
||||
|
||||
def test_inventory_execution_keeps_legacy_fallback_without_active_link(app):
|
||||
"""无活动 Link 的历史任务仍可读取请求库存或旧缓存,避免升级后无法恢复。"""
|
||||
"""无活动 Link 的历史任务仍可读取请求库存,避免升级后无法恢复。"""
|
||||
with app.app_context():
|
||||
task = ShippingNotice(
|
||||
task_no='TASK-INVENTORY-LEGACY', inventory_lines_json=[{'part_number': 'CACHE'}],
|
||||
)
|
||||
task = ShippingOrderTask(task_no='OT-INVENTORY-LEGACY', user_id=1)
|
||||
db.session.add(task)
|
||||
db.session.flush()
|
||||
|
||||
assert resolve_inventory_lines_for_execution(
|
||||
task, legacy_payload_lines=[{'part_number': 'PAYLOAD'}],
|
||||
) == [{'part_number': 'PAYLOAD'}]
|
||||
assert resolve_inventory_lines_for_execution(task) == [{'part_number': 'CACHE'}]
|
||||
# 既无活动 Link 也无旧缓存时返回空,不伪造或回退到其它任务库存。
|
||||
assert resolve_inventory_lines_for_execution(task) == []
|
||||
|
||||
|
||||
def test_active_inventory_json_is_not_silently_reparsed_from_stale_file(app, tmp_path, monkeypatch):
|
||||
@@ -208,7 +267,7 @@ def test_active_inventory_json_is_not_silently_reparsed_from_stale_file(app, tmp
|
||||
with app.app_context():
|
||||
storage_path = tmp_path / 'stale.xlsx'
|
||||
storage_path.write_bytes(b'stale-source')
|
||||
task = ShippingNotice(task_no='TASK-INVENTORY-NO-REPARSE')
|
||||
task = ShippingOrderTask(task_no='OT-INVENTORY-NO-REPARSE', user_id=1)
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-INVENTORY-NO-REPARSE', storage_path=str(storage_path),
|
||||
inventory_lines_json=[{'1': 'PN-A', '2': 'RSV-A', '6': 'ODM-FIXED'}],
|
||||
@@ -269,6 +328,8 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path):
|
||||
"""发布模板后按稳定 field_id 写入订单值,并锁定模板、Schema、Profile 与库存快照。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
from tests.conftest import confirm_test_customer_resolution
|
||||
|
||||
schema = ShippingOrderSchema(schema_code=DEFAULT_SCHEMA_FAMILY_CODE, display_name='Order')
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
@@ -315,10 +376,15 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path):
|
||||
parsing_profile_id=parsing.id, excel_template_id=published['id'], warehouse_resolution_mode='fixed',
|
||||
fixed_warehouse_id='DUB', report_path_json={}, query_parameters_json=[],
|
||||
)
|
||||
extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted')
|
||||
ot = ShippingOrderTask(task_no='OT-EXPORT-1', user_id=1, status='ready', current_step='customer_review')
|
||||
db.session.add(ot)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
task_id=ot.id, schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted',
|
||||
)
|
||||
db.session.add_all([source, extraction])
|
||||
db.session.flush()
|
||||
order_line = ShippingOrderLine(extraction_id=extraction.id, position=1, line_key='1')
|
||||
order_line = ShippingOrderLine(extraction_id=extraction.id, position=1, line_no=2)
|
||||
db.session.add(order_line)
|
||||
db.session.flush()
|
||||
header_decision = ShippingOrderFieldDecision(extraction_id=extraction.id, field_id=customer.id, decision_status='accepted', resolved_value_json='acme')
|
||||
@@ -336,21 +402,26 @@ def test_published_template_generates_dynamic_artifact(app, tmp_path):
|
||||
)
|
||||
db.session.add(confirmed_customer)
|
||||
db.session.flush()
|
||||
task = ShippingNotice(
|
||||
task_no='TASK-EXPORT-1', current_order_extraction_id=extraction.id, inventory_source_code='DUB',
|
||||
customer_id=confirmed_customer.id,
|
||||
customer_resolution_status='confirmed',
|
||||
# 此模板只消费 ODM 等 inventory_field;任务级 Warehouse ID 缺失不应阻断导出。
|
||||
inventory_warehouse_id=None, inventory_lines_json=[{
|
||||
confirm_test_customer_resolution(ot, customer=confirmed_customer, extraction=extraction)
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-EXPORT-1', user_id=None,
|
||||
source_file_name='inventory.xlsx', storage_path=str(tmp_path / 'inventory.xlsx'),
|
||||
inventory_lines_json=[{
|
||||
_inventory_field_id('part_number'): 'PN-1', _inventory_field_id('odm_id'): 'ODM-9',
|
||||
}], inventory_snapshot_id=None,
|
||||
}],
|
||||
line_count=1, share_mode='task_only', warehouse_id='DUB', source_code='DUB', snapshot_status='ready',
|
||||
)
|
||||
db.session.add(task)
|
||||
db.session.add(inventory_file)
|
||||
db.session.flush()
|
||||
_freeze_export_snapshot(
|
||||
task, extraction, version,
|
||||
snapshot = _freeze_export_snapshot(
|
||||
ot, extraction, version,
|
||||
header={customer.id: 'acme', po_number.id: '16754796'},
|
||||
lines=[(1, part.id, 'PN-1', 1, '1000000001')],
|
||||
customer_id=confirmed_customer.id, inventory_file_id=inventory_file.id,
|
||||
)
|
||||
# 此模板只消费 ODM 等 inventory_field;任务级 Warehouse ID 缺失不应阻断导出。
|
||||
task = _materialize_export_notice(
|
||||
ot=ot, snapshot=snapshot, inventory_file=inventory_file, source_code='DUB', notice_no='TASK-EXPORT-1',
|
||||
)
|
||||
|
||||
assert task.business_no is None
|
||||
@@ -427,7 +498,7 @@ def test_export_mapping_uses_sequence_but_never_derives_formal_line_amount(app):
|
||||
|
||||
assert _mapping_value(
|
||||
{'source_kind': 'order_field', 'source_key': fields['line_no'].id, 'formatter': 'integer', 'row_mode': 'line'},
|
||||
task=task, order_values={}, inventory_values={}, export_sequence=1,
|
||||
task=task, order_values={}, inventory_values={}, notice_line_no=1,
|
||||
) == 1
|
||||
assert _mapping_value(
|
||||
{'source_kind': 'order_field', 'source_key': fields['line_amount_with_tax'].id, 'formatter': 'decimal', 'row_mode': 'line'},
|
||||
@@ -523,6 +594,8 @@ def test_export_matches_inventory_by_profile_keys_not_row_position(app, tmp_path
|
||||
"""库存行顺序与订单相反时仍须按稳定 match_keys 写入正确 ODM,禁止按数组下标配对。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
from tests.conftest import confirm_test_customer_resolution
|
||||
|
||||
schema = ShippingOrderSchema(schema_code=DEFAULT_SCHEMA_FAMILY_CODE, display_name='Order')
|
||||
db.session.add(schema); db.session.flush()
|
||||
part = _lookup_standard_fields('part_number')['part_number']
|
||||
@@ -552,10 +625,16 @@ def test_export_matches_inventory_by_profile_keys_not_row_position(app, tmp_path
|
||||
parsing_profile_id=parsing.id, excel_template_id=published['id'], warehouse_resolution_mode='fixed',
|
||||
fixed_warehouse_id='DUB', report_path_json={}, query_parameters_json=[],
|
||||
))
|
||||
extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted')
|
||||
customer = ShippingCustomer(standard_name='键控匹配客户', short_code='KEY', status='active')
|
||||
db.session.add(customer); db.session.flush()
|
||||
ot = ShippingOrderTask(task_no='OT-KEYED', user_id=1, status='ready', current_step='customer_review')
|
||||
db.session.add(ot); db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
task_id=ot.id, schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction); db.session.flush()
|
||||
for position, value in enumerate(('PN-A', 'PN-B'), start=1):
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=position, line_key=str(position))
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=position, line_no=position + 1)
|
||||
db.session.add(line); db.session.flush()
|
||||
decision = ShippingOrderFieldDecision(
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=part.id,
|
||||
@@ -566,20 +645,27 @@ def test_export_matches_inventory_by_profile_keys_not_row_position(app, tmp_path
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=part.id,
|
||||
value_text=value, decision_id=decision.id,
|
||||
))
|
||||
task = ShippingNotice(
|
||||
task_no='TASK-KEYED', current_order_extraction_id=extraction.id, inventory_source_code='KEYED',
|
||||
inventory_warehouse_id='DUB', inventory_lines_json=[
|
||||
confirm_test_customer_resolution(ot, customer=customer, extraction=extraction)
|
||||
inventory_file = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-KEYED', user_id=None, source_file_name='keyed.xlsx',
|
||||
storage_path=str(tmp_path / 'keyed.xlsx'),
|
||||
inventory_lines_json=[
|
||||
{_inventory_field_id('part_number'): 'PN-B', _inventory_field_id('odm_id'): 'ODM-B'},
|
||||
{_inventory_field_id('part_number'): 'PN-A', _inventory_field_id('odm_id'): 'ODM-A'},
|
||||
],
|
||||
line_count=2, share_mode='task_only', warehouse_id='DUB', source_code='KEYED', snapshot_status='ready',
|
||||
)
|
||||
db.session.add(task); db.session.flush()
|
||||
_freeze_export_snapshot(
|
||||
task, extraction, version,
|
||||
db.session.add(inventory_file); db.session.flush()
|
||||
snapshot = _freeze_export_snapshot(
|
||||
ot, extraction, version,
|
||||
lines=[
|
||||
(1, part.id, 'PN-A', 1, '1000000002'),
|
||||
(2, part.id, 'PN-B', 1, '1000000003'),
|
||||
],
|
||||
customer_id=customer.id, inventory_file_id=inventory_file.id,
|
||||
)
|
||||
task = _materialize_export_notice(
|
||||
ot=ot, snapshot=snapshot, inventory_file=inventory_file, source_code='KEYED', notice_no='TASK-KEYED',
|
||||
)
|
||||
|
||||
path, _filename, _artifact = generate_shipment_excel(task)
|
||||
@@ -700,6 +786,8 @@ def test_export_uses_active_inventory_link_instead_of_stale_task_cache(app, tmp_
|
||||
"""导出应读取活动库存 Link;无 Link 时旧缓存冲突仍须阻断且不留半成品。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
from tests.conftest import confirm_test_customer_resolution
|
||||
|
||||
schema = ShippingOrderSchema(schema_code=DEFAULT_SCHEMA_FAMILY_CODE, display_name='Order')
|
||||
db.session.add(schema); db.session.flush()
|
||||
part = _lookup_standard_fields('part_number')['part_number']
|
||||
@@ -726,9 +814,15 @@ def test_export_uses_active_inventory_link_instead_of_stale_task_cache(app, tmp_
|
||||
parsing_profile_id=parsing.id, excel_template_id=published['id'], warehouse_resolution_mode='fixed',
|
||||
fixed_warehouse_id='DUB', report_path_json={}, query_parameters_json=[],
|
||||
))
|
||||
extraction = ShippingOrderExtraction(schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted')
|
||||
customer = ShippingCustomer(standard_name='模糊匹配客户', short_code='AMB', status='active')
|
||||
db.session.add(customer); db.session.flush()
|
||||
ot = ShippingOrderTask(task_no='OT-AMBIGUOUS', user_id=1, status='ready', current_step='customer_review')
|
||||
db.session.add(ot); db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
task_id=ot.id, schema_version_id=version.id, input_snapshot_hash='i' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction); db.session.flush()
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=1, line_key='1')
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=1, line_no=2)
|
||||
db.session.add(line); db.session.flush()
|
||||
decision = ShippingOrderFieldDecision(
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=part.id,
|
||||
@@ -739,17 +833,25 @@ def test_export_uses_active_inventory_link_instead_of_stale_task_cache(app, tmp_
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=part.id,
|
||||
value_text='PN-A', decision_id=decision.id,
|
||||
))
|
||||
task = ShippingNotice(
|
||||
task_no='TASK-AMBIGUOUS', current_order_extraction_id=extraction.id,
|
||||
inventory_source_code='AMBIGUOUS', inventory_warehouse_id='DUB', inventory_lines_json=[
|
||||
confirm_test_customer_resolution(ot, customer=customer, extraction=extraction)
|
||||
ambiguous_file = ShippingInventoryFile(
|
||||
inventory_file_no='SIF-AMBIGUOUS', user_id=None, source_file_name='ambiguous.xlsx',
|
||||
storage_path=str(tmp_path / 'ambiguous.xlsx'),
|
||||
inventory_lines_json=[
|
||||
{_inventory_field_id('part_number'): 'PN-A', _inventory_field_id('odm_id'): 'ODM-1'},
|
||||
{_inventory_field_id('part_number'): 'PN-A', _inventory_field_id('odm_id'): 'ODM-2'},
|
||||
],
|
||||
line_count=2, share_mode='task_only', warehouse_id='DUB', source_code='AMBIGUOUS',
|
||||
snapshot_status='ready',
|
||||
)
|
||||
db.session.add(task); db.session.flush()
|
||||
_freeze_export_snapshot(
|
||||
task, extraction, version,
|
||||
lines=[(1, part.id, 'PN-A', 1, '1000000004')],
|
||||
db.session.add(ambiguous_file); db.session.flush()
|
||||
snapshot = _freeze_export_snapshot(
|
||||
ot, extraction, version,
|
||||
lines=[(1, part.id, 'PN-A', 1, '1000000004')],
|
||||
customer_id=customer.id, inventory_file_id=ambiguous_file.id,
|
||||
)
|
||||
task = _materialize_export_notice(
|
||||
ot=ot, snapshot=snapshot, inventory_file=ambiguous_file, source_code='AMBIGUOUS', notice_no='TASK-AMBIGUOUS',
|
||||
)
|
||||
|
||||
with pytest.raises(ValueError, match='库存字段“ODM 编号”'):
|
||||
@@ -770,7 +872,9 @@ def test_export_uses_active_inventory_link_instead_of_stale_task_cache(app, tmp_
|
||||
db.session.add(inventory_file)
|
||||
db.session.flush()
|
||||
replace_task_inventory_link(task, inventory_file, role='owner')
|
||||
task.inventory_snapshot_id = inventory_file.id
|
||||
# 切换活动库存后,行级匹配事实须指向新快照;导出只读取活动 Link。
|
||||
for match in ShippingNoticeLineInventoryMatch.query.filter_by(task_id=ot.id, is_current=True).all():
|
||||
match.inventory_snapshot_id = inventory_file.id
|
||||
db.session.flush()
|
||||
|
||||
path, _filename_value, artifact = generate_shipment_excel(task)
|
||||
@@ -781,7 +885,6 @@ def test_export_uses_active_inventory_link_instead_of_stale_task_cache(app, tmp_
|
||||
finally:
|
||||
workbook.close()
|
||||
assert artifact.inventory_snapshot_id == inventory_file.id
|
||||
assert task.inventory_lines_json[0][_inventory_field_id('odm_id')] == 'ODM-1'
|
||||
|
||||
|
||||
def test_export_commit_failure_removes_generated_file(app, tmp_path, monkeypatch):
|
||||
|
||||
Loaded 100 of 691 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user