feat(in-transit-transfer): 实现在途仓自动调拨Agent一期完整功能
包含后端服务层、任务处理器与消费Worker、前端聊天组件、数据库模型与迁移脚本、测试用例,同时新增外部系统连接器框架基础能力并更新相关文档。
This commit is contained in:
1 parent
f3050164d0
commit
6b53b563e7
177 files changed
+17260
-36
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,146 @@
|
||||
"""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
|
||||
@@ -651,6 +651,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")
|
||||
@@ -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,64 @@
|
||||
"""tests/services/integration_connector/test_migration.py
|
||||
|
||||
用途:验证 Integration Connector 迁移可独立升级与回滚,且正确链在当前 head 之后。
|
||||
依赖:Alembic Operations、SQLAlchemy SQLite、ic1a2b3c4d5f 迁移。
|
||||
逻辑:空库升级后 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
|
||||
|
||||
|
||||
EXPECTED_TABLES = {
|
||||
'integration_credential_references',
|
||||
'integration_client_instances',
|
||||
'integration_interface_definitions',
|
||||
'integration_bindings',
|
||||
'integration_calls',
|
||||
}
|
||||
|
||||
|
||||
def _load_migration():
|
||||
"""加载连接器框架建表迁移。"""
|
||||
path = Path(__file__).parents[3] / 'migrations' / 'versions' / 'ic1a2b3c4d5f_add_integration_connector.py'
|
||||
spec = importlib.util.spec_from_file_location('integration_connector_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_migration_chains_after_head():
|
||||
"""新迁移必须挂接在既有链 head it1a2b3c4d5e 之后。"""
|
||||
migration = _load_migration()
|
||||
assert migration.revision == 'ic1a2b3c4d5f'
|
||||
assert migration.down_revision == 'it1a2b3c4d5e'
|
||||
|
||||
|
||||
def test_integration_connector_migration_round_trip():
|
||||
"""空库升级后 5 表存在;回滚后全部删除。"""
|
||||
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.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
|
||||
binding_indexes = {item['name'] for item in inspector.get_indexes('integration_bindings')}
|
||||
assert 'ix_integration_bindings_cap_env_status' in binding_indexes
|
||||
|
||||
migration.downgrade()
|
||||
assert EXPECTED_TABLES.isdisjoint(set(sa.inspect(connection).get_table_names()))
|
||||
@@ -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/endpoint 时 fail-closed 抛 TransportNotFrozenError。"""
|
||||
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"
|
||||
@@ -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
|
||||
@@ -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'
|
||||
@@ -0,0 +1,23 @@
|
||||
"""在途调拨 transfer 队列 Worker 入口测试。
|
||||
|
||||
用途:验证 workers/worker_in_transit_transfer.py 可导入、目标队列为 transfer,
|
||||
且模块导入不触发主循环(__main__ 守卫)。
|
||||
依赖:workers.worker_in_transit_transfer(import 级验证,不启动进程)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
|
||||
|
||||
def test_worker_module_imports_and_targets_transfer_queue():
|
||||
"""worker 模块可导入并声明 transfer 队列。"""
|
||||
module = importlib.import_module("workers.worker_in_transit_transfer")
|
||||
assert module.QUEUES == ["transfer"]
|
||||
|
||||
|
||||
def test_worker_main_guard_prevents_auto_start():
|
||||
"""模块导入不执行 main(__main__ 守卫)。"""
|
||||
module = importlib.import_module("workers.worker_in_transit_transfer")
|
||||
assert hasattr(module, "main")
|
||||
assert module.__name__ == "workers.worker_in_transit_transfer"
|
||||
Reference in new issue
Block a user