Merge branch 'dev' into snow
# Conflicts: # backend/app/api/chat.py # backend/app/services/admin/permission_service.py # frontend/src/features/user/views/UserProfilePage.vue
This commit is contained in:
commit
5faf86b184
691 files changed
+55948
-17728
No files matched your search
@@ -29,8 +29,8 @@ def _jwt_headers(user: User) -> dict:
|
||||
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")
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps)
|
||||
return deps
|
||||
|
||||
@@ -99,7 +99,7 @@ def test_create_precheck_returns_envelope_with_precheck_id(app, client, admin_he
|
||||
data = body["data"]
|
||||
assert data["precheck_id"].startswith("TPC-")
|
||||
assert data["precheck_hash"].startswith("sha256:")
|
||||
assert data["estimated_erp_write_count"] == 2
|
||||
assert data["estimated_external_write_count"] == 2
|
||||
assert body.get("request_id")
|
||||
|
||||
|
||||
@@ -136,6 +136,25 @@ def test_create_precheck_validates_source_codes(app, client, admin_headers, tran
|
||||
assert response.get_json()["success"] is False
|
||||
|
||||
|
||||
def test_create_precheck_accepts_transfer_type_and_rejects_placeholder(app, client, admin_headers, transfer_deps):
|
||||
"""transfer_type 合法值放行;占位类型(类型2/3)与非法值 → 400 fail-closed。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
"transfer_type": "in_transit_to_hub",
|
||||
})
|
||||
assert created.status_code == 201
|
||||
|
||||
for bad_type in ("hub_repair_out", "hub_to_hub", "bogus_type"):
|
||||
response = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
"transfer_type": bad_type,
|
||||
})
|
||||
assert response.status_code == 400, bad_type
|
||||
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={
|
||||
@@ -146,7 +165,7 @@ def test_restore_precheck_progress(app, client, admin_headers, transfer_deps):
|
||||
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"}
|
||||
assert {item["invoice_no"] for item in body["items"]} == {"HOM-001", "HOX-002"}
|
||||
|
||||
|
||||
def test_restore_unknown_precheck_404(app, client, admin_headers, transfer_deps):
|
||||
@@ -156,14 +175,14 @@ def test_restore_unknown_precheck_404(app, client, admin_headers, transfer_deps)
|
||||
|
||||
|
||||
def test_execute_precheck_creates_run_and_projects_documents(app, client, admin_headers, transfer_deps):
|
||||
"""执行预检 → 201 run_no;GET run 返回 ERP 单号聚合结果。"""
|
||||
"""执行预检 → 201 run_no;GET run 返回 外部系统 单号聚合结果。"""
|
||||
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"]},
|
||||
headers=admin_headers, json={"invoice_nos": ["HOM-001", "HOX-002"]},
|
||||
)
|
||||
assert executed.status_code == 201
|
||||
run_no = executed.get_json()["data"]["run_no"]
|
||||
@@ -172,7 +191,7 @@ def test_execute_precheck_creates_run_and_projects_documents(app, client, admin_
|
||||
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 len(result["external_documents"]) == 2
|
||||
assert result["exceptions"] == []
|
||||
|
||||
|
||||
@@ -190,7 +209,7 @@ def test_execute_unconfirmed_precheck_rejected(app, client, admin_headers, trans
|
||||
db.session.commit()
|
||||
response = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={"invoice_nos": ["INV-001"]},
|
||||
headers=admin_headers, json={"invoice_nos": ["HOM-001"]},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert response.get_json()["error"]["code"] == "TRANSFER_CONFIRMATION_REQUIRED"
|
||||
@@ -219,7 +238,7 @@ def test_cancel_run_marks_remaining_cancelled(app, client, admin_headers, transf
|
||||
}).get_json()["data"]
|
||||
executed = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={"invoice_nos": ["INV-001", "INV-002"]},
|
||||
headers=admin_headers, json={"invoice_nos": ["HOM-001", "HOX-002"]},
|
||||
)
|
||||
run_no = executed.get_json()["data"]["run_no"]
|
||||
# 模拟执行中状态:Run 回退 executing,INV-002 尚未开始
|
||||
@@ -228,9 +247,9 @@ def test_cancel_run_marks_remaining_cancelled(app, client, admin_headers, transf
|
||||
|
||||
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 = TransferInvoiceItem.query.filter_by(run_id=run.id, invoice_no="HOX-002").first()
|
||||
item.status = "ready_to_execute"
|
||||
item.erp_document_no = None
|
||||
item.external_document_no = None
|
||||
db.session.commit()
|
||||
response = client.post(f"{API_PREFIX}/runs/{run_no}/cancel", headers=admin_headers, json={
|
||||
"reason": "货源调整,停止剩余",
|
||||
@@ -248,7 +267,7 @@ def test_manual_close_item_requires_reason(app, client, admin_headers, transfer_
|
||||
with app.app_context():
|
||||
from app.models import TransferInvoiceItem
|
||||
|
||||
item = TransferInvoiceItem.query.filter_by(invoice_no="INV-001").first()
|
||||
item = TransferInvoiceItem.query.filter_by(invoice_no="HOM-001").first()
|
||||
item.status = "blocked_recoverable"
|
||||
item.result_code = "blocked_quantity_mismatch"
|
||||
db.session.commit()
|
||||
@@ -266,7 +285,7 @@ def test_manual_close_item_success(app, client, admin_headers, transfer_deps):
|
||||
with app.app_context():
|
||||
from app.models import TransferInvoiceItem
|
||||
|
||||
item = TransferInvoiceItem.query.filter_by(invoice_no="INV-001").first()
|
||||
item = TransferInvoiceItem.query.filter_by(invoice_no="HOM-001").first()
|
||||
item.status = "blocked_recoverable"
|
||||
item.result_code = "blocked_quantity_mismatch"
|
||||
db.session.commit()
|
||||
@@ -286,7 +305,7 @@ def test_exceptions_excel_download(app, transfer_db, client, admin_headers, tran
|
||||
}).get_json()["data"]
|
||||
executed = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={"invoice_nos": ["INV-001", "INV-002"]},
|
||||
headers=admin_headers, json={"invoice_nos": ["HOM-001", "HOX-002"]},
|
||||
)
|
||||
run_no = executed.get_json()["data"]["run_no"]
|
||||
response = client.get(f"{API_PREFIX}/runs/{run_no}/exceptions.xlsx", headers=admin_headers)
|
||||
@@ -308,7 +327,7 @@ def test_receipt_files_download_records_access_audit(app, transfer_db, client, a
|
||||
}).get_json()["data"]
|
||||
executed = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={"invoice_nos": ["INV-001", "INV-002"]},
|
||||
headers=admin_headers, json={"invoice_nos": ["HOM-001", "HOX-002"]},
|
||||
)
|
||||
run_no = executed.get_json()["data"]["run_no"]
|
||||
response = client.get(f"{API_PREFIX}/runs/{run_no}/receipt-files", headers=admin_headers)
|
||||
@@ -322,24 +341,24 @@ def test_receipt_files_download_records_access_audit(app, transfer_db, client, a
|
||||
|
||||
|
||||
def test_erp_inventory_download_records_access_audit(app, transfer_db, client, admin_headers, transfer_deps):
|
||||
"""下载预检冻结的 ERP 库存表 → 200(csv),记录访问审计。"""
|
||||
"""下载预检冻结的 外部系统 库存表 → 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"]},
|
||||
headers=admin_headers, json={"invoice_nos": ["HOM-001", "HOX-002"]},
|
||||
)
|
||||
run_no = executed.get_json()["data"]["run_no"]
|
||||
response = client.get(f"{API_PREFIX}/runs/{run_no}/erp-inventory", headers=admin_headers)
|
||||
response = client.get(f"{API_PREFIX}/runs/{run_no}/external-inventory", headers=admin_headers)
|
||||
assert response.status_code == 200
|
||||
assert "csv" in response.content_type
|
||||
assert b"INV-001" in response.data
|
||||
assert b"HOM-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()
|
||||
audit = TransferAuditEvent.query.filter_by(event_type="TRANSFER_EXTERNAL_INVENTORY_DOWNLOADED").first()
|
||||
assert audit is not None
|
||||
|
||||
|
||||
@@ -355,7 +374,7 @@ def test_downloads_forbidden_without_permission(app, transfer_db, client, admin_
|
||||
)
|
||||
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}/external-inventory",
|
||||
f"{API_PREFIX}/runs/{run_no}/exceptions.xlsx"):
|
||||
response = client.get(path, headers=unauthorized_headers)
|
||||
assert response.status_code == 403, path
|
||||
@@ -370,7 +389,7 @@ def test_execute_ignores_forged_warehouse_and_quantity(app, transfer_db, client,
|
||||
executed = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={
|
||||
"invoice_nos": ["INV-001"],
|
||||
"invoice_nos": ["HOM-001"],
|
||||
"from_warehouse": "FAKE-TRANSIT",
|
||||
"to_warehouse": "FAKE-HUB",
|
||||
"quantity": "1",
|
||||
@@ -379,7 +398,7 @@ def test_execute_ignores_forged_warehouse_and_quantity(app, transfer_db, client,
|
||||
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"]
|
||||
documents = run["result"]["external_documents"]
|
||||
assert documents[0]["from_warehouse"] == "DBS-TRANSIT" # 冻结值,非伪造值
|
||||
assert documents[0]["to_warehouse"] == "HUB-CN01"
|
||||
assert documents[0]["total_quantity"] == "1200"
|
||||
@@ -395,17 +414,17 @@ def test_backlog_list_and_summary(app, transfer_db, client, admin_headers, trans
|
||||
with app.app_context():
|
||||
from app.models import TransferInvoiceItem
|
||||
|
||||
item = TransferInvoiceItem.query.filter_by(invoice_no="INV-001").first()
|
||||
item = TransferInvoiceItem.query.filter_by(invoice_no="HOM-001").first()
|
||||
item.status = "blocked_recoverable"
|
||||
item.result_code = "blocked_quantity_mismatch"
|
||||
item.result_message = "收料 1200 / ERP 1000"
|
||||
item.result_message = "收料 1200 / 外部系统 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 "HOM-001" in invoice_set
|
||||
assert "HOX-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)
|
||||
@@ -446,3 +465,37 @@ def test_metrics_endpoint(app, transfer_db, client, admin_headers, transfer_deps
|
||||
data = response.get_json()["data"]
|
||||
assert "runs" in data and "items" in data and "backlog" in data
|
||||
assert "notification_failed_runs" in data["runs"]
|
||||
|
||||
|
||||
def test_requery_items_returns_envelope(app, client, admin_headers, monkeypatch, dbs_ready_file):
|
||||
"""POST /prechecks/{no}/items/requery → 200 envelope,逐票返回重查结果。
|
||||
|
||||
[断言意图] 回归防线(2026-09-21):该端点曾引用未定义的 _actor_id 导致
|
||||
500/SYSTEM.INTERNAL_ERROR;本用例锁定端点在真实鉴权链路下可完整执行,
|
||||
用户上下文(actor_id)随请求正确传递。
|
||||
"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") # 与文件 1200 不符 → blocked_quantity_mismatch
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps)
|
||||
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
})
|
||||
precheck_no = created.get_json()["data"]["precheck_id"]
|
||||
|
||||
response = client.post(
|
||||
f"{API_PREFIX}/prechecks/{precheck_no}/items/requery",
|
||||
headers=admin_headers,
|
||||
json={"invoice_nos": ["HOM-001"]},
|
||||
)
|
||||
assert response.status_code == 200
|
||||
body = response.get_json()
|
||||
assert body["success"] is True
|
||||
data = body["data"]
|
||||
assert data["precheck_no"] == precheck_no
|
||||
assert data["total"] == 1
|
||||
result = data["results"][0]
|
||||
assert result["invoice_no"] == "HOM-001"
|
||||
assert result["ok"] is True
|
||||
@@ -146,6 +146,69 @@ def test_client_instance_test_connection(app, client, admin_headers, fake_gatewa
|
||||
assert response.get_json()["data"]["ok"] is True
|
||||
|
||||
|
||||
class ProbeSpyTransport:
|
||||
"""记录 probe 收到的 client 配置,验证独立列(endpoint/timeout)已拼回 config_json。"""
|
||||
|
||||
connector_type = "soap"
|
||||
|
||||
def __init__(self):
|
||||
self.seen = None
|
||||
|
||||
def probe(self, *, client):
|
||||
self.seen = client
|
||||
return {"ok": True, "code": "HTTP_200", "message": "wsdl root <definitions>"}
|
||||
|
||||
def call(self, *, client, interface, request): # pragma: no cover — 走到即失败
|
||||
self.seen = {"unexpected_call": True}
|
||||
|
||||
|
||||
def test_client_instance_test_connection_merges_endpoint_column(app, client, admin_headers, fake_gateway):
|
||||
"""连接测试回归:endpoint 存独立列(config_json 为空)时必须拼回配置再探测。
|
||||
|
||||
曾因测试端点只透传 config_json,SOAP 客户端误报
|
||||
'SOAP contract not frozen (missing wsdl/endpoint)'。
|
||||
"""
|
||||
created = client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-SOAP", "name": "soap client", "connector_type": "soap", "environment": "prod",
|
||||
"endpoint": "https://erp.invalid/wsdl", "timeout_seconds": 45,
|
||||
"config_json": {},
|
||||
})
|
||||
assert created.status_code == 201
|
||||
|
||||
spy = ProbeSpyTransport()
|
||||
fake_gateway.transports["soap"] = spy
|
||||
response = client.post(f"{API_PREFIX}/client-instances/CLI-SOAP/test", headers=admin_headers)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.get_json()["data"]
|
||||
assert data["ok"] is True
|
||||
# 独立列值必须出现在传给 transport 的 config_json 里(关键断言)。
|
||||
assert spy.seen["config_json"]["endpoint"] == "https://erp.invalid/wsdl"
|
||||
assert spy.seen["config_json"]["timeout_seconds"] == 45
|
||||
|
||||
|
||||
def test_client_instance_test_connection_reports_unreachable(app, client, admin_headers, fake_gateway):
|
||||
"""probe 探测不通 → 仍 200 但 ok=False(探测结果是业务结果,不是请求错误)。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-DOWN", "name": "down", "connector_type": "rest", "environment": "prod",
|
||||
"endpoint": "https://down.invalid",
|
||||
})
|
||||
|
||||
class DownTransport:
|
||||
connector_type = "rest"
|
||||
|
||||
def probe(self, *, client):
|
||||
return {"ok": False, "code": "CONNECTION_FAILED", "message": "connection refused"}
|
||||
|
||||
fake_gateway.transports["rest"] = DownTransport()
|
||||
response = client.post(f"{API_PREFIX}/client-instances/CLI-DOWN/test", headers=admin_headers)
|
||||
assert response.status_code == 200
|
||||
data = response.get_json()["data"]
|
||||
assert data["ok"] is False
|
||||
assert data["status"] == "failed"
|
||||
assert data["result"]["code"] == "CONNECTION_FAILED"
|
||||
|
||||
|
||||
def test_update_client_instance(app, client, admin_headers):
|
||||
"""PUT /client-instances/<code> → 200,更新 name/config/enabled。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
@@ -162,13 +225,13 @@ def test_update_client_instance(app, client, admin_headers):
|
||||
|
||||
|
||||
def test_update_interface_definition(app, client, admin_headers):
|
||||
"""PUT /interface-definitions/<code> → 200,更新模板/回传映射/状态。"""
|
||||
"""PUT /interface-definitions/<code> → 200,更新模板/回传映射;body 里的 status 被忽略。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-I", "name": "cli", "connector_type": "rest", "environment": "prod",
|
||||
"config_json": {},
|
||||
})
|
||||
client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
|
||||
"code": "IF-U", "name": "iface", "client_instance_code": "CLI-I", "connector_type": "rest",
|
||||
"code": "IF-U", "name": "iface", "client_instance_code": "CLI-I",
|
||||
"request_spec_json": {"path": "/v1/old"}, "status": "draft",
|
||||
})
|
||||
response = client.put(f"{API_PREFIX}/interface-definitions/IF-U", headers=admin_headers, json={
|
||||
@@ -177,12 +240,86 @@ def test_update_interface_definition(app, client, admin_headers):
|
||||
})
|
||||
assert response.status_code == 200
|
||||
data = response.get_json()["data"]
|
||||
assert data["status"] == "published"
|
||||
# 状态只能经生命周期动作端点流转:PUT 携带 status 不生效,仍为创建时的 draft
|
||||
assert data["status"] == "draft"
|
||||
assert data["request_spec_json"] == {"path": "/v1/new"}
|
||||
assert data["response_mapping_json"] == {"qty": "data.quantity"}
|
||||
|
||||
|
||||
def test_interface_connector_type_derived_from_client(app, client, admin_headers):
|
||||
"""连接器类型由所属客户端实例服务端推导:创建/换绑客户端均以客户端为准,body 传值被忽略。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-D1", "name": "soap cli", "connector_type": "soap", "environment": "prod",
|
||||
"config_json": {},
|
||||
})
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-D2", "name": "rest cli", "connector_type": "rest", "environment": "prod",
|
||||
"config_json": {},
|
||||
})
|
||||
# 创建:body 误传 rest(与客户端 soap 不一致)→ 落库以客户端为准
|
||||
created = client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
|
||||
"code": "IF-DERIVE", "name": "iface", "client_instance_code": "CLI-D1",
|
||||
"connector_type": "rest",
|
||||
})
|
||||
assert created.status_code == 201
|
||||
assert created.get_json()["data"]["connector_type"] == "soap"
|
||||
# 换绑客户端 → 类型跟随新客户端
|
||||
updated = client.put(f"{API_PREFIX}/interface-definitions/IF-DERIVE", headers=admin_headers, json={
|
||||
"client_instance_code": "CLI-D2",
|
||||
})
|
||||
assert updated.status_code == 200
|
||||
assert updated.get_json()["data"]["connector_type"] == "rest"
|
||||
# 客户端不存在 → 400(而非依赖外键报 500)
|
||||
missing = client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
|
||||
"code": "IF-NOCLI", "name": "iface", "client_instance_code": "CLI-NOT-EXIST",
|
||||
})
|
||||
assert missing.status_code == 400
|
||||
|
||||
|
||||
def test_interface_create_freezes_enabled(app, client, admin_headers):
|
||||
"""接口定义 enabled 冻结:请求体传值被忽略,可用性只由 status 生命周期表达。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-FE", "name": "cli", "connector_type": "rest", "environment": "prod",
|
||||
})
|
||||
created = client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
|
||||
"code": "IF-FE", "name": "iface", "client_instance_code": "CLI-FE", "enabled": False,
|
||||
})
|
||||
assert created.status_code == 201
|
||||
assert created.get_json()["data"]["enabled"] is True
|
||||
|
||||
|
||||
def test_interface_lifecycle_transitions(app, client, admin_headers):
|
||||
"""发布/撤回/退役/恢复按转移表流转;非法转移与未知动作被拒绝。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-LC", "name": "cli", "connector_type": "rest", "environment": "prod",
|
||||
"config_json": {},
|
||||
})
|
||||
client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
|
||||
"code": "IF-LC", "name": "iface", "client_instance_code": "CLI-LC",
|
||||
})
|
||||
|
||||
def lifecycle(action, code="IF-LC"):
|
||||
return client.post(f"{API_PREFIX}/interface-definitions/{code}/{action}", headers=admin_headers)
|
||||
|
||||
# draft 上直接撤回/退役 → 400(源状态不符)
|
||||
assert lifecycle("unpublish").status_code == 400
|
||||
assert lifecycle("retire").status_code == 400
|
||||
# draft → published → draft(撤回)→ published → retired(退役)→ draft(恢复)
|
||||
assert lifecycle("publish").get_json()["data"]["status"] == "published"
|
||||
assert lifecycle("unpublish").get_json()["data"]["status"] == "draft"
|
||||
assert lifecycle("publish").get_json()["data"]["status"] == "published"
|
||||
assert lifecycle("retire").get_json()["data"]["status"] == "retired"
|
||||
# retired 不能直接发布,须经恢复为草稿
|
||||
illegal = lifecycle("publish")
|
||||
assert illegal.status_code == 400
|
||||
assert illegal.get_json()["error"]["code"] == "INTEGRATION.ILLEGAL_STATUS_TRANSITION"
|
||||
assert lifecycle("reopen").get_json()["data"]["status"] == "draft"
|
||||
# 接口不存在 → 404
|
||||
assert lifecycle("publish", code="IF-NOPE").status_code == 404
|
||||
|
||||
|
||||
def test_update_binding(app, client, admin_headers):
|
||||
"""PUT /bindings/<id> → 200,更新映射版本/优先级/状态。"""
|
||||
"""PUT /bindings/<id> → 200,更新映射版本/优先级;状态不经 PUT 改写(走生命周期端点)。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-B", "name": "cli", "connector_type": "rest", "environment": "prod",
|
||||
"config_json": {},
|
||||
@@ -192,7 +329,7 @@ def test_update_binding(app, client, admin_headers):
|
||||
})
|
||||
created = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={
|
||||
"capability": "in_transit_transfer.query_inventory", "client_instance_code": "CLI-B",
|
||||
"interface_definition_code": "IF-B", "status": "draft",
|
||||
"interface_definition_code": "IF-B",
|
||||
})
|
||||
binding_id = created.get_json()["data"]["id"]
|
||||
response = client.put(f"{API_PREFIX}/bindings/{binding_id}", headers=admin_headers, json={
|
||||
@@ -202,24 +339,153 @@ def test_update_binding(app, client, admin_headers):
|
||||
data = response.get_json()["data"]
|
||||
assert data["priority"] == 5
|
||||
assert data["mapping_version"] == 2
|
||||
assert data["status"] == "published"
|
||||
# 请求体携带 status 被忽略:状态只能经 /publish 动作端点流转
|
||||
assert data["status"] == "draft"
|
||||
|
||||
# 发布绑定有就绪门禁:接口定义须先发布
|
||||
client.post(f"{API_PREFIX}/interface-definitions/IF-B/publish", headers=admin_headers)
|
||||
published = client.post(f"{API_PREFIX}/bindings/{binding_id}/publish", headers=admin_headers)
|
||||
assert published.get_json()["data"]["status"] == "published"
|
||||
|
||||
|
||||
def test_binding_create_forces_draft_and_pair_validation(app, client, admin_headers):
|
||||
"""新建绑定固定落 draft;客户端与接口成对校验(错配/缺失均 400)。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-BC", "name": "cli", "connector_type": "rest", "environment": "prod",
|
||||
"endpoint": "https://erp.invalid",
|
||||
})
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-OTHER", "name": "other", "connector_type": "rest", "environment": "prod",
|
||||
})
|
||||
client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
|
||||
"code": "IF-BC", "name": "iface", "client_instance_code": "CLI-BC", "connector_type": "rest",
|
||||
})
|
||||
# 请求体携带 status / context_source_code 均被忽略:状态走生命周期端点,
|
||||
# 来源路由条件统一由 context_selector_json 表达(无独立快捷列)
|
||||
created = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={
|
||||
"capability": "in_transit_transfer.query_inventory",
|
||||
"client_instance_code": "CLI-BC", "interface_definition_code": "IF-BC",
|
||||
"status": "published", "context_source_code": "DBS-AWSBI",
|
||||
})
|
||||
assert created.status_code == 201
|
||||
data = created.get_json()["data"]
|
||||
assert data["status"] == "draft"
|
||||
assert "context_source_code" not in data
|
||||
|
||||
# 接口定义不属于所选客户端 → 400(fail-fast,不留给调用期)
|
||||
mismatch = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={
|
||||
"capability": "in_transit_transfer.query_inventory",
|
||||
"client_instance_code": "CLI-OTHER", "interface_definition_code": "IF-BC",
|
||||
})
|
||||
assert mismatch.status_code == 400
|
||||
assert mismatch.get_json()["error"]["code"] == "INTEGRATION.BINDING_PAIR_MISMATCH"
|
||||
# 客户端/接口不存在 → 400(而非依赖外键报 500)
|
||||
assert client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={
|
||||
"capability": "in_transit_transfer.query_inventory",
|
||||
"client_instance_code": "CLI-NOT-EXIST", "interface_definition_code": "IF-BC",
|
||||
}).status_code == 400
|
||||
assert client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={
|
||||
"capability": "in_transit_transfer.query_inventory",
|
||||
"client_instance_code": "CLI-BC", "interface_definition_code": "IF-NOT-EXIST",
|
||||
}).status_code == 400
|
||||
|
||||
# 更新换绑接口时同样成对校验:以变更后的最终组合为准
|
||||
binding_id = data["id"]
|
||||
updated = client.put(f"{API_PREFIX}/bindings/{binding_id}", headers=admin_headers, json={
|
||||
"client_instance_code": "CLI-OTHER",
|
||||
})
|
||||
assert updated.status_code == 400
|
||||
assert updated.get_json()["error"]["code"] == "INTEGRATION.BINDING_PAIR_MISMATCH"
|
||||
|
||||
|
||||
def test_binding_lifecycle_transitions(app, client, admin_headers):
|
||||
"""发布/撤回/退役/恢复按转移表流转;发布有就绪门禁(接口须已发布且客户端启用)。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-BLC", "name": "cli", "connector_type": "rest", "environment": "prod",
|
||||
"config_json": {},
|
||||
})
|
||||
client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
|
||||
"code": "IF-BLC", "name": "iface", "client_instance_code": "CLI-BLC",
|
||||
})
|
||||
created = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={
|
||||
"capability": "in_transit_transfer.query_inventory",
|
||||
"client_instance_code": "CLI-BLC", "interface_definition_code": "IF-BLC",
|
||||
})
|
||||
binding_id = created.get_json()["data"]["id"]
|
||||
|
||||
def lifecycle(action):
|
||||
return client.post(f"{API_PREFIX}/bindings/{binding_id}/{action}", headers=admin_headers)
|
||||
|
||||
# 接口定义还是草稿 → 发布绑定被就绪门禁拦截(避免发布永不生效的死绑定)
|
||||
not_ready = lifecycle("publish")
|
||||
assert not_ready.status_code == 400
|
||||
assert not_ready.get_json()["error"]["code"] == "INTEGRATION.BINDING_TARGET_NOT_READY"
|
||||
|
||||
# 接口发布后:draft → published → draft(撤回)→ published → retired(退役)→ draft(恢复)
|
||||
client.post(f"{API_PREFIX}/interface-definitions/IF-BLC/publish", headers=admin_headers)
|
||||
assert lifecycle("publish").get_json()["data"]["status"] == "published"
|
||||
assert lifecycle("unpublish").get_json()["data"]["status"] == "draft"
|
||||
assert lifecycle("publish").get_json()["data"]["status"] == "published"
|
||||
assert lifecycle("retire").get_json()["data"]["status"] == "retired"
|
||||
# retired 不能直接发布,须经恢复为草稿
|
||||
illegal = lifecycle("publish")
|
||||
assert illegal.status_code == 400
|
||||
assert illegal.get_json()["error"]["code"] == "INTEGRATION.ILLEGAL_STATUS_TRANSITION"
|
||||
assert lifecycle("reopen").get_json()["data"]["status"] == "draft"
|
||||
# 绑定不存在 → 404
|
||||
assert client.post(f"{API_PREFIX}/bindings/999999/publish", headers=admin_headers).status_code == 404
|
||||
|
||||
|
||||
def test_update_credential_reference(app, client, admin_headers):
|
||||
"""PUT /credential-references/<code> → 200,更新 secret_ref/status,且不回显明文。"""
|
||||
"""PUT /credential-references/<code> → 200,更新 secret_ref,且不回显明文。"""
|
||||
client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={
|
||||
"code": "CRED-U", "secret_ref": "IN_TRANSIT_ERP_PASSWORD",
|
||||
})
|
||||
response = client.put(f"{API_PREFIX}/credential-references/CRED-U", headers=admin_headers, json={
|
||||
"secret_ref": "IN_TRANSIT_ERP_PASSWORD_ROTATED", "status": "rotating",
|
||||
"secret_ref": "IN_TRANSIT_ERP_PASSWORD_ROTATED",
|
||||
})
|
||||
assert response.status_code == 200
|
||||
data = response.get_json()["data"]
|
||||
assert data["secret_ref"] == "IN_TRANSIT_ERP_PASSWORD_ROTATED"
|
||||
assert data["status"] == "rotating"
|
||||
assert "secret" not in str(data).lower() or data.get("secret") is None
|
||||
|
||||
|
||||
def test_credential_status_two_state_toggle(app, client, admin_headers):
|
||||
"""凭据状态两态开关:active/retired 可经 PUT 互切;rotating 不可进入;存量 rotating 可恢复。"""
|
||||
client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={
|
||||
"code": "CRED-TS", "secret_ref": "IN_TRANSIT_ERP_PASSWORD",
|
||||
})
|
||||
# active → retired(停用;解析层只认 active,停用即断流)
|
||||
retired = client.put(f"{API_PREFIX}/credential-references/CRED-TS", headers=admin_headers, json={
|
||||
"status": "retired",
|
||||
})
|
||||
assert retired.status_code == 200
|
||||
assert retired.get_json()["data"]["status"] == "retired"
|
||||
# rotating 不可进入(其现语义等于断供,真实版本化轮换属 P2)
|
||||
rotating = client.put(f"{API_PREFIX}/credential-references/CRED-TS", headers=admin_headers, json={
|
||||
"status": "rotating",
|
||||
})
|
||||
assert rotating.status_code == 400
|
||||
# retired → active(恢复启用)
|
||||
reactivated = client.put(f"{API_PREFIX}/credential-references/CRED-TS", headers=admin_headers, json={
|
||||
"status": "active",
|
||||
})
|
||||
assert reactivated.get_json()["data"]["status"] == "active"
|
||||
# 存量 rotating 数据(经 create 兼容通道落库)可经 PUT 置回 active 恢复
|
||||
client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={
|
||||
"code": "CRED-LEGACY", "secret_ref": "LEGACY_KEY", "status": "rotating",
|
||||
})
|
||||
recovered = client.put(f"{API_PREFIX}/credential-references/CRED-LEGACY", headers=admin_headers, json={
|
||||
"status": "active",
|
||||
})
|
||||
assert recovered.status_code == 200
|
||||
assert recovered.get_json()["data"]["status"] == "active"
|
||||
# 非法状态值 → 400
|
||||
assert client.put(f"{API_PREFIX}/credential-references/CRED-TS", headers=admin_headers, json={
|
||||
"status": "bogus",
|
||||
}).status_code == 400
|
||||
|
||||
|
||||
def test_client_instance_split_columns(app, client, admin_headers):
|
||||
"""POST /client-instances 写 endpoint/timeout_seconds 独立列,config_json 仅存扩展。"""
|
||||
created = client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
@@ -265,26 +531,101 @@ def test_interface_definition_split_columns(app, client, admin_headers):
|
||||
assert updated.get_json()["data"]["request_path"] == "/inventory/{invoice_no}"
|
||||
|
||||
|
||||
def test_binding_split_columns(app, client, admin_headers):
|
||||
"""POST/PUT /bindings 写 context_source_code 独立列并回显。"""
|
||||
# ---- 绑定参数映射 / 凭据 db 模式 ----
|
||||
|
||||
def test_binding_param_mapping_round_trip(app, client, admin_headers):
|
||||
"""POST/PUT /bindings 透传 param_mapping_json,序列化原样返回。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-BC", "name": "cli", "connector_type": "rest", "environment": "prod",
|
||||
"code": "CLI-PM", "name": "cli", "connector_type": "rest", "environment": "prod",
|
||||
"endpoint": "https://erp.invalid",
|
||||
})
|
||||
client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
|
||||
"code": "IF-BC", "name": "iface", "client_instance_code": "CLI-BC", "connector_type": "rest",
|
||||
"code": "IFACE-PM", "name": "iface", "client_instance_code": "CLI-PM", "connector_type": "rest",
|
||||
})
|
||||
created = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={
|
||||
"capability": "in_transit_transfer.query_inventory",
|
||||
"client_instance_code": "CLI-BC", "interface_definition_code": "IF-BC",
|
||||
"context_source_code": "DBS-AWSBI", "status": "published",
|
||||
"client_instance_code": "CLI-PM", "interface_definition_code": "IFACE-PM",
|
||||
"param_mapping_json": {"organization": {"expr": "external_org"},
|
||||
"condition": {"template": "img04 = '{invoice_no}'"}},
|
||||
})
|
||||
assert created.status_code == 201
|
||||
data = created.get_json()["data"]
|
||||
assert data["context_source_code"] == "DBS-AWSBI"
|
||||
assert data["param_mapping_json"]["organization"] == {"expr": "external_org"}
|
||||
|
||||
updated = client.put(f"{API_PREFIX}/bindings/{data['id']}", headers=admin_headers, json={
|
||||
"context_source_code": "CRANE-SZ",
|
||||
})
|
||||
updated = client.put(f"{API_PREFIX}/bindings/{data['id']}", headers=admin_headers,
|
||||
json={"param_mapping_json": {"condition": {"template": "img02 = '{warehouse}'"}}})
|
||||
assert updated.status_code == 200
|
||||
assert updated.get_json()["data"]["context_source_code"] == "CRANE-SZ"
|
||||
assert updated.get_json()["data"]["param_mapping_json"] == {
|
||||
"condition": {"template": "img02 = '{warehouse}'"},
|
||||
}
|
||||
|
||||
|
||||
def test_credential_db_mode_round_trip(app, client, admin_headers):
|
||||
"""db 模式:按凭据类型加密字段落库;回显非密字段、绝不回显密文;只改密码保留用户名。"""
|
||||
from cryptography.fernet import Fernet
|
||||
|
||||
app.config["INTEGRATION_CREDENTIAL_KEY"] = Fernet.generate_key().decode("ascii")
|
||||
created = client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={
|
||||
"code": "CRED-DB", "secret_provider": "db",
|
||||
"username": "erp_user", "password": "erp_pass",
|
||||
})
|
||||
assert created.status_code == 201
|
||||
data = created.get_json()["data"]
|
||||
assert data["secret_fields"] == {"username": "erp_user"}
|
||||
assert data["has_secret"] is True
|
||||
assert "erp_pass" not in created.get_data(as_text=True)
|
||||
assert "secret_ciphertext" not in data
|
||||
|
||||
updated = client.put(f"{API_PREFIX}/credential-references/CRED-DB", headers=admin_headers,
|
||||
json={"password": "new_pass"})
|
||||
assert updated.status_code == 200
|
||||
data = updated.get_json()["data"]
|
||||
assert data["secret_fields"] == {"username": "erp_user"} # 只改密码时用户名保留
|
||||
assert "new_pass" not in updated.get_data(as_text=True)
|
||||
|
||||
|
||||
def test_credential_db_mode_token_type_and_types_endpoint(app, client, admin_headers):
|
||||
"""token 类型按其字段清单组装;类型清单端点返回注册表。"""
|
||||
from cryptography.fernet import Fernet
|
||||
|
||||
app.config["INTEGRATION_CREDENTIAL_KEY"] = Fernet.generate_key().decode("ascii")
|
||||
types = client.get(f"{API_PREFIX}/credential-references/types", headers=admin_headers)
|
||||
assert types.status_code == 200
|
||||
type_names = {item["type"] for item in types.get_json()["data"]}
|
||||
assert type_names == {"password", "token", "api_key"}
|
||||
|
||||
created = client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={
|
||||
"code": "CRED-TOKEN", "secret_provider": "db", "credential_type": "token",
|
||||
"token": "tk-123",
|
||||
})
|
||||
assert created.status_code == 201
|
||||
data = created.get_json()["data"]
|
||||
assert data["credential_type"] == "token"
|
||||
assert data["secret_fields"] == {} # token 是密文字段,不回显
|
||||
assert "tk-123" not in created.get_data(as_text=True)
|
||||
|
||||
# token 必填缺失 → 400
|
||||
missing = client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={
|
||||
"code": "CRED-TOKEN2", "secret_provider": "db", "credential_type": "token",
|
||||
})
|
||||
assert missing.status_code == 400
|
||||
|
||||
|
||||
def test_credential_db_mode_unknown_type_rejected(app, client, admin_headers):
|
||||
"""未知凭据类型 → 400(fail-closed)。"""
|
||||
from cryptography.fernet import Fernet
|
||||
|
||||
app.config["INTEGRATION_CREDENTIAL_KEY"] = Fernet.generate_key().decode("ascii")
|
||||
response = client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={
|
||||
"code": "CRED-BAD", "secret_provider": "db", "credential_type": "nope",
|
||||
"username": "u", "password": "p",
|
||||
})
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_credential_db_mode_requires_username_and_password(app, client, admin_headers):
|
||||
"""db 模式创建缺用户名或密码 → 400。"""
|
||||
response = client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={
|
||||
"code": "CRED-DB2", "secret_provider": "db", "username": "only-user",
|
||||
})
|
||||
assert response.status_code == 400
|
||||
+29
-18
@@ -85,8 +85,8 @@ def _shipping_notice_stable_auto_config(request, monkeypatch):
|
||||
return
|
||||
app = request.getfixturevalue("app")
|
||||
tmp_path = request.getfixturevalue("tmp_path")
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(tmp_path / "shipping_notice" / "freight_rpa" / "upload_queue")
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR"] = str(
|
||||
app.config["FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(tmp_path / "shipping_notice" / "freight_rpa" / "upload_queue")
|
||||
app.config["FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR"] = str(
|
||||
tmp_path / "shipping_notice" / "freight_rpa" / "upload_triggers"
|
||||
)
|
||||
if request.node.get_closest_marker("auto_rpa"):
|
||||
@@ -108,9 +108,9 @@ def _shipping_notice_stable_auto_config(request, monkeypatch):
|
||||
app.config["SHIPPING_NOTICE_AUTO_UPLOAD_ENABLED"] = False
|
||||
app.config["SHIPPING_NOTICE_BATCH_ORCHESTRATOR_ENABLED"] = False
|
||||
app.config["ENV_NAME"] = "dev"
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = False
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = False
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import reset_rpa_worker_heartbeat_state_for_tests
|
||||
|
||||
reset_rpa_worker_heartbeat_state_for_tests()
|
||||
@@ -686,7 +686,12 @@ def client(app):
|
||||
|
||||
@pytest.fixture
|
||||
def dbs_ready_file() -> dict:
|
||||
"""当日 ready 收料全量文件(DBS-AWSBI),含重复 Invoice 多行。"""
|
||||
"""当日 ready 收料全量文件(DBS-AWSBI),含重复 Invoice 多行。
|
||||
|
||||
rows 使用 movement 领域字段键(doc_no/material_code/quantity/movement_date),
|
||||
与真实仓库 movement_file_repository 产出一致(B5 接线后 run_precheck 按
|
||||
parse_movement_rows 解析);sheet/row_no 为解析必带溯源字段。
|
||||
"""
|
||||
return {
|
||||
"source_code": "DBS-AWSBI",
|
||||
"business_date": "2026-08-06",
|
||||
@@ -696,22 +701,25 @@ def dbs_ready_file() -> dict:
|
||||
"checksum": "d" * 64,
|
||||
"status": "ready",
|
||||
"rows": [
|
||||
{"sheet": "Receipt", "row_no": 10, "invoice_no": "INV-001", "material_no": "MAT-001",
|
||||
{"sheet": "Receipt", "row_no": 10, "doc_no": "HOM-001", "lot_no": "LOT-10", "material_code": "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",
|
||||
"movement_date": "2026-08-05", "quantity": "500", "source_code": "DBS-AWSBI"},
|
||||
{"sheet": "Receipt", "row_no": 11, "doc_no": "HOM-001", "lot_no": "LOT-10", "material_code": "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",
|
||||
"movement_date": "2026-08-05", "quantity": "700", "source_code": "DBS-AWSBI"},
|
||||
{"sheet": "Receipt", "row_no": 20, "doc_no": "HOX-002", "lot_no": "LOT-20", "material_code": "MAT-002",
|
||||
"material_name": "控制器组件", "specification": "标准型 / 48V",
|
||||
"receipt_date": "2026-08-05", "receipt_quantity": "1200", "source_code": "DBS-AWSBI"},
|
||||
"movement_date": "2026-08-05", "quantity": "1200", "source_code": "DBS-AWSBI"},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def crane_ready_file() -> dict:
|
||||
"""当日 ready 收料全量文件(CRANE-SZ),独立来源。"""
|
||||
"""当日 ready 收料全量文件(CRANE-SZ),独立来源。
|
||||
|
||||
rows 使用 movement 领域字段键,与真实仓库产出一致(B5 接线后)。
|
||||
"""
|
||||
return {
|
||||
"source_code": "CRANE-SZ",
|
||||
"business_date": "2026-08-06",
|
||||
@@ -721,16 +729,19 @@ def crane_ready_file() -> dict:
|
||||
"checksum": "c" * 64,
|
||||
"status": "ready",
|
||||
"rows": [
|
||||
{"sheet": "Inbound", "row_no": 5, "invoice_no": "INV-008", "material_no": "MAT-200",
|
||||
{"sheet": "Inbound", "row_no": 5, "doc_no": "WTP-008", "lot_no": "LOT-8", "material_code": "MAT-200",
|
||||
"material_name": "传感器模组", "specification": "SZ-8 / IP67",
|
||||
"receipt_date": "2026-08-05", "receipt_quantity": "600", "source_code": "CRANE-SZ"},
|
||||
"movement_date": "2026-08-05", "quantity": "600", "source_code": "CRANE-SZ"},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def same_day_receipt_file() -> dict:
|
||||
"""含业务日期当天收料的文件;这些 Invoice 必须标记 not_matured。"""
|
||||
"""含业务日期当天收料的文件;这些 Invoice 必须标记 not_matured。
|
||||
|
||||
rows 使用 movement 领域字段键,与真实仓库产出一致(B5 接线后)。
|
||||
"""
|
||||
return {
|
||||
"source_code": "DBS-AWSSG",
|
||||
"business_date": "2026-08-06",
|
||||
@@ -740,9 +751,9 @@ def same_day_receipt_file() -> dict:
|
||||
"checksum": "s" * 64,
|
||||
"status": "ready",
|
||||
"rows": [
|
||||
{"sheet": "Receipt", "row_no": 3, "invoice_no": "INV-041", "material_no": "MAT-041",
|
||||
{"sheet": "Receipt", "row_no": 3, "doc_no": "HOM-3", "lot_no": "INV-041", "material_code": "MAT-041",
|
||||
"material_name": "连接器组件", "specification": "C 型",
|
||||
"receipt_date": "2026-08-06", "receipt_quantity": "400", "source_code": "DBS-AWSSG"},
|
||||
"movement_date": "2026-08-06", "quantity": "400", "source_code": "DBS-AWSSG"},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@@ -23,8 +23,8 @@ from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
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")
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps)
|
||||
return deps
|
||||
|
||||
@@ -90,12 +90,12 @@ def test_item_job_handler_executes_single_item(transfer_db, dbs_ready_file, tran
|
||||
|
||||
create_execution_run(precheck, deps=transfer_deps, actor_id=None)
|
||||
item = db.session.query(TransferInvoiceItem).filter_by(
|
||||
invoice_no="INV-001",
|
||||
invoice_no="HOM-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
|
||||
assert refreshed.external_document_no
|
||||
|
||||
@@ -13,7 +13,42 @@ from app.jobs.context import JobContext
|
||||
from app.jobs.handlers.schedule_run import run_schedule
|
||||
from app.jobs.types import JobType
|
||||
from app.models import Job, ScheduleRun, ScheduleTask, User
|
||||
from app.services.schedule.queue_service import enqueue_due_schedule_runs, enqueue_manual_schedule_run
|
||||
from app.services.schedule.queue_service import (
|
||||
enqueue_due_schedule_runs,
|
||||
enqueue_manual_schedule_run,
|
||||
prepare_schedule_queue,
|
||||
)
|
||||
|
||||
|
||||
def test_prepare_schedule_queue_recovers_transfer_waiting_source_jobs_every_cycle(app, monkeypatch):
|
||||
"""关键断言:调拨来源等待回调 Job 的超时回收每轮领取都执行,不只在 worker 启动时扫一次。
|
||||
|
||||
[STEP 1] 用计数桩替换 receipt_callback_bridge.recover_stale_waiting_source_jobs(queue_service
|
||||
在函数体内延迟 import,桩生效)并复位 _worker_initialized,隔离模块级启动标记。
|
||||
[STEP 2] 连续两轮调用真实 prepare_schedule_queue(空库下其余恢复均为 no-op)。
|
||||
[STEP 3] 第二轮后计数必须为 2:若回收仍挂在启动一次性分支,第二次调用不会触发,计数停留 1。
|
||||
"""
|
||||
from app.services.in_transit_transfer import receipt_callback_bridge
|
||||
from app.services.schedule import queue_service
|
||||
from app.services.shipping_notice import rpa_worker_heartbeat_alert
|
||||
|
||||
calls: list[int] = []
|
||||
|
||||
def _fake_recover() -> int:
|
||||
calls.append(1)
|
||||
return 0
|
||||
|
||||
def _fake_heartbeat(**_kwargs):
|
||||
return {"skipped": True, "reason": "test_stub"}
|
||||
|
||||
monkeypatch.setattr(receipt_callback_bridge, "recover_stale_waiting_source_jobs", _fake_recover)
|
||||
monkeypatch.setattr(rpa_worker_heartbeat_alert, "maybe_alert_rpa_worker_status", _fake_heartbeat)
|
||||
monkeypatch.setattr(queue_service, "_worker_initialized", False)
|
||||
|
||||
assert prepare_schedule_queue() == 0
|
||||
assert len(calls) == 1 # 第一轮:启动 + 每轮维护都应触发回收
|
||||
assert prepare_schedule_queue() == 0
|
||||
assert len(calls) == 2 # 第二轮:回收仍须执行(修复前停留 1,此处为核心回归断言)
|
||||
|
||||
|
||||
def _create_task(*, due: bool = False, platform_api_path: str | None = None, name: str = "schedule queue test") -> ScheduleTask:
|
||||
|
||||
@@ -16,18 +16,19 @@ from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
|
||||
def _bulk_file(count: int) -> dict:
|
||||
"""生成 count 行收料文件(每 Invoice 单行)。"""
|
||||
"""生成 count 行收料文件(每 Invoice 单行;movement 领域字段键 + 类型1前缀)。"""
|
||||
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}",
|
||||
"doc_no": f"HOM-BULK-{index:04d}",
|
||||
"lot_no": f"LOT-BULK-{index:04d}",
|
||||
"material_code": f"MAT-{index:04d}",
|
||||
"material_name": "批量物料",
|
||||
"specification": "T-100",
|
||||
"receipt_date": "2026-08-05",
|
||||
"receipt_quantity": "100",
|
||||
"movement_date": "2026-08-05",
|
||||
"quantity": "100",
|
||||
"source_code": "DBS-AWSBI",
|
||||
})
|
||||
return {
|
||||
@@ -41,7 +42,8 @@ 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")
|
||||
# 库存种子按 (料号, 拨出库位, 拨出批号) 三元组与文件行一一对应。
|
||||
erp.seed_stock(f"MAT-{index:04d}", "DBS-TRANSIT", f"LOT-BULK-{index:04d}", "100")
|
||||
|
||||
started = time.perf_counter()
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
|
||||
@@ -16,7 +16,7 @@ from openpyxl import Workbook
|
||||
from werkzeug.datastructures import FileStorage
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import (
|
||||
ShippingCustomer,
|
||||
ShippingCustomerExternalRef,
|
||||
@@ -177,8 +177,8 @@ def test_publish_uses_row_source_system_for_customer_and_identifier(app):
|
||||
assert b'identifier_created' in csv_content
|
||||
|
||||
|
||||
def test_publish_conflict_rolls_back_entire_batch(app):
|
||||
"""发布中出现简码唯一冲突时,客户、来源映射和逐行结果全部回滚。"""
|
||||
def test_publish_allows_duplicate_short_codes(app):
|
||||
"""简码允许重复:同批两行共用简码须整批发布成功,创建两个同简码客户。"""
|
||||
with app.app_context():
|
||||
batch = create_import_batch(
|
||||
_make_upload([
|
||||
@@ -188,12 +188,12 @@ def test_publish_conflict_rolls_back_entire_batch(app):
|
||||
source_system='ERP',
|
||||
actor_id=None,
|
||||
)
|
||||
published = publish_import_batch(batch['id'], actor_id=None)
|
||||
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
publish_import_batch(batch['id'], actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.CUSTOMER_IMPORT_PUBLISH_CONFLICT'
|
||||
assert db.session.query(ShippingCustomer).count() == 0
|
||||
assert db.session.query(ShippingCustomerExternalRef).count() == 0
|
||||
persisted = db.session.get(ShippingCustomerImportBatch, batch['id'])
|
||||
assert persisted.status == 'validated'
|
||||
assert all(row.result_status is None for row in persisted.rows)
|
||||
# 断言整批发布成功且两个客户共用简码 DUP,各自持有独立来源映射
|
||||
assert published['status'] == 'published'
|
||||
customers = db.session.query(ShippingCustomer).filter_by(short_code='DUP').all()
|
||||
assert len(customers) == 2
|
||||
assert {ref.legacy_customer_key for ref in db.session.query(ShippingCustomerExternalRef).all()} == {
|
||||
'ERP-101', 'ERP-102',
|
||||
}
|
||||
@@ -12,7 +12,7 @@ import pytest
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.core.errors import ValidationError
|
||||
from app.models import (
|
||||
ShippingCustomer, ShippingCustomerIdentifier, ShippingCustomerLifecycleEvent, ShippingNotice,
|
||||
ShippingOrderExtraction, ShippingOrderSchema, ShippingOrderSchemaVersion,
|
||||
@@ -56,15 +56,16 @@ def _notice_for_customer(customer_id: int) -> ShippingNotice:
|
||||
return notice
|
||||
|
||||
|
||||
def test_customer_short_code_is_normalized_and_unique(app):
|
||||
"""简码统一转大写,且标准化后重复必须返回冲突。"""
|
||||
def test_customer_short_code_is_normalized_and_duplicate_allowed(app):
|
||||
"""简码统一转大写;业务允许不同标准客户共用同一简码,仅格式非法才拒绝。"""
|
||||
with app.app_context():
|
||||
created = _create_customer(short_code='wyc')
|
||||
assert created['short_code'] == 'WYC'
|
||||
|
||||
with pytest.raises(ConflictError) as exc_info:
|
||||
_create_customer(name='另一客户', short_code='WYC')
|
||||
assert exc_info.value.code == 'SHIPPING.CUSTOMER_SHORT_CODE_EXISTS'
|
||||
# 重复简码(含小写归一后撞码)必须创建成功,不再返回冲突
|
||||
duplicated = _create_customer(name='另一客户', short_code='wyc')
|
||||
assert duplicated['short_code'] == 'WYC'
|
||||
assert db.session.query(ShippingCustomer).filter_by(short_code='WYC').count() == 2
|
||||
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
_create_customer(name='格式错误客户', short_code='W1')
|
||||
|
||||
@@ -158,7 +158,7 @@ def _published_route_field_id() -> str:
|
||||
|
||||
def test_profile_credentials_are_not_returned(app):
|
||||
"""Profile 保存后只返回配置标记,响应中不能含凭据明文或密文。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
payload = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
|
||||
assert payload['password_configured'] is True
|
||||
@@ -169,7 +169,7 @@ def test_profile_credentials_are_not_returned(app):
|
||||
|
||||
def test_profile_rejects_page_operation_configuration(app):
|
||||
"""货代登录连接不得保存报表路径、selector 或下载策略,防止连接越界成为业务配置源。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
payload = _profile_data()
|
||||
payload['login_config_json'] = {'auth_mode': 'password', 'navigation': {'report_name': 'Wrong'}}
|
||||
@@ -180,7 +180,7 @@ def test_profile_rejects_page_operation_configuration(app):
|
||||
|
||||
def test_multiple_dbs_profiles_bind_independent_sources(app):
|
||||
"""同一 DBS connector 可配置多个登录连接,每个 Source 稳定绑定自己的 Profile。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
first = shipping_inventory_service.save_profile(_profile_data(code='DBS_EU_A'), actor_id=None)
|
||||
second = shipping_inventory_service.save_profile(_profile_data(code='DBS_EU_B'), actor_id=None)
|
||||
@@ -192,7 +192,7 @@ def test_multiple_dbs_profiles_bind_independent_sources(app):
|
||||
|
||||
def test_source_rejects_profile_connector_mismatch(app):
|
||||
"""库存源不能绑定不同 Driver 的 Profile。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
profile = shipping_inventory_service.save_profile(_profile_data(connector_type='crane'), actor_id=None)
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
@@ -202,7 +202,7 @@ def test_source_rejects_profile_connector_mismatch(app):
|
||||
|
||||
def test_disabled_source_can_be_saved_before_profile_and_template_binding(app):
|
||||
"""禁用库存源允许分步配置;启用时必须补齐 published 解析 Profile 和模板。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
login = shipping_inventory_service.save_profile(_profile_data(code='DRAFT_SOURCE_LOGIN'), actor_id=None)
|
||||
payload = _source_data(login['id'], code='DRAFT_SOURCE')
|
||||
@@ -227,7 +227,7 @@ def test_disabled_source_can_be_saved_before_profile_and_template_binding(app):
|
||||
|
||||
def test_activation_is_a_separate_gate_and_reports_unfinished_steps(app):
|
||||
"""普通保存只能保留停用站点;独立启用动作必须返回尚未完成的测试步骤。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
login = shipping_inventory_service.save_profile(_profile_data(code='ACTIVATION_LOGIN'), actor_id=None)
|
||||
payload = _source_data(login['id'], code='ACTIVATION_SOURCE')
|
||||
@@ -250,7 +250,7 @@ def test_activation_is_a_separate_gate_and_reports_unfinished_steps(app):
|
||||
|
||||
def test_activation_status_exposes_structured_checks_without_duplicate_test_blocks(app):
|
||||
"""未测试站点应显示后续验证步骤,但只由测试门禁阻断,避免管理员面对重复待办。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
login = shipping_inventory_service.save_profile(_profile_data(code='CHECKS_LOGIN'), actor_id=None)
|
||||
payload = {
|
||||
@@ -279,7 +279,7 @@ def test_activation_status_exposes_structured_checks_without_duplicate_test_bloc
|
||||
|
||||
def test_enabled_source_rejects_disabled_rpa_profile(app):
|
||||
"""启用库存源不得绑定停用连接,避免后台配置与运行时读取结果不一致。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
profile = shipping_inventory_service.save_profile(
|
||||
{**_profile_data(code='DISABLED_LOGIN'), 'enabled': False}, actor_id=None,
|
||||
@@ -291,7 +291,7 @@ def test_enabled_source_rejects_disabled_rpa_profile(app):
|
||||
|
||||
def test_dbs_source_persists_report_path_parameters_and_aliases(app):
|
||||
"""数据库库存源必须承载 DBS 报表路径、查询参数与识别别名,不依赖 Profile 的页面配置。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
|
||||
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
|
||||
@@ -303,11 +303,11 @@ def test_dbs_source_persists_report_path_parameters_and_aliases(app):
|
||||
|
||||
def test_source_rejects_driver_selector_in_business_parameters(app):
|
||||
"""业务参数不得保存 selector 等 Driver 细节,避免后台配置与 RPA 模板耦合。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
|
||||
payload = _source_data(profile['id'])
|
||||
payload['query_parameters_json'][0]['selector_env'] = 'SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR'
|
||||
payload['query_parameters_json'][0]['selector_env'] = 'FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR'
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
shipping_inventory_service.save_source(payload, actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.INVENTORY_SOURCE_CONFIG_INVALID'
|
||||
@@ -315,7 +315,7 @@ def test_source_rejects_driver_selector_in_business_parameters(app):
|
||||
|
||||
def test_crane_source_rejects_dbs_report_path(app):
|
||||
"""动态仓 Crane 库存源不得误填 DBS 四级报表路径。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
profile = shipping_inventory_service.save_profile(_profile_data(code='CRANE', connector_type='crane'), actor_id=None)
|
||||
payload = _source_data(profile['id'], code='CRANE', connector_type='crane')
|
||||
@@ -328,7 +328,7 @@ def test_crane_source_rejects_dbs_report_path(app):
|
||||
|
||||
def test_direct_parsing_profile_binding_keeps_source_disabled_and_writes_audit(app):
|
||||
"""停用站点可直接绑定已发布方案;绑定必须递增版本并留下不可变审计。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
login = shipping_inventory_service.save_profile(_profile_data(code='DIRECT_BIND_LOGIN'), actor_id=7)
|
||||
payload = _source_data(login['id'], code='DIRECT_BIND_SOURCE')
|
||||
@@ -357,7 +357,7 @@ def test_direct_parsing_profile_binding_keeps_source_disabled_and_writes_audit(a
|
||||
|
||||
def test_bulk_parsing_profile_binding_is_atomic_when_one_site_is_enabled(app):
|
||||
"""批量绑定必须先全量预检;已启用站点阻断时其余站点不能部分写入。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
login = shipping_inventory_service.save_profile(_profile_data(code='BULK_BIND_LOGIN'), actor_id=None)
|
||||
disabled_payload = _source_data(login['id'], code='BULK_BIND_DISABLED')
|
||||
@@ -380,7 +380,7 @@ def test_bulk_parsing_profile_binding_is_atomic_when_one_site_is_enabled(app):
|
||||
|
||||
def test_direct_parsing_binding_rejects_template_fields_missing_from_profile(app):
|
||||
"""直接绑定必须在提交前复核发货模板库存字段,防止问题延后到正式导出。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
login = shipping_inventory_service.save_profile(_profile_data(code='TEMPLATE_GATE_LOGIN'), actor_id=None)
|
||||
payload = _source_data(login['id'], code='TEMPLATE_GATE_SOURCE')
|
||||
@@ -407,7 +407,7 @@ def test_direct_parsing_binding_rejects_template_fields_missing_from_profile(app
|
||||
|
||||
def test_published_rule_cannot_be_mutated_in_place(app):
|
||||
"""发布规则必须依靠新版本演进,避免改写历史任务依据。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
profile = shipping_inventory_service.save_profile(_profile_data(code='IMMUTABLE_RULE_LOGIN'), actor_id=None)
|
||||
source = shipping_inventory_service.save_source(_source_data(profile['id'], code='DBS_DUB'), actor_id=None)
|
||||
@@ -469,7 +469,7 @@ def test_rule_condition_value_type_follows_the_selected_operator(app):
|
||||
|
||||
def test_lifecycle_allows_safe_delete_and_rejects_referenced_configuration(app):
|
||||
"""未引用的误建配置可删除;一旦绑定库存源或发布,必须改为停用/归档。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
unused = shipping_inventory_service.save_profile(_profile_data(code='UNUSED'), actor_id=None)
|
||||
shipping_inventory_service.delete_profile(unused['id'])
|
||||
@@ -500,7 +500,7 @@ def test_lifecycle_allows_safe_delete_and_rejects_referenced_configuration(app):
|
||||
|
||||
def test_publish_rule_rejects_missing_source_but_allows_disabled_source(app):
|
||||
"""发布只校验 Source 存在;停用 Source 由实际 RPA 运行期门禁阻断。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
profile = shipping_inventory_service.save_profile(_profile_data(code='ROUTE_LOGIN'), actor_id=None)
|
||||
source = shipping_inventory_service.save_source(_source_data(profile['id'], code='ROUTE_SOURCE'), actor_id=None)
|
||||
@@ -534,37 +534,69 @@ def test_publish_rule_rejects_missing_source_but_allows_disabled_source(app):
|
||||
|
||||
|
||||
def test_active_default_external_mapping_is_unique_per_source(app):
|
||||
"""同一库存源只能有一条启用的默认外部系统映射。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
"""同一库存源同一货代仓库身份只能有一条启用的映射。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
|
||||
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
|
||||
payload = {
|
||||
'inventory_source_id': source['id'], 'external_system_code': 'TOPGP', 'external_organization_code': None,
|
||||
'external_site_code': 'EU01', 'external_warehouse_code': 'DUB01', 'external_warehouse_name': 'Dublin', 'enabled': True,
|
||||
'inventory_source_id': source['id'], 'freight_warehouse_id': 'DUB', 'external_system_code': 'TOPGP',
|
||||
'external_organization_code': None, 'external_site_code': 'EU01',
|
||||
'external_warehouse_code': 'DUB01', 'external_warehouse_name': 'Dublin',
|
||||
'in_transit_warehouse_code': 'TZR2', 'enabled': True,
|
||||
}
|
||||
shipping_inventory_service.save_external_mapping(payload, actor_id=None)
|
||||
with pytest.raises(ConflictError):
|
||||
shipping_inventory_service.save_external_mapping(payload, actor_id=None)
|
||||
|
||||
|
||||
def test_external_mapping_allows_empty_freight_warehouse(app):
|
||||
"""货代仓库改为可选:空值保存为 NULL(空库位默认映射行),供 inventory_match 源兜底匹配。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
|
||||
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
|
||||
# [断言意图] 货代仓库为空不阻断保存;在途仓编码必填且大写归一后随 payload 返回。
|
||||
mapping = shipping_inventory_service.save_external_mapping({
|
||||
'inventory_source_id': source['id'], 'freight_warehouse_id': None, 'external_system_code': 'TOPGP',
|
||||
'external_warehouse_code': 'DUB01', 'external_warehouse_name': 'Dublin',
|
||||
'in_transit_warehouse_code': 'tzr2', 'enabled': True,
|
||||
}, actor_id=None)
|
||||
assert mapping['freight_warehouse_id'] is None
|
||||
assert mapping['in_transit_warehouse_code'] == 'TZR2'
|
||||
|
||||
|
||||
def test_external_mapping_requires_in_transit_warehouse_code(app):
|
||||
"""在途仓编码是在途调拨拨出库位来源——缺省必须在保存端拒绝(fail-closed 前置)。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
|
||||
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
|
||||
# [断言意图] 缺在途仓编码的映射会让调拨拨出库位无来源,保存端必须 fail-closed。
|
||||
with pytest.raises(ValidationError):
|
||||
shipping_inventory_service.save_external_mapping({
|
||||
'inventory_source_id': source['id'], 'freight_warehouse_id': 'DUB', 'external_system_code': 'TOPGP',
|
||||
'external_warehouse_code': 'DUB01', 'external_warehouse_name': 'Dublin', 'enabled': True,
|
||||
}, actor_id=None)
|
||||
|
||||
|
||||
def test_external_mapping_normalizes_freight_warehouse_identity(app):
|
||||
"""配置端小写货代仓应与库存行大写 Warehouse 使用同一精确映射身份。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
"""配置端小写货代仓应与收料文件仓库值(大写归一后)使用同一精确映射身份。"""
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
|
||||
source = shipping_inventory_service.save_source(_source_data(profile['id']), actor_id=None)
|
||||
mapping = shipping_inventory_service.save_external_mapping({
|
||||
'inventory_source_id': source['id'], 'freight_warehouse_id': 'dub',
|
||||
'external_system_code': 'TOPGP', 'external_warehouse_code': 'DUB01',
|
||||
'external_warehouse_name': 'Dublin', 'enabled': True,
|
||||
'external_warehouse_name': 'Dublin', 'in_transit_warehouse_code': 'TZR2', 'enabled': True,
|
||||
}, actor_id=None)
|
||||
assert mapping['freight_warehouse_id'] == 'DUB'
|
||||
|
||||
|
||||
def test_upload_config_change_does_not_bump_rpa_profile_version(app):
|
||||
"""连接级上传配置(upload_config_json)变更不递增 config_version。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
|
||||
base_version = profile['config_version']
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
"""在途调拨测试断言辅助。
|
||||
|
||||
用途:统一断言外部调用次数、审计字段完整率与 Hash 可复算。
|
||||
依赖:fakes.ErpCallRecord。
|
||||
依赖:fakes.ExternalCallRecord。
|
||||
逻辑:所有副作用断言优先读 Fake 的 call log,不猜测实现内部状态。
|
||||
"""
|
||||
|
||||
@@ -10,26 +10,26 @@ from __future__ import annotations
|
||||
from decimal import Decimal
|
||||
from typing import Any
|
||||
|
||||
from tests.services.in_transit_transfer.fakes import ErpCallRecord, FakeERP
|
||||
from tests.services.in_transit_transfer.fakes import ExternalCallRecord, FakeCapabilityClient
|
||||
|
||||
|
||||
def assert_erp_calls(erp: FakeERP, expected: int, *, invoice_no: str | None = None) -> None:
|
||||
"""断言 ERP 调用次数(可按 Invoice 过滤)。"""
|
||||
def assert_erp_calls(erp: FakeCapabilityClient, expected: int, *, invoice_no: str | None = None) -> None:
|
||||
"""断言 外部系统 调用次数(可按 Invoice 过滤)。"""
|
||||
calls = erp.calls(invoice_no=invoice_no)
|
||||
assert len(calls) == expected, f"expected {expected} ERP calls, got {len(calls)}: {calls}"
|
||||
assert len(calls) == expected, f"expected {expected} 外部系统 calls, got {len(calls)}: {calls}"
|
||||
|
||||
|
||||
def assert_erp_write_zero(erp: FakeERP) -> None:
|
||||
"""断言没有任何 ERP 写调用(fail-closed 场景通用断言)。"""
|
||||
def assert_external_write_zero(erp: FakeCapabilityClient) -> None:
|
||||
"""断言没有任何 外部系统 写调用(fail-closed 场景通用断言)。"""
|
||||
writes = erp.write_calls()
|
||||
assert not writes, f"unexpected ERP write calls: {writes}"
|
||||
assert not writes, f"unexpected 外部系统 write calls: {writes}"
|
||||
|
||||
|
||||
def assert_call_fields(record: ErpCallRecord) -> None:
|
||||
"""断言单次 ERP 调用携带全部必需追踪字段。"""
|
||||
def assert_call_fields(record: ExternalCallRecord) -> None:
|
||||
"""断言单次 外部系统 调用携带全部必需追踪字段。"""
|
||||
assert record.operation_id
|
||||
assert record.invoice_no
|
||||
assert record.erp_org
|
||||
assert record.external_org
|
||||
assert record.from_warehouse
|
||||
assert record.to_warehouse
|
||||
assert isinstance(record.quantity, Decimal)
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
用途:为 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。
|
||||
same_day_receipt_file),并组装 FakeCapabilityClient/FakeRPA/FakeWeCom。
|
||||
依赖:根 tests/conftest 的 app fixture(SQLite 内存库)、fakes 模块。
|
||||
逻辑:纯单元用例(marker pure_unit 且未请求 app)不创建 Flask/DB;
|
||||
请求 transfer_db 的用例复用 app fixture 的 create_all/drop_all 隔离。
|
||||
@@ -12,7 +12,7 @@ from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.services.in_transit_transfer.fakes import FakeClock, FakeERP, FakeRPA, FakeWeCom
|
||||
from tests.services.in_transit_transfer.fakes import FakeClock, FakeCapabilityClient, FakeRPA, FakeWeCom
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
@@ -22,9 +22,9 @@ def fixed_clock() -> FakeClock:
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def erp_fake() -> FakeERP:
|
||||
"""FakeERP:账面库存与写响应全部可注入,调用记录可断言。"""
|
||||
return FakeERP()
|
||||
def erp_fake() -> FakeCapabilityClient:
|
||||
"""FakeCapabilityClient:账面库存与写响应全部可注入,调用记录可断言。"""
|
||||
return FakeCapabilityClient()
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
|
||||
@@ -18,7 +18,7 @@ class ReceiptRow:
|
||||
|
||||
sheet: str = "Receipt"
|
||||
row_no: int = 1
|
||||
invoice_no: str = "INV-001"
|
||||
invoice_no: str = "HOM-001"
|
||||
material_no: str = "MAT-001"
|
||||
material_name: str = "连接器组件"
|
||||
specification: str = "A 型 / 24PIN"
|
||||
@@ -43,11 +43,11 @@ class ReceiptRow:
|
||||
|
||||
def make_invoice_item(
|
||||
*,
|
||||
invoice_no: str = "INV-001",
|
||||
invoice_no: str = "HOM-001",
|
||||
source_code: str = "DBS-AWSBI",
|
||||
material_no: str = "MAT-001",
|
||||
receipt_quantity: Decimal | str | int = "1200",
|
||||
erp_quantity: Decimal | str | int | None = "1200",
|
||||
external_quantity: Decimal | str | int | None = "1200",
|
||||
receipt_date: str = "2026-08-05",
|
||||
) -> dict[str, Any]:
|
||||
"""构造一条预检明细项(默认严格匹配、可执行)。"""
|
||||
@@ -59,5 +59,5 @@ def make_invoice_item(
|
||||
"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)),
|
||||
"external_quantity": None if external_quantity is None else Decimal(str(external_quantity)),
|
||||
}
|
||||
@@ -1,13 +1,12 @@
|
||||
"""在途调拨测试的可控外部系统替身:FakeERP / FakeRPA / FakeWeCom / FakeClock。
|
||||
"""在途调拨测试的可控外部系统替身:FakeCapabilityClient / FakeRPA / FakeWeCom / FakeClock。
|
||||
|
||||
用途:让 L0/L1 测试在不接触真实 RPA、ERP、企业微信的前提下覆盖全部业务分支,
|
||||
用途:让 L0/L1 测试在不接触真实 RPA、外部系统、企业微信的前提下覆盖全部业务分支,
|
||||
并把每一次外部调用完整记录到 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 单号)。
|
||||
依赖:标准库(dataclasses / decimal / zoneinfo)、capability_client(域类型)。
|
||||
逻辑:FakeCapabilityClient 以 (料号, 拨出库位, 拨出批号) 三元组维护账面库存;
|
||||
query_stock 一次返回组内全部命中行;create_transfer 按注入的 scenario
|
||||
返回已分类的 TransferWriteResult(success / duplicate_success /
|
||||
business_failed / technical_failed / result_unknown)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -18,7 +17,12 @@ from decimal import Decimal
|
||||
from typing import Any
|
||||
from zoneinfo import ZoneInfo
|
||||
|
||||
from app.services.in_transit_transfer.erp_adapter import ErpWriteTimeoutError
|
||||
from app.services.in_transit_transfer.capability_client import (
|
||||
ExternalQueryTimeoutError,
|
||||
StockQueryResult,
|
||||
StockRow,
|
||||
TransferWriteResult,
|
||||
)
|
||||
|
||||
|
||||
class FakeClock:
|
||||
@@ -41,149 +45,182 @@ class FakeClock:
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class ErpCallRecord:
|
||||
"""FakeERP 单次调用的事实记录;测试断言优先读取该记录。"""
|
||||
class ExternalCallRecord:
|
||||
"""FakeCapabilityClient 单次调用的事实记录;测试断言优先读取该记录。"""
|
||||
|
||||
operation_id: str
|
||||
invoice_no: str
|
||||
erp_org: str
|
||||
from_warehouse: str
|
||||
to_warehouse: str
|
||||
quantity: Decimal
|
||||
external_org: str
|
||||
call_seq: int
|
||||
returned_status: str
|
||||
method: str
|
||||
# 查询调用:记录目标元组;写调用:invoice_no + 数量。
|
||||
targets: tuple[tuple[str, str, str], ...] = ()
|
||||
invoice_no: str = ""
|
||||
document_no: str | None = None
|
||||
|
||||
|
||||
class FakeERP:
|
||||
"""可注入账面库存与响应场景的 ERP 替身;每次调用写入 call log。"""
|
||||
class FakeCapabilityClient:
|
||||
"""可注入账面库存与响应场景的外部系统客户端替身;每次调用写入 call log。"""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.inventory: dict[str, dict[str, Any]] = {}
|
||||
self.inventory: dict[tuple[str, str, str], Decimal] = {}
|
||||
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.call_log: list[ExternalCallRecord] = []
|
||||
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_stock(self, material_no: str, from_warehouse: str, lot_no: str,
|
||||
quantity: str | int | Decimal) -> None:
|
||||
"""设置指定 (料号, 拨出库位, 拨出批号) 的账面库存。"""
|
||||
key = (str(material_no).strip(), str(from_warehouse).strip(), str(lot_no).strip())
|
||||
self.inventory[key] = Decimal(str(quantity))
|
||||
|
||||
def clear_stock(self) -> None:
|
||||
"""清空全部账面库存(模拟 外部系统 库存被移走/未上账)。"""
|
||||
self.inventory.clear()
|
||||
|
||||
def seed_document(self, invoice_no: str, document_no: str, *, posted: bool = True) -> None:
|
||||
"""预置某 Invoice 已存在的 ERP 单据(幂等重复场景)。"""
|
||||
"""预置某 Invoice 已存在的单据(幂等重复场景)。"""
|
||||
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。"""
|
||||
"""normal | inventory_not_found | timeout | error。"""
|
||||
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 场景抛超时异常。"""
|
||||
# -- 外部系域能力 ----------------------------------------------------------
|
||||
def query_stock(self, *, operation_id: str, external_org: str,
|
||||
targets: list) -> StockQueryResult:
|
||||
"""按组织批量返回库存行;timeout/error 场景按客户端语义抛错。"""
|
||||
self._seq += 1
|
||||
key = str(invoice_no).strip()
|
||||
target_keys = [
|
||||
(str(t.material_no).strip(), str(t.from_warehouse).strip(), str(t.lot_no).strip())
|
||||
for t in targets
|
||||
]
|
||||
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}
|
||||
raise ExternalQueryTimeoutError(f"query timeout operation_id={operation_id}")
|
||||
if self.query_scenario == "error":
|
||||
self.call_log.append(ExternalCallRecord(
|
||||
operation_id, external_org, self._seq, "error", "query_stock",
|
||||
targets=tuple(target_keys),
|
||||
))
|
||||
raise RuntimeError("binding not found for capability query_inventory")
|
||||
rows: list[StockRow] = []
|
||||
for key in target_keys:
|
||||
if self.query_scenario == "inventory_not_found":
|
||||
continue
|
||||
if key in self.inventory:
|
||||
rows.append(StockRow(
|
||||
material_no=key[0], from_warehouse=key[1], lot_no=key[2],
|
||||
quantity=self.inventory[key],
|
||||
))
|
||||
self.call_log.append(ExternalCallRecord(
|
||||
operation_id, external_org, self._seq,
|
||||
"success" if rows else "inventory_not_found", "query_stock",
|
||||
targets=tuple(target_keys),
|
||||
))
|
||||
return StockQueryResult(rows=tuple(rows))
|
||||
|
||||
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]:
|
||||
"""原子建单/审核/过账;按注入场景返回结果并记录调用。"""
|
||||
invoice_no: str, external_org: str, from_warehouse: str,
|
||||
to_warehouse: str, quantity: Decimal) -> TransferWriteResult:
|
||||
"""原子建单/审核/过账;按注入场景返回已分类结果并记录调用。"""
|
||||
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,
|
||||
)
|
||||
self.call_log.append(ExternalCallRecord(
|
||||
operation_id, external_org, self._seq, "timeout_before_commit",
|
||||
"create_transfer", invoice_no=key,
|
||||
))
|
||||
# 可证明未落单 → 明确技术失败(不产生单据)。
|
||||
return TransferWriteResult(status="technical_failed", error_code="EXTERNAL_TIMEOUT_BEFORE_COMMIT")
|
||||
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,
|
||||
document_no = self.documents[key]
|
||||
self.call_log.append(ExternalCallRecord(
|
||||
operation_id, external_org, self._seq, "timeout_after_commit",
|
||||
"create_transfer", invoice_no=key, document_no=document_no,
|
||||
))
|
||||
return TransferWriteResult(
|
||||
status="result_unknown", error_code="EXTERNAL_TIMEOUT_AFTER_COMMIT",
|
||||
document_no=document_no,
|
||||
)
|
||||
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}
|
||||
self.call_log.append(ExternalCallRecord(
|
||||
operation_id, external_org, self._seq, "business_failed",
|
||||
"create_transfer", invoice_no=key,
|
||||
))
|
||||
return TransferWriteResult(
|
||||
status="business_failed", error_code="EXTERNAL_BUSINESS_REJECT",
|
||||
error_message="rejected by external system",
|
||||
)
|
||||
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),
|
||||
}
|
||||
posted = self.verified_posted.get(key, False)
|
||||
status = "duplicate_success" if posted else "duplicate_unverified"
|
||||
self.call_log.append(ExternalCallRecord(
|
||||
operation_id, external_org, self._seq, status,
|
||||
"create_transfer", invoice_no=key, document_no=document_no,
|
||||
))
|
||||
return TransferWriteResult(
|
||||
status=status, document_no=document_no, verified_posted=posted,
|
||||
error_code=None if posted else "TRANSFER_DUPLICATE_NOT_VERIFIED",
|
||||
)
|
||||
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}
|
||||
self.call_log.append(ExternalCallRecord(
|
||||
operation_id, external_org, self._seq, "success",
|
||||
"create_transfer", invoice_no=key, document_no=document_no,
|
||||
))
|
||||
return TransferWriteResult(status="success", document_no=document_no, verified_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_no: str, external_org: str, from_warehouse: str,
|
||||
to_warehouse: str, quantity: Decimal) -> TransferWriteResult:
|
||||
"""核实重复 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}
|
||||
self.call_log.append(ExternalCallRecord(
|
||||
operation_id, external_org, self._seq, "duplicate_unverified", "verify_duplicate",
|
||||
invoice_no=key,
|
||||
))
|
||||
return TransferWriteResult(
|
||||
status="duplicate_unverified", error_code="TRANSFER_DUPLICATE_NOT_VERIFIED",
|
||||
)
|
||||
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}
|
||||
self.call_log.append(ExternalCallRecord(
|
||||
operation_id, external_org, self._seq, status, "verify_duplicate",
|
||||
invoice_no=key, document_no=document_no,
|
||||
))
|
||||
return TransferWriteResult(
|
||||
status=status, document_no=document_no,
|
||||
verified_posted=posted if posted else None,
|
||||
error_code=None if posted else "TRANSFER_DUPLICATE_NOT_VERIFIED",
|
||||
)
|
||||
|
||||
# -- 断言辅助 ----------------------------------------------------------
|
||||
def calls(self, *, invoice_no: str | None = None) -> list[ErpCallRecord]:
|
||||
"""按 Invoice 过滤调用记录(默认返回全部)。"""
|
||||
def calls(self, *, invoice_no: str | None = None) -> list[ExternalCallRecord]:
|
||||
"""按 Invoice 过滤调用记录(默认返回全部;查询调用 invoice_no 为空串)。"""
|
||||
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]:
|
||||
def write_calls(self) -> list[ExternalCallRecord]:
|
||||
"""仅返回 create_transfer 调用记录(写副作用断言)。"""
|
||||
return [record for record in self.call_log if record.method == "create_transfer"]
|
||||
|
||||
|
||||
@@ -4,15 +4,14 @@
|
||||
ReceiptFileRepository、RouteResolver 与组装好的 TransferDeps。
|
||||
依赖:app.services.in_transit_transfer(仅类型)、fakes。
|
||||
逻辑:所有替身只返回测试注入的值,不触碰真实存储;
|
||||
TransferDeps.erp 统一使用 ErpAdapter(FakeERP) 以匹配 Adapter 契约。
|
||||
TransferDeps.capabilities 直接注入 FakeCapabilityClient(客户端替身)。
|
||||
"""
|
||||
|
||||
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
|
||||
from tests.services.in_transit_transfer.fakes import FakeCapabilityClient, FakeRPA
|
||||
|
||||
|
||||
class FakeReceiptFileRepository:
|
||||
@@ -45,38 +44,38 @@ def make_ready_repo(*files: dict) -> FakeReceiptFileRepository:
|
||||
|
||||
def make_transfer_deps(
|
||||
*files: dict,
|
||||
erp: FakeERP | None = None,
|
||||
capabilities: FakeCapabilityClient | None = None,
|
||||
rpa: FakeRPA | None = None,
|
||||
routes: dict[str, RouteMapping] | None = None,
|
||||
) -> tuple[TransferDeps, FakeERP, FakeRPA]:
|
||||
"""组装注入 Fake 的 TransferDeps(erp 统一包装为 ErpAdapter)。
|
||||
) -> tuple[TransferDeps, FakeCapabilityClient, FakeRPA]:
|
||||
"""组装注入 Fake 的 TransferDeps(外部访问直接注入客户端替身)。
|
||||
|
||||
Returns:
|
||||
(deps, erp_fake, rpa_fake) 元组。
|
||||
(deps, capabilities_fake, rpa_fake) 元组。
|
||||
"""
|
||||
erp = erp or FakeERP()
|
||||
capabilities = capabilities or FakeCapabilityClient()
|
||||
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"),
|
||||
capabilities=capabilities,
|
||||
)
|
||||
return deps, erp, rpa
|
||||
return deps, capabilities, 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"),
|
||||
"DBS-AWSBI": RouteMapping(external_org="HX-CN01", from_warehouse="DBS-TRANSIT", to_warehouse="HUB-CN01"),
|
||||
"DBS-AWSSG": RouteMapping(external_org="HX-CN01", from_warehouse="AWSSG-TRANSIT", to_warehouse="HUB-SG"),
|
||||
"CRANE-SZ": RouteMapping(external_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:
|
||||
def resolve(self, *, source_code: str, invoice_no: str, warehouse_code: str = "") -> RouteMapping:
|
||||
"""返回来源路由;未配置来源抛 RouteNotResolvedError。"""
|
||||
if source_code in self.raised_on:
|
||||
raise RuntimeError("route resolution failed")
|
||||
|
||||
@@ -42,7 +42,7 @@ class FakeObjectStore:
|
||||
|
||||
|
||||
def _sample_data() -> bytes:
|
||||
return b"erp-inventory-snapshot,2026-08-06,INV-001,1200,1200,executable\n"
|
||||
return b"external-inventory-snapshot,2026-08-06,INV-001,1200,1200,executable\n"
|
||||
|
||||
|
||||
def test_archive_snapshot_persists_index_and_audit(transfer_db):
|
||||
@@ -50,17 +50,17 @@ def test_archive_snapshot_persists_index_and_audit(transfer_db):
|
||||
store = FakeObjectStore()
|
||||
data = _sample_data()
|
||||
archive = archive_snapshot(
|
||||
object_type="erp_inventory_snapshot",
|
||||
object_type="external_inventory_snapshot",
|
||||
object_id="TPC-20260806-001",
|
||||
data=data,
|
||||
original_filename="erp-inventory-20260806.csv",
|
||||
original_filename="external-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 archive.object_type == "external_inventory_snapshot"
|
||||
assert store.objects # 对象已写入存储
|
||||
audit = TransferAuditEvent.query.filter_by(event_type="TRANSFER_ARCHIVED").first()
|
||||
assert audit is not None
|
||||
@@ -72,7 +72,7 @@ def test_verify_archive_hash_ok_and_corruption_detected(transfer_db):
|
||||
store = FakeObjectStore()
|
||||
data = _sample_data()
|
||||
archive = archive_snapshot(
|
||||
object_type="erp_inventory_snapshot", object_id="OBJ-1", data=data,
|
||||
object_type="external_inventory_snapshot", object_id="OBJ-1", data=data,
|
||||
original_filename="a.csv", content_type="text/csv",
|
||||
object_store=store, bucket="hxops-transfer",
|
||||
)
|
||||
@@ -89,7 +89,7 @@ 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,
|
||||
object_type="external_inventory_snapshot", object_id="OBJ-2", data=data,
|
||||
original_filename="a.csv", content_type="text/csv",
|
||||
object_store=store, bucket="hxops-transfer",
|
||||
)
|
||||
|
||||
@@ -111,7 +111,7 @@ def test_event_hash_recomputable_from_fields():
|
||||
actor_type="worker",
|
||||
operation_id="op_002",
|
||||
result="success",
|
||||
after={"erp_document_no": "TRF-10001"},
|
||||
after={"external_document_no": "TRF-10001"},
|
||||
)
|
||||
assert compute_event_hash(event) == event.event_hash
|
||||
|
||||
|
||||
@@ -25,8 +25,8 @@ 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
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") # 1200 ≠ 1000 → blocked
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200") # executable
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
return summary
|
||||
|
||||
@@ -47,18 +47,18 @@ def test_list_backlog_includes_blocked_only(transfer_db, dbs_ready_file):
|
||||
_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
|
||||
assert "HOM-001" in invoice_set
|
||||
assert "HOX-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 = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-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")
|
||||
target = next(item_dto for item_dto in items if item_dto.invoice_no == "HOM-001")
|
||||
assert target.age_days == 6
|
||||
assert target.aging_level == "escalate_5d"
|
||||
|
||||
@@ -66,7 +66,7 @@ def test_backlog_aging_from_attempt_age(transfer_db, dbs_ready_file):
|
||||
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 = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
|
||||
item.status = "manually_closed"
|
||||
item.manually_closed_reason = "线下处理"
|
||||
db.session.commit()
|
||||
|
||||
@@ -19,10 +19,10 @@ 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)
|
||||
erp = __import__("tests.services.in_transit_transfer.fakes", fromlist=["FakeCapabilityClient"]).FakeCapabilityClient()
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
deps, _, _ = make_transfer_deps(dbs_ready_file, capabilities=erp)
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
return deps, summary
|
||||
|
||||
@@ -46,14 +46,14 @@ def test_cancel_marks_unstarted_items_only(transfer_db, dbs_ready_file):
|
||||
# 模拟执行中状态: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",
|
||||
run_id=run.id, invoice_no="HOX-002",
|
||||
).first()
|
||||
item.status = "ready_to_execute"
|
||||
item.erp_document_no = None
|
||||
item.external_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 items["HOM-001"].status == "success" # 已成功单据保留
|
||||
assert items["HOX-002"].status == "cancelled" # 未开始项取消
|
||||
assert result["cancelled_count"] == 1
|
||||
@@ -0,0 +1,38 @@
|
||||
"""tests/services/in_transit_transfer/test_capabilities.py
|
||||
|
||||
用途:验证在途调拨域能力声明模块:import/显式注册后注册表含三个能力且 write 标志正确。
|
||||
依赖:services/in_transit_transfer/capabilities.py、integration_connector.capability(机制层)。
|
||||
逻辑:能力契约属领域包——声明随域代码版本化;reset 后可经 register_transfer_capabilities 重建。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.in_transit_transfer.capabilities import register_transfer_capabilities
|
||||
from app.services.integration_connector.capability import (
|
||||
get_capability,
|
||||
list_capabilities,
|
||||
reset_capability_registry_for_tests,
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _fresh_registry():
|
||||
reset_capability_registry_for_tests()
|
||||
yield
|
||||
reset_capability_registry_for_tests()
|
||||
|
||||
|
||||
def test_register_transfer_capabilities_registers_three():
|
||||
"""注册后含三个在途调拨能力,write 标志与读写语义一致。"""
|
||||
register_transfer_capabilities()
|
||||
names = {spec.name for spec in list_capabilities()}
|
||||
assert {
|
||||
"in_transit_transfer.query_inventory",
|
||||
"in_transit_transfer.create_transfer",
|
||||
"in_transit_transfer.verify_duplicate",
|
||||
} == 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,190 @@
|
||||
"""在途调拨 CapabilityClient 查询/写分类契约测试(L0 纯单元)。
|
||||
|
||||
用途:验证 query_stock 请求携带 (external_org, targets) 契约并正确分类
|
||||
有库存/无库存/超时/网关失败;写路径在契约未冻结前 fail-closed,
|
||||
注入 transport 后超时按 committed 分类(technical_failed / result_unknown)。
|
||||
依赖:capability_client + integration_connector.transports.base.IntegrationCallResult。
|
||||
逻辑:CapabilityClient 是唯一外部访问边界;查询经注入的假网关,
|
||||
写经注入的 transport 替身(生产 Phase 2 前恒为 fail-closed)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import AppError
|
||||
from app.services.in_transit_transfer.capability_client import (
|
||||
CapabilityClient,
|
||||
ExternalNotFrozenError,
|
||||
ExternalQueryTimeoutError,
|
||||
ExternalWriteTimeoutError,
|
||||
StockQueryResult,
|
||||
StockTarget,
|
||||
TransferWriteResult,
|
||||
_classify_write_response,
|
||||
)
|
||||
from app.services.integration_connector.transports.base import IntegrationCallResult
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
class FakeGateway:
|
||||
"""按 inventory 字典应答的假网关;可注入 status 覆盖。"""
|
||||
|
||||
def __init__(self, rows: list[dict], *, status: str = "success", error_code: str | None = None):
|
||||
self.rows = rows
|
||||
self.status = status
|
||||
self.error_code = error_code
|
||||
self.seen: dict | None = None
|
||||
|
||||
def call(self, *, capability, context, params, operation_id, **kwargs):
|
||||
self.seen = {"capability": capability, "params": params, "operation_id": operation_id}
|
||||
if self.status != "success":
|
||||
return IntegrationCallResult(status=self.status, error_code=self.error_code)
|
||||
return IntegrationCallResult(status="success", data={"rows": self.rows})
|
||||
|
||||
|
||||
def _targets(**overrides) -> list[StockTarget]:
|
||||
value = [StockTarget(material_no="MAT-001", from_warehouse="DBS-TRANSIT", lot_no="LOT-10")]
|
||||
return overrides.get("targets", value)
|
||||
|
||||
|
||||
def test_query_stock_found_returns_row():
|
||||
"""命中库存 → StockQueryResult 携带数量行。"""
|
||||
gateway = FakeGateway([{"material_no": "MAT-001", "from_warehouse": "DBS-TRANSIT",
|
||||
"lot_no": "LOT-10", "quantity": "1200"}])
|
||||
client = CapabilityClient(gateway=gateway)
|
||||
result = client.query_stock(
|
||||
operation_id="op-001", external_org="HX-CN01",
|
||||
targets=_targets(),
|
||||
)
|
||||
assert isinstance(result, StockQueryResult)
|
||||
assert result.lookup(material_no="MAT-001", from_warehouse="DBS-TRANSIT", lot_no="LOT-10") == Decimal("1200")
|
||||
|
||||
|
||||
def test_query_stock_missing_tuple_is_none():
|
||||
"""响应无该元组 → lookup None(上层归 inventory_not_found)。"""
|
||||
client = CapabilityClient(gateway=FakeGateway([]))
|
||||
result = client.query_stock(operation_id="op-001", external_org="HX-CN01", targets=_targets())
|
||||
assert result.lookup(material_no="MAT-001", from_warehouse="DBS-TRANSIT", lot_no="LOT-10") is None
|
||||
|
||||
|
||||
def test_query_stock_params_carry_contract():
|
||||
"""网关入参严格为 (external_org, targets) 契约;不含发票/数量/凭据字段。"""
|
||||
gateway = FakeGateway([])
|
||||
CapabilityClient(gateway=gateway).query_stock(
|
||||
operation_id="op-001", external_org="HX-CN01", targets=_targets(),
|
||||
)
|
||||
assert gateway.seen["capability"] == "in_transit_transfer.query_inventory"
|
||||
assert gateway.seen["params"]["external_org"] == "HX-CN01"
|
||||
assert gateway.seen["params"]["targets"] == [
|
||||
{"material_no": "MAT-001", "from_warehouse": "DBS-TRANSIT", "lot_no": "LOT-10"},
|
||||
]
|
||||
serialized = str(gateway.seen)
|
||||
for fragment in ("password", "secret", "token", "ciphertext", "credential", "api_key", "quantity"):
|
||||
assert fragment not in serialized.lower()
|
||||
|
||||
|
||||
def test_query_stock_timeout_classified_retryable():
|
||||
"""网关超时 → ExternalQueryTimeoutError(可重试)。"""
|
||||
client = CapabilityClient(gateway=FakeGateway([], status="timeout"))
|
||||
with pytest.raises(ExternalQueryTimeoutError) as excinfo:
|
||||
client.query_stock(operation_id="op-001", external_org="HX-CN01", targets=_targets())
|
||||
assert excinfo.value.retryable is True
|
||||
|
||||
|
||||
def test_query_stock_gateway_failure_fail_closed():
|
||||
"""网关失败(如绑定缺失)→ AppError fail-closed。"""
|
||||
client = CapabilityClient(gateway=FakeGateway([], status="failed", error_code="INTEGRATION.BINDING_NOT_FOUND"))
|
||||
with pytest.raises(AppError) as excinfo:
|
||||
client.query_stock(operation_id="op-001", external_org="HX-CN01", targets=_targets())
|
||||
assert excinfo.value.code == "INTEGRATION.BINDING_NOT_FOUND"
|
||||
|
||||
|
||||
def _write_kwargs(**overrides):
|
||||
kwargs = {
|
||||
"operation_id": "op-001", "run_no": "RUN-1", "attempt_no": 1,
|
||||
"invoice_no": "INV-001", "external_org": "HX-CN01",
|
||||
"from_warehouse": "DBS-TRANSIT", "to_warehouse": "HUB-CN01",
|
||||
"quantity": Decimal("1200"),
|
||||
}
|
||||
kwargs.update(overrides)
|
||||
return kwargs
|
||||
|
||||
|
||||
class _ScriptedWriteTransport:
|
||||
"""按脚本返回/抛出的写传输替身。"""
|
||||
|
||||
def __init__(self, outcome):
|
||||
self.outcome = outcome
|
||||
|
||||
def create_transfer(self, **kwargs):
|
||||
if isinstance(self.outcome, Exception):
|
||||
raise self.outcome
|
||||
return self.outcome
|
||||
|
||||
def verify_duplicate(self, **kwargs):
|
||||
return {"status": "duplicate_success", "document_no": "TRF-OLD", "verified_posted": True}
|
||||
|
||||
|
||||
def test_write_fail_closed_before_contract_frozen():
|
||||
"""写契约未冻结(未注入 transport)→ ExternalNotFrozenError。"""
|
||||
client = CapabilityClient()
|
||||
with pytest.raises(ExternalNotFrozenError):
|
||||
client.create_transfer(**_write_kwargs())
|
||||
with pytest.raises(ExternalNotFrozenError):
|
||||
client.verify_duplicate(**_write_kwargs())
|
||||
|
||||
|
||||
def test_create_transfer_success_classified():
|
||||
"""success 响应 → TransferWriteResult(success, document_no)。"""
|
||||
client = CapabilityClient(write_transport=_ScriptedWriteTransport(
|
||||
{"status": "success", "document_no": "TRF-1"}))
|
||||
result = client.create_transfer(**_write_kwargs())
|
||||
assert isinstance(result, TransferWriteResult)
|
||||
assert result.status == "success"
|
||||
assert result.document_no == "TRF-1"
|
||||
|
||||
|
||||
def test_create_transfer_business_failed_classified():
|
||||
"""business_failed → 保留外部拒绝码。"""
|
||||
client = CapabilityClient(write_transport=_ScriptedWriteTransport(
|
||||
{"status": "business_failed", "code": "EXTERNAL_BUSINESS_REJECT", "message": "reject"}))
|
||||
result = client.create_transfer(**_write_kwargs())
|
||||
assert result.status == "business_failed"
|
||||
assert result.error_code == "EXTERNAL_BUSINESS_REJECT"
|
||||
|
||||
|
||||
def test_create_transfer_timeout_before_commit_technical_failed():
|
||||
"""提交前超时(可证明未落单)→ technical_failed。"""
|
||||
client = CapabilityClient(write_transport=_ScriptedWriteTransport(
|
||||
ExternalWriteTimeoutError("timeout", committed=False)))
|
||||
result = client.create_transfer(**_write_kwargs())
|
||||
assert result.status == "technical_failed"
|
||||
assert result.error_code == "EXTERNAL_TIMEOUT_BEFORE_COMMIT"
|
||||
|
||||
|
||||
def test_create_transfer_timeout_after_commit_result_unknown():
|
||||
"""提交后超时(无法确认)→ result_unknown,禁止自动重试。"""
|
||||
client = CapabilityClient(write_transport=_ScriptedWriteTransport(
|
||||
ExternalWriteTimeoutError("timeout", committed=True, document_no="TRF-9")))
|
||||
result = client.create_transfer(**_write_kwargs())
|
||||
assert result.status == "result_unknown"
|
||||
assert result.error_code == "EXTERNAL_TIMEOUT_AFTER_COMMIT"
|
||||
assert result.document_no == "TRF-9"
|
||||
|
||||
|
||||
def test_verify_duplicate_posted_returns_original_document():
|
||||
"""verify_duplicate 已过账 → duplicate_success 含原单号。"""
|
||||
client = CapabilityClient(write_transport=_ScriptedWriteTransport(None))
|
||||
result = client.verify_duplicate(**_write_kwargs())
|
||||
assert result.status == "duplicate_success"
|
||||
assert result.document_no == "TRF-OLD"
|
||||
|
||||
|
||||
def test_classify_write_response_unknown_shape_technical_failed():
|
||||
"""未知响应形状 → technical_failed(fail-closed)。"""
|
||||
result = _classify_write_response({"status": "weird"})
|
||||
assert result.status == "technical_failed"
|
||||
@@ -71,8 +71,8 @@ def test_transfer_action_agent_permission_enforced():
|
||||
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")
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps)
|
||||
|
||||
events = list(TransferPrecheckAction().stream(_ctx("in_transit_transfer", ACTION_TRANSFER_PRECHECK, {
|
||||
@@ -84,16 +84,16 @@ def test_precheck_action_streams_card(transfer_db, dbs_ready_file, monkeypatch):
|
||||
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["summary"]["estimated_external_write_count"] == 2
|
||||
assert {item["invoice_no"] for item in payload["items"]} == {"HOM-001", "HOX-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 单号聚合)。"""
|
||||
"""transfer.execute 流式产出 transfer-result 卡片(按 外部系统 单号聚合)。"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1200")
|
||||
erp.seed_inventory("INV-002", "1200")
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps)
|
||||
|
||||
# 先跑预检拿 precheck_id
|
||||
@@ -105,10 +105,10 @@ def test_execute_action_streams_result_card(transfer_db, dbs_ready_file, monkeyp
|
||||
|
||||
execute_events = list(TransferExecuteAction().stream(_ctx(
|
||||
"in_transit_transfer", ACTION_TRANSFER_EXECUTE,
|
||||
{"precheck_id": precheck_id, "invoice_nos": ["INV-001", "INV-002"]},
|
||||
{"precheck_id": precheck_id, "invoice_nos": ["HOM-001", "HOX-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
|
||||
assert len(payload["run"]["result"]["external_documents"]) == 2
|
||||
@@ -1,9 +1,9 @@
|
||||
"""在途调拨 DTO 与错误码契约测试(L0 纯单元)。
|
||||
|
||||
用途:验证预检 DTO 字段(范围、数量、预计写入数、过期时间、Hash)、
|
||||
ERP 单据按单号聚合投影,以及一期冻结错误码完整且唯一。
|
||||
外部系统 单据按单号聚合投影,以及一期冻结错误码完整且唯一。
|
||||
依赖:app.services.in_transit_transfer.contracts。
|
||||
逻辑:DTO 为 frozen dataclass,聚合函数按 ERP 单号分组并统计物料数/总数量。
|
||||
逻辑:DTO 为 frozen dataclass,聚合函数按 外部系统 单号分组并统计物料数/总数量。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -21,7 +21,7 @@ from app.services.in_transit_transfer.contracts import (
|
||||
PrecheckCountsDTO,
|
||||
PrecheckInvoiceItemDTO,
|
||||
PrecheckSummaryDTO,
|
||||
aggregate_erp_documents,
|
||||
aggregate_external_documents,
|
||||
require_known_error_code,
|
||||
)
|
||||
|
||||
@@ -34,7 +34,7 @@ EXPECTED_ERROR_CODES = {
|
||||
"TRANSFER_FILE_SCHEMA_INVALID",
|
||||
"TRANSFER_INVOICE_CONFLICT",
|
||||
"TRANSFER_QUANTITY_MISMATCH",
|
||||
"TRANSFER_ERP_INVENTORY_NOT_FOUND",
|
||||
"TRANSFER_EXTERNAL_INVENTORY_NOT_FOUND",
|
||||
"TRANSFER_PRECHECK_EXPIRED",
|
||||
"TRANSFER_CONFIRMATION_REQUIRED",
|
||||
"TRANSFER_DUPLICATE_NOT_VERIFIED",
|
||||
@@ -77,7 +77,7 @@ def test_precheck_counts_dto_fields():
|
||||
|
||||
|
||||
def test_precheck_summary_dto_carries_estimate_and_hash():
|
||||
"""预检摘要 DTO 必须携带预计调拨数量、预计 ERP 写入数与预检 Hash。"""
|
||||
"""预检摘要 DTO 必须携带预计调拨数量、预计 外部系统 写入数与预检 Hash。"""
|
||||
summary = PrecheckSummaryDTO(
|
||||
precheck_id="TPC-20260806-001",
|
||||
status="ready_to_execute",
|
||||
@@ -86,11 +86,11 @@ def test_precheck_summary_dto_carries_estimate_and_hash():
|
||||
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,
|
||||
estimated_external_write_count=27,
|
||||
precheck_hash="sha256:abc",
|
||||
)
|
||||
assert summary.estimated_transfer_quantity == "18460"
|
||||
assert summary.estimated_erp_write_count == 27
|
||||
assert summary.estimated_external_write_count == 27
|
||||
assert summary.precheck_hash.startswith("sha256:")
|
||||
|
||||
|
||||
@@ -108,32 +108,32 @@ def test_invoice_item_dto_carries_warehouse_and_quantity_pairs():
|
||||
assert item.from_quantity == item.to_quantity
|
||||
|
||||
|
||||
def test_aggregate_erp_documents_groups_by_document_no():
|
||||
"""结果页按 ERP 单号聚合:物料数、调拨总数量、拨出/拨入仓。"""
|
||||
def test_aggregate_external_documents_groups_by_document_no():
|
||||
"""结果页按 外部系统 单号聚合:物料数、调拨总数量、拨出/拨入仓。"""
|
||||
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",
|
||||
result="success", external_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",
|
||||
result="success", external_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",
|
||||
result="success", external_document_no="TRF-10008",
|
||||
),
|
||||
]
|
||||
documents = aggregate_erp_documents(items)
|
||||
documents = aggregate_external_documents(items)
|
||||
assert len(documents) == 2
|
||||
by_no = {document.document_no: document for document in documents}
|
||||
first = by_no["TRF-10001"]
|
||||
|
||||
@@ -14,6 +14,7 @@ import pytest
|
||||
|
||||
from app.services.in_transit_transfer.date_policy import (
|
||||
business_date_now,
|
||||
business_date_utc_window,
|
||||
eligible_receipt_date_to,
|
||||
maturity_status,
|
||||
)
|
||||
@@ -24,7 +25,7 @@ BUSINESS_T = date(2026, 8, 6)
|
||||
|
||||
|
||||
def test_same_day_receipt_is_not_matured():
|
||||
"""当天收料必须返回 not_matured;成熟门禁不查询 ERP(调用次数由服务层保证为 0)。"""
|
||||
"""当天收料必须返回 not_matured;成熟门禁不查询 外部系统(调用次数由服务层保证为 0)。"""
|
||||
assert maturity_status(date(2026, 8, 6), BUSINESS_T) == "not_matured"
|
||||
|
||||
|
||||
@@ -72,6 +73,22 @@ def test_business_date_now_defaults_to_shanghai_now():
|
||||
assert business_date_now() == today
|
||||
|
||||
|
||||
def test_business_date_utc_window_maps_shanghai_day_to_utc():
|
||||
"""业务日窗口必须换算 UTC+8:上海 9-22 全天 = UTC [9-21 16:00, 9-22 16:00)。
|
||||
|
||||
[断言意图] 库里存 naive UTC 时间,判定"文件是否当天抓取"不得直接取 .date()
|
||||
比较(会漂移 8 小时);窗口起止与 naive-UTC 入参口径须与 business_date_now 一致。
|
||||
"""
|
||||
# [边界] UTC 15:00 = 上海 23:00,仍属 9-22 → 窗口 [9-21 16:00, 9-22 16:00)。
|
||||
start, end = business_date_utc_window(datetime(2026, 9, 22, 15, 0))
|
||||
assert (start, end) == (datetime(2026, 9, 21, 16, 0), datetime(2026, 9, 22, 16, 0))
|
||||
# [边界] UTC 16:30 = 上海次日 00:30 → 窗口滚动到上海 9-23。
|
||||
start_next, end_next = business_date_utc_window(datetime(2026, 9, 22, 16, 30))
|
||||
assert (start_next, end_next) == (datetime(2026, 9, 22, 16, 0), datetime(2026, 9, 23, 16, 0))
|
||||
# [断言意图] 窗口固定 24 小时,止为开区间。
|
||||
assert (end_next - start_next).total_seconds() == 24 * 3600
|
||||
|
||||
|
||||
def test_invalid_date_string_raises():
|
||||
"""非法日期字符串必须抛 ValueError,不得静默解析。"""
|
||||
with pytest.raises(ValueError):
|
||||
|
||||
@@ -1,219 +0,0 @@
|
||||
"""在途调拨 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
|
||||
@@ -24,9 +24,9 @@ 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"
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
erp.write_scenarios["HOM-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
|
||||
@@ -46,10 +46,10 @@ def test_workbook_classifies_exceptions(transfer_db, 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技术失败"]
|
||||
assert "HOX-002" in summary_text
|
||||
failed_sheet = workbook["外部系统技术失败"]
|
||||
failed_text = _sheet_text(failed_sheet)
|
||||
assert "INV-001" in failed_text
|
||||
assert "HOM-001" in failed_text
|
||||
|
||||
|
||||
def test_workbook_contains_raw_line_trace(transfer_db, dbs_ready_file):
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
用途:验证确认门禁(未确认/过期/快照变化均写入 0)、写前复查(库存变化阻断)、
|
||||
Invoice 幂等(重复成功)、result_unknown 不自动重试、单项失败不阻断其他项、
|
||||
选择子集执行、重复点击防重与按 ERP 单号投影最终结果。
|
||||
选择子集执行、重复点击防重与按 外部系统 单号投影最终结果。
|
||||
依赖:app fixture、transfer_db、fakes、repo_fakes、precheck_service、execution_service。
|
||||
逻辑:全部经真实 ORM 落库;外部依赖注入 Fake 替身。
|
||||
"""
|
||||
@@ -22,23 +22,31 @@ from app.services.in_transit_transfer.contracts import (
|
||||
)
|
||||
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.fakes import FakeCapabilityClient
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
|
||||
def _ready_precheck(*files: dict, erp=None, source_codes=None) -> tuple:
|
||||
def _ready_precheck(*files: dict, capabilities=None, source_codes=None) -> tuple:
|
||||
"""创建已预检(ready_to_execute)的 precheck 并返回 (deps, erp_fake, summary)。"""
|
||||
deps, erp_fake, _ = make_transfer_deps(*files, erp=erp)
|
||||
deps, erp_fake, _ = make_transfer_deps(*files, capabilities=capabilities)
|
||||
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()
|
||||
_INVOICE_TUPLES = {
|
||||
# dbs_ready_file 汇总键 (料号, 拨出库位, 拨出批号) —— 与夹具行一致。
|
||||
"HOM-001": ("MAT-001", "DBS-TRANSIT", "LOT-10"),
|
||||
"HOX-002": ("MAT-002", "DBS-TRANSIT", "LOT-20"),
|
||||
}
|
||||
|
||||
|
||||
def _erp_with_stock(dbs_ready_file, *seeds) -> FakeCapabilityClient:
|
||||
"""按 Invoice 预置账面库存的 FakeCapabilityClient(发票号映射到夹具三元组)。"""
|
||||
erp = FakeCapabilityClient()
|
||||
for invoice_no, quantity in seeds:
|
||||
erp.seed_inventory(invoice_no, quantity)
|
||||
material_no, from_warehouse, lot_no = _INVOICE_TUPLES[invoice_no]
|
||||
erp.seed_stock(material_no, from_warehouse, lot_no, quantity)
|
||||
return erp
|
||||
|
||||
|
||||
@@ -51,61 +59,61 @@ def _load_items(run_no: str) -> dict[str, TransferInvoiceItem]:
|
||||
|
||||
|
||||
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)
|
||||
"""两个可执行 Invoice → Run 成功,按 外部系统 单号投影两张单据,Attempt 落库。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"))
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=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 len(outcome.result.external_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())
|
||||
assert all(item.external_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
|
||||
assert len([a for a in attempts if a.kind == "external_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)
|
||||
erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"))
|
||||
erp.seed_document("HOX-002", "TRF-OLD-002", posted=True)
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=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"
|
||||
assert items["HOX-002"].status == "duplicate_success"
|
||||
assert items["HOX-002"].external_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)
|
||||
erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"))
|
||||
erp.write_scenarios["HOM-001"] = "business_failed"
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=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 items["HOM-001"].status == "blocked_recoverable"
|
||||
assert items["HOX-002"].status == "success"
|
||||
# 异常项进入结果页"未生成单据"区
|
||||
assert any(exc.invoice_no == "INV-001" for exc in outcome.result.exceptions)
|
||||
assert any(exc.invoice_no == "HOM-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 = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"))
|
||||
erp.set_write_scenario("timeout_after_commit")
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, erp=erp)
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp)
|
||||
|
||||
outcome = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
assert outcome.status == "partial_failed"
|
||||
@@ -116,9 +124,9 @@ def test_execute_result_unknown_no_auto_retry(transfer_db, dbs_ready_file):
|
||||
|
||||
|
||||
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)
|
||||
"""预检未就绪(prechecking)→ 拒绝执行,外部系统 写入为 0。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"))
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp)
|
||||
precheck = db.session.query(TransferPrecheck).filter_by(precheck_no=summary.precheck_id).first()
|
||||
precheck.status = "prechecking"
|
||||
db.session.commit()
|
||||
@@ -130,9 +138,9 @@ def test_execute_unconfirmed_precheck_no_write(transfer_db, dbs_ready_file):
|
||||
|
||||
|
||||
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)
|
||||
"""确认过期(超过 10 分钟)→ 拒绝执行,外部系统 写入为 0。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"))
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=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()
|
||||
@@ -144,9 +152,9 @@ def test_execute_expired_precheck_no_write(transfer_db, dbs_ready_file):
|
||||
|
||||
|
||||
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)
|
||||
"""预检快照(数量)变化 → fail-closed,外部系统 写入为 0。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"))
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=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"
|
||||
@@ -160,19 +168,19 @@ def test_execute_snapshot_change_blocks_write(transfer_db, dbs_ready_file):
|
||||
|
||||
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)
|
||||
erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"))
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp)
|
||||
|
||||
outcome = execute_precheck(
|
||||
precheck_id=summary.precheck_id, deps=deps, selected_invoice_nos=["INV-001"],
|
||||
precheck_id=summary.precheck_id, deps=deps, selected_invoice_nos=["HOM-001"],
|
||||
)
|
||||
assert outcome.status == "success"
|
||||
assert len(outcome.result.erp_documents) == 1
|
||||
assert [record.invoice_no for record in erp.write_calls()] == ["INV-001"]
|
||||
assert len(outcome.result.external_documents) == 1
|
||||
assert [record.invoice_no for record in erp.write_calls()] == ["HOM-001"]
|
||||
|
||||
|
||||
def test_execute_rejects_not_matured_selection(transfer_db, same_day_receipt_file):
|
||||
"""勾选当天收料项 → 拒绝,ERP 写入为 0。"""
|
||||
"""勾选当天收料项 → 拒绝,外部系统 写入为 0。"""
|
||||
deps, erp_fake, summary = _ready_precheck(same_day_receipt_file, source_codes=["DBS-AWSSG"])
|
||||
with pytest.raises(AppError):
|
||||
execute_precheck(
|
||||
@@ -183,8 +191,8 @@ def test_execute_rejects_not_matured_selection(transfer_db, same_day_receipt_fil
|
||||
|
||||
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)
|
||||
erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"))
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp)
|
||||
|
||||
first = execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
with pytest.raises(AppError) as excinfo:
|
||||
@@ -199,26 +207,26 @@ def test_execute_double_click_rejected(transfer_db, dbs_ready_file):
|
||||
|
||||
|
||||
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") # 预检后库存变化
|
||||
"""写前复查发现 外部系统 库存变化 → 该项阻断不写,其余项正常。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"))
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=erp)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "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"]
|
||||
assert items["HOM-001"].status == "blocked_recoverable"
|
||||
assert items["HOX-002"].status == "success"
|
||||
assert [record.invoice_no for record in erp.write_calls()] == ["HOX-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)
|
||||
"""GET run → 按 外部系统 单号聚合单据 + 未生成单据异常分开展示。"""
|
||||
erp = _erp_with_stock(dbs_ready_file, ("HOM-001", "1200"), ("HOX-002", "1200"))
|
||||
erp.write_scenarios["HOM-001"] = "business_failed"
|
||||
deps, _, summary = _ready_precheck(dbs_ready_file, capabilities=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"])
|
||||
assert len(restored["result"]["external_documents"]) == 1
|
||||
assert any(exc["invoice_no"] == "HOM-001" for exc in restored["result"]["exceptions"])
|
||||
@@ -16,7 +16,6 @@ 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,
|
||||
)
|
||||
|
||||
@@ -30,12 +29,14 @@ def _parsed(rows: list[dict]) -> list:
|
||||
|
||||
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:
|
||||
quantity: str = "500", row_no: int = 10, sheet: str = "Receipt",
|
||||
warehouse_code: str = "WMS-A") -> 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",
|
||||
"warehouse_code": warehouse_code,
|
||||
}
|
||||
|
||||
|
||||
@@ -66,25 +67,29 @@ def test_distinct_invoices_stay_separate_and_sorted():
|
||||
assert [item.invoice_no for item in invoices] == ["INV-001", "INV-002"]
|
||||
|
||||
|
||||
def test_multiple_material_no_conflict_blocks_invoice():
|
||||
"""同一 Invoice 出现多个料号 → 整单阻断。"""
|
||||
def test_same_invoice_multiple_materials_split_into_separate_invoices():
|
||||
"""同一 Invoice(ASN)跨料号 → 按料号拆分为多张调拨发票,不再整单阻断。"""
|
||||
rows = [
|
||||
_row("INV-001", material_no="MAT-001", row_no=1),
|
||||
_row("INV-001", material_no="MAT-002", row_no=2),
|
||||
_row("ASN-001", material_no="MAT-001", row_no=1, quantity="100"),
|
||||
_row("ASN-001", material_no="MAT-002", row_no=2, quantity="200"),
|
||||
]
|
||||
with pytest.raises(InvoiceConflictError) as excinfo:
|
||||
aggregate_invoices(_parsed(rows))
|
||||
assert excinfo.value.details.get("invoice_no") == "INV-001"
|
||||
invoices = aggregate_invoices(_parsed(rows))
|
||||
# [断言意图] Invoice 语义 = 调拨拨出单据号;料号维度自然拆分,保留各自数量与原始行。
|
||||
assert [(i.material_no, i.receipt_quantity) for i in invoices] == [
|
||||
("MAT-001", Decimal("100")), ("MAT-002", Decimal("200")),
|
||||
]
|
||||
assert all(i.invoice_no == "ASN-001" for i in invoices)
|
||||
|
||||
|
||||
def test_multiple_receipt_date_conflict_blocks_invoice():
|
||||
"""同一 Invoice 出现多个收料日期 → 整单阻断。"""
|
||||
def test_same_invoice_material_multiple_dates_split_by_date():
|
||||
"""同 Invoice 同料号跨收料日期(部分交付)→ 按日期拆分,不再整单阻断。"""
|
||||
rows = [
|
||||
_row("INV-001", receipt_date="2026-08-05", row_no=1),
|
||||
_row("INV-001", receipt_date="2026-08-06", row_no=2),
|
||||
_row("ASN-001", receipt_date="2026-08-05", row_no=1, quantity="100"),
|
||||
_row("ASN-001", receipt_date="2026-08-06", row_no=2, quantity="50"),
|
||||
]
|
||||
with pytest.raises(InvoiceConflictError):
|
||||
aggregate_invoices(_parsed(rows))
|
||||
invoices = aggregate_invoices(_parsed(rows))
|
||||
assert [str(i.receipt_date) for i in invoices] == ["2026-08-05", "2026-08-06"]
|
||||
assert [i.receipt_quantity for i in invoices] == [Decimal("100"), Decimal("50")]
|
||||
|
||||
|
||||
def test_aggregated_invoice_keeps_material_identity():
|
||||
@@ -102,6 +107,17 @@ def test_aggregated_invoice_keeps_material_identity():
|
||||
assert invoice.receipt_date == date(2026, 8, 5)
|
||||
|
||||
|
||||
def test_aggregated_invoice_keeps_first_row_warehouse_code():
|
||||
"""汇总发票取组内首行的仓库值(与 lot_no 同策略),供路由匹配使用。"""
|
||||
rows = [
|
||||
_row("INV-001", warehouse_code="WMS-A", row_no=10),
|
||||
_row("INV-001", warehouse_code="WMS-B", row_no=11),
|
||||
]
|
||||
invoices = aggregate_invoices(_parsed(rows))
|
||||
# [断言意图] 同单多行仓库值不一致时取首行,保证路由匹配输入确定。
|
||||
assert invoices[0].warehouse_code == "WMS-A"
|
||||
|
||||
|
||||
def test_raw_lines_carry_file_version():
|
||||
"""原始行追溯包含文件版本(决策 11:来源证据)。"""
|
||||
rows = [
|
||||
|
||||
@@ -20,8 +20,8 @@ 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")
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
execute_precheck(precheck_id=summary.precheck_id, deps=deps)
|
||||
|
||||
@@ -33,10 +33,10 @@ def test_collect_metrics_counts_runs_and_items(transfer_db, dbs_ready_file):
|
||||
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")
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") # mismatch → blocked
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "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 = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
|
||||
item.updated_at = item.updated_at # 保持默认年龄
|
||||
db.session.commit()
|
||||
|
||||
|
||||
@@ -77,7 +77,7 @@ def test_run_source_job_item_attempt_roundtrip(transfer_db):
|
||||
from_warehouse="DBS-TRANSIT",
|
||||
to_warehouse="HUB-CN01",
|
||||
receipt_quantity="1200",
|
||||
erp_quantity="1200",
|
||||
external_quantity="1200",
|
||||
status="ready_to_execute",
|
||||
raw_lines_json=[{"sheet": "Receipt", "row_no": 10, "file_version": "v3"}],
|
||||
)
|
||||
@@ -87,7 +87,7 @@ def test_run_source_job_item_attempt_roundtrip(transfer_db):
|
||||
attempt = TransferAttempt(
|
||||
item_id=item.id,
|
||||
attempt_no=1,
|
||||
kind="erp_query",
|
||||
kind="external_query",
|
||||
status="success",
|
||||
request_snapshot_json={"invoice_no": "INV-001"},
|
||||
operation_id="op_001",
|
||||
@@ -127,7 +127,7 @@ def test_invoice_item_unique_per_precheck(transfer_db):
|
||||
from_warehouse="DBS-TRANSIT",
|
||||
to_warehouse="HUB-CN01",
|
||||
receipt_quantity="1200",
|
||||
erp_quantity="1200",
|
||||
external_quantity="1200",
|
||||
status="ready_to_execute",
|
||||
raw_lines_json=[],
|
||||
)
|
||||
@@ -164,7 +164,7 @@ def test_invoice_item_status_check_constraint(transfer_db):
|
||||
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",
|
||||
receipt_quantity="1", external_quantity="1",
|
||||
status="no_such_status", raw_lines_json=[],
|
||||
))
|
||||
with pytest.raises(IntegrityError):
|
||||
@@ -197,12 +197,12 @@ def test_archive_roundtrip(transfer_db):
|
||||
"""归档记录保存对象路径与 Hash,供 Phase 4 MinIO 归档校验。"""
|
||||
archive = TransferArchive(
|
||||
archive_no="ARC-20260806-001",
|
||||
object_type="erp_inventory_snapshot",
|
||||
object_type="external_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",
|
||||
original_filename="external-inventory-20260806.xlsx",
|
||||
file_size=1024,
|
||||
sha256="a" * 64,
|
||||
)
|
||||
@@ -210,4 +210,4 @@ def test_archive_roundtrip(transfer_db):
|
||||
transfer_db.session.commit()
|
||||
loaded = transfer_db.session.get(TransferArchive, archive.id)
|
||||
assert loaded.sha256 == "a" * 64
|
||||
assert loaded.object_type == "erp_inventory_snapshot"
|
||||
assert loaded.object_type == "external_inventory_snapshot"
|
||||
@@ -13,6 +13,7 @@ import pytest
|
||||
from openpyxl import Workbook
|
||||
|
||||
from app.services.in_transit_transfer.movement_file_repository import _extract_movement_rows
|
||||
from app.services.in_transit_transfer.file_parser import parse_movement_rows
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
@@ -44,7 +45,7 @@ def _movement_xlsx_bytes() -> bytes:
|
||||
|
||||
|
||||
def test_extract_movement_rows_maps_columns_to_domain_fields():
|
||||
"""表头别名被映射为定死领域字段 code 的行字段。"""
|
||||
"""表头别名被映射为定死领域字段 code 的行字段,并携带真实溯源 sheet/row_no。"""
|
||||
rows = _extract_movement_rows(
|
||||
_movement_xlsx_bytes(),
|
||||
field_mapping=MOVEMENT_MAPPING,
|
||||
@@ -59,6 +60,55 @@ def test_extract_movement_rows_maps_columns_to_domain_fields():
|
||||
assert str(first['movement_date']) == '2026-08-05'
|
||||
second = rows[1]
|
||||
assert second['quantity'] == 300
|
||||
# [断言意图] 溯源字段必须指向真实电子表格位置:sheet=实际工作表标题,
|
||||
# row_no=工作表 1-based 行号(表头第 1 行 → 数据行在第 2/3 行)。
|
||||
assert first['sheet'] == 'Movement'
|
||||
assert second['sheet'] == 'Movement'
|
||||
assert first['row_no'] == 2
|
||||
assert second['row_no'] == 3
|
||||
# [断言意图] 仓库产出直连解析器:含溯源字段的行必须通过 parse_movement_rows
|
||||
# 行校验(不出现 missing_sheet_or_row_no 整链阻断),证据行号透传到解析行。
|
||||
parsed = parse_movement_rows(source_code='DBS-AWSBI', rows=rows)
|
||||
assert [row.row_no for row in parsed] == [2, 3]
|
||||
assert [row.invoice_no for row in parsed] == ['MOV-001', 'MOV-001']
|
||||
# [断言意图] 批号透传进解析行(预检拨出/拨入批号展示的数据来源)。
|
||||
assert [row.lot_no for row in parsed] == ['LOT-9', 'LOT-9']
|
||||
|
||||
|
||||
def test_extract_movement_rows_supports_multiple_fields_sharing_one_alias():
|
||||
"""两个字段映射同一表头别名时都必须提取,互不覆盖。
|
||||
|
||||
[断言意图] CRANE 实况回归(2026-09-21 预检全 0 根因):批号由单号(ASN)
|
||||
同列派生,field_mapping 中 doc_no/lot_no 合法指向同一别名;别名反查若
|
||||
一别名只允许一个 code,后写覆盖先写 → doc_no 全丢 → 整文件解析失败。
|
||||
此处锁定:共用别名的每个字段都拿到该列单元格值,且直连解析器可通过。
|
||||
"""
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = 'S'
|
||||
ws.append(['单据编号', '料号', '数量', '异动日期'])
|
||||
ws.append(['ASN-77', 'MAT-7', 8, '2026-09-18'])
|
||||
buf = BytesIO()
|
||||
wb.save(buf)
|
||||
rows = _extract_movement_rows(
|
||||
buf.getvalue(),
|
||||
field_mapping={
|
||||
'doc_no': '单据编号',
|
||||
'lot_no': '单据编号',
|
||||
'material_code': '料号',
|
||||
'quantity': '数量',
|
||||
'movement_date': '异动日期',
|
||||
},
|
||||
sheet_name='S',
|
||||
header_row_index=1,
|
||||
)
|
||||
# [断言意图] 同名列同时喂给 doc_no 与 lot_no,任一字段不得丢失。
|
||||
assert rows[0]['doc_no'] == 'ASN-77'
|
||||
assert rows[0]['lot_no'] == 'ASN-77'
|
||||
# [断言意图] 仓库产出直连解析器:共用别名不会触发 missing_invoice_no 整链阻断。
|
||||
parsed = parse_movement_rows(source_code='CRANE', rows=rows)
|
||||
assert parsed[0].invoice_no == 'ASN-77'
|
||||
assert parsed[0].lot_no == 'ASN-77'
|
||||
|
||||
|
||||
def test_extract_movement_rows_skips_missing_alias_columns():
|
||||
@@ -79,3 +129,6 @@ def test_extract_movement_rows_skips_missing_alias_columns():
|
||||
assert rows[0]['doc_no'] == 'MOV-9'
|
||||
assert rows[0]['quantity'] == 120
|
||||
assert 'movement_date' not in rows[0]
|
||||
# 部分映射下溯源字段仍在:sheet/row_no 不依赖业务列是否齐全。
|
||||
assert rows[0]['sheet'] == 'S'
|
||||
assert rows[0]['row_no'] == 2
|
||||
@@ -92,3 +92,52 @@ def test_optional_fields_default_empty():
|
||||
)
|
||||
row = parsed[0]
|
||||
assert row.material_name == ""
|
||||
|
||||
|
||||
def test_movement_row_keeps_warehouse_code():
|
||||
"""收料文件「仓库」列必须透传到解析行——inventory_match 源映射行匹配键的数据源头。"""
|
||||
parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=_rows())
|
||||
assert parsed[0].warehouse_code == "DBS-TRANSIT"
|
||||
|
||||
|
||||
def test_pending_intransit_rows_are_skipped():
|
||||
"""未收料在途行(无异动日期且数量为空/0)是 WMS 报告常态——必须跳过而不是整文件报错。"""
|
||||
pending_zero_qty = {"sheet": "Movement", "row_no": 2, "doc_no": "MOV-100", "material_code": "MAT-X",
|
||||
"quantity": 0, "movement_date": None, "source_code": "DBS-AWSBI"}
|
||||
pending_blank_qty = {"sheet": "Movement", "row_no": 3, "doc_no": "MOV-101", "material_code": "MAT-X",
|
||||
"quantity": None, "movement_date": "", "source_code": "DBS-AWSBI"}
|
||||
received = dict(VALID_MOVEMENT_ROW)
|
||||
parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=[pending_zero_qty, pending_blank_qty, received])
|
||||
# [断言意图] 只有真实收料行进入解析结果,在途行静默跳过且不阻断整文件。
|
||||
assert [row.invoice_no for row in parsed] == ["MOV-001"]
|
||||
|
||||
|
||||
def test_receiving_in_progress_rows_are_skipped():
|
||||
"""收料执行中(Qty 已计数但日期未盖章)与未收料在途行同属无收料事实——一并跳过。"""
|
||||
executing = {"sheet": "Movement", "row_no": 4, "doc_no": "MOV-200", "material_code": "MAT-X",
|
||||
"quantity": "1", "movement_date": None, "source_code": "DBS-AWSBI"}
|
||||
parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=[executing, dict(VALID_MOVEMENT_ROW)])
|
||||
# [断言意图] 无日期行不参与预检也不阻断文件;ASN 完成后由下次抓取补齐。
|
||||
assert [row.invoice_no for row in parsed] == ["MOV-001"]
|
||||
|
||||
|
||||
def test_unparseable_date_still_fails():
|
||||
"""日期有值但不可解析仍是数据损坏——跳过守卫不得吞掉真正的脏数据。"""
|
||||
corrupted = dict(VALID_MOVEMENT_ROW, row_no=5, doc_no="MOV-300", movement_date="not-a-date")
|
||||
with pytest.raises(ReceiptFileSchemaError) as exc_info:
|
||||
parse_movement_rows(source_code="DBS-AWSBI", rows=[corrupted])
|
||||
assert any("invalid_receipt_date" in error.get("reason", "")
|
||||
for error in exc_info.value.details["rows"])
|
||||
|
||||
|
||||
def test_datetime_cell_and_timed_string_dates_are_accepted():
|
||||
"""Excel 日期单元格抽出 datetime 对象、字符串型日期常带时间部分——都必须取日期部分解析。"""
|
||||
from datetime import datetime
|
||||
|
||||
datetime_cell = dict(VALID_MOVEMENT_ROW, row_no=8, doc_no="MOV-002",
|
||||
movement_date=datetime(2026, 8, 26, 17, 38, 38))
|
||||
timed_string = dict(VALID_MOVEMENT_ROW, row_no=9, doc_no="MOV-003",
|
||||
movement_date="2026-09-08 00:00:00")
|
||||
parsed = parse_movement_rows(source_code="DBS-AWSBI", rows=[datetime_cell, timed_string])
|
||||
# [断言意图] WMS 报表真实日期形态不能被 ISO 纯日期校验误杀。
|
||||
assert [row.receipt_date for row in parsed] == [date(2026, 8, 26), date(2026, 9, 8)]
|
||||
@@ -1,9 +1,9 @@
|
||||
"""在途调拨企微汇总通知测试(Phase 3,L1)。
|
||||
|
||||
用途:验证每个非空 Run 恰好一条汇总通知、空数据不通知、
|
||||
通知失败不改变 ERP 结果(run.status 保持)。
|
||||
通知失败不改变 外部系统 结果(run.status 保持)。
|
||||
依赖:transfer_db、execution_service、notification、fakes.FakeWeCom。
|
||||
逻辑:通知状态独立于 ERP 业务状态;失败记录 notification_failed。
|
||||
逻辑:通知状态独立于 外部系统 业务状态;失败记录 notification_failed。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -21,8 +21,8 @@ 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")
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "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
|
||||
@@ -39,7 +39,7 @@ def test_non_empty_run_sends_exactly_one_summary(transfer_db, dbs_ready_file):
|
||||
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 结果不受影响
|
||||
assert run.status == "success" # 外部系统 结果不受影响
|
||||
|
||||
|
||||
def test_notification_failure_does_not_change_erp_result(transfer_db, dbs_ready_file):
|
||||
@@ -51,4 +51,4 @@ def test_notification_failure_does_not_change_erp_result(transfer_db, dbs_ready_
|
||||
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 业务结果
|
||||
assert run.status == "success" # 关键:通知失败不改变 外部系统 业务结果
|
||||
@@ -16,16 +16,16 @@ 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.fakes import FakeCapabilityClient
|
||||
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)
|
||||
erp = FakeCapabilityClient()
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
deps, _, _ = make_transfer_deps(dbs_ready_file, capabilities=erp)
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
return deps, summary
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""在途调拨预检服务测试(L1,SQLite 内存库)。
|
||||
|
||||
用途:验证 D+1 过滤(当天收料 ERP 调用=0)、严格数量匹配、来源隔离、
|
||||
用途:验证 D+1 过滤(当天收料 外部系统 调用=0)、严格数量匹配、来源隔离、
|
||||
预检快照 Hash 稳定、缺文件等待与进度恢复。
|
||||
依赖:app fixture、transfer_db、fakes、repo_fakes、precheck_service。
|
||||
逻辑:全部经真实 ORM 落库(create_precheck/restore_precheck),
|
||||
@@ -11,28 +11,32 @@ from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.in_transit_transfer.erp_adapter import ErpAdapter
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.in_transit_transfer.precheck_service import (
|
||||
RouteMapping,
|
||||
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.fakes import FakeCapabilityClient, 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]:
|
||||
def _deps(*files: dict, erp: FakeCapabilityClient | None = None, rpa: FakeRPA | None = None) -> tuple[TransferDeps, FakeCapabilityClient, FakeRPA]:
|
||||
"""构造注入 Fake 依赖的 TransferDeps。"""
|
||||
return make_transfer_deps(*files, erp=erp, rpa=rpa)
|
||||
return make_transfer_deps(*files, capabilities=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)
|
||||
for material, warehouse, lot, qty in [
|
||||
("MAT-001", "DBS-TRANSIT", "LOT-10", "1200"), ("MAT-002", "DBS-TRANSIT", "LOT-20", "1200"),
|
||||
("MAT-200", "CRANE-SZ-TRANSIT", "LOT-8", "600"),
|
||||
]:
|
||||
erp.seed_stock(material, warehouse, lot, qty)
|
||||
|
||||
result = run_precheck(
|
||||
source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06", deps=deps,
|
||||
@@ -43,55 +47,70 @@ def test_happy_path_two_sources_all_executable(dbs_ready_file, crane_ready_file)
|
||||
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
|
||||
assert summary.estimated_external_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 # 多行汇总保留原始行
|
||||
assert items["HOM-001"].from_warehouse == "DBS-TRANSIT"
|
||||
assert items["HOM-001"].to_warehouse == "HUB-CN01"
|
||||
assert items["HOM-001"].from_quantity == items["HOM-001"].to_quantity == 1200
|
||||
assert len(items["HOM-001"].raw_lines) == 2 # 多行汇总保留原始行
|
||||
|
||||
|
||||
def test_same_day_receipt_not_matured_no_erp_call(same_day_receipt_file):
|
||||
"""当天收料 → not_matured,ERP 调用次数为 0。"""
|
||||
"""当天收料 → not_matured,外部系统 调用次数为 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 result.summary.estimated_external_write_count == 0
|
||||
assert_erp_calls(erp, 0)
|
||||
|
||||
|
||||
def test_quantity_mismatch_blocked_no_write(dbs_ready_file):
|
||||
"""收料 1200 vs ERP 1000 → blocked_recoverable;无任何写调用。"""
|
||||
"""收料 1200 vs 外部系统 1000 → blocked_recoverable;无任何写调用。"""
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1000")
|
||||
erp.seed_inventory("INV-002", "1200")
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "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 items["HOM-001"].result == "blocked_quantity_mismatch"
|
||||
assert items["HOX-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。"""
|
||||
"""外部系统 无库存 → blocked_inventory_not_found。"""
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1200") # INV-002 无库存
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "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"
|
||||
assert items["HOX-002"].result == "blocked_inventory_not_found"
|
||||
|
||||
|
||||
def test_external_query_failure_degrades_to_blocked_item(dbs_ready_file):
|
||||
"""外部系统 网关故障(绑定缺失/连接失败等非超时异常)→ 单据级阻断,不得炸掉整个来源。"""
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.query_scenario = "error"
|
||||
result = run_precheck(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
|
||||
)
|
||||
# [断言意图] 外部系统 基础设施故障必须降级为逐票 blocked_external_query_failed:
|
||||
# 来源保持 file_ready,发票全部带原因出现在列表里,而不是来源消失、预检全 0。
|
||||
assert result.sources[0].stage == "file_ready"
|
||||
assert result.items and all(item.result == "blocked_external_query_failed" for item in result.items)
|
||||
assert all("query_inventory" in item.reason for item in result.items)
|
||||
assert result.summary.counts.blocked_count == len(result.items)
|
||||
|
||||
|
||||
def test_missing_file_waits_without_erp():
|
||||
"""缺文件 → 来源阶段 waiting_rpa_callback,无 ERP 调用。"""
|
||||
"""缺文件 → 来源阶段 waiting_rpa_callback,无 外部系统 调用。"""
|
||||
deps, erp, _ = _deps()
|
||||
result = run_precheck(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
|
||||
@@ -105,7 +124,7 @@ 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")
|
||||
erp.seed_stock("MAT-200", "CRANE-SZ-TRANSIT", "LOT-8", "600")
|
||||
result = run_precheck(
|
||||
source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06", deps=deps,
|
||||
)
|
||||
@@ -113,14 +132,14 @@ def test_source_isolation_dbs_failure_does_not_block_crane(crane_ready_file):
|
||||
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"
|
||||
assert items["WTP-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")
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "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
|
||||
@@ -129,8 +148,8 @@ def test_snapshot_hash_is_stable(dbs_ready_file):
|
||||
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")
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
|
||||
summary = create_precheck(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
|
||||
@@ -140,21 +159,128 @@ def test_create_and_restore_precheck(transfer_db, dbs_ready_file):
|
||||
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"
|
||||
assert set(restored_items) == {"HOM-001", "HOX-002"}
|
||||
assert restored_items["HOM-001"].result == "executable"
|
||||
# 落库数量与 DTO 一致(Decimal 文本持久化)
|
||||
assert str(restored_items["INV-001"].to_quantity) == "1200"
|
||||
assert str(restored_items["HOM-001"].to_quantity) == "1200"
|
||||
# [断言意图] 收料日期与批号必须随明细恢复——聊天卡片收料日期/拨出批号/拨入批号列的数据来源。
|
||||
assert restored_items["HOM-001"].receipt_date == "2026-08-05"
|
||||
assert restored_items["HOM-001"].lot_no == "LOT-10"
|
||||
assert restored_items["HOX-002"].lot_no == "LOT-20"
|
||||
|
||||
|
||||
def test_parse_failure_persists_source_error_visible_on_restore(transfer_db):
|
||||
"""解析失败 → 来源级 error 落库并经 restore 透出(预检全 0 复发防线)。
|
||||
|
||||
[断言意图] CRANE 实况回归(2026-09-21):行缺 doc_no(别名覆盖症状)时
|
||||
整文件 ReceiptFileSchemaError;失败事实必须持久化到 source_job,恢复后
|
||||
error_code/error_message 仍可见,不得静默呈现为"无错误的全 0"。
|
||||
"""
|
||||
deps, _erp, _rpa = make_transfer_deps(
|
||||
{
|
||||
"source_code": "DSV360_AWSDU", "business_date": "2026-09-17",
|
||||
"file_no": "F1", "file_version": "v1", "checksum": "sha:x",
|
||||
"rows": [{
|
||||
# 行缺 doc_no(单号被同名列覆盖时的真实形态)
|
||||
"sheet": "Movement", "row_no": 1,
|
||||
"lot_no": "LOT-1", "material_code": "M1",
|
||||
"quantity": 5, "movement_date": "2026-09-16",
|
||||
}],
|
||||
},
|
||||
routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
|
||||
)
|
||||
summary = create_precheck(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps)
|
||||
assert summary.status == "file_pending"
|
||||
assert summary.counts.file_invoice_count == 0
|
||||
|
||||
restored = restore_precheck(summary.precheck_id)
|
||||
source = next(s for s in restored["sources"] if s.source_code == "DSV360_AWSDU")
|
||||
# [断言意图] 失败原因跨刷新可见:stage=failed + error_code/message 非空。
|
||||
assert source.stage == "failed"
|
||||
assert source.error_code == "TRANSFER_FILE_SCHEMA_INVALID"
|
||||
assert source.error_message
|
||||
|
||||
|
||||
def test_repeated_precheck_refreshes_instead_of_accumulating(transfer_db, dbs_ready_file):
|
||||
"""同一数据重复预检 → 不新增异常行,原地刷新并挂到最新预检(累加缺陷回归防线)。"""
|
||||
from app.models import TransferInvoiceItem, TransferPrecheck
|
||||
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.query_scenario = "error" # 全部阻断:正是此前不断累加"可恢复异常"的场景
|
||||
create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
first_count = TransferInvoiceItem.query.count()
|
||||
assert first_count == 2
|
||||
|
||||
# [断言意图] 第二次相同预检必须复用既有行(不出现 2×116 式累加),并挂到最新预检。
|
||||
create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
assert TransferInvoiceItem.query.count() == first_count
|
||||
latest_precheck_id = TransferPrecheck.query.order_by(TransferPrecheck.id.desc()).first().id
|
||||
assert all(row.precheck_id == latest_precheck_id for row in TransferInvoiceItem.query.all())
|
||||
|
||||
|
||||
def test_same_lot_multiple_materials_persist_without_conflict(transfer_db):
|
||||
"""同一批号(ASN)跨料号 → 按新聚合粒度拆分多行落库,不再撞 (预检,单号) 唯一约束。"""
|
||||
deps, erp_fake, _rpa = make_transfer_deps(
|
||||
{
|
||||
"source_code": "DSV360_AWSDU", "business_date": "2026-09-17",
|
||||
"file_no": "F1", "file_version": "v1", "checksum": "sha:x",
|
||||
"rows": [
|
||||
{"sheet": "Movement", "row_no": 1, "doc_no": "HOM-1", "lot_no": "ASN-1",
|
||||
"material_code": "M1", "material_name": "物料1",
|
||||
"quantity": 5, "movement_date": "2026-09-16"},
|
||||
{"sheet": "Movement", "row_no": 2, "doc_no": "HOX-2", "lot_no": "ASN-1",
|
||||
"material_code": "M2", "material_name": "物料2",
|
||||
"quantity": 7, "movement_date": "2026-09-16"},
|
||||
],
|
||||
},
|
||||
routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
|
||||
)
|
||||
erp_fake.query_scenario = "error"
|
||||
summary = create_precheck(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps)
|
||||
# [断言意图] 新唯一粒度 = (预检,来源,单号,料号,日期):同批号多料号必须共存于同一预检。
|
||||
assert summary.counts.file_invoice_count == 2
|
||||
|
||||
|
||||
def test_receipt_date_range_filters_invoices(transfer_db, dbs_ready_file):
|
||||
"""收料日期范围作为预检查询范围:范围外发票不进入明细。"""
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
summary = create_precheck(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
|
||||
receipt_date_from="2026-08-05", receipt_date_to="2026-08-05",
|
||||
)
|
||||
assert summary.counts.file_invoice_count == 2
|
||||
|
||||
empty = create_precheck(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
|
||||
receipt_date_from="2026-08-01", receipt_date_to="2026-08-04",
|
||||
)
|
||||
assert empty.counts.file_invoice_count == 0
|
||||
|
||||
|
||||
def test_receipt_date_range_end_beyond_d1_rejected(transfer_db, dbs_ready_file):
|
||||
"""卡控:截止日期超出 D+1 规则(业务日期-1)必须拒绝。"""
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
deps, erp, _ = _deps(dbs_ready_file)
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
create_precheck(
|
||||
source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps,
|
||||
receipt_date_from="2026-08-04", receipt_date_to="2026-08-06",
|
||||
)
|
||||
assert exc_info.value.code == "TRANSFER.RECEIPT_DATE_RANGE_INVALID"
|
||||
|
||||
|
||||
def test_route_not_resolved_marks_source_failed(dbs_ready_file):
|
||||
"""来源缺少路由映射 → 该来源阶段失败,其余来源继续(fail-closed)。"""
|
||||
erp = FakeERP()
|
||||
erp = FakeCapabilityClient()
|
||||
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"),
|
||||
capabilities=erp,
|
||||
)
|
||||
result = run_precheck(
|
||||
source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06", deps=deps,
|
||||
@@ -162,3 +288,138 @@ def test_route_not_resolved_marks_source_failed(dbs_ready_file):
|
||||
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" # 无文件 → 等待,不阻断
|
||||
|
||||
|
||||
def test_run_precheck_consumes_movement_field_rows(app):
|
||||
"""run_precheck 必须按 movement 领域字段(doc_no/quantity)解析真实仓库产出的行。"""
|
||||
# [断言意图] 真实仓库 rows 以 doc_no/material_code/quantity/movement_date 为键;
|
||||
# 预检应正确产出 executable 明细而非 ReceiptFileSchemaError
|
||||
# 注:sheet/row_no 为解析校验必带的溯源字段(与 parse_movement_rows 契约一致,同校验)。
|
||||
deps, erp_fake, _rpa = make_transfer_deps(
|
||||
{
|
||||
"source_code": "DSV360_AWSDU", "business_date": "2026-09-17",
|
||||
"file_no": "F1", "file_version": "v1", "checksum": "sha:x",
|
||||
"rows": [{
|
||||
"sheet": "Movement", "row_no": 1,
|
||||
"doc_no": "WTP-1", "lot_no": "LOT-1", "material_code": "M1", "material_name": "物料1",
|
||||
"quantity": 5, "movement_date": "2026-09-16",
|
||||
}],
|
||||
},
|
||||
routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
|
||||
)
|
||||
erp_fake.seed_stock("M1", "WH1", "LOT-1", 5) # 按 (料号, 拨出库位, 拨出批号) 维护账面库存
|
||||
result = run_precheck(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps)
|
||||
item = next(i for i in result.items if i.invoice_no == "WTP-1")
|
||||
assert item.result == "executable"
|
||||
|
||||
|
||||
# ---- 调拨类型(2026-09-22)-------------------------------------------------
|
||||
|
||||
def test_type1_filters_invoices_by_prefix(app):
|
||||
"""类型 1(在途仓至HUB仓)只纳入 INVOICE 前缀 HOM/HOX/WTP 的票,范围外静默排除。"""
|
||||
# [断言意图] INV-9 不匹配任何前缀 → 不入明细、不产生 blocked 行;
|
||||
# HOM/HOX/WTP 前缀票正常走完整预检(成熟 + 外部系统 匹配)。
|
||||
deps, erp_fake, _rpa = make_transfer_deps(
|
||||
{
|
||||
"source_code": "DSV360_AWSDU", "business_date": "2026-09-17",
|
||||
"file_no": "F1", "file_version": "v1", "checksum": "sha:x",
|
||||
"rows": [
|
||||
{"sheet": "Movement", "row_no": 1, "doc_no": "HOM-100", "lot_no": "LOT-1",
|
||||
"material_code": "M1", "material_name": "物料1",
|
||||
"quantity": 5, "movement_date": "2026-09-16"},
|
||||
{"sheet": "Movement", "row_no": 2, "doc_no": "INV-9", "lot_no": "LOT-2",
|
||||
"material_code": "M2", "material_name": "物料2",
|
||||
"quantity": 6, "movement_date": "2026-09-16"},
|
||||
{"sheet": "Movement", "row_no": 3, "doc_no": "WTP-300", "lot_no": "LOT-3",
|
||||
"material_code": "M3", "material_name": "物料3",
|
||||
"quantity": 7, "movement_date": "2026-09-16"},
|
||||
],
|
||||
},
|
||||
routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
|
||||
)
|
||||
erp_fake.seed_stock("M1", "WH1", "LOT-1", 5)
|
||||
erp_fake.seed_stock("M3", "WH1", "LOT-3", 7)
|
||||
result = run_precheck(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps)
|
||||
invoice_nos = {item.invoice_no for item in result.items}
|
||||
assert invoice_nos == {"HOM-100", "WTP-300"}
|
||||
assert all(item.result == "executable" for item in result.items)
|
||||
assert result.summary.counts.executable_count == 2
|
||||
|
||||
|
||||
def test_create_precheck_persists_transfer_type_on_run_and_scope(transfer_db):
|
||||
"""create_precheck 落库 Run.transfer_type 与 Precheck.scope_json 类型口径。"""
|
||||
deps, erp_fake, _rpa = make_transfer_deps(
|
||||
{
|
||||
"source_code": "DSV360_AWSDU", "business_date": "2026-09-17",
|
||||
"file_no": "F1", "file_version": "v1", "checksum": "sha:x",
|
||||
"rows": [{
|
||||
"sheet": "Movement", "row_no": 1, "doc_no": "HOX-1", "lot_no": "LOT-1",
|
||||
"material_code": "M1", "material_name": "物料1",
|
||||
"quantity": 5, "movement_date": "2026-09-16",
|
||||
}],
|
||||
},
|
||||
routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
|
||||
)
|
||||
erp_fake.seed_stock("M1", "WH1", "LOT-1", 5)
|
||||
summary = create_precheck(
|
||||
source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps,
|
||||
transfer_type="in_transit_to_hub",
|
||||
)
|
||||
from app.models import TransferPrecheck, TransferRun
|
||||
|
||||
run = TransferRun.query.filter_by(run_no=summary.precheck_id and TransferRun.query.first().run_no).first()
|
||||
precheck = TransferPrecheck.query.filter_by(precheck_no=summary.precheck_id).first()
|
||||
assert run is not None and run.transfer_type == "in_transit_to_hub"
|
||||
scope = precheck.scope_json
|
||||
assert scope["transfer_type"] == "in_transit_to_hub"
|
||||
assert scope["transfer_type_scope"] == "invoice_prefix:hom+hox+wtp"
|
||||
|
||||
|
||||
def test_create_precheck_defaults_transfer_type_when_omitted(transfer_db):
|
||||
"""缺省 transfer_type → 类型 1(存量调用方/排程行为不变但纳入前缀过滤)。"""
|
||||
deps, erp_fake, _rpa = make_transfer_deps(
|
||||
{
|
||||
"source_code": "DSV360_AWSDU", "business_date": "2026-09-17",
|
||||
"file_no": "F1", "file_version": "v1", "checksum": "sha:x",
|
||||
"rows": [{
|
||||
"sheet": "Movement", "row_no": 1, "doc_no": "HOM-1", "lot_no": "LOT-1",
|
||||
"material_code": "M1", "material_name": "物料1",
|
||||
"quantity": 5, "movement_date": "2026-09-16",
|
||||
}],
|
||||
},
|
||||
routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
|
||||
)
|
||||
erp_fake.seed_stock("M1", "WH1", "LOT-1", 5)
|
||||
summary = create_precheck(source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps)
|
||||
from app.models import TransferPrecheck, TransferRun
|
||||
|
||||
run = TransferRun.query.first()
|
||||
precheck = TransferPrecheck.query.filter_by(precheck_no=summary.precheck_id).first()
|
||||
assert run.transfer_type == "in_transit_to_hub"
|
||||
assert precheck.scope_json["transfer_type"] == "in_transit_to_hub"
|
||||
|
||||
|
||||
def test_placeholder_transfer_types_fail_closed():
|
||||
"""类型 2/3(占位)fail-closed:非法值/未支持类型均 ValidationError,不产生 Run。"""
|
||||
from app.models import TransferRun
|
||||
|
||||
deps, _erp, _rpa = make_transfer_deps(
|
||||
{
|
||||
"source_code": "DSV360_AWSDU", "business_date": "2026-09-17",
|
||||
"file_no": "F1", "file_version": "v1", "checksum": "sha:x",
|
||||
"rows": [],
|
||||
},
|
||||
)
|
||||
with pytest.raises(ValidationError) as not_supported:
|
||||
create_precheck(
|
||||
source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps,
|
||||
transfer_type="hub_repair_out",
|
||||
)
|
||||
assert not_supported.value.code == "TRANSFER.TRANSFER_TYPE_NOT_SUPPORTED"
|
||||
with pytest.raises(ValidationError) as invalid:
|
||||
create_precheck(
|
||||
source_codes=["DSV360_AWSDU"], business_date="2026-09-17", deps=deps,
|
||||
transfer_type="bogus_type",
|
||||
)
|
||||
assert invalid.value.code == "TRANSFER.TRANSFER_TYPE_INVALID"
|
||||
assert TransferRun.query.count() == 0
|
||||
@@ -1,6 +1,6 @@
|
||||
"""在途调拨严格数量门禁测试(L0 纯单元)。
|
||||
|
||||
用途:验证"收料数量 == ERP 账面库存 才可执行",大于/小于/缺失均阻断,
|
||||
用途:验证"收料数量 == 外部系统 账面库存 才可执行",大于/小于/缺失均阻断,
|
||||
且不允许 0、负数、非数字与隐式截断。
|
||||
依赖:app.services.in_transit_transfer.quantity。
|
||||
逻辑:数量比较全部基于 Decimal 精确语义,杜绝浮点误差。
|
||||
@@ -28,17 +28,17 @@ def test_equal_quantities_are_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)→ 阻断,与数量不一致分开归类。"""
|
||||
"""外部系统 无库存(None)→ 阻断,与数量不一致分开归类。"""
|
||||
assert classify_quantity_match(Decimal("1200"), None) == "blocked_inventory_not_found"
|
||||
|
||||
|
||||
|
||||
@@ -1,8 +1,9 @@
|
||||
"""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。
|
||||
用途:验证调拨 query_inventory 经 CapabilityGateway 接线——网关被调用且入参为
|
||||
(external_org, targets) 契约、成熟过滤(当天收料不查)、fail-closed
|
||||
(无绑定来源逐票降级但不阻断其他来源)。
|
||||
依赖:run_precheck、CapabilityClient、repo_fakes.make_transfer_deps、transports.base。
|
||||
逻辑:领域规则(严格数量匹配/D+1/来源隔离)仍在领域层;接口选择与调用由连接器框架承担。
|
||||
"""
|
||||
|
||||
@@ -12,7 +13,7 @@ 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.capability_client import CapabilityClient
|
||||
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
|
||||
@@ -20,9 +21,9 @@ 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:
|
||||
def __init__(self, inventory: dict[tuple[str, str, str], str] | None = None, *, fail: bool = False) -> None:
|
||||
self.inventory = inventory or {}
|
||||
self.fail = fail
|
||||
self.calls: list[tuple[str, dict, dict]] = []
|
||||
@@ -31,35 +32,44 @@ class FakeGateway:
|
||||
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)})
|
||||
rows = []
|
||||
for target in params["targets"]:
|
||||
key = (target["material_no"], target["from_warehouse"], target["lot_no"])
|
||||
qty = self.inventory.get(key)
|
||||
if qty is not None:
|
||||
rows.append({"material_no": key[0], "from_warehouse": key[1],
|
||||
"lot_no": key[2], "quantity": Decimal(qty)})
|
||||
return IntegrationCallResult(status="success", data={"rows": rows})
|
||||
|
||||
|
||||
def _cap_deps(file, gw):
|
||||
deps, _, _ = make_transfer_deps(file)
|
||||
return replace(deps, erp=CapabilityErpAdapter(gateway=gw))
|
||||
return replace(deps, capabilities=CapabilityClient(gateway=gw))
|
||||
|
||||
|
||||
def test_query_inventory_routed_through_gateway(app, dbs_ready_file):
|
||||
"""成熟 Invoice 的库存查询经网关;严格数量匹配仍由领域控制。"""
|
||||
gw = FakeGateway(inventory={"INV-001": "1200", "INV-002": "1200"})
|
||||
gw = FakeGateway(inventory={
|
||||
("MAT-001", "DBS-TRANSIT", "LOT-10"): "1200",
|
||||
("MAT-002", "DBS-TRANSIT", "LOT-20"): "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 能力名
|
||||
# 网关被调用,且携带 query_inventory 能力名与 (external_org, targets) 契约
|
||||
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")
|
||||
capability, _, params = next(c for c in gw.calls if c[0] == "in_transit_transfer.query_inventory")
|
||||
assert params["external_org"] == "HX-CN01"
|
||||
assert {"material_no": "MAT-001", "from_warehouse": "DBS-TRANSIT", "lot_no": "LOT-10"} in params["targets"]
|
||||
# INV-001 汇总 1200 == 库存 1200 → executable
|
||||
item = next(i for i in result.items if i.invoice_no == "HOM-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——网关零调用。"""
|
||||
"""当天收料(not_matured)不查外部系统——网关零调用。"""
|
||||
gw = FakeGateway(inventory={})
|
||||
result = run_precheck(
|
||||
source_codes=["DBS-AWSSG"], business_date="2026-08-06",
|
||||
@@ -70,27 +80,37 @@ def test_not_matured_not_queried(app, same_day_receipt_file):
|
||||
|
||||
|
||||
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)成功。"""
|
||||
"""按来源区分失败:DBS(拨出仓 DBS-TRANSIT)失败,CRANE 成功。"""
|
||||
|
||||
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"}:
|
||||
warehouses = {t["from_warehouse"] for t in kwargs["params"]["targets"]}
|
||||
if "DBS-TRANSIT" in warehouses:
|
||||
raise BindingNotFoundError(capability="in_transit_transfer.query_inventory")
|
||||
return IntegrationCallResult(status="success", data={"found": True, "quantity": Decimal("600")})
|
||||
rows = [
|
||||
{"material_no": t["material_no"], "from_warehouse": t["from_warehouse"],
|
||||
"lot_no": t["lot_no"], "quantity": Decimal("600")}
|
||||
for t in kwargs["params"]["targets"]
|
||||
]
|
||||
return IntegrationCallResult(status="success", data={"rows": rows})
|
||||
|
||||
deps, _, _ = make_transfer_deps(dbs_ready_file, crane_ready_file)
|
||||
deps = replace(deps, erp=CapabilityErpAdapter(gateway=_SplitGateway()))
|
||||
deps = replace(deps, capabilities=CapabilityClient(gateway=_SplitGateway()))
|
||||
result = run_precheck(
|
||||
source_codes=["DBS-AWSBI", "CRANE-SZ"], business_date="2026-08-06",
|
||||
deps=deps, run_no="RUN-T",
|
||||
)
|
||||
# [断言意图] 外部系统基础设施故障降级为逐票 blocked_external_query_failed:
|
||||
# 来源保持 file_ready,发票带原因可见,其余来源(CRANE)不受影响。
|
||||
dbs_source = next(s for s in result.sources if s.source_code == "DBS-AWSBI")
|
||||
assert dbs_source.stage == "failed"
|
||||
assert dbs_source.stage == "file_ready"
|
||||
dbs_items = [i for i in result.items if i.source_code == "DBS-AWSBI"]
|
||||
assert dbs_items and all(i.result == "blocked_external_query_failed" for i in dbs_items)
|
||||
assert all("no binding for capability" in i.reason for i in dbs_items)
|
||||
# CRANE 正常执行 → 出可执行项
|
||||
assert any(i.invoice_no == "INV-008" and i.result == "executable" for i in result.items)
|
||||
assert any(i.invoice_no == "WTP-008" and i.result == "executable" for i in result.items)
|
||||
@@ -0,0 +1,55 @@
|
||||
"""收料回调桥与超时回收测试。
|
||||
|
||||
用途:验证收料回调终态能推进调拨 waiting_rpa_callback 来源任务(Task 6),
|
||||
以及超时未回调的任务被回收为 failed(Task 8)。
|
||||
依赖:app(SQLite)fixture、TransferSourceJob/TransferRun 工厂、回调桥函数。
|
||||
逻辑:成功带文件 → file_ready;失败/空数据 → failed 带错误码;桥内异常不外抛。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from app import db
|
||||
from app.models import TransferSourceJob, TransferRun
|
||||
from app.services.in_transit_transfer.receipt_callback_bridge import (
|
||||
advance_source_job_from_receipt_callback,
|
||||
)
|
||||
|
||||
|
||||
def _make_waiting_job(run_no: str, source_code: str = "DSV360_AWSDU") -> TransferSourceJob:
|
||||
"""造一个处于 waiting_rpa_callback 的来源任务(status/trigger_type 必须取冻结枚举值)。"""
|
||||
run = TransferRun(run_no=run_no, business_date="2026-09-17", status="preparing_files", trigger_type="manual")
|
||||
db.session.add(run)
|
||||
db.session.flush()
|
||||
job = TransferSourceJob(run_id=run.id, source_code=source_code, status="waiting_rpa_callback")
|
||||
db.session.add(job)
|
||||
db.session.commit()
|
||||
return job
|
||||
|
||||
|
||||
def test_success_callback_advances_job_to_file_ready(app):
|
||||
"""成功回调(含文件号/sha256)应把最新等待任务推进为 file_ready。"""
|
||||
job = _make_waiting_job("RUN-BRIDGE-1")
|
||||
advanced = advance_source_job_from_receipt_callback(
|
||||
source_code=job.source_code, file_no="42", file_sha256="abc", callback_ok=True,
|
||||
)
|
||||
assert advanced is not None and advanced.status == "file_ready"
|
||||
assert advanced.file_no == "42" and advanced.file_sha256 == "abc"
|
||||
assert advanced.finished_at is not None
|
||||
|
||||
|
||||
def test_recover_stale_waiting_source_jobs(app):
|
||||
"""超过收料回调超时的等待任务回收为 failed;新任务不动。"""
|
||||
from app.services.in_transit_transfer.receipt_callback_bridge import recover_stale_waiting_source_jobs
|
||||
|
||||
stale = _make_waiting_job("RUN-BRIDGE-STALE-1", "DSV360_AWSDU")
|
||||
stale.updated_at = datetime.utcnow() - timedelta(seconds=3600)
|
||||
fresh = _make_waiting_job("RUN-BRIDGE-STALE-2", "DSV360_AWSSG")
|
||||
assert fresh.updated_at > datetime.utcnow() - timedelta(seconds=60)
|
||||
recovered = recover_stale_waiting_source_jobs()
|
||||
db.session.expire_all()
|
||||
assert recovered == 1
|
||||
assert db.session.get(TransferSourceJob, stale.id).status == "failed"
|
||||
assert db.session.get(TransferSourceJob, stale.id).error_code == "RPA_RECEIPT_CALLBACK_TIMEOUT"
|
||||
assert db.session.get(TransferSourceJob, fresh.id).status == "waiting_rpa_callback"
|
||||
@@ -1,7 +1,8 @@
|
||||
"""真实收料 RPA 触发服务测试。
|
||||
|
||||
用途:验证 trigger_receipt_rpa 按来源装配收料 trigger unit 并调用写者;
|
||||
配置/来源/触发目录缺失时 fail-closed(ok=False)。
|
||||
触发先落 ShippingReceiptRpaUnitRun(awaiting_rpa、真实 unit_run_id 进载荷);
|
||||
配置/来源/触发目录缺失时 fail-closed(ok=False 或单元标 failed)。
|
||||
依赖:app(SQLite)fixture、receipt_trigger_service.trigger_receipt_rpa、
|
||||
既有测试种子(ShippingRpaProfile/ShippingInventorySource)。
|
||||
逻辑:来源停用或收料配置缺失不写 trigger,返回 ok=False。
|
||||
@@ -21,9 +22,9 @@ 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,
|
||||
inventory_source_id=source.id,
|
||||
report_path_json={'program_group': 'Bison', 'report_name': 'On Hand Inventory By Location 3lv'},
|
||||
query_parameters_json=[], warehouse_ids_json=[],
|
||||
query_parameters_json=[{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': False, 'select_all': False}],
|
||||
)
|
||||
from app import db
|
||||
|
||||
@@ -50,6 +51,8 @@ def test_trigger_receipt_rpa_writes_batch_trigger(app, receipt_source):
|
||||
assert result['callback_id']
|
||||
assert result['trigger_path'].endswith('.json')
|
||||
assert calls['units'][0]['source_code'] == 'DSV360_AWSDU'
|
||||
# 关键断言:按需触发取 Warehouse 条件的第一个仓作为拆分维度。
|
||||
assert calls['units'][0]['warehouse_id'] == 'AWSDU'
|
||||
assert calls['units'][0]['credential_envelope']
|
||||
assert calls['payload']['schema_version'] == 'shipping_receipt_rpa.v1'
|
||||
|
||||
@@ -70,3 +73,97 @@ 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
|
||||
|
||||
|
||||
def test_trigger_receipt_rpa_creates_unit_run_before_writing_trigger(app, receipt_source):
|
||||
"""触发必须先落 ShippingReceiptRpaUnitRun(awaiting_rpa),否则回调按 callback_id 404。"""
|
||||
from app import db
|
||||
from app.models import ShippingReceiptRpaUnitRun
|
||||
|
||||
captured: dict = {}
|
||||
|
||||
def fake_writer(run_no, units, payload=None):
|
||||
# [断言意图] writer 收到的载荷必须携带真实 unit.id——
|
||||
# 单元行先 flush 拿 id,再序列化进 trigger,回调才能按 callback_id 找到单元。
|
||||
captured["units"] = units
|
||||
return "trigger.json"
|
||||
|
||||
outcome = trigger_receipt_rpa(
|
||||
source_code=receipt_source.source_code, business_date="2026-09-17",
|
||||
reason="transfer_retry_receipt", writer=fake_writer,
|
||||
)
|
||||
assert outcome["ok"] is True
|
||||
unit = ShippingReceiptRpaUnitRun.query.filter_by(callback_id=outcome["callback_id"]).one()
|
||||
assert unit.status == "awaiting_rpa"
|
||||
# [断言意图] 按需触发无排程 run,schedule_run_id 必须为 NULL——
|
||||
# PostgreSQL 上 FK 禁止 0 占位(SQLite 测试库不强制 FK,需显式守住列可空契约)。
|
||||
assert unit.schedule_run_id is None
|
||||
assert ShippingReceiptRpaUnitRun.__table__.columns['schedule_run_id'].nullable is True
|
||||
assert captured["units"][0]["unit_run_id"] == unit.id
|
||||
assert unit.trigger_snapshot_json["callback_id"] == unit.callback_id
|
||||
|
||||
|
||||
def _bind_published_movement_profile(config: ShippingReceiptReportConfig) -> None:
|
||||
"""给收料配置绑定一条已发布 movement 规则(仅满足守卫校验,不参与解析)。"""
|
||||
from app import db
|
||||
from app.models import ShippingInventoryParsingProfile
|
||||
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
purpose='movement', profile_code='MOVE_TRIGGER_STD', display_name='收料异动规则',
|
||||
version=1, status='published', file_format='xlsx',
|
||||
definition_json={'sheet_name': None, 'header_row_index': 1,
|
||||
'field_mapping': {'doc_no': '单据编号', 'material_code': '料号',
|
||||
'quantity': '数量', 'movement_date': '异动日期'},
|
||||
'match_keys': []},
|
||||
)
|
||||
db.session.add(profile)
|
||||
db.session.flush()
|
||||
config.parsing_profile_id = profile.id
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def test_default_rpa_trigger_writes_real_trigger_file(app, receipt_source, tmp_path, monkeypatch):
|
||||
"""deps 默认触发器必须真写 trigger 文件,不得只查配置就返回 ok=True(B1 断线根因)。"""
|
||||
from app.services.in_transit_transfer.deps import _DefaultRpaTrigger
|
||||
|
||||
with app.app_context():
|
||||
config = ShippingReceiptReportConfig.query.filter_by(
|
||||
inventory_source_id=receipt_source.id).one()
|
||||
_bind_published_movement_profile(config)
|
||||
|
||||
monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', str(tmp_path))
|
||||
outcome = _DefaultRpaTrigger().trigger(
|
||||
source_code=receipt_source.source_code, business_date="2026-09-17", reason="precheck_missing_ready_file",
|
||||
)
|
||||
assert outcome["ok"] is True
|
||||
# [断言意图] 真实落盘:Worker 轮询目录必须能看到待领取 trigger
|
||||
assert list(tmp_path.glob("receipt_export_batch_*.json")), "trigger file not written"
|
||||
|
||||
|
||||
def test_default_trigger_fails_closed_when_movement_profile_missing(app, receipt_source, tmp_path, monkeypatch):
|
||||
"""收料配置存在但未绑已发布 movement 规则 → ok=False 且不写 trigger(防徒劳抓取)。"""
|
||||
from app.services.in_transit_transfer.deps import _DefaultRpaTrigger
|
||||
|
||||
monkeypatch.setitem(app.config, 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR', str(tmp_path))
|
||||
outcome = _DefaultRpaTrigger().trigger(
|
||||
source_code=receipt_source.source_code, business_date="2026-09-17", reason="precheck_missing_ready_file",
|
||||
)
|
||||
# [断言意图] 未绑规则时抓回文件也无法解析复用,必须 fail-closed 且不落 trigger 文件。
|
||||
assert outcome["ok"] is False
|
||||
assert outcome["error_code"] == "RPA_RECEIPT_MOVEMENT_PROFILE_MISSING"
|
||||
assert list(tmp_path.glob("receipt_export_batch_*.json")) == []
|
||||
|
||||
|
||||
def test_trigger_receipt_rpa_marks_unit_failed_when_trigger_unavailable(app, receipt_source):
|
||||
"""trigger 目录不可用(writer 返回 None)时单元必须标 failed,不留永久 awaiting 幽灵。"""
|
||||
from app.models import ShippingReceiptRpaUnitRun
|
||||
|
||||
outcome = trigger_receipt_rpa(
|
||||
source_code=receipt_source.source_code, business_date="2026-09-17",
|
||||
reason="transfer_retry_receipt", writer=lambda *a, **k: None,
|
||||
)
|
||||
assert outcome["ok"] is False
|
||||
unit = ShippingReceiptRpaUnitRun.query.filter_by(source_code=receipt_source.source_code).order_by(
|
||||
ShippingReceiptRpaUnitRun.id.desc()).first()
|
||||
assert unit.status == "failed"
|
||||
assert unit.error_code == "RPA_RECEIPT_TRIGGER_UNAVAILABLE"
|
||||
@@ -3,7 +3,7 @@
|
||||
用途:验证历史可恢复项下一排程重新预检并创建新 Attempt;
|
||||
result_unknown / manually_closed / success 不自动写入。
|
||||
依赖:transfer_db、precheck_service、recovery_service、repo_fakes。
|
||||
逻辑:恢复 = 重新预检(仅查询/匹配),不写 ERP;每次恢复新 Attempt。
|
||||
逻辑:恢复 = 重新预检(仅查询/匹配),不写 外部系统;每次恢复新 Attempt。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -20,20 +20,20 @@ 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
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000") # mismatch → blocked
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "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 落库。"""
|
||||
"""外部系统 修正后恢复 → 项转 ready_to_execute,新 Attempt 落库。"""
|
||||
deps, erp, summary = _mixed_precheck(dbs_ready_file)
|
||||
item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="INV-001").first()
|
||||
item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
|
||||
assert item.status == "blocked_recoverable"
|
||||
old_attempt_no = item.attempt_no
|
||||
|
||||
erp.seed_inventory("INV-001", "1200")
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
outcome = run_daily_recovery(business_date="2026-08-06", deps=deps)
|
||||
assert outcome.recovered_count == 1
|
||||
assert outcome.attempts_created == 1
|
||||
@@ -42,15 +42,15 @@ def test_recovery_reprechecks_and_creates_new_attempt(transfer_db, dbs_ready_fil
|
||||
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 len(attempts) == 1 and attempts[0].kind == "external_query"
|
||||
# 恢复仅预检,不写 外部系统
|
||||
assert erp.write_calls() == []
|
||||
|
||||
|
||||
def test_recovery_skips_result_unknown_without_erp(transfer_db, dbs_ready_file):
|
||||
"""result_unknown 不自动恢复,也不产生 ERP 调用。"""
|
||||
"""result_unknown 不自动恢复,也不产生 外部系统 调用。"""
|
||||
deps, erp, summary = _mixed_precheck(dbs_ready_file)
|
||||
item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="INV-001").first()
|
||||
item = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
|
||||
item.status = "result_unknown"
|
||||
db.session.commit()
|
||||
|
||||
@@ -63,10 +63,10 @@ def test_recovery_skips_result_unknown_without_erp(transfer_db, dbs_ready_file):
|
||||
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 = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOM-001").first()
|
||||
blocked.status = "manually_closed"
|
||||
blocked.manually_closed_reason = "线下处理"
|
||||
success = db.session.query(TransferInvoiceItem).filter_by(invoice_no="INV-002").first()
|
||||
success = db.session.query(TransferInvoiceItem).filter_by(invoice_no="HOX-002").first()
|
||||
success.status = "success"
|
||||
db.session.commit()
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""在途调拨人工重试与人工关闭测试(Phase 3,L1)。
|
||||
|
||||
用途:验证人工重试只创建新 Attempt(重新查询 ERP,不重新抓 RPA、不写 ERP),
|
||||
用途:验证人工重试只创建新 Attempt(重新查询 外部系统,不重新抓 RPA、不写 外部系统),
|
||||
result_unknown 拒绝重试;人工关闭原因必填且永久排除。
|
||||
依赖:transfer_db、precheck_service、retry_service、manual_close_service、repo_fakes。
|
||||
逻辑:重试前冻结文件不变;每次重试 attempt_no 递增且旧 Attempt 保留。
|
||||
@@ -15,15 +15,15 @@ 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 app.services.in_transit_transfer.retry_service import requery_items, 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")
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1000")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "1200")
|
||||
summary = create_precheck(source_codes=["DBS-AWSBI"], business_date="2026-08-06", deps=deps)
|
||||
return deps, erp, summary
|
||||
|
||||
@@ -33,13 +33,13 @@ def _item_by_invoice(invoice_no: str) -> TransferInvoiceItem:
|
||||
|
||||
|
||||
def test_retry_creates_new_attempt_and_matches(transfer_db, dbs_ready_file):
|
||||
"""ERP 修正后重试 → 新 Attempt,状态进入 ready_to_execute。"""
|
||||
"""外部系统 修正后重试 → 新 Attempt,状态进入 ready_to_execute。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
item = _item_by_invoice("INV-001")
|
||||
item = _item_by_invoice("HOM-001")
|
||||
assert item.status == "blocked_recoverable"
|
||||
old_attempt_count = item.attempt_no
|
||||
|
||||
erp.seed_inventory("INV-001", "1200") # 人工在 ERP 修正库存
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") # 人工在 外部系统 修正库存
|
||||
result = retry_item(item_id=item.id, deps=deps)
|
||||
assert result["status"] == "ready_to_execute"
|
||||
assert result["attempt_no"] == old_attempt_count + 1
|
||||
@@ -49,25 +49,79 @@ def test_retry_creates_new_attempt_and_matches(transfer_db, dbs_ready_file):
|
||||
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 attempts[0].kind == "external_query"
|
||||
# 重试不写 外部系统
|
||||
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")
|
||||
item = _item_by_invoice("HOM-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
|
||||
# [断言意图] 数量不足也是 外部系统 的真实答复:外部系统 库存数必须落库(从数量列可见),
|
||||
# 用户不得因只看到"已阻断"而误以为查询失败。
|
||||
refreshed = db.session.get(TransferInvoiceItem, item.id)
|
||||
assert refreshed.external_quantity == "1000"
|
||||
assert refreshed.result_code == "blocked_quantity_mismatch"
|
||||
|
||||
|
||||
def test_retry_not_found_shows_zero_stock(transfer_db, dbs_ready_file):
|
||||
"""重查后外部系统查无记录 → 库存数按 0 落库展示,不显示"-"误导为查询失败。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
item = _item_by_invoice("HOM-001")
|
||||
retry_item(item_id=item.id, deps=deps) # 先产生 external_quantity=1000
|
||||
assert _item_by_invoice("HOM-001").external_quantity == "1000"
|
||||
|
||||
erp.clear_stock() # 外部系统库存被移走(查无记录)
|
||||
retry_item(item_id=item.id, deps=deps)
|
||||
|
||||
refreshed = db.session.get(TransferInvoiceItem, item.id)
|
||||
assert refreshed.result_code == "blocked_inventory_not_found"
|
||||
# [断言意图] 无记录按 0 展示而非空值,用户可直观看到"外部系统已无库存"。
|
||||
assert refreshed.external_quantity == "0"
|
||||
|
||||
|
||||
def test_retry_ready_row_allowed(transfer_db, dbs_ready_file):
|
||||
"""可执行(ready_to_execute)行也允许重查:预检后库存变化需可复核。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
item = _item_by_invoice("HOM-001")
|
||||
item.status = "ready_to_execute"
|
||||
db.session.commit()
|
||||
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") # 库存已补足
|
||||
result = retry_item(item_id=item.id, deps=deps)
|
||||
|
||||
assert result["status"] == "ready_to_execute"
|
||||
refreshed = db.session.get(TransferInvoiceItem, item.id)
|
||||
assert refreshed.external_quantity == "1200"
|
||||
|
||||
|
||||
def test_requery_includes_ready_rows(transfer_db, dbs_ready_file):
|
||||
"""批量重查范围含可执行行:可执行行也会被逐票刷新,而非只刷阻断行。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
item = _item_by_invoice("HOM-001")
|
||||
item.status = "ready_to_execute"
|
||||
db.session.commit()
|
||||
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "500") # 库存被挪用
|
||||
result = requery_items(precheck_no=summary.precheck_id, deps=deps)
|
||||
|
||||
# [断言意图] 可执行行不再被重查排除;库存变化后被重查回阻断态并保留 外部系统 数。
|
||||
assert result["total"] == 2
|
||||
refreshed = db.session.get(TransferInvoiceItem, item.id)
|
||||
assert refreshed.status == "blocked_recoverable"
|
||||
assert refreshed.result_code == "blocked_quantity_mismatch"
|
||||
assert refreshed.external_quantity == "500"
|
||||
|
||||
|
||||
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 = _item_by_invoice("HOM-001")
|
||||
item.status = "result_unknown"
|
||||
item.result_code = "result_unknown"
|
||||
db.session.commit()
|
||||
@@ -79,7 +133,7 @@ def test_retry_result_unknown_rejected(transfer_db, dbs_ready_file):
|
||||
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")
|
||||
item = _item_by_invoice("HOM-001")
|
||||
with pytest.raises(ValidationError):
|
||||
retry_item(item_id=item.id, deps=deps, kind="rpa_refetch")
|
||||
|
||||
@@ -87,7 +141,7 @@ def test_retry_rpa_refetch_rejected_after_run(transfer_db, dbs_ready_file):
|
||||
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")
|
||||
item = _item_by_invoice("HOM-001")
|
||||
with pytest.raises(ValidationError):
|
||||
manual_close_item(item_id=item.id, reason="")
|
||||
|
||||
@@ -95,7 +149,7 @@ def test_manual_close_requires_reason(transfer_db, dbs_ready_file):
|
||||
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")
|
||||
item = _item_by_invoice("HOM-001")
|
||||
result = manual_close_item(item_id=item.id, reason="货代确认无需调拨")
|
||||
assert result["status"] == "manually_closed"
|
||||
refreshed = db.session.get(TransferInvoiceItem, item.id)
|
||||
@@ -110,8 +164,68 @@ def test_manual_close_marks_terminal(transfer_db, dbs_ready_file):
|
||||
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 = _item_by_invoice("HOM-001")
|
||||
item.status = "result_unknown"
|
||||
db.session.commit()
|
||||
with pytest.raises(ValidationError):
|
||||
manual_close_item(item_id=item.id, reason="尝试关闭未知项")
|
||||
|
||||
|
||||
def test_requery_items_refreshes_blocked_rows(transfer_db, dbs_ready_file):
|
||||
"""批量重查:同预检全部可重查行(阻断 + 可执行)逐票刷新,结果按行回报。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200") # 人工在 外部系统 修正库存
|
||||
result = requery_items(precheck_no=summary.precheck_id, deps=deps)
|
||||
# [断言意图] 阻断行(HOM-001)与可执行行(HOX-002)都在重查范围内。
|
||||
assert result["total"] == 2
|
||||
rows = {row["invoice_no"]: row for row in result["results"]}
|
||||
assert rows["HOM-001"]["ok"] is True
|
||||
assert rows["HOM-001"]["status"] == "ready_to_execute"
|
||||
assert rows["HOX-002"]["ok"] is True
|
||||
assert rows["HOX-002"]["status"] == "ready_to_execute"
|
||||
|
||||
|
||||
def test_requery_items_invoice_filter_targets_only_given_rows(transfer_db, dbs_ready_file):
|
||||
"""invoice_nos 限定范围:不在清单的阻断行不被触碰。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
blocked = db.session.query(TransferInvoiceItem).filter_by(status="blocked_recoverable").all()
|
||||
assert [i.invoice_no for i in blocked] == ["HOM-001"]
|
||||
|
||||
result = requery_items(precheck_no=summary.precheck_id, deps=deps, invoice_nos=["INV-XXX"])
|
||||
assert result["total"] == 0
|
||||
assert _item_by_invoice("HOM-001").status == "blocked_recoverable"
|
||||
|
||||
|
||||
def test_retry_erp_binding_failure_degrades_instead_of_raising(transfer_db, dbs_ready_file):
|
||||
"""[回归防线 2026-09-21] 外部系统 网关/绑定故障 → 单行重查降级为
|
||||
blocked_external_query_failed + 原因,不向调用方抛异常。
|
||||
|
||||
此前该场景抛 BindingNotFoundError('no binding for capability'),
|
||||
与 precheck 的逐票降级语义不一致,用户侧表现为全局错误弹窗。
|
||||
"""
|
||||
deps, erp, _summary = _mismatch_precheck(dbs_ready_file)
|
||||
erp.set_query_scenario("error") # RuntimeError: binding not found for capability query_inventory
|
||||
item = _item_by_invoice("HOM-001")
|
||||
old_attempts = db.session.query(TransferAttempt).filter_by(item_id=item.id).count()
|
||||
|
||||
result = retry_item(item_id=item.id, deps=deps) # 不得抛出
|
||||
|
||||
assert result["status"] == "blocked_recoverable"
|
||||
refreshed = db.session.get(TransferInvoiceItem, item.id)
|
||||
# [断言意图] 失败事实落库可见:结果码 + 原因行内可解释。
|
||||
assert refreshed.result_code == "blocked_external_query_failed"
|
||||
assert "binding not found" in (refreshed.result_message or "")
|
||||
attempts = (db.session.query(TransferAttempt).filter_by(item_id=item.id)
|
||||
.order_by(TransferAttempt.id).all())
|
||||
assert len(attempts) == old_attempts + 1
|
||||
assert attempts[-1].status == "failed"
|
||||
|
||||
|
||||
def test_requery_with_erp_gateway_failure_stays_batched(transfer_db, dbs_ready_file):
|
||||
"""批量重查遇 外部系统 故障:逐票降级、批次正常完成,不炸整批。"""
|
||||
deps, erp, summary = _mismatch_precheck(dbs_ready_file)
|
||||
erp.set_query_scenario("error")
|
||||
result = requery_items(precheck_no=summary.precheck_id, deps=deps)
|
||||
assert result["total"] == 2
|
||||
assert all(row["ok"] for row in result["results"])
|
||||
assert _item_by_invoice("HOM-001").result_code == "blocked_external_query_failed"
|
||||
@@ -0,0 +1,126 @@
|
||||
"""调拨路由解析器测试。
|
||||
|
||||
用途:验证 DefaultRouteResolver 的拨出库位与映射行选择契约——
|
||||
拨出库位 = 仓库映射的在途仓编码(必填),拨入仓库 = 映射的目标仓库代码;
|
||||
inventory_match 源优先按「收料文件仓库 == 货代仓库」精确匹配,
|
||||
匹配不到回退「货代仓库为空」的默认映射行(空库位兜底)。
|
||||
依赖:app fixture 种子站点、ShippingInventoryExternalMapping、DefaultRouteResolver。
|
||||
逻辑:fixed 源仅一条启用映射直接取用;任何映射行缺失或在途仓编码未维护 fail-closed。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.extensions import db
|
||||
from app.models import ShippingInventoryExternalMapping, ShippingInventorySource
|
||||
from app.services.in_transit_transfer.deps import DefaultRouteResolver
|
||||
from app.services.in_transit_transfer.precheck_service import RouteNotResolvedError
|
||||
|
||||
|
||||
def _seed_mapping(
|
||||
source: ShippingInventorySource, *, freight_warehouse_id: str | None,
|
||||
in_transit_warehouse_code: str = 'TZT-01',
|
||||
) -> ShippingInventoryExternalMapping:
|
||||
"""在既有种子来源上挂一条启用映射。"""
|
||||
mapping = ShippingInventoryExternalMapping(
|
||||
inventory_source_id=source.id, freight_warehouse_id=freight_warehouse_id,
|
||||
external_system_code='TOPGP', external_organization_code='TGHX',
|
||||
external_warehouse_code='HUB-CN01', external_warehouse_name='HUB 仓',
|
||||
in_transit_warehouse_code=in_transit_warehouse_code, enabled=True,
|
||||
)
|
||||
db.session.add(mapping)
|
||||
db.session.commit()
|
||||
return mapping
|
||||
|
||||
|
||||
def _seed_inventory_match_source() -> ShippingInventorySource:
|
||||
"""以种子站点(fixed)的绑定配置为模板,新建 inventory_match 识别方式的来源。"""
|
||||
template = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source = ShippingInventorySource(
|
||||
source_code='DSV360_CRANE', display_name='Crane 测试源', connector_type='crane',
|
||||
rpa_profile_id=template.rpa_profile_id, parsing_profile_id=template.parsing_profile_id,
|
||||
excel_template_id=template.excel_template_id,
|
||||
warehouse_resolution_mode='inventory_match', fixed_warehouse_id=None, enabled=True,
|
||||
)
|
||||
db.session.add(source)
|
||||
db.session.commit()
|
||||
return source
|
||||
|
||||
|
||||
def test_fixed_source_uses_single_mapping_in_transit_code(app):
|
||||
"""fixed 源仅一条启用映射:拨出库位取该行在途仓编码而非货代仓库/站点固定仓。"""
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
# 种子站点 fixed_warehouse_id='AWSDU';断言取映射在途仓 'TZT-01',证明拨出库位来自新字段。
|
||||
_seed_mapping(source, freight_warehouse_id='TZR2')
|
||||
|
||||
route = DefaultRouteResolver().resolve(
|
||||
source_code='DSV360_AWSDU', invoice_no='INV-1', warehouse_code='')
|
||||
|
||||
assert route.from_warehouse == 'TZT-01'
|
||||
assert route.to_warehouse == 'HUB-CN01'
|
||||
assert route.external_org == 'TGHX'
|
||||
|
||||
|
||||
def test_inventory_match_prefers_receipt_warehouse_exact_mapping(app):
|
||||
"""inventory_match 源:收料仓库与某行货代仓库精确匹配 → 取该行在途仓编码。"""
|
||||
with app.app_context():
|
||||
source = _seed_inventory_match_source()
|
||||
_seed_mapping(source, freight_warehouse_id=None, in_transit_warehouse_code='TZT-DEFAULT')
|
||||
_seed_mapping(source, freight_warehouse_id='WMS-A', in_transit_warehouse_code='TZT-A')
|
||||
|
||||
route = DefaultRouteResolver().resolve(
|
||||
source_code='DSV360_CRANE', invoice_no='INV-1', warehouse_code='wms-a')
|
||||
|
||||
# [断言意图] 收料仓库小写传入也须命中大写归一的货代仓库身份。
|
||||
assert route.from_warehouse == 'TZT-A'
|
||||
assert route.to_warehouse == 'HUB-CN01'
|
||||
|
||||
|
||||
def test_inventory_match_falls_back_to_empty_freight_mapping(app):
|
||||
"""inventory_match 源:收料仓库无精确映射 → 回退货代仓库为空的默认映射行(空库位兜底)。"""
|
||||
with app.app_context():
|
||||
source = _seed_inventory_match_source()
|
||||
_seed_mapping(source, freight_warehouse_id=None, in_transit_warehouse_code='TZT-DEFAULT')
|
||||
_seed_mapping(source, freight_warehouse_id='WMS-A', in_transit_warehouse_code='TZT-A')
|
||||
|
||||
route = DefaultRouteResolver().resolve(
|
||||
source_code='DSV360_CRANE', invoice_no='INV-1', warehouse_code='WMS-UNKNOWN')
|
||||
|
||||
assert route.from_warehouse == 'TZT-DEFAULT'
|
||||
|
||||
|
||||
def test_inventory_match_blank_warehouse_goes_to_default_mapping(app):
|
||||
"""inventory_match 源:收料文件仓库列缺失 → 直接走空库位默认映射行。"""
|
||||
with app.app_context():
|
||||
source = _seed_inventory_match_source()
|
||||
_seed_mapping(source, freight_warehouse_id=None, in_transit_warehouse_code='TZT-DEFAULT')
|
||||
_seed_mapping(source, freight_warehouse_id='WMS-A', in_transit_warehouse_code='TZT-A')
|
||||
|
||||
route = DefaultRouteResolver().resolve(
|
||||
source_code='DSV360_CRANE', invoice_no='INV-1', warehouse_code='')
|
||||
|
||||
assert route.from_warehouse == 'TZT-DEFAULT'
|
||||
|
||||
|
||||
def test_inventory_match_fails_closed_without_any_match(app):
|
||||
"""inventory_match 源:无精确映射也无默认映射行 → fail-closed。"""
|
||||
with app.app_context():
|
||||
source = _seed_inventory_match_source()
|
||||
_seed_mapping(source, freight_warehouse_id='WMS-A', in_transit_warehouse_code='TZT-A')
|
||||
|
||||
with pytest.raises(RouteNotResolvedError):
|
||||
DefaultRouteResolver().resolve(
|
||||
source_code='DSV360_CRANE', invoice_no='INV-1', warehouse_code='WMS-UNKNOWN')
|
||||
|
||||
|
||||
def test_route_resolver_fails_closed_without_in_transit_code(app):
|
||||
"""映射未维护在途仓编码(存量空串)→ 拨出库位无来源,fail-closed。"""
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
_seed_mapping(source, freight_warehouse_id=None, in_transit_warehouse_code='')
|
||||
|
||||
with pytest.raises(RouteNotResolvedError):
|
||||
DefaultRouteResolver().resolve(
|
||||
source_code='DSV360_AWSDU', invoice_no='INV-1', warehouse_code='')
|
||||
@@ -1,14 +1,16 @@
|
||||
"""来源收料文件状态投影服务测试。
|
||||
|
||||
用途:验证 resolve_source_file_status 只读货代收料事实(UnitRun/ReportFile),
|
||||
按来源投影 ready/fetching/failed/none。调拨不维护独立抓取状态表。
|
||||
按来源投影 ready/fetching/failed/expired/none。调拨不维护独立抓取状态表。
|
||||
依赖:app(SQLite)、ShippingInventorySource 种子、ScheduleTask/ScheduleRun/UnitRun/ReportFile。
|
||||
逻辑:有文件→ready;有进行中单元→fetching;最新单元失败终态→failed;否则→none。
|
||||
逻辑:有当天(业务日)抓取且未过期文件→ready;有进行中单元→fetching;
|
||||
最新单元失败终态→failed;保留期已到或隔日旧文件(未清理)→expired;否则→none。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
import pytest
|
||||
|
||||
@@ -86,3 +88,69 @@ def test_report_file_is_ready(app, receipt_unit_run):
|
||||
assert status['has_ready_file'] is True
|
||||
assert status['file_no'] == 'receipt.xlsx'
|
||||
assert status['file_sha256'] == digest
|
||||
|
||||
|
||||
def test_expired_report_is_expired(app, receipt_unit_run):
|
||||
"""保留期已到但清理任务未删 → expired,不得误报 ready。"""
|
||||
# [断言意图] 过期判定只看 archive_expires_at,不依赖保留期清理任务是否已落位。
|
||||
from app import db
|
||||
from app.models import ShippingReceiptReportFile
|
||||
|
||||
receipt_unit_run.status = 'success'
|
||||
db.session.add(ShippingReceiptReportFile(
|
||||
unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test',
|
||||
storage_key='shipping/receipt/expired.xlsx', original_filename='expired.xlsx',
|
||||
file_size=16, sha256=hashlib.sha256(b'expired workbook').hexdigest(),
|
||||
archive_expires_at=datetime.utcnow() - timedelta(days=1),
|
||||
))
|
||||
db.session.commit()
|
||||
status = resolve_source_file_status(source_code=SOURCE_CODE)
|
||||
assert status['file_status'] == 'expired'
|
||||
assert status['has_ready_file'] is False
|
||||
|
||||
|
||||
def test_newer_valid_report_wins_over_expired(app, receipt_unit_run):
|
||||
"""过期文件之后又抓到未过期文件 → 以最新未过期文件为准(ready)。"""
|
||||
# [断言意图] ready 查询过滤掉过期记录后仍按 created_at/id 倒序取最新一条。
|
||||
from app import db
|
||||
from app.models import ShippingReceiptReportFile
|
||||
|
||||
receipt_unit_run.status = 'success'
|
||||
digest = hashlib.sha256(b'fresh workbook').hexdigest()
|
||||
db.session.add(ShippingReceiptReportFile(
|
||||
unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test',
|
||||
storage_key='shipping/receipt/expired.xlsx', original_filename='expired.xlsx',
|
||||
file_size=16, sha256=hashlib.sha256(b'expired workbook').hexdigest(),
|
||||
archive_expires_at=datetime.utcnow() - timedelta(days=1),
|
||||
))
|
||||
db.session.add(ShippingReceiptReportFile(
|
||||
unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test',
|
||||
storage_key='shipping/receipt/fresh.xlsx', original_filename='fresh.xlsx',
|
||||
file_size=16, sha256=digest,
|
||||
archive_expires_at=datetime.utcnow() + timedelta(days=365),
|
||||
))
|
||||
db.session.commit()
|
||||
status = resolve_source_file_status(source_code=SOURCE_CODE)
|
||||
assert status['file_status'] == 'ready'
|
||||
assert status['file_no'] == 'fresh.xlsx'
|
||||
assert status['file_sha256'] == digest
|
||||
|
||||
|
||||
def test_stale_report_is_expired(app, receipt_unit_run):
|
||||
"""文件保留期未到但非当天(业务日)抓取 → expired,不得误报 ready。"""
|
||||
# [断言意图] 新鲜度按 Asia/Shanghai 业务日窗口判定(UTC 库存时间须换算):
|
||||
# 隔日抓取的文件对 D+1 预检是旧数据,投影 expired 引导重试重抓。
|
||||
from app import db
|
||||
from app.models import ShippingReceiptReportFile
|
||||
|
||||
receipt_unit_run.status = 'success'
|
||||
db.session.add(ShippingReceiptReportFile(
|
||||
unit_run_id=receipt_unit_run.id, storage_provider='minio', storage_bucket='test',
|
||||
storage_key='shipping/receipt/stale.xlsx', original_filename='stale.xlsx',
|
||||
file_size=16, sha256=hashlib.sha256(b'stale workbook').hexdigest(),
|
||||
created_at=datetime.utcnow() - timedelta(days=1),
|
||||
))
|
||||
db.session.commit()
|
||||
status = resolve_source_file_status(source_code=SOURCE_CODE)
|
||||
assert status['file_status'] == 'expired'
|
||||
assert status['has_ready_file'] is False
|
||||
@@ -1,7 +1,7 @@
|
||||
"""在途调拨状态机与转换门禁测试(L0 纯单元)。
|
||||
|
||||
用途:验证提示词冻结的 13 个状态全部存在、非法迁移被服务端拒绝、
|
||||
result_unknown / manually_closed / success 无出边、通知失败不改变 ERP 结果。
|
||||
result_unknown / manually_closed / success 无出边、通知失败不改变 外部系统 结果。
|
||||
依赖:app.services.in_transit_transfer.status。
|
||||
逻辑:所有转换必须显式声明于转换表;未声明迁移一律抛 TransferStateError。
|
||||
"""
|
||||
@@ -93,7 +93,7 @@ def test_unknown_status_rejected():
|
||||
|
||||
|
||||
def test_not_matured_has_no_outgoing_edges():
|
||||
"""not_matured 无出边:当天不得查询 ERP、不得生成调拨单。"""
|
||||
"""not_matured 无出边:当天不得查询 外部系统、不得生成调拨单。"""
|
||||
assert ITEM_TRANSITIONS[TransferStatus.NOT_MATURED.value] == frozenset()
|
||||
|
||||
|
||||
@@ -106,13 +106,13 @@ def test_run_transition_queued_to_executing_path():
|
||||
|
||||
|
||||
def test_notification_failed_does_not_change_erp_result():
|
||||
"""通知失败不改变 ERP 结果:apply_notification_failure 返回原 ERP 终态。"""
|
||||
"""通知失败不改变 外部系统 结果:apply_notification_failure 返回原 外部系统 终态。"""
|
||||
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 阶段)。"""
|
||||
"""非终态 Run 不允许记录通知失败(必须先结束 外部系统 阶段)。"""
|
||||
with pytest.raises(TransferStateError):
|
||||
apply_notification_failure(TransferRunStatus.EXECUTING.value)
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
"""在途调拨策略硬门禁测试(L0 纯单元)。
|
||||
|
||||
用途:验证一期策略禁止部分数量调拨、数量容差与 ERP 自动重试,
|
||||
用途:验证一期策略禁止部分数量调拨、数量容差与 外部系统 自动重试,
|
||||
并强制默认确认有效期(10 分钟)。
|
||||
依赖:app.services.in_transit_transfer.strategy。
|
||||
逻辑:任何策略变体触碰三项禁令之一即抛 StrategyViolationError。
|
||||
@@ -45,15 +45,15 @@ def test_quantity_tolerance_rejected():
|
||||
|
||||
|
||||
def test_erp_auto_retry_rejected():
|
||||
"""开启 ERP 自动重试必须被拒绝(result_unknown 严禁自动重试)。"""
|
||||
strategy = TransferStrategyPolicy(allow_erp_auto_retry=True)
|
||||
"""开启 外部系统 自动重试必须被拒绝(result_unknown 严禁自动重试)。"""
|
||||
strategy = TransferStrategyPolicy(allow_external_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)
|
||||
strategy = TransferStrategyPolicy(allow_partial=True, allow_external_auto_retry=True)
|
||||
with pytest.raises(StrategyViolationError):
|
||||
validate_strategy(strategy)
|
||||
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
"""在途调拨类型契约测试(L1 纯单元)。
|
||||
|
||||
用途:验证调拨类型规范化/支持性门禁/类型 1 INVOICE 前缀过滤与范围说明。
|
||||
依赖:transfer_type 模块、invoice_aggregator(构造汇总票)。
|
||||
逻辑:纯函数测试,不创建 Flask/DB。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import ValidationError
|
||||
from app.services.in_transit_transfer.invoice_aggregator import AggregatedInvoice
|
||||
from app.services.in_transit_transfer.transfer_type import (
|
||||
HUB_REPAIR_OUT_ODM_ID,
|
||||
IN_TRANSIT_TO_HUB_INVOICE_PREFIXES,
|
||||
TRANSFER_TYPE_NOT_SUPPORTED,
|
||||
TransferType,
|
||||
ensure_transfer_type_supported,
|
||||
filter_invoices_for_type,
|
||||
normalize_transfer_type,
|
||||
transfer_type_scope_note,
|
||||
)
|
||||
|
||||
|
||||
def _invoice(invoice_no: str) -> AggregatedInvoice:
|
||||
"""构造最小汇总票(过滤只看 invoice_no)。"""
|
||||
return AggregatedInvoice(
|
||||
source_code="DBS-AWSBI", invoice_no=invoice_no, material_no="MAT-001",
|
||||
material_name="连接器组件", specification="A 型",
|
||||
receipt_date=date(2026, 8, 5), receipt_quantity=Decimal("100"),
|
||||
raw_lines=(),
|
||||
)
|
||||
|
||||
|
||||
def test_normalize_transfer_type_defaults_to_in_transit_to_hub():
|
||||
"""缺省/空值/None 回落类型 1(存量调用方语义不变)。"""
|
||||
assert normalize_transfer_type(None) == TransferType.IN_TRANSIT_TO_HUB
|
||||
assert normalize_transfer_type("") == TransferType.IN_TRANSIT_TO_HUB
|
||||
assert normalize_transfer_type("in_transit_to_hub") == TransferType.IN_TRANSIT_TO_HUB
|
||||
assert normalize_transfer_type(TransferType.HUB_TO_HUB) == TransferType.HUB_TO_HUB
|
||||
|
||||
|
||||
def test_normalize_transfer_type_rejects_unknown_value():
|
||||
"""非法类型值 → ValidationError(TRANSFER.TRANSFER_TYPE_INVALID)。"""
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
normalize_transfer_type("not_a_type")
|
||||
assert exc_info.value.code == "TRANSFER.TRANSFER_TYPE_INVALID"
|
||||
|
||||
|
||||
def test_ensure_supported_rejects_placeholder_types():
|
||||
"""类型 2/3 一期占位:进入处理链路被 fail-closed 拒绝。"""
|
||||
ensure_transfer_type_supported(TransferType.IN_TRANSIT_TO_HUB)
|
||||
for placeholder in (TransferType.HUB_REPAIR_OUT, TransferType.HUB_TO_HUB):
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
ensure_transfer_type_supported(placeholder)
|
||||
assert exc_info.value.code == TRANSFER_TYPE_NOT_SUPPORTED
|
||||
|
||||
|
||||
def test_filter_type1_keeps_invoice_prefixes_case_insensitive():
|
||||
"""类型 1 只保留 INVOICE 前缀 HOM/HOX/WTP(大小写不敏感)。"""
|
||||
invoices = [
|
||||
_invoice("HOM-20260801-01"),
|
||||
_invoice("hox-20260801-02"),
|
||||
_invoice("WTP-20260801-03"),
|
||||
_invoice("INV-001"),
|
||||
_invoice("RCP-9"),
|
||||
_invoice("OTHER-1"),
|
||||
]
|
||||
kept = filter_invoices_for_type(invoices, TransferType.IN_TRANSIT_TO_HUB)
|
||||
assert [invoice.invoice_no for invoice in kept] == [
|
||||
"HOM-20260801-01", "hox-20260801-02", "WTP-20260801-03",
|
||||
]
|
||||
|
||||
|
||||
def test_filter_type1_empty_invoice_no_excluded():
|
||||
"""空/空白 Invoice 号不匹配任何前缀 → 排除(防御性)。"""
|
||||
kept = filter_invoices_for_type([_invoice("")], TransferType.IN_TRANSIT_TO_HUB)
|
||||
assert kept == []
|
||||
assert set(IN_TRANSIT_TO_HUB_INVOICE_PREFIXES) == {"HOM", "HOX", "WTP"}
|
||||
assert HUB_REPAIR_OUT_ODM_ID == "HoxinRMA"
|
||||
|
||||
|
||||
def test_scope_note_records_type_rule():
|
||||
"""范围说明写入 scope_json 的审计口径。"""
|
||||
assert transfer_type_scope_note(TransferType.IN_TRANSIT_TO_HUB) == "invoice_prefix:hom+hox+wtp"
|
||||
assert transfer_type_scope_note(TransferType.HUB_REPAIR_OUT) == "odm_id:HoxinRMA"
|
||||
assert transfer_type_scope_note(TransferType.HUB_TO_HUB) == "pending_rule"
|
||||
@@ -3,7 +3,7 @@
|
||||
用途:验证执行中(executing)且租约过期的项可恢复(依赖 Invoice 幂等,不重复建单)、
|
||||
停滞 Run 可终态收尾、result_unknown 不被自动重试。
|
||||
依赖:transfer_db、precheck/execution/recovery、repo_fakes。
|
||||
逻辑:恢复 = 重新写前复查 + 幂等写入;已落单场景由 ERP 返回 duplicate_success。
|
||||
逻辑:恢复 = 重新写前复查 + 幂等写入;已落单场景由 外部系统 返回 duplicate_success。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -27,8 +27,8 @@ 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")
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "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"
|
||||
@@ -44,13 +44,13 @@ def test_recover_stale_execution_items_completes_writes(transfer_db, dbs_ready_f
|
||||
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)
|
||||
assert all(item.external_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)。"""
|
||||
"""result_unknown 不自动重试(不触碰、不写 外部系统)。"""
|
||||
deps, erp = _executing_precheck(dbs_ready_file)
|
||||
item = db.session.query(TransferInvoiceItem).first()
|
||||
item.status = "result_unknown"
|
||||
@@ -68,14 +68,14 @@ def test_finalize_stale_runs_marks_terminal(transfer_db, dbs_ready_file):
|
||||
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")
|
||||
erp.seed_stock("MAT-001", "DBS-TRANSIT", "LOT-10", "1200")
|
||||
erp.seed_stock("MAT-002", "DBS-TRANSIT", "LOT-20", "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"
|
||||
item.external_document_no = "TRF-DONE"
|
||||
db.session.commit()
|
||||
|
||||
run_ids = finalize_stale_runs()
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
用途:验证 Binding 解析与版本冻结——默认/上下文覆盖/优先级/生效区间/状态门禁/fail-closed。
|
||||
依赖:IntegrationBinding 等模型、binding.py、errors.py。
|
||||
逻辑:只匹配 published + environment + 生效区间 + context_selector 子集;
|
||||
接口定义须 published、客户端须 enabled,否则同样 fail-closed;
|
||||
无命中抛 BindingNotFoundError;快照冻结 interface 版本与配置(调用期冻结,非活表)。
|
||||
"""
|
||||
|
||||
@@ -120,3 +121,43 @@ def test_freeze_versions_in_snapshot(app):
|
||||
assert snap.credential_ref_code is None
|
||||
assert snap.request_spec.get("path") == "/stock"
|
||||
assert snap.config.get("endpoint") == "https://erp.invalid"
|
||||
|
||||
|
||||
def test_snapshot_carries_param_mapping_and_input_schema(app):
|
||||
"""快照冻结绑定参数映射与接口入参 Schema(引擎翻译契约)。"""
|
||||
db.session.add_all([
|
||||
_client(),
|
||||
_interface(input_schema_json={"type": "object", "required": ["condition"]}),
|
||||
_binding(param_mapping_json={"condition": {"template": "img04 = '{invoice_no}'"}}),
|
||||
])
|
||||
db.session.commit()
|
||||
snap = resolve_binding("in_transit_transfer.query_inventory", {}, "prod")
|
||||
assert snap.param_mapping == {"condition": {"template": "img04 = '{invoice_no}'"}}
|
||||
assert snap.input_schema == {"type": "object", "required": ["condition"]}
|
||||
|
||||
|
||||
def test_draft_interface_not_matched(app):
|
||||
"""接口定义为 draft 时不命中(fail-closed):绑定已发布但接口未发布视同无可用绑定。"""
|
||||
db.session.add_all([_client(), _interface(status="draft"), _binding()])
|
||||
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_retired_interface_not_matched(app):
|
||||
"""接口定义为 retired 时不命中:退役是引用它的所有绑定的总开关。"""
|
||||
db.session.add_all([_client(), _interface(status="retired"), _binding()])
|
||||
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_disabled_client_not_matched(app):
|
||||
"""客户端实例停用(enabled=False)时不命中:列表行内启停开关具备调用期语义。"""
|
||||
db.session.add_all([_client(enabled=False), _interface(), _binding()])
|
||||
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"
|
||||
@@ -11,9 +11,7 @@ import pytest
|
||||
|
||||
from app.services.integration_connector.capability import (
|
||||
CapabilitySpec,
|
||||
ensure_capabilities_loaded,
|
||||
get_capability,
|
||||
list_capabilities,
|
||||
register_capability,
|
||||
reset_capability_registry_for_tests,
|
||||
)
|
||||
@@ -47,13 +45,3 @@ def test_get_unregistered_raises_not_found():
|
||||
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,51 @@
|
||||
"""tests/services/integration_connector/test_credential_types.py
|
||||
|
||||
用途:验证凭据类型注册表——字段组装/必填校验/非密回显/未知类型 fail-closed。
|
||||
依赖:credential_types(纯函数)。
|
||||
逻辑:build_secret_dict 只保留类型定义内字段且必填齐全;visible_fields 只回显非密字段。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import AppError
|
||||
from app.services.integration_connector.credential_types import (
|
||||
build_secret_dict,
|
||||
get_credential_type,
|
||||
list_credential_types,
|
||||
visible_fields,
|
||||
)
|
||||
|
||||
|
||||
def test_registry_contains_builtin_types():
|
||||
"""内置 password/token/api_key 三种类型,字段定义齐全。"""
|
||||
types = {item["type"] for item in list_credential_types()}
|
||||
assert types == {"password", "token", "api_key"}
|
||||
password_fields = {f["key"]: f for f in get_credential_type("password")["fields"]}
|
||||
assert set(password_fields) == {"username", "password"}
|
||||
assert password_fields["password"]["secret"] is True
|
||||
assert password_fields["username"]["secret"] is False
|
||||
|
||||
|
||||
def test_build_secret_dict_keeps_defined_keys_only():
|
||||
"""只保留类型定义内的键(未知键丢弃),必填齐全。"""
|
||||
values = {"username": "u", "password": "p", "evil": "x"}
|
||||
assert build_secret_dict("password", values) == {"username": "u", "password": "p"}
|
||||
|
||||
|
||||
def test_build_secret_dict_missing_required_fail_closed():
|
||||
"""必填字段缺失 → ValidationError。"""
|
||||
with pytest.raises(AppError):
|
||||
build_secret_dict("password", {"username": "u"})
|
||||
|
||||
|
||||
def test_build_secret_dict_unknown_type_fail_closed():
|
||||
with pytest.raises(AppError):
|
||||
build_secret_dict("nope", {})
|
||||
|
||||
|
||||
def test_visible_fields_returns_non_secret_only():
|
||||
assert visible_fields("password", {"username": "u", "password": "p"}) == {"username": "u"}
|
||||
assert visible_fields("token", {"token": "t"}) == {}
|
||||
assert visible_fields("nope", {"x": "y"}) == {}
|
||||
@@ -16,10 +16,20 @@ 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.in_transit_transfer.capabilities import register_transfer_capabilities
|
||||
from app.services.integration_connector.capability import reset_capability_registry_for_tests
|
||||
from app.services.integration_connector.engine import CapabilityGateway
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _transfer_capabilities():
|
||||
"""每用例前重建在途调拨能力注册:能力声明已移至领域包,注册表可能被其他用例 reset。"""
|
||||
reset_capability_registry_for_tests()
|
||||
register_transfer_capabilities()
|
||||
yield
|
||||
reset_capability_registry_for_tests()
|
||||
|
||||
|
||||
class FakeTransport:
|
||||
"""可注入响应或异常的传输替身。"""
|
||||
|
||||
@@ -60,14 +70,16 @@ def _seed(capability, *, connector_type="rest", response_mapping=None, output_sc
|
||||
|
||||
|
||||
def _params(**overrides):
|
||||
values = {"invoice_no": "INV-001", "from_warehouse": "W1", "to_warehouse": "W2", "quantity": 100}
|
||||
values = {
|
||||
"external_org": "HX-CN01",
|
||||
"targets": [{"material_no": "M-1", "from_warehouse": "W1", "lot_no": "L-1"}],
|
||||
}
|
||||
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(
|
||||
@@ -83,7 +95,6 @@ def test_call_success_records_integration_call(app):
|
||||
|
||||
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(
|
||||
@@ -95,7 +106,6 @@ def test_call_input_invalid_raises(app):
|
||||
|
||||
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={},
|
||||
@@ -106,7 +116,6 @@ def test_call_no_binding_raises(app):
|
||||
|
||||
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(
|
||||
@@ -119,7 +128,6 @@ def test_call_write_business_failed(app):
|
||||
|
||||
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={},
|
||||
@@ -130,7 +138,6 @@ def test_call_transport_timeout_returns_timeout(app):
|
||||
|
||||
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"}}})
|
||||
@@ -145,7 +152,6 @@ def test_call_mapping_invalid_raises(app):
|
||||
|
||||
def test_call_result_unknown_no_auto_retry(app):
|
||||
"""result_unknown 不自动重试:transport 仅被调用一次。"""
|
||||
ensure_capabilities_loaded()
|
||||
_seed("in_transit_transfer.create_transfer")
|
||||
calls = []
|
||||
|
||||
@@ -160,3 +166,109 @@ def test_call_result_unknown_no_auto_retry(app):
|
||||
)
|
||||
assert result.status == "result_unknown"
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
# ---- 参数映射与凭据注入(P1 绑定翻译契约)----
|
||||
|
||||
def _seed_full_params(*, param_mapping=None, input_schema=None, credential_ref=None):
|
||||
client = IntegrationClientInstance(
|
||||
code="CLI-P", name="client", connector_type="rest", environment="prod",
|
||||
config_json={"endpoint": "https://erp.invalid"}, credential_ref_code=credential_ref,
|
||||
)
|
||||
iface = IntegrationInterfaceDefinition(
|
||||
code="IFACE-P", name="iface", client_instance_code="CLI-P", connector_type="rest",
|
||||
request_spec_json={"method": "GET", "path": "/stock"},
|
||||
input_schema_json=input_schema or {},
|
||||
response_mapping_json={"found": {"expr": "found"}, "quantity": {"expr": "quantity", "transform": "decimal"}},
|
||||
output_schema_json={"type": "object", "properties": {"found": {"type": "boolean"}, "quantity": {"type": "number"}}},
|
||||
version=1, status="published",
|
||||
)
|
||||
db.session.add_all([client, iface])
|
||||
db.session.flush()
|
||||
binding = IntegrationBinding(
|
||||
capability="in_transit_transfer.query_inventory", context_selector_json={},
|
||||
param_mapping_json=param_mapping or {},
|
||||
client_instance_code="CLI-P", interface_definition_code="IFACE-P",
|
||||
mapping_version=1, priority=0, environment="prod", status="published",
|
||||
)
|
||||
db.session.add(binding)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def test_call_applies_binding_param_mapping(app):
|
||||
"""绑定配置 param_mapping 时域参数先翻译为接口参数再下传传输层。"""
|
||||
_seed_full_params(
|
||||
param_mapping={"organization": {"expr": "external_org"},
|
||||
"condition": {"template": "{targets}",
|
||||
"args": {"list_item_template": "img04 = '{lot_no}'", "separator": " OR "}}},
|
||||
input_schema={"type": "object", "required": ["organization", "condition"],
|
||||
"properties": {"organization": {"type": "string"}, "condition": {"type": "string"}}},
|
||||
)
|
||||
captured = {}
|
||||
|
||||
class _Capture(FakeTransport):
|
||||
def call(self, *, client, interface, request):
|
||||
captured.update(params=request["params"], interface=interface)
|
||||
return {"found": True, "quantity": "5"}
|
||||
|
||||
result = CapabilityGateway(transports={"rest": _Capture(None)}).call(
|
||||
capability="in_transit_transfer.query_inventory", context={},
|
||||
params=_params(external_org="TGHX", targets=[{"material_no": "M-9", "from_warehouse": "W1", "lot_no": "L-9"}]),
|
||||
operation_id="OP-PM", environment="prod",
|
||||
)
|
||||
assert captured["params"] == {"organization": "TGHX", "condition": "img04 = 'L-9'"}
|
||||
assert result.status == "success"
|
||||
|
||||
|
||||
def test_call_mapped_params_fail_interface_schema(app):
|
||||
"""映射结果不合接口入参 Schema → INTEGRATION.MAPPING_INVALID(fail-closed)。"""
|
||||
_seed_full_params(
|
||||
param_mapping={"organization": {"expr": "external_org"}},
|
||||
input_schema={"type": "object", "required": ["organization", "condition"],
|
||||
"properties": {"organization": {"type": "string"}, "condition": {"type": "string"}}},
|
||||
)
|
||||
with pytest.raises(AppError) as exc:
|
||||
CapabilityGateway(transports={"rest": FakeTransport({"found": True})}).call(
|
||||
capability="in_transit_transfer.query_inventory", context={},
|
||||
params=_params(external_org="TGHX"),
|
||||
operation_id="OP-PM2", environment="prod",
|
||||
)
|
||||
assert exc.value.code == "INTEGRATION.MAPPING_INVALID"
|
||||
|
||||
|
||||
def test_call_injects_resolved_credential(app):
|
||||
"""客户端实例引用凭据时,引擎解析凭据并经 client['credential'] 注入传输层。"""
|
||||
_seed_full_params(credential_ref="CRED-1")
|
||||
app.config["CRED1_CFG"] = {"username": "u", "password": "p"}
|
||||
from app import db as _db
|
||||
from app.models import IntegrationCredentialReference
|
||||
_db.session.add(IntegrationCredentialReference(
|
||||
code="CRED-1", secret_ref="CRED1_CFG", secret_provider="env",
|
||||
credential_type="password", version=1, status="active",
|
||||
))
|
||||
_db.session.commit()
|
||||
captured = {}
|
||||
|
||||
class _Capture(FakeTransport):
|
||||
def call(self, *, client, interface, request):
|
||||
captured.update(credential=client["credential"])
|
||||
return {"found": True, "quantity": "5"}
|
||||
|
||||
CapabilityGateway(transports={"rest": _Capture(None)}).call(
|
||||
capability="in_transit_transfer.query_inventory", context={},
|
||||
params=_params(), operation_id="OP-CRED", environment="prod",
|
||||
)
|
||||
assert captured["credential"] == {"username": "u", "password": "p"}
|
||||
|
||||
|
||||
def test_call_read_capability_failure_passthrough(app):
|
||||
"""读能力返回带失败 status 的原始 dict 时原样分类,不做输出映射。"""
|
||||
_seed_full_params()
|
||||
result = CapabilityGateway(transports={"rest": FakeTransport(
|
||||
{"status": "business_failed", "code": "HTTP_500", "message": "boom"}
|
||||
)}).call(
|
||||
capability="in_transit_transfer.query_inventory", context={},
|
||||
params=_params(), operation_id="OP-RF", environment="prod",
|
||||
)
|
||||
assert result.status == "business_failed"
|
||||
assert result.error_code == "HTTP_500"
|
||||
@@ -8,6 +8,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
@@ -94,3 +95,246 @@ def test_map_response_enum_violation_raises():
|
||||
},
|
||||
)
|
||||
assert exc.value.code == "INTEGRATION.MAPPING_INVALID"
|
||||
|
||||
|
||||
# ---- pick:键值对记录列表取值(XML Field[@name,@value] 归一化的通用消费方式)----
|
||||
|
||||
def _field_rows():
|
||||
return [
|
||||
{"@name": "img04", "@value": "HOW25071402"},
|
||||
{"@name": "img11", "@value": "30.000"},
|
||||
]
|
||||
|
||||
|
||||
def test_pick_returns_value_with_decimal_cast():
|
||||
mapped = map_response(
|
||||
{"quantity": {"expr": "rows", "transform": "pick",
|
||||
"args": {"key_field": "@name", "key_value": "img11", "value_field": "@value", "cast": "decimal"}}},
|
||||
{"rows": _field_rows()},
|
||||
{"type": "object", "properties": {"quantity": {"type": "number"}}},
|
||||
)
|
||||
assert mapped["quantity"] == Decimal("30.000")
|
||||
|
||||
|
||||
def test_pick_exists_boolean():
|
||||
mapped = map_response(
|
||||
{"found": {"expr": "rows", "transform": "pick",
|
||||
"args": {"key_field": "@name", "key_value": "img04", "exists": True}}},
|
||||
{"rows": _field_rows()},
|
||||
{"type": "object", "properties": {"found": {"type": "boolean"}}},
|
||||
)
|
||||
assert mapped["found"] is True
|
||||
mapped_absent = map_response(
|
||||
{"found": {"expr": "rows", "transform": "pick",
|
||||
"args": {"key_field": "@name", "key_value": "nope", "exists": True}}},
|
||||
{"rows": _field_rows()},
|
||||
{"type": "object", "properties": {"found": {"type": "boolean"}}},
|
||||
)
|
||||
assert mapped_absent["found"] is False
|
||||
|
||||
|
||||
def test_pick_requires_list_and_key_args():
|
||||
with pytest.raises(AppError):
|
||||
map_response({"q": {"expr": "rows", "transform": "pick", "args": {"key_field": "@name", "key_value": "x"}}},
|
||||
{"rows": {"not": "a list"}}, {})
|
||||
with pytest.raises(AppError):
|
||||
map_response({"q": {"expr": "rows", "transform": "pick", "args": {"key_field": "@name"}}},
|
||||
{"rows": _field_rows()}, {})
|
||||
|
||||
|
||||
def test_pick_miss_returns_missing_so_field_absent():
|
||||
mapped = map_response(
|
||||
{"quantity": {"expr": "rows", "transform": "pick",
|
||||
"args": {"key_field": "@name", "key_value": "nope", "value_field": "@value"}}},
|
||||
{"rows": _field_rows()},
|
||||
{"type": "object", "properties": {"quantity": {"type": "number"}}},
|
||||
)
|
||||
assert "quantity" not in mapped
|
||||
|
||||
|
||||
# ---- template:参数模板填充(域参数→接口参数翻译的列表渲染)----
|
||||
|
||||
def test_template_renders_list_into_in_clause():
|
||||
mapped = map_response(
|
||||
{"condition": {"template": "img02 = '{warehouse}' AND img04 IN ({lots})",
|
||||
"args": {"list_item_template": "'{item}'", "separator": ",", "escape": "quote"}}},
|
||||
{"warehouse": "HTP-D43", "lots": ["HOW25071402", "HOW25081302"]},
|
||||
{"type": "object", "properties": {"condition": {"type": "string"}}},
|
||||
)
|
||||
assert mapped["condition"] == "img02 = 'HTP-D43' AND img04 IN ('HOW25071402','HOW25081302')"
|
||||
|
||||
|
||||
def test_template_escapes_single_quotes_in_values():
|
||||
mapped = map_response(
|
||||
{"condition": {"template": "img02 = '{warehouse}'", "args": {"escape": "quote"}}},
|
||||
{"warehouse": "HT'D43"},
|
||||
{"type": "object", "properties": {"condition": {"type": "string"}}},
|
||||
)
|
||||
assert mapped["condition"] == "img02 = 'HT''D43'"
|
||||
|
||||
|
||||
def test_template_missing_param_fail_closed():
|
||||
with pytest.raises(AppError) as exc:
|
||||
map_response(
|
||||
{"condition": {"template": "img04 = '{invoice_no}'"}},
|
||||
{},
|
||||
{"type": "object", "properties": {"condition": {"type": "string"}}},
|
||||
)
|
||||
assert exc.value.code == "INTEGRATION.MAPPING_INVALID"
|
||||
|
||||
|
||||
# ---- dict 项列表模板:域元组列表 → OR 拼接条件(料号+库位+批号批量查询)----
|
||||
|
||||
def test_template_renders_dict_items_with_field_refs():
|
||||
mapped = map_response(
|
||||
{"condition": {"template": "{targets}",
|
||||
"args": {"list_item_template": "(img01 = '{material_no}' AND img02 = '{from_warehouse}' AND img04 = '{lot_no}')",
|
||||
"separator": " OR ", "escape": "quote"}}},
|
||||
{"targets": [
|
||||
{"material_no": "M-1", "from_warehouse": "HTP-D43", "lot_no": "LOT-1"},
|
||||
{"material_no": "M'2", "from_warehouse": "HTP-D49", "lot_no": "LOT-2"},
|
||||
]},
|
||||
{"type": "object", "properties": {"condition": {"type": "string"}}},
|
||||
)
|
||||
assert mapped["condition"] == (
|
||||
"(img01 = 'M-1' AND img02 = 'HTP-D43' AND img04 = 'LOT-1') OR "
|
||||
"(img01 = 'M''2' AND img02 = 'HTP-D49' AND img04 = 'LOT-2')"
|
||||
)
|
||||
|
||||
|
||||
def test_template_dict_item_missing_field_fail_closed():
|
||||
with pytest.raises(AppError) as exc:
|
||||
map_response(
|
||||
{"condition": {"template": "{targets}",
|
||||
"args": {"list_item_template": "(img01 = '{material_no}' AND img04 = '{lot_no}')",
|
||||
"separator": " OR "}}},
|
||||
{"targets": [{"material_no": "M-1"}]},
|
||||
{"type": "object", "properties": {"condition": {"type": "string"}}},
|
||||
)
|
||||
assert exc.value.code == "INTEGRATION.MAPPING_INVALID"
|
||||
|
||||
|
||||
# ---- each:列表逐元素子映射(多条外部记录 → 多行结果)----
|
||||
|
||||
def test_each_maps_record_list_via_pick_and_cast():
|
||||
raw = {"Master": [
|
||||
{"Record": {"Field": [
|
||||
{"name": "img01", "value": "M-1"}, {"name": "img02", "value": "W1"},
|
||||
{"name": "img04", "value": "L-1"}, {"name": "img11", "value": "36"}]}},
|
||||
{"Record": {"Field": [
|
||||
{"name": "img01", "value": "M-2"}, {"name": "img02", "value": "W2"},
|
||||
{"name": "img04", "value": "L-2"}, {"name": "img11", "value": "0"}]}},
|
||||
]}
|
||||
mapped = map_response(
|
||||
{"rows": {"expr": "Master", "transform": "each", "args": {"fields": {
|
||||
"material_no": {"expr": "Record.Field", "transform": "pick",
|
||||
"args": {"key_field": "name", "key_value": "img01", "value_field": "value"}},
|
||||
"lot_no": {"expr": "Record.Field", "transform": "pick",
|
||||
"args": {"key_field": "name", "key_value": "img04", "value_field": "value"}},
|
||||
"quantity": {"expr": "Record.Field", "transform": "pick",
|
||||
"args": {"key_field": "name", "key_value": "img11", "value_field": "value", "cast": "decimal"}},
|
||||
}}}},
|
||||
raw,
|
||||
{"type": "object", "required": ["rows"], "properties": {"rows": {"type": "array"}}},
|
||||
)
|
||||
assert mapped["rows"] == [
|
||||
{"material_no": "M-1", "lot_no": "L-1", "quantity": Decimal("36")},
|
||||
{"material_no": "M-2", "lot_no": "L-2", "quantity": Decimal("0")},
|
||||
]
|
||||
|
||||
|
||||
def test_each_single_record_dict_wrapped_to_one_row():
|
||||
"""XML 归一化单条记录为 dict → 自动包装为单元素列表,不 fail-closed。"""
|
||||
mapped = map_response(
|
||||
{"rows": {"expr": "Master", "transform": "each", "args": {"fields": {
|
||||
"lot_no": {"expr": "Record.Field", "transform": "pick",
|
||||
"args": {"key_field": "@name", "key_value": "img04", "value_field": "@value"}}}}}},
|
||||
{"Master": {"Record": {"Field": [{"@name": "img04", "@value": "L-1"}]}}},
|
||||
{"type": "object", "properties": {"rows": {"type": "array"}}},
|
||||
)
|
||||
assert mapped["rows"] == [{"lot_no": "L-1"}]
|
||||
|
||||
|
||||
def test_each_missing_target_yields_empty_rows():
|
||||
"""目标记录集整体缺失(外部系统对"查无记录"返回空 XML)→ 空列表而非 fail-closed。
|
||||
|
||||
空结果是合法答案:交领域层归类为"未找到",不因输出 Schema 校验抛映射错误。
|
||||
"""
|
||||
mapped = map_response(
|
||||
{"rows": {"expr": "GetItemStockListResponse.response.Response.ResponseContent.Document.RecordSet.Master",
|
||||
"transform": "each", "args": {"fields": {
|
||||
"lot_no": {"expr": "Record.Field", "transform": "pick",
|
||||
"args": {"key_field": "@name", "key_value": "img04", "value_field": "@value"}}}}}},
|
||||
{"GetItemStockListResponse": {"response": {"Response": {"ResponseContent": {"Document": {}}}}}},
|
||||
{"type": "object", "required": ["rows"], "properties": {"rows": {"type": "array"}}},
|
||||
)
|
||||
assert mapped["rows"] == []
|
||||
|
||||
|
||||
def test_each_skips_items_with_all_fields_missing():
|
||||
"""Master 存在但无 Record 子节点 → 逐字段全缺失的空行被跳过,不产出违反行 Schema 的 {}。"""
|
||||
mapped = map_response(
|
||||
{"rows": {"expr": "Master", "transform": "each", "args": {"fields": {
|
||||
"lot_no": {"expr": "Record.Field", "transform": "pick",
|
||||
"args": {"key_field": "@name", "key_value": "img04", "value_field": "@value"}}}}}},
|
||||
{"Master": {"@name": "img_file"}},
|
||||
{"type": "object", "required": ["rows"], "properties": {"rows": {"type": "array"}}},
|
||||
)
|
||||
assert mapped["rows"] == []
|
||||
|
||||
|
||||
def test_each_flattens_repeated_recordset_from_multi_target_query():
|
||||
"""多条件批量查询返回多个 RecordSet(重复节点列表)→ 路径扇出收集,行全部拉平。
|
||||
|
||||
[回归防线 2026-09-22] TIPTOP 对 OR 多目标查询按条件拆多个 RecordSet 返回:
|
||||
路径遇列表做逐元素收集后 each 正常产出全部行,不得误判为"查无记录"。
|
||||
"""
|
||||
raw = json.loads(r"""
|
||||
{"GetItemStockListResponse": {"response": {"Response": {"ResponseContent": {"Document": {"RecordSet": [
|
||||
{"@id": "1", "Master": {"@name": "img_file", "Record": {"Field": [
|
||||
{"@name": "img01", "@value": "M-1"}, {"@name": "img04", "@value": "L-1"},
|
||||
{"@name": "img10", "@value": "0.000"}]}}},
|
||||
{"@id": "2", "Master": {"@name": "img_file", "Record": {"Field": [
|
||||
{"@name": "img01", "@value": "M-2"}, {"@name": "img04", "@value": "L-2"},
|
||||
{"@name": "img10", "@value": "5.000"}]}}}
|
||||
]}}}}}
|
||||
}""")
|
||||
mapped = map_response(
|
||||
{"rows": {"expr": "GetItemStockListResponse.response.Response.ResponseContent.Document.RecordSet.Master",
|
||||
"transform": "each", "args": {"fields": {
|
||||
"material_no": {"expr": "Record.Field", "transform": "pick",
|
||||
"args": {"key_field": "@name", "key_value": "img01", "value_field": "@value"}},
|
||||
"lot_no": {"expr": "Record.Field", "transform": "pick",
|
||||
"args": {"key_field": "@name", "key_value": "img04", "value_field": "@value"}},
|
||||
"quantity": {"expr": "Record.Field", "transform": "pick",
|
||||
"args": {"key_field": "@name", "key_value": "img10", "value_field": "@value",
|
||||
"cast": "decimal"}}}}}},
|
||||
raw,
|
||||
{"type": "object", "required": ["rows"], "properties": {"rows": {"type": "array"}}},
|
||||
)
|
||||
# [断言意图] 两个条件的记录都进入 rows,数量不足/未找到的判定输入完整。
|
||||
assert mapped["rows"] == [
|
||||
{"material_no": "M-1", "lot_no": "L-1", "quantity": Decimal("0.000")},
|
||||
{"material_no": "M-2", "lot_no": "L-2", "quantity": Decimal("5.000")},
|
||||
]
|
||||
|
||||
|
||||
def test_each_target_not_list_fail_closed():
|
||||
with pytest.raises(AppError) as exc:
|
||||
map_response(
|
||||
{"rows": {"expr": "Master", "transform": "each", "args": {"fields": {}}}},
|
||||
{"Master": "not a dict or list"},
|
||||
{"type": "object", "properties": {"rows": {"type": "array"}}},
|
||||
)
|
||||
assert exc.value.code == "INTEGRATION.MAPPING_INVALID"
|
||||
|
||||
|
||||
def test_each_unknown_nested_transform_fail_closed():
|
||||
with pytest.raises(AppError) as exc:
|
||||
map_response(
|
||||
{"rows": {"expr": "Master", "transform": "each", "args": {"fields": {
|
||||
"x": {"expr": "a", "transform": "no_such_fn"}}}}},
|
||||
{"Master": [{"a": 1}]},
|
||||
{"type": "object", "properties": {"rows": {"type": "array"}}},
|
||||
)
|
||||
assert exc.value.code == "INTEGRATION.MAPPING_INVALID"
|
||||
@@ -84,3 +84,31 @@ def test_split_migration_chains_after_create():
|
||||
split = _load_migration('integration_connector_columns_migration', 'ix1a2b3c4d5e_split_integration_connector_columns.py')
|
||||
assert split.revision == 'ix1a2b3c4d5e'
|
||||
assert split.down_revision == 'iy1a2b3c4d5e'
|
||||
|
||||
|
||||
def test_drop_context_source_code_migration_round_trip():
|
||||
"""删列迁移承接 head rd1e2f3a4b5c:升级后 context_source_code 消失,回滚后恢复。"""
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
base = _load_migration('integration_connector_migration', 'ic1a2b3c4d5f_add_integration_connector.py')
|
||||
split = _load_migration('integration_connector_columns_migration', 'ix1a2b3c4d5e_split_integration_connector_columns.py')
|
||||
drop = _load_migration(
|
||||
'integration_binding_drop_source_code_migration',
|
||||
're1f3a4b5c6d_drop_integration_binding_context_source_code.py',
|
||||
)
|
||||
assert drop.revision == 're1f3a4b5c6d'
|
||||
assert drop.down_revision == 'rd1e2f3a4b5c'
|
||||
with engine.begin() as connection:
|
||||
context = MigrationContext.configure(connection)
|
||||
operations = Operations(context)
|
||||
for module in (base, split, drop):
|
||||
module.op = operations
|
||||
|
||||
base.upgrade()
|
||||
split.upgrade()
|
||||
drop.upgrade()
|
||||
cols = {item['name'] for item in sa.inspect(connection).get_columns('integration_bindings')}
|
||||
assert 'context_source_code' not in cols
|
||||
|
||||
drop.downgrade()
|
||||
cols = {item['name'] for item in sa.inspect(connection).get_columns('integration_bindings')}
|
||||
assert 'context_source_code' in cols
|
||||
@@ -71,3 +71,59 @@ def test_credential_summary_has_no_plaintext(app):
|
||||
assert "s3cretLY" not in json.dumps(summary)
|
||||
assert "svc_user_erp" not in json.dumps(summary)
|
||||
assert summary["version"] == 1
|
||||
|
||||
|
||||
# ---- db 模式:密文落库 + 主密钥解密 ----
|
||||
|
||||
def _add_db_credential(code="DB-CRED", ciphertext=None):
|
||||
cred = IntegrationCredentialReference(
|
||||
code=code, secret_ref=f"db:{code}", secret_provider="db",
|
||||
credential_type="password", version=1, status="active",
|
||||
secret_ciphertext=ciphertext,
|
||||
)
|
||||
db.session.add(cred)
|
||||
db.session.commit()
|
||||
return cred
|
||||
|
||||
|
||||
def _crypto_codes():
|
||||
from app.core.credential_crypto import CredentialCryptoErrorCodes
|
||||
return CredentialCryptoErrorCodes(
|
||||
key_missing="K1", key_invalid="K2", secret_empty="S0", secret_missing="S1", secret_invalid="S2",
|
||||
)
|
||||
|
||||
|
||||
def test_resolve_credential_db_mode_decrypts(app):
|
||||
"""db 模式:用 INTEGRATION_CREDENTIAL_KEY 解密密文还原凭据字典。"""
|
||||
from cryptography.fernet import Fernet
|
||||
|
||||
from app.core.credential_crypto import encrypt_secret
|
||||
app.config["INTEGRATION_CREDENTIAL_KEY"] = Fernet.generate_key().decode("ascii")
|
||||
ciphertext = encrypt_secret(
|
||||
json.dumps({"username": "u", "password": "p"}),
|
||||
key_config_name="INTEGRATION_CREDENTIAL_KEY", codes=_crypto_codes(),
|
||||
)
|
||||
_add_db_credential(ciphertext=ciphertext)
|
||||
assert resolve_credential("DB-CRED") == {"username": "u", "password": "p"}
|
||||
|
||||
|
||||
def test_resolve_credential_db_mode_missing_ciphertext_fail_closed(app):
|
||||
"""db 模式缺密文 → CredentialUnresolvedError。"""
|
||||
_add_db_credential(ciphertext=None)
|
||||
with pytest.raises(AppError) as exc:
|
||||
resolve_credential("DB-CRED")
|
||||
assert exc.value.code == "INTEGRATION.CREDENTIAL_UNRESOLVED"
|
||||
|
||||
|
||||
def test_resolve_credential_db_mode_missing_master_key_fail_closed(app):
|
||||
"""主密钥无效 → 统一折算为 CredentialUnresolvedError(fail-closed)。"""
|
||||
from cryptography.fernet import Fernet
|
||||
|
||||
from app.core.credential_crypto import encrypt_secret
|
||||
app.config["INTEGRATION_CREDENTIAL_KEY"] = Fernet.generate_key().decode("ascii")
|
||||
ciphertext = encrypt_secret("x", key_config_name="INTEGRATION_CREDENTIAL_KEY", codes=_crypto_codes())
|
||||
_add_db_credential(ciphertext=ciphertext)
|
||||
app.config["INTEGRATION_CREDENTIAL_KEY"] = "not-a-valid-key"
|
||||
with pytest.raises(AppError) as exc:
|
||||
resolve_credential("DB-CRED")
|
||||
assert exc.value.code == "INTEGRATION.CREDENTIAL_UNRESOLVED"
|
||||
@@ -1,9 +1,10 @@
|
||||
"""tests/services/integration_connector/test_transports.py
|
||||
|
||||
用途:验证 REST/SOAP Transport 的请求构造、业务错误映射与 fail-closed;
|
||||
以及结果分类(classify_transport_response)的六态语义。
|
||||
连接测试探针(probe)的可达判定;以及结果分类(classify_transport_response)的六态语义。
|
||||
依赖:transports/base.py、transports/rest.py、transports/soap.py、errors.py。
|
||||
逻辑:Transport.call 返回原始 dict;分类器把 dict 归一为 IntegrationCallResult。
|
||||
probe 只做网络可达性探测(REST 任意响应即通;SOAP 校验 WSDL/Envelope 根元素)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -102,3 +103,289 @@ def test_classify_transport_response_states():
|
||||
assert dup.status == "duplicate_success"
|
||||
unknown = classify_transport_response({})
|
||||
assert unknown.status == "technical_failed"
|
||||
|
||||
|
||||
# ---- SOAP Transport 实装 ----
|
||||
|
||||
_SOAP_TEMPLATE = (
|
||||
'<?xml version="1.0" encoding="utf-8"?>'
|
||||
'<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'
|
||||
'<soap:Body><fjs:GetItemStockListRequest xmlns:fjs="http://www.dsc.com.tw/tiptop/TIPTOPServiceGateWay">'
|
||||
'<fjs:request><![CDATA[<Request><Organization name="{organization}"/>'
|
||||
'<Field name="condition" value="{condition}"/>'
|
||||
'<Authentication user="{credential_username}" password="{credential_password}"/>'
|
||||
'</Request>]]></fjs:request></fjs:GetItemStockListRequest></soap:Body></soap:Envelope>'
|
||||
)
|
||||
|
||||
# 带命名空间前缀 + 转义内嵌 XML 的典型网关响应。
|
||||
_SOAP_RESPONSE = (
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="no"?>'
|
||||
'<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">'
|
||||
'<SOAP-ENV:Body>'
|
||||
'<fjs1:GetItemStockListResponse xmlns:fjs1="http://www.dsc.com.tw/tiptop/TIPTOPServiceGateWay">'
|
||||
'<fjs1:response><Response>'
|
||||
'<Execution><Status code="0" sqlcode="0" description=""/></Execution>'
|
||||
'<ResponseContent><Parameter/>'
|
||||
'<Document><RecordSet id="1"><Master name="img_file"><Record>'
|
||||
'<Field name="img04" value="HOW25071402"/>'
|
||||
'<Field name="img11" value="30.000"/>'
|
||||
'</Record></Master></RecordSet></Document>'
|
||||
'</ResponseContent></Response></fjs1:response>'
|
||||
'</fjs1:GetItemStockListResponse>'
|
||||
'</SOAP-ENV:Body></SOAP-ENV:Envelope>'
|
||||
)
|
||||
|
||||
|
||||
def _soap_client(**overrides):
|
||||
cfg = {"endpoint": "https://erp.invalid/ws", "timeout_seconds": 30}
|
||||
cfg.update(overrides)
|
||||
return {"config_json": cfg, "credential": {"username": "u1", "password": "p1"}}
|
||||
|
||||
|
||||
def test_soap_fills_template_with_params_and_credential():
|
||||
"""模板占位符从请求参数与凭据(credential_* 前缀)填充,按 text/xml POST。"""
|
||||
captured = {}
|
||||
|
||||
def fake_http(method, url, **kw):
|
||||
captured.update(method=method, url=url, data=kw.get("data"), headers=kw.get("headers"))
|
||||
return _resp(200, text=_SOAP_RESPONSE)
|
||||
|
||||
result = SoapTransport(http_request=fake_http).call(
|
||||
client=_soap_client(),
|
||||
interface={"request_spec_json": {"method": "POST", "soap": {"action": "", "body_template": _SOAP_TEMPLATE}}},
|
||||
request={"params": {"organization": "TGHX", "condition": "img04 IN ('HOW25071402')"}},
|
||||
)
|
||||
body = captured["data"].decode("utf-8")
|
||||
assert captured["method"] == "POST"
|
||||
assert captured["url"] == "https://erp.invalid/ws"
|
||||
assert captured["headers"]["Content-Type"].startswith("text/xml")
|
||||
assert captured["headers"]["SOAPAction"] == '""' # SOAPAction 头恒存在(空契约即带引号空串)
|
||||
assert 'name="TGHX"' in body
|
||||
assert "img04 IN ('HOW25071402')" in body
|
||||
assert 'user="u1"' in body and 'password="p1"' in body
|
||||
# 内嵌转义 XML 被递归展开,且按 localname 归一化(前缀 fjs1 不出现)。
|
||||
assert result["GetItemStockListResponse"]["response"]["Response"]["Execution"]["Status"]["@code"] == "0"
|
||||
fields = result["GetItemStockListResponse"]["response"]["Response"]["ResponseContent"]["Document"]["RecordSet"]["Master"]["Record"]["Field"]
|
||||
by_name = {f["@name"]: f["@value"] for f in fields}
|
||||
assert by_name["img11"] == "30.000"
|
||||
|
||||
|
||||
def test_soap_missing_template_param_fail_closed():
|
||||
"""占位符缺值 → INTEGRATION.INPUT_INVALID(fail-closed,不静默出空串)。"""
|
||||
from app.core.errors import AppError
|
||||
transport = SoapTransport(http_request=lambda *a, **k: None)
|
||||
with pytest.raises(AppError) as exc:
|
||||
transport.call(
|
||||
client=_soap_client(),
|
||||
interface={"request_spec_json": {"soap": {"body_template": _SOAP_TEMPLATE}}},
|
||||
request={"params": {"condition": "x"}}, # 缺 organization
|
||||
)
|
||||
assert exc.value.code == "INTEGRATION.INPUT_INVALID"
|
||||
|
||||
|
||||
def test_soap_cdata_terminator_rejected():
|
||||
"""参数值含 CDATA 终止符 ]]> 时拒绝,防报文被截断。"""
|
||||
from app.core.errors import AppError
|
||||
transport = SoapTransport(http_request=lambda *a, **k: None)
|
||||
with pytest.raises(AppError) as exc:
|
||||
transport.call(
|
||||
client=_soap_client(),
|
||||
interface={"request_spec_json": {"soap": {"body_template": _SOAP_TEMPLATE}}},
|
||||
request={"params": {"organization": "TGHX", "condition": "a]]>b"}},
|
||||
)
|
||||
assert exc.value.details.get("reason") == "soap_cdata_terminator_in_params"
|
||||
|
||||
|
||||
def test_soap_fail_closed_without_body_template():
|
||||
"""endpoint 存在但缺 soap.body_template → 仍 fail-closed。"""
|
||||
transport = SoapTransport(http_request=lambda *a, **k: None)
|
||||
with pytest.raises(TransportNotFrozenError):
|
||||
transport.call(
|
||||
client=_soap_client(),
|
||||
interface={"request_spec_json": {"soap": {}}},
|
||||
request={"params": {}},
|
||||
)
|
||||
|
||||
|
||||
def test_soap_fault_maps_to_business_failed():
|
||||
"""标准 SOAP Fault → business_failed dict(faultcode/faultstring 透传)。"""
|
||||
fault = (
|
||||
'<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">'
|
||||
'<SOAP-ENV:Body><SOAP-ENV:Fault><faultcode>soap:Client</faultcode>'
|
||||
'<faultstring>bad request</faultstring></SOAP-ENV:Fault></SOAP-ENV:Body></SOAP-ENV:Envelope>'
|
||||
)
|
||||
transport = SoapTransport(http_request=lambda *a, **k: _resp(200, text=fault))
|
||||
result = transport.call(
|
||||
client=_soap_client(),
|
||||
interface={"request_spec_json": {"soap": {"body_template": _SOAP_TEMPLATE}}},
|
||||
request={"params": {"organization": "TGHX", "condition": "c"}},
|
||||
)
|
||||
assert result["status"] == "business_failed"
|
||||
assert result["message"] == "bad request"
|
||||
|
||||
|
||||
def test_soap_http_error_and_non_xml():
|
||||
"""HTTP 5xx → business_failed;200 非 XML → technical_failed(与 REST 同语义)。"""
|
||||
transport = SoapTransport(http_request=lambda *a, **k: _resp(500, text="boom"))
|
||||
result = transport.call(
|
||||
client=_soap_client(),
|
||||
interface={"request_spec_json": {"soap": {"body_template": _SOAP_TEMPLATE}}},
|
||||
request={"params": {"organization": "T", "condition": "c"}},
|
||||
)
|
||||
assert result["status"] == "business_failed" and result["code"] == "HTTP_500"
|
||||
|
||||
transport = SoapTransport(http_request=lambda *a, **k: _resp(200, text="<html>not soap"))
|
||||
result = transport.call(
|
||||
client=_soap_client(),
|
||||
interface={"request_spec_json": {"soap": {"body_template": _SOAP_TEMPLATE}}},
|
||||
request={"params": {"organization": "T", "condition": "c"}},
|
||||
)
|
||||
assert result["status"] == "technical_failed" and result["code"] == "NON_XML"
|
||||
|
||||
|
||||
def test_soap_error_message_masks_credentials():
|
||||
"""错误回显(可能含请求体)中的凭据值必须替换为 ***,不得进审计/响应。"""
|
||||
transport = SoapTransport(http_request=lambda *a, **k: _resp(500, text='echo: password="p1" failed'))
|
||||
result = transport.call(
|
||||
client=_soap_client(),
|
||||
interface={"request_spec_json": {"soap": {"body_template": _SOAP_TEMPLATE}}},
|
||||
request={"params": {"organization": "T", "condition": "c"}},
|
||||
)
|
||||
assert result["message"] == 'echo: password="***" failed'
|
||||
assert "p1" not in result["message"]
|
||||
|
||||
|
||||
def test_soap_params_cannot_shadow_credentials():
|
||||
"""请求参数不得冒充 credential_* 占位符值(凭据注入永远后写覆盖)。"""
|
||||
captured = {}
|
||||
|
||||
def fake_http(method, url, **kw):
|
||||
captured.update(data=kw.get("data"))
|
||||
return _resp(200, text=_SOAP_RESPONSE)
|
||||
|
||||
SoapTransport(http_request=fake_http).call(
|
||||
client=_soap_client(),
|
||||
interface={"request_spec_json": {"soap": {"body_template": _SOAP_TEMPLATE}}},
|
||||
request={"params": {"organization": "T", "condition": "c", "credential_password": "evil"}},
|
||||
)
|
||||
assert 'password="p1"' in captured["data"].decode("utf-8")
|
||||
assert "evil" not in captured["data"].decode("utf-8")
|
||||
|
||||
|
||||
def test_soap_action_header_sent_when_configured():
|
||||
"""soap.action 非空时写入 SOAPAction 头。"""
|
||||
captured = {}
|
||||
|
||||
def fake_http(method, url, **kw):
|
||||
captured.update(headers=kw.get("headers"))
|
||||
return _resp(200, text=_SOAP_RESPONSE)
|
||||
|
||||
SoapTransport(http_request=fake_http).call(
|
||||
client=_soap_client(),
|
||||
interface={"request_spec_json": {"soap": {"action": "urn:GetItemStockList", "body_template": _SOAP_TEMPLATE}}},
|
||||
request={"params": {"organization": "T", "condition": "c"}},
|
||||
)
|
||||
assert captured["headers"]["SOAPAction"] == '"urn:GetItemStockList"' # 按规范带引号
|
||||
|
||||
|
||||
# ---- 连接测试探针(probe):只证明网络/服务可达,不做业务调用 ----
|
||||
|
||||
_WSDL = (
|
||||
'<?xml version="1.0" encoding="utf-8"?>'
|
||||
'<wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" targetNamespace="urn:t">'
|
||||
'</wsdl:definitions>'
|
||||
)
|
||||
|
||||
|
||||
def test_rest_probe_reachable_on_any_http_response():
|
||||
"""REST probe:任意 HTTP 响应(含 404)都证明 endpoint 网络可达。"""
|
||||
captured = {}
|
||||
|
||||
def fake_http(method, url, **kw):
|
||||
captured.update(method=method, url=url)
|
||||
return _resp(404, text="not found")
|
||||
|
||||
result = RestTransport(http_request=fake_http).probe(client=_client())
|
||||
assert captured["method"] == "GET"
|
||||
assert captured["url"] == "https://erp.invalid"
|
||||
assert result["ok"] is True
|
||||
assert result["code"] == "HTTP_404"
|
||||
|
||||
|
||||
def test_rest_probe_connection_failure_not_ok_and_masked():
|
||||
"""REST probe:连接异常 → ok=False,异常回显中凭据值脱敏。"""
|
||||
|
||||
def fake_http(method, url, **kw):
|
||||
raise ConnectionError('connect failed with password="p1"')
|
||||
|
||||
probe_client = _client()
|
||||
probe_client["credential"] = {"password": "p1"}
|
||||
result = RestTransport(http_request=fake_http).probe(client=probe_client)
|
||||
assert result["ok"] is False
|
||||
assert result["code"] == "CONNECTION_FAILED"
|
||||
assert "p1" not in result["message"]
|
||||
|
||||
|
||||
def test_rest_probe_fail_closed_without_endpoint():
|
||||
"""REST probe:endpoint 未冻结时同样 fail-closed。"""
|
||||
transport = RestTransport(http_request=lambda *a, **k: None)
|
||||
with pytest.raises(TransportNotFrozenError):
|
||||
transport.probe(client={"config_json": {}})
|
||||
|
||||
|
||||
def test_soap_probe_wsdl_and_envelope_reachable():
|
||||
"""SOAP probe:WSDL(definitions)与直连服务端点(Envelope)根元素均算可达。"""
|
||||
captured = {}
|
||||
|
||||
def fake_http(method, url, **kw):
|
||||
captured.update(method=method, url=url)
|
||||
return _resp(200, text=_WSDL)
|
||||
|
||||
result = SoapTransport(http_request=fake_http).probe(client=_soap_client())
|
||||
assert captured["method"] == "GET"
|
||||
# 裸服务端点自动补 ?wsdl:SOAP 端点对裸 GET 常返回 404/405/501
|
||||
assert captured["url"] == "https://erp.invalid/ws?wsdl"
|
||||
assert result["ok"] is True
|
||||
|
||||
envelope = (
|
||||
'<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">'
|
||||
'<SOAP-ENV:Body/></SOAP-ENV:Envelope>'
|
||||
)
|
||||
ok_envelope = SoapTransport(http_request=lambda *a, **k: _resp(200, text=envelope))
|
||||
assert ok_envelope.probe(client=_soap_client())["ok"] is True
|
||||
|
||||
|
||||
def test_soap_probe_keeps_existing_query():
|
||||
"""SOAP probe:endpoint 已带 query(如 ?wsdl)时按原地址探测,不重复追加。"""
|
||||
captured = {}
|
||||
|
||||
def fake_http(method, url, **kw):
|
||||
captured.update(url=url)
|
||||
return _resp(200, text=_WSDL)
|
||||
|
||||
result = SoapTransport(http_request=fake_http).probe(
|
||||
client=_soap_client(endpoint="https://erp.invalid/web/ws/r/aws_ttsrv2?wsdl"),
|
||||
)
|
||||
assert captured["url"] == "https://erp.invalid/web/ws/r/aws_ttsrv2?wsdl"
|
||||
assert result["ok"] is True
|
||||
|
||||
|
||||
def test_soap_probe_failure_paths():
|
||||
"""SOAP probe:HTTP 错误/非 XML/根元素不符/连接异常 → ok=False;缺 wsdl fail-closed。"""
|
||||
http_error = SoapTransport(http_request=lambda *a, **k: _resp(500, text="boom"))
|
||||
result = http_error.probe(client=_soap_client())
|
||||
assert result["ok"] is False and result["code"] == "HTTP_500"
|
||||
|
||||
not_xml = SoapTransport(http_request=lambda *a, **k: _resp(200, text="<html>broken"))
|
||||
assert not_xml.probe(client=_soap_client())["code"] == "NON_XML"
|
||||
|
||||
wrong_root = SoapTransport(http_request=lambda *a, **k: _resp(200, text="<html></html>"))
|
||||
assert wrong_root.probe(client=_soap_client())["code"] == "NOT_WSDL"
|
||||
|
||||
def unreachable(method, url, **kw):
|
||||
raise ConnectionError("connection refused")
|
||||
|
||||
assert SoapTransport(http_request=unreachable).probe(client=_soap_client())["ok"] is False
|
||||
|
||||
with pytest.raises(TransportNotFrozenError):
|
||||
SoapTransport().probe(client={"config_json": {}})
|
||||
@@ -0,0 +1,384 @@
|
||||
"""
|
||||
backend/tests/services/shipping_notice/test_customer_identity_tier_matching.py
|
||||
|
||||
用途:验证客户识别三级命中(canonical 等值 > 完整包含 > 截断包含)与受控自动确认边界。
|
||||
依赖:内存数据库、customer_normalization、identity_resolution.resolver、
|
||||
customer_auto_resolution、customer_shadow_resolution。
|
||||
逻辑:以 QCH/Quanta 真实差异形态(标点变体、c/o 截断、折行块整段提取、家族前缀、
|
||||
跨行 vs 单行证据)构造分支,断言影子候选层级、状态语义,以及自动确认只放行
|
||||
「等值唯一」与「完整包含唯一且证据授权」,截断建议永不自动确认。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingCustomer,
|
||||
ShippingIdentityDefinition,
|
||||
ShippingIdentityEvidence,
|
||||
ShippingIdentityRuleSet,
|
||||
ShippingOrderCandidate,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderIntake,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.customer_auto_resolution import resolve_auto_customer_decision
|
||||
from app.services.shipping_notice.customer_normalization import (
|
||||
IDENTITY_MATCH_CONTAINMENT_STRONG,
|
||||
IDENTITY_MATCH_CONTAINMENT_WEAK,
|
||||
IDENTITY_MATCH_EQUALITY,
|
||||
canonical_identity_key,
|
||||
classify_identity_containment,
|
||||
normalize_identity_evidence_value,
|
||||
)
|
||||
from app.services.shipping_notice.customer_shadow_resolution import refresh_candidate_shadow_resolution
|
||||
from app.services.shipping_notice.identity_resolution import resolve_candidate_identity
|
||||
|
||||
FIELD_ID = 'fid-ship-to-customer'
|
||||
RULE_SET_DEF_ID = 'def-ship-to-customer'
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
class TestCanonicalIdentityKey:
|
||||
"""canonical 键:标点/空白/大小写不敏感,中文保留。"""
|
||||
|
||||
def test_punctuation_whitespace_case_insensitive(self):
|
||||
# 关键断言:QCH 注册值与 PDF 打印值的标点/空格差异不再分裂等值命中。
|
||||
assert canonical_identity_key('QCH, INC., A NEVADA CORPORATION') == canonical_identity_key(
|
||||
'qch inc a nevada corporation',
|
||||
)
|
||||
|
||||
def test_keeps_cjk_word_chars(self):
|
||||
# 关键断言:中文客户名不被剔除,仍可参与等值比较。
|
||||
assert canonical_identity_key('英業達股份有限公司桃科廠') == '英業達股份有限公司桃科廠'
|
||||
assert canonical_identity_key('Inventec 英業達') == 'inventec英業達'
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
class TestNormalizeIdentityEvidenceValue:
|
||||
"""识别证据统一归一化:三处调用点同源,兜底分支折叠内部空白。"""
|
||||
|
||||
def test_fallback_collapses_newlines(self):
|
||||
# 关键断言:多行提取值折叠换行后可与单行注册证据等值(修复换行不对称缺陷)。
|
||||
assert normalize_identity_evidence_value('QUANTA MFG,\n1 WALDENBOOKS DR.') == 'QUANTA MFG, 1 WALDENBOOKS DR.'
|
||||
|
||||
def test_name_normalizer_strips_punctuation(self):
|
||||
assert normalize_identity_evidence_value('Hyve, Solutions', normalizer_key='name') == 'HYVESOLUTIONS'
|
||||
|
||||
def test_email_branch_keeps_semantic_chars(self):
|
||||
assert normalize_identity_evidence_value('A@B.COM', option_key='from_email') == 'a@b.com'
|
||||
|
||||
def test_blank_returns_none(self):
|
||||
assert normalize_identity_evidence_value(' ') is None
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
class TestClassifyIdentityContainment:
|
||||
"""双向包含分级:强=指纹完整出现;弱=提取值疑似截断;邮箱/域名不参与。"""
|
||||
|
||||
EVIDENCE = 'QCH INC., A NEVADA CORPORATION C/O QUANTA'
|
||||
|
||||
def test_strong_when_fingerprint_fully_inside_runtime(self):
|
||||
# 关键断言:折行块整段进入字段值时,完整指纹命中判强包含(可受控自动确认)。
|
||||
assert classify_identity_containment(
|
||||
'QCH, INC., A NEVADA CORPORATION c/o Quanta Manufacturing Nashville, LLC', self.EVIDENCE,
|
||||
) == IDENTITY_MATCH_CONTAINMENT_STRONG
|
||||
|
||||
def test_weak_when_runtime_is_truncation(self):
|
||||
# 关键断言:截断方向只判弱命中——剩余部分未经验证,禁止自动确认。
|
||||
assert classify_identity_containment(
|
||||
'QCH, INC., A NEVADA CORPORATION c/o', self.EVIDENCE,
|
||||
) == IDENTITY_MATCH_CONTAINMENT_WEAK
|
||||
|
||||
def test_fragment_below_minimum_chars_rejected(self):
|
||||
# 关键断言:'c/o'→'CO' 这类短碎片不得产生包含噪声。
|
||||
assert classify_identity_containment('c/o', self.EVIDENCE) is None
|
||||
|
||||
def test_email_domain_never_contained(self):
|
||||
assert classify_identity_containment('ops@corp.com', 'ops@corp', option_key='from_email') is None
|
||||
|
||||
def test_unrelated_values_rejected(self):
|
||||
assert classify_identity_containment('HYVE SOLUTIONS CORPORATION', self.EVIDENCE) is None
|
||||
|
||||
|
||||
def _build_identity_world(*, runtime_value: str, evidences: list[dict]):
|
||||
"""
|
||||
构建最小识别世界:发布规则集 + 单 Header 字段抽取链 + 客户/证据主数据。
|
||||
|
||||
Args:
|
||||
runtime_value: 已裁决 Header 字段值(模拟 PDF 提取结果)。
|
||||
evidences: 注册证据列表,每项含 customer_name/short_code/normalized_value,
|
||||
可选 auto(默认 True,对应 auto_match_allowed)。
|
||||
Returns:
|
||||
(candidate, intake) 供 resolve_candidate_identity / 影子刷新使用。
|
||||
"""
|
||||
user = User(username='tier-user', email='tier@example.com', role='user')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
schema = ShippingOrderSchema.query.filter_by(schema_code='SHIPPING_ORDER').one_or_none()
|
||||
if schema is None:
|
||||
schema = ShippingOrderSchema(schema_code='SHIPPING_ORDER', display_name='订单')
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published', lock_version=1, checksum='1' * 64,
|
||||
definition_json={'fields': [{
|
||||
'field_id': FIELD_ID, 'field_code': 'ship_to_customer', 'display_name': 'Ship To Customer',
|
||||
'scope': 'header', 'value_type': 'string', 'enabled': True,
|
||||
'available_for_customer_identity': True, 'normalizer_key': 'trim',
|
||||
}]},
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
definition_json = {
|
||||
'order_schema': {'id': version.id, 'version': version.version, 'checksum': version.checksum},
|
||||
'definitions': [{
|
||||
'id': RULE_SET_DEF_ID, 'definition_code': 'ship_to_customer_rule',
|
||||
'display_name': 'Ship To Customer', 'evidence_label': 'Ship To',
|
||||
'target_type': 'customer', 'context_field_id': FIELD_ID,
|
||||
'default_weight': 100, 'max_automation': 'conditional', 'status': 'active',
|
||||
'field_config': {
|
||||
'field_id': FIELD_ID, 'field_code': 'ship_to_customer', 'scope': 'header',
|
||||
'value_type': 'string', 'normalizer_key': 'trim',
|
||||
'context_source': {'provider': 'order_field', 'option_key': None},
|
||||
'available_for_customer_identity': True,
|
||||
},
|
||||
}],
|
||||
}
|
||||
db.session.add(ShippingIdentityRuleSet(version=1, status='published', definition_json=definition_json, checksum='c' * 64))
|
||||
db.session.add(ShippingIdentityDefinition(
|
||||
id=RULE_SET_DEF_ID, definition_code='ship_to_customer_rule', target_type='customer',
|
||||
context_field_id=FIELD_ID, default_weight=100, max_automation='conditional', status='active',
|
||||
))
|
||||
intake = ShippingOrderIntake(intake_no='INT-TIER', asset_id=1, user_id=user.id, parser_version='test')
|
||||
db.session.add(intake)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
intake_id=intake.id, schema_version_id=version.id, input_snapshot_hash='h' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
decision = ShippingOrderFieldDecision(
|
||||
extraction_id=extraction.id, field_id=FIELD_ID, decision_status='accepted', decided_at=datetime.utcnow(),
|
||||
)
|
||||
db.session.add(decision)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderFieldValue(
|
||||
extraction_id=extraction.id, field_id=FIELD_ID, decision_id=decision.id, value_text=runtime_value,
|
||||
))
|
||||
candidate = ShippingOrderCandidate(
|
||||
candidate_no='CAND-TIER', intake_id=intake.id, primary_document_id=1,
|
||||
candidate_key='tier-test', candidate_status='accepted', order_extraction_id=extraction.id,
|
||||
)
|
||||
db.session.add(candidate)
|
||||
for index, spec in enumerate(evidences, start=1):
|
||||
customer = ShippingCustomer(
|
||||
standard_name=spec['customer_name'], short_code=spec['short_code'], status='active',
|
||||
)
|
||||
db.session.add(customer)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingIdentityEvidence(
|
||||
definition_id=RULE_SET_DEF_ID, customer_id=customer.id,
|
||||
raw_value=spec['normalized_value'], normalized_value=spec['normalized_value'],
|
||||
status='approved', auto_match_allowed=spec.get('auto', True),
|
||||
))
|
||||
db.session.commit()
|
||||
return candidate, intake
|
||||
|
||||
|
||||
class TestResolverTierMatching:
|
||||
"""影子识别三级命中与状态语义(resolve_candidate_identity)。"""
|
||||
|
||||
def test_punctuation_variant_hits_equality_tier(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:'QCH,' vs 'QCH' 标点差异经 canonical 等值命中,不再是 unmatched。
|
||||
candidate, intake = _build_identity_world(
|
||||
runtime_value='QCH, INC., A NEVADA CORPORATION',
|
||||
evidences=[{
|
||||
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
|
||||
'normalized_value': 'QCH INC., A NEVADA CORPORATION',
|
||||
}],
|
||||
)
|
||||
result = resolve_candidate_identity(candidate, intake)
|
||||
assert result['status'] == 'unique_candidate'
|
||||
assert result['customer_matches'][0]['match_kind'] == IDENTITY_MATCH_EQUALITY
|
||||
|
||||
def test_truncated_runtime_becomes_weak_suggestion(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:c/o 截断形态产出唯一弱命中候选(unique_candidate 仅表示展示层唯一),
|
||||
# match_kind=containment_weak,交由人工确认。
|
||||
candidate, intake = _build_identity_world(
|
||||
runtime_value='QCH, INC., A NEVADA CORPORATION c/o',
|
||||
evidences=[{
|
||||
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
|
||||
'normalized_value': 'QCH INC., A NEVADA CORPORATION C/O QUANTA',
|
||||
}],
|
||||
)
|
||||
result = resolve_candidate_identity(candidate, intake)
|
||||
assert result['status'] == 'unique_candidate'
|
||||
assert result['customer_matches'][0]['match_kind'] == IDENTITY_MATCH_CONTAINMENT_WEAK
|
||||
|
||||
def test_wrapped_block_hits_strong_containment(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:折行块整段提取时完整指纹出现,判强包含。
|
||||
candidate, intake = _build_identity_world(
|
||||
runtime_value='QCH, INC., A NEVADA CORPORATION c/o Quanta Manufacturing Nashville, LLC',
|
||||
evidences=[{
|
||||
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
|
||||
'normalized_value': 'QCH INC., A NEVADA CORPORATION C/O QUANTA',
|
||||
}],
|
||||
)
|
||||
result = resolve_candidate_identity(candidate, intake)
|
||||
assert result['status'] == 'unique_candidate'
|
||||
assert result['customer_matches'][0]['match_kind'] == IDENTITY_MATCH_CONTAINMENT_STRONG
|
||||
|
||||
def test_family_prefix_stays_ambiguous(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:家族共享前缀同时包含命中 QCG/TW 两个站点客户 → ambiguous,不取首条。
|
||||
candidate, intake = _build_identity_world(
|
||||
runtime_value='Quanta Computer Inc.',
|
||||
evidences=[
|
||||
{
|
||||
'customer_name': 'QUANTA QCG', 'short_code': 'QCG',
|
||||
'normalized_value': 'QUANTA COMPUTER INC. DE 2470.58.340',
|
||||
},
|
||||
{
|
||||
'customer_name': 'QUANTA TW', 'short_code': 'TWQ',
|
||||
'normalized_value': 'QUANTA COMPUTER INC. HQ PLANT',
|
||||
},
|
||||
],
|
||||
)
|
||||
result = resolve_candidate_identity(candidate, intake)
|
||||
assert result['status'] == 'ambiguous'
|
||||
assert {item['match_kind'] for item in result['customer_matches']} == {IDENTITY_MATCH_CONTAINMENT_WEAK}
|
||||
|
||||
def test_equality_beats_containment_in_order(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:等值候选排在包含候选之前,且顶层唯一时状态为 unique_candidate。
|
||||
candidate, intake = _build_identity_world(
|
||||
runtime_value='WISTRON CORPORATION C/O WIWYNN CZECH',
|
||||
evidences=[
|
||||
{
|
||||
'customer_name': 'WIWYNN CZ', 'short_code': 'WYC',
|
||||
'normalized_value': 'WISTRON CORPORATION',
|
||||
},
|
||||
{
|
||||
'customer_name': 'WIWYNN CZ BRNO', 'short_code': 'WCB',
|
||||
'normalized_value': 'WISTRON CORPORATION C/O WIWYNN CZECH',
|
||||
},
|
||||
],
|
||||
)
|
||||
result = resolve_candidate_identity(candidate, intake)
|
||||
assert result['status'] == 'unique_candidate'
|
||||
names = {item['standard_name']: item for item in result['customer_matches']}
|
||||
# 关键断言:等值候选排第一,强包含候选次之;强层级唯一 → unique_candidate。
|
||||
assert result['customer_matches'][0]['standard_name'] == 'WIWYNN CZ BRNO'
|
||||
assert names['WIWYNN CZ BRNO']['match_kind'] == IDENTITY_MATCH_EQUALITY
|
||||
assert names['WIWYNN CZ']['match_kind'] == IDENTITY_MATCH_CONTAINMENT_STRONG
|
||||
|
||||
def test_multiline_runtime_matches_single_line_evidence(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:运行侧换行折叠修复后,跨行提取值可与单行注册证据等值命中。
|
||||
candidate, intake = _build_identity_world(
|
||||
runtime_value='Quanta Manufacturing Nashville, LLC,\n1 Waldenbooks Dr.',
|
||||
evidences=[{
|
||||
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
|
||||
'normalized_value': 'QUANTA MANUFACTURING NASHVILLE, LLC, 1 WALDENBOOKS DR.',
|
||||
}],
|
||||
)
|
||||
result = resolve_candidate_identity(candidate, intake)
|
||||
assert result['status'] == 'unique_candidate'
|
||||
assert result['customer_matches'][0]['match_kind'] == IDENTITY_MATCH_EQUALITY
|
||||
|
||||
|
||||
class TestAutoConfirmDecision:
|
||||
"""自动确认分级裁决(resolve_auto_customer_decision)。"""
|
||||
|
||||
def _shadow(self, candidate):
|
||||
return refresh_candidate_shadow_resolution(candidate)
|
||||
|
||||
def test_equality_unique_confirms_strong(self, app):
|
||||
with app.app_context():
|
||||
candidate, _intake = _build_identity_world(
|
||||
runtime_value='QCH, INC., A NEVADA CORPORATION',
|
||||
evidences=[{
|
||||
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
|
||||
'normalized_value': 'QCH INC., A NEVADA CORPORATION',
|
||||
}],
|
||||
)
|
||||
decision = resolve_auto_customer_decision(self._shadow(candidate))
|
||||
assert decision['status'] == 'unique_strong_match'
|
||||
assert decision['customer_id'] is not None
|
||||
|
||||
def test_containment_strong_unique_confirms_with_match_kind(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:指纹完整出现的唯一包含命中且证据授权 → unique_containment_match,
|
||||
# 审计证据带 match_kind=containment_strong 溯源。
|
||||
candidate, _intake = _build_identity_world(
|
||||
runtime_value='QCH, INC., A NEVADA CORPORATION c/o Quanta Manufacturing Nashville, LLC',
|
||||
evidences=[{
|
||||
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
|
||||
'normalized_value': 'QCH INC., A NEVADA CORPORATION C/O QUANTA',
|
||||
}],
|
||||
)
|
||||
decision = resolve_auto_customer_decision(self._shadow(candidate))
|
||||
assert decision['status'] == 'unique_containment_match'
|
||||
assert decision['customer_id'] is not None
|
||||
assert decision['evidence'][0]['match_kind'] == IDENTITY_MATCH_CONTAINMENT_STRONG
|
||||
|
||||
def test_truncation_only_never_confirms(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:截断形态(本单 7911678818.PDF)永不自动确认,保持 unmatched 交人工。
|
||||
candidate, _intake = _build_identity_world(
|
||||
runtime_value='QCH, INC., A NEVADA CORPORATION c/o',
|
||||
evidences=[{
|
||||
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
|
||||
'normalized_value': 'QCH INC., A NEVADA CORPORATION C/O QUANTA',
|
||||
}],
|
||||
)
|
||||
decision = resolve_auto_customer_decision(self._shadow(candidate))
|
||||
assert decision['status'] == 'unmatched'
|
||||
assert decision['customer_id'] is None
|
||||
|
||||
def test_unauthorized_evidence_never_confirms(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:auto_match_allowed=False 的证据即使等值唯一也不自动确认。
|
||||
candidate, _intake = _build_identity_world(
|
||||
runtime_value='QCH, INC., A NEVADA CORPORATION',
|
||||
evidences=[{
|
||||
'customer_name': 'QUANTA QMN', 'short_code': 'QMN',
|
||||
'normalized_value': 'QCH INC., A NEVADA CORPORATION', 'auto': False,
|
||||
}],
|
||||
)
|
||||
decision = resolve_auto_customer_decision(self._shadow(candidate))
|
||||
assert decision['status'] == 'unmatched'
|
||||
assert decision['customer_id'] is None
|
||||
|
||||
def test_equality_precedes_containment(self, app):
|
||||
with app.app_context():
|
||||
# 关键断言:等值命中存在时包含命中不参与裁决,等值客户唯一即确认。
|
||||
candidate, _intake = _build_identity_world(
|
||||
runtime_value='WISTRON CORPORATION C/O WIWYNN CZECH',
|
||||
evidences=[
|
||||
{
|
||||
'customer_name': 'WIWYNN CZ', 'short_code': 'WYC',
|
||||
'normalized_value': 'WISTRON CORPORATION',
|
||||
},
|
||||
{
|
||||
'customer_name': 'WIWYNN CZ BRNO', 'short_code': 'WCB',
|
||||
'normalized_value': 'WISTRON CORPORATION C/O WIWYNN CZECH',
|
||||
},
|
||||
],
|
||||
)
|
||||
decision = resolve_auto_customer_decision(self._shadow(candidate))
|
||||
assert decision['status'] == 'unique_strong_match'
|
||||
customers = {c.id: c.standard_name for c in ShippingCustomer.query.all()}
|
||||
assert customers[decision['customer_id']] == 'WIWYNN CZ BRNO'
|
||||
@@ -235,6 +235,180 @@ def test_case_bundle_prefers_persisted_formal_gate_over_case_draft(monkeypatch):
|
||||
assert bundle['user_status'] == 'waiting_human'
|
||||
|
||||
|
||||
# ============================================================
|
||||
# [BR] blocking_reason 资格快照回退:
|
||||
# automation 无具体原因码时,回退到草稿校验快照(validation_result_json)
|
||||
# 中首要 blocking issue 的冻结 explainability 透传(code/message/next_action),
|
||||
# 让批次中心与工作台展示具体原因,而非「当前步骤需要人工处理」兜底。
|
||||
# ============================================================
|
||||
|
||||
def _validation_snapshot_with_issues(issues: list[dict]) -> dict:
|
||||
"""构造与 order_build_eligibility 持久化结构一致的 validation 快照。"""
|
||||
return {'can_build': False, 'can_auto_create': False, 'issues': issues}
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_bundle_falls_back_to_primary_validation_issue_when_automation_lacks_reason():
|
||||
"""[BR-1] automation 无具体原因码时,blocking_reason 必须回退到首要 blocking issue。"""
|
||||
from app.services.shipping_notice.reconciliation_projector import (
|
||||
project_review_case_projection_bundle,
|
||||
)
|
||||
|
||||
case = _fake_case(status='draft', candidate_id=None)
|
||||
bundle = project_review_case_projection_bundle(
|
||||
case,
|
||||
validation=_validation_snapshot_with_issues([
|
||||
{
|
||||
'code': 'customer_unresolved',
|
||||
'severity': 'blocking',
|
||||
'owning_gate_code': 'customer_resolution',
|
||||
'message': '客户尚未确认',
|
||||
'explainability': {
|
||||
'reason_code': 'customer_unresolved',
|
||||
'message': '客户尚未确认',
|
||||
'next_action': 'confirm_customer',
|
||||
},
|
||||
},
|
||||
]),
|
||||
post_confirm=None,
|
||||
is_admin=False,
|
||||
)
|
||||
|
||||
reason = bundle['blocking_reason']
|
||||
# 断言意图:透传冻结契约的事实三元组,前端据此展示「客户尚未确认 / 确认客户」
|
||||
assert reason['code'] == 'customer_unresolved'
|
||||
assert reason['message'] == '客户尚未确认'
|
||||
assert reason['next_action'] == 'confirm_customer'
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_validation_fallback_skips_degraded_and_non_blocking_issues():
|
||||
"""[BR-2] 降级码(unknown_business_failure)与非 blocking issue 不进入回退。"""
|
||||
from app.services.shipping_notice.reconciliation_projector import (
|
||||
project_review_case_projection_bundle,
|
||||
)
|
||||
|
||||
case = _fake_case(status='draft', candidate_id=None)
|
||||
bundle = project_review_case_projection_bundle(
|
||||
case,
|
||||
validation=_validation_snapshot_with_issues([
|
||||
# 仅阻断自动建单,不属用户阻断
|
||||
{
|
||||
'code': 'candidate_qualification_blocked',
|
||||
'severity': 'auto_create_blocking',
|
||||
'explainability': {
|
||||
'reason_code': 'llm_path_cannot_auto_freeze',
|
||||
'message': '智能识别结果尚未通过自动建单资格检查',
|
||||
'next_action': 'open_order_review',
|
||||
},
|
||||
},
|
||||
# 契约降级码:不透传给用户
|
||||
{
|
||||
'code': 'weird_new_issue',
|
||||
'severity': 'blocking',
|
||||
'explainability': {
|
||||
'reason_code': 'unknown_business_failure',
|
||||
'message': '业务处理失败,请凭请求编号联系管理员',
|
||||
'next_action': '',
|
||||
},
|
||||
},
|
||||
# 首个可用 blocking issue
|
||||
{
|
||||
'code': 'required_field_missing',
|
||||
'severity': 'blocking',
|
||||
'field_code': 'reservation_id',
|
||||
'explainability': {
|
||||
'reason_code': 'required_field_missing',
|
||||
'message': '缺少创建订单所需字段',
|
||||
'next_action': 'open_order_review',
|
||||
},
|
||||
},
|
||||
]),
|
||||
post_confirm=None,
|
||||
is_admin=False,
|
||||
)
|
||||
|
||||
reason = bundle['blocking_reason']
|
||||
assert reason['code'] == 'required_field_missing'
|
||||
assert reason['next_action'] == 'open_order_review'
|
||||
assert reason['details'].get('field_code') == 'reservation_id'
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_bundle_keeps_mapped_automation_reason_over_validation_fallback(monkeypatch):
|
||||
"""[BR-3] automation 已有映射的具体原因码时不回退,避免覆盖更精确的裁决。"""
|
||||
from app.services.shipping_notice import reconciliation_projector
|
||||
|
||||
case = _fake_case(status='draft', candidate_id=None)
|
||||
monkeypatch.setattr(
|
||||
reconciliation_projector,
|
||||
'project_case_automation_status',
|
||||
lambda case, *, validation, post_confirm: {
|
||||
'status': 'manual_fallback',
|
||||
'retryable': False,
|
||||
'reason_code': 'duplicate_decision_required',
|
||||
},
|
||||
)
|
||||
bundle = reconciliation_projector.project_review_case_projection_bundle(
|
||||
case,
|
||||
validation=_validation_snapshot_with_issues([
|
||||
{
|
||||
'code': 'customer_unresolved',
|
||||
'severity': 'blocking',
|
||||
'explainability': {
|
||||
'reason_code': 'customer_unresolved',
|
||||
'message': '客户尚未确认',
|
||||
'next_action': 'confirm_customer',
|
||||
},
|
||||
},
|
||||
]),
|
||||
post_confirm=None,
|
||||
is_admin=False,
|
||||
)
|
||||
|
||||
reason = bundle['blocking_reason']
|
||||
assert reason['code'] == 'duplicate_decision_required'
|
||||
assert reason.get('message') is None
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_bundle_without_usable_issues_keeps_legacy_blocking_reason():
|
||||
"""[BR-4] 快照无可用 issue 时保持既有兜底行为(不得抛错、不得造原因)。"""
|
||||
from app.services.shipping_notice.reconciliation_projector import (
|
||||
project_review_case_projection_bundle,
|
||||
)
|
||||
|
||||
case = _fake_case(status='draft', candidate_id=None)
|
||||
bundle = project_review_case_projection_bundle(
|
||||
case,
|
||||
validation={'can_build': True, 'can_auto_create': True, 'issues': []},
|
||||
post_confirm=None,
|
||||
is_admin=False,
|
||||
)
|
||||
|
||||
reason = bundle['blocking_reason']
|
||||
assert isinstance(reason, dict)
|
||||
assert reason.get('message') is None
|
||||
assert reason.get('next_action') is None
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_unmapped_automation_reason_uses_existing_generic_i18n_key():
|
||||
"""[BR-5] 未映射原因码的 fail-closed 兜底必须指向前端真实存在的键。"""
|
||||
from app.services.shipping_notice.reconciliation_projector import (
|
||||
project_case_blocking_reason,
|
||||
)
|
||||
|
||||
reason = project_case_blocking_reason({
|
||||
'status': 'manual_fallback',
|
||||
'reason_code': 'totally_new_unmapped_code',
|
||||
})
|
||||
|
||||
assert reason['code'] == 'totally_new_unmapped_code'
|
||||
# 此前指向不存在的 shipping.review.blocked_generic,任何未映射码都会双重落空
|
||||
assert reason['i18n_key'] == 'chat.shippingProcessing.reasonCode.unknown'
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
def test_pending_successor_gate_clears_a_resolved_field_conflict_from_current_task():
|
||||
"""字段冲突 Gate 已通过后,下游 pending 只能表示系统推进,不能回退旧 STP 冲突。"""
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
"""
|
||||
标准异动字段目录接口测试。
|
||||
|
||||
用途:验证 GET /api/admin/shipping-notice/movement-fields 下发只读领域契约。
|
||||
依赖:Flask 管理 API、movement_contract 契约常量。
|
||||
逻辑:字段目录是 immutable 常量的投影——码/类型/必填/身份标记与契约逐项一致,
|
||||
不提供任何增删改入口,字段 label 由前端 i18n 渲染。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from tests.conftest import parse_api_data
|
||||
|
||||
|
||||
def _headers() -> dict[str, str]:
|
||||
"""构造管理 API 身份 Header(与收料配置接口测试同款)。"""
|
||||
return {'X-Username': 'movement-admin', 'X-Role': 'admin', 'Content-Type': 'application/json'}
|
||||
|
||||
|
||||
def test_movement_fields_returns_fixed_catalog(app, client):
|
||||
"""标准异动字段目录:10 个定死字段、顺序稳定、必填/身份标记与契约一致。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
from app.models import User
|
||||
from app import db
|
||||
db.session.add(User(username='movement-admin', email='movement-admin@example.com', role='admin', status='active'))
|
||||
db.session.commit()
|
||||
|
||||
response = client.get('/api/admin/shipping-notice/movement-fields', headers=_headers())
|
||||
assert response.status_code == 200
|
||||
data = parse_api_data(response.get_json())
|
||||
# [断言意图] 字段码与顺序是前后端共同契约——后端 movement_contract 变更必须显式同步本断言。
|
||||
assert [field['code'] for field in data] == [
|
||||
'doc_no', 'line_no', 'in_out_flag', 'material_code', 'material_name',
|
||||
'warehouse_code', 'storage_code', 'lot_no', 'quantity', 'movement_date',
|
||||
]
|
||||
required = {field['code'] for field in data if field['required']}
|
||||
assert required == {'doc_no', 'material_code', 'quantity', 'movement_date'}
|
||||
identity = {field['code'] for field in data if field['is_identity']}
|
||||
assert identity == {'doc_no', 'material_code', 'movement_date'}
|
||||
assert {field['value_type'] for field in data} <= {'text', 'decimal', 'date'}
|
||||
|
||||
|
||||
def test_movement_fields_rejects_non_admin(app, client):
|
||||
"""字段目录是管理端配置资产,非 admin 角色 403。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.models import User
|
||||
db.session.add(User(username='movement-user', email='movement-user@example.com', role='user', status='active'))
|
||||
db.session.commit()
|
||||
|
||||
response = client.get('/api/admin/shipping-notice/movement-fields', headers={
|
||||
'X-Username': 'movement-user', 'X-Role': 'user', 'Content-Type': 'application/json',
|
||||
})
|
||||
assert response.status_code == 403
|
||||
@@ -29,15 +29,16 @@ def _create_users() -> None:
|
||||
|
||||
|
||||
def _dbs_payload() -> dict:
|
||||
"""构造 DBS 收料配置;日期未出现表示保持系统页面默认 NULL。"""
|
||||
"""构造 DBS 收料配置;Warehouse 条件即逐仓拆分维度,日期未出现表示保持系统页面默认 NULL。"""
|
||||
return {
|
||||
'enabled': True,
|
||||
'report_path_json': {
|
||||
'program_group': 'Bison', 'program_label': 'AWSBI',
|
||||
'report_group': 'Inbound', 'report_name': 'Receipt Detail',
|
||||
},
|
||||
'warehouse_ids_json': ['AWSDU', 'AWSDU-02'],
|
||||
'query_parameters_json': [{'name': 'Owner', 'mode': 'single', 'values': ['AWS'], 'required': False, 'select_all': False}],
|
||||
'query_parameters_json': [
|
||||
{'name': 'Warehouse', 'mode': 'multi_text', 'values': ['AWSDU', 'AWSDU-02'], 'required': False, 'select_all': False},
|
||||
{'name': 'Owner', 'mode': 'single', 'values': ['AWS'], 'required': False, 'select_all': False},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
@@ -65,7 +66,9 @@ def test_admin_saves_independent_dbs_receipt_config_and_audit(app, client):
|
||||
)
|
||||
assert response.status_code == 200
|
||||
config = parse_api_data(response.get_json())
|
||||
assert config['warehouse_ids_json'] == ['AWSDU', 'AWSDU-02']
|
||||
# 关键断言:Warehouse 条件原样保存,作为逐仓拆分维度的唯一持久化位置。
|
||||
warehouse_condition = next(item for item in config['query_parameters_json'] if item['name'] == 'Warehouse')
|
||||
assert warehouse_condition['values'] == ['AWSDU', 'AWSDU-02']
|
||||
assert config['report_path_json']['report_group'] == 'Inbound'
|
||||
|
||||
with app.app_context():
|
||||
@@ -78,7 +81,7 @@ def test_admin_saves_independent_dbs_receipt_config_and_audit(app, client):
|
||||
event_type='shipping_receipt_report_config_saved', aggregate_id=str(source_id),
|
||||
).one()
|
||||
assert audit.before_snapshot_json is None
|
||||
assert audit.after_snapshot_json['warehouse_ids_json'] == ['AWSDU', 'AWSDU-02']
|
||||
assert audit.after_snapshot_json['query_parameters_json'][0]['values'] == ['AWSDU', 'AWSDU-02']
|
||||
|
||||
|
||||
def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, client):
|
||||
@@ -120,9 +123,40 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c
|
||||
assert response.status_code == 400
|
||||
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
|
||||
|
||||
# 关键断言:Warehouse 条件即逐仓拆分维度——缺失、重复、空值都必须拒绝。
|
||||
missing_warehouse = _dbs_payload()
|
||||
missing_warehouse['query_parameters_json'] = [{'name': 'Owner', 'mode': 'single', 'values': ['AWS'], 'required': False, 'select_all': False}]
|
||||
response = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{dbs_id}/receipt-report-config',
|
||||
json=missing_warehouse, headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
|
||||
|
||||
duplicate_warehouse = _dbs_payload()
|
||||
duplicate_warehouse['query_parameters_json'] = [
|
||||
{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU'], 'required': False, 'select_all': False},
|
||||
{'name': 'Warehouse', 'mode': 'single', 'values': ['AWSDU-02'], 'required': False, 'select_all': False},
|
||||
]
|
||||
response = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{dbs_id}/receipt-report-config',
|
||||
json=duplicate_warehouse, headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
|
||||
|
||||
empty_warehouse = _dbs_payload()
|
||||
empty_warehouse['query_parameters_json'] = [{'name': 'Warehouse', 'mode': 'multi_text', 'values': [], 'required': False, 'select_all': False}]
|
||||
response = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{dbs_id}/receipt-report-config',
|
||||
json=empty_warehouse, headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
|
||||
|
||||
invalid_crane = {
|
||||
'enabled': True, 'report_path_json': {'report_name': 'Other Report'},
|
||||
'warehouse_ids_json': ['NOT-ALLOWED'], 'query_parameters_json': [],
|
||||
'report_path_json': {'report_name': 'Other Report'},
|
||||
'query_parameters_json': [],
|
||||
}
|
||||
response = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{crane_id}/receipt-report-config',
|
||||
@@ -132,6 +166,102 @@ def test_receipt_config_rejects_date_selector_and_invalid_connector_rules(app, c
|
||||
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_REPORT_CONFIG_INVALID'
|
||||
|
||||
|
||||
def _create_movement_profile(profile_code: str, *, status: str, purpose: str):
|
||||
"""创建异动/库存解析 Profile 种子;定义仅用于绑定校验,不参与解析。"""
|
||||
from app import db
|
||||
from app.models import ShippingInventoryParsingProfile
|
||||
|
||||
profile = ShippingInventoryParsingProfile(
|
||||
purpose=purpose, profile_code=profile_code, display_name=f'{profile_code} 规则',
|
||||
version=1, status=status, file_format='xlsx',
|
||||
definition_json={'sheet_name': 'Movement', 'header_row_index': 1,
|
||||
'field_mapping': {'doc_no': '单据编号', 'material_code': '料号',
|
||||
'quantity': '数量', 'movement_date': '异动日期'},
|
||||
'match_keys': []},
|
||||
)
|
||||
db.session.add(profile)
|
||||
db.session.commit()
|
||||
return profile
|
||||
|
||||
|
||||
def test_receipt_config_binds_published_movement_profile(app, client):
|
||||
"""绑定已发布 movement 规则 → 保存成功,payload 携带 parsing_profile_id 与摘要,审计留痕。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
_create_users()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source_id = source.id
|
||||
profile = _create_movement_profile('CRANE_MOVE_STD', status='published', purpose='movement')
|
||||
profile_id = profile.id
|
||||
|
||||
payload = {**_dbs_payload(), 'parsing_profile_id': profile_id}
|
||||
response = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config',
|
||||
json=payload, headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert response.status_code == 200
|
||||
config = parse_api_data(response.get_json())
|
||||
# 关键断言:绑定 id 与规则摘要(码/版本/状态)必须回显,供抽屉展示当前绑定。
|
||||
assert config['parsing_profile_id'] == profile_id
|
||||
assert config['parsing_profile']['profile_code'] == 'CRANE_MOVE_STD'
|
||||
assert config['parsing_profile']['status'] == 'published'
|
||||
|
||||
from app.models import ShippingAuditEvent
|
||||
audit = ShippingAuditEvent.query.filter_by(
|
||||
event_type='shipping_receipt_report_config_saved', aggregate_id=str(source_id),
|
||||
).order_by(ShippingAuditEvent.id.desc()).first()
|
||||
assert audit.metadata_json['parsing_profile_id'] == profile_id
|
||||
|
||||
|
||||
def test_receipt_config_rejects_draft_or_non_movement_profile(app, client):
|
||||
"""draft/库存用途/不存在 的规则一律拒绝,防止误绑导致预检无法解析收料文件。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
_create_users()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source_id = source.id
|
||||
draft = _create_movement_profile('MOVE_DRAFT', status='draft', purpose='movement')
|
||||
inventory_profile = _create_movement_profile('INV_PUBLISHED', status='published', purpose='inventory')
|
||||
cases = [draft.id, inventory_profile.id, 999999]
|
||||
|
||||
for profile_id in cases:
|
||||
response = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config',
|
||||
json={**_dbs_payload(), 'parsing_profile_id': profile_id},
|
||||
headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert response.status_code == 400, f'profile_id={profile_id}'
|
||||
# 关键断言:非"已发布 movement"绑定必须走统一错误码,fail-closed。
|
||||
assert parse_api_error(response.get_json())['code'] == 'SHIPPING.RECEIPT_MOVEMENT_PROFILE_INVALID'
|
||||
|
||||
|
||||
def test_receipt_config_empty_profile_id_unbinds(app, client):
|
||||
"""parsing_profile_id 传 None → 解绑(置空),不做校验也不报错。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
with app.app_context():
|
||||
_create_users()
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
source_id = source.id
|
||||
profile = _create_movement_profile('MOVE_UNBIND', status='published', purpose='movement')
|
||||
profile_id = profile.id
|
||||
|
||||
bound = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config',
|
||||
json={**_dbs_payload(), 'parsing_profile_id': profile_id},
|
||||
headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert bound.status_code == 200
|
||||
|
||||
unbound = client.put(
|
||||
f'/api/admin/shipping-notice/sources/{source_id}/receipt-report-config',
|
||||
json={**_dbs_payload(), 'parsing_profile_id': None},
|
||||
headers=_headers('receipt-admin', 'admin'),
|
||||
)
|
||||
assert unbound.status_code == 200
|
||||
# 关键断言:None 表示显式解绑,payload 的绑定字段回到空值。
|
||||
assert parse_api_data(unbound.get_json())['parsing_profile_id'] is None
|
||||
|
||||
|
||||
def test_crane_receipt_config_rejects_query_parameters(app, client):
|
||||
"""Crane 固定使用页面默认值直接 Run Report,管理员不能维护查询条件。"""
|
||||
app.config['AUTH_JWT_REQUIRED'] = False
|
||||
@@ -153,7 +283,7 @@ def test_crane_receipt_config_rejects_query_parameters(app, client):
|
||||
crane_id = crane_source.id
|
||||
|
||||
default_query = {
|
||||
'enabled': True, 'report_path_json': {'report_name': 'Inbound Details'}, 'warehouse_ids_json': [],
|
||||
'report_path_json': {'report_name': 'Inbound Details'},
|
||||
'query_parameters_json': [],
|
||||
}
|
||||
response = client.put(
|
||||
|
||||
@@ -19,7 +19,7 @@ def test_agent_type_catalog_contains_three_seed_types():
|
||||
"""Catalog 应包含 generic、shipping_notice、file_check 等注册类型(含后续扩展)。"""
|
||||
assert {
|
||||
'generic', 'shipping_notice', 'file_check',
|
||||
'procurement_contract_review', 'in_transit_transfer',
|
||||
'procurement_contract_review', 'in_transit_transfer', 'contract_payment', 'voucher_check',
|
||||
} <= set(AGENT_TYPE_CATALOG.keys())
|
||||
|
||||
|
||||
@@ -28,12 +28,14 @@ def test_list_type_catalog_includes_agent_code_and_label():
|
||||
catalog = list_type_catalog()
|
||||
assert len(catalog) >= 5
|
||||
codes = {entry['agent_code'] for entry in catalog}
|
||||
assert {'generic', 'shipping_notice', 'file_check', 'in_transit_transfer'} <= codes
|
||||
assert {'generic', 'shipping_notice', 'file_check', 'in_transit_transfer', 'contract_payment', 'voucher_check'} <= codes
|
||||
labels = {entry['label'] for entry in catalog}
|
||||
assert '通用问答 / 知识库' in labels
|
||||
assert '在途仓自动调拨' in labels
|
||||
assert '货代发货通知' in labels
|
||||
assert '文件检核' in labels
|
||||
assert '合同付款预警' in labels
|
||||
assert '立账凭证' in labels
|
||||
|
||||
|
||||
def test_get_catalog_entry_returns_runtime_handler_for_hybrid_types():
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
"""
|
||||
backend/tests/test_agent_registry_contract_payment.py
|
||||
|
||||
用途:验证 contract_payment 已注册为 builtin Chat Agent 类型。
|
||||
依赖:catalog_loader / catalog_bindings / handlers.bootstrap。
|
||||
逻辑:只读断言 Catalog 声明与 Handler 绑定;不创建 Flask 应用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
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.handlers.base import AgentHandler
|
||||
from app.services.agent_registry.handlers.bootstrap import load_handlers, reset_handlers_for_tests
|
||||
from app.services.agent_registry.handlers.registry import HANDLER_REGISTRY
|
||||
|
||||
|
||||
def test_contract_payment_type_in_catalog():
|
||||
"""catalog 必须包含 contract_payment,默认 builtin + task_chat。"""
|
||||
entry = get_catalog_entry('contract_payment')
|
||||
assert entry is not None
|
||||
assert entry.get('label') == '合同付款预警'
|
||||
assert entry.get('runtime_provider_default') == 'builtin'
|
||||
assert entry.get('conversation_mode_default') == 'task_chat'
|
||||
assert entry.get('runtime_handler') == 'contract_payment'
|
||||
|
||||
|
||||
def test_contract_payment_bound_to_runtime_handler():
|
||||
"""catalog_bindings 必须把 contract_payment 绑定到同名 HANDLER_REGISTRY key。"""
|
||||
assert catalog_bindings.RUNTIME_HANDLER_BINDINGS['contract_payment'] == 'contract_payment'
|
||||
|
||||
|
||||
def test_contract_payment_handler_registered():
|
||||
"""bootstrap 加载后 HANDLER_REGISTRY 包含 ContractPaymentHandler。"""
|
||||
reset_handlers_for_tests()
|
||||
load_handlers()
|
||||
handler = HANDLER_REGISTRY.get('contract_payment')
|
||||
assert handler is not None
|
||||
assert isinstance(handler, AgentHandler)
|
||||
assert handler.handler_key == 'contract_payment'
|
||||
reset_handlers_for_tests()
|
||||
|
||||
|
||||
def test_contract_payment_present_in_full_catalog():
|
||||
"""完整 catalog 与既有类型共存。"""
|
||||
catalog = build_agent_type_catalog()
|
||||
assert 'contract_payment' in catalog
|
||||
assert 'shipping_notice' in catalog
|
||||
@@ -0,0 +1,48 @@
|
||||
"""
|
||||
backend/tests/test_agent_registry_voucher_check.py
|
||||
|
||||
用途:验证 voucher_check 已注册为 builtin Chat Agent 类型。
|
||||
依赖:catalog_loader / catalog_bindings / handlers.bootstrap。
|
||||
逻辑:只读断言 Catalog 声明与 Handler 绑定;不创建 Flask 应用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
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.handlers.base import AgentHandler
|
||||
from app.services.agent_registry.handlers.bootstrap import load_handlers, reset_handlers_for_tests
|
||||
from app.services.agent_registry.handlers.registry import HANDLER_REGISTRY
|
||||
|
||||
|
||||
def test_voucher_check_type_in_catalog():
|
||||
"""catalog 必须包含 voucher_check,默认 builtin + task_chat。"""
|
||||
entry = get_catalog_entry('voucher_check')
|
||||
assert entry is not None
|
||||
assert entry.get('label') == '立账凭证'
|
||||
assert entry.get('runtime_provider_default') == 'builtin'
|
||||
assert entry.get('conversation_mode_default') == 'task_chat'
|
||||
assert entry.get('runtime_handler') == 'voucher_check'
|
||||
|
||||
|
||||
def test_voucher_check_bound_to_runtime_handler():
|
||||
"""catalog_bindings 必须把 voucher_check 绑定到同名 HANDLER_REGISTRY key。"""
|
||||
assert catalog_bindings.RUNTIME_HANDLER_BINDINGS['voucher_check'] == 'voucher_check'
|
||||
|
||||
|
||||
def test_voucher_check_handler_registered():
|
||||
"""bootstrap 加载后 HANDLER_REGISTRY 包含 VoucherCheckHandler。"""
|
||||
reset_handlers_for_tests()
|
||||
load_handlers()
|
||||
handler = HANDLER_REGISTRY.get('voucher_check')
|
||||
assert handler is not None
|
||||
assert isinstance(handler, AgentHandler)
|
||||
assert handler.handler_key == 'voucher_check'
|
||||
reset_handlers_for_tests()
|
||||
|
||||
|
||||
def test_voucher_check_present_in_full_catalog():
|
||||
"""完整 catalog 与既有类型共存。"""
|
||||
catalog = build_agent_type_catalog()
|
||||
assert 'voucher_check' in catalog
|
||||
assert 'contract_payment' in catalog
|
||||
@@ -104,7 +104,7 @@ def test_try_fast_route_hr_leave_when_route_declared(monkeypatch):
|
||||
staticmethod(lambda query, agent, session_id=None: False),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.plm_oracle.PLMOracleService.supports',
|
||||
'app.services.integrations.plm.oracle.PLMOracleService.supports',
|
||||
classmethod(lambda cls, query, agent: False),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
@@ -136,11 +136,11 @@ def test_try_fast_route_text2sql_for_erp_kb(monkeypatch):
|
||||
staticmethod(lambda query, agent, session_id=None: False),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.plm_oracle.PLMOracleService.supports',
|
||||
'app.services.integrations.plm.oracle.PLMOracleService.supports',
|
||||
classmethod(lambda cls, query, agent: False),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.text2sql.Text2SQLService.stream_chat',
|
||||
'app.services.integrations.text2sql.Text2SQLService.stream_chat',
|
||||
classmethod(lambda cls, *args, **kwargs: iter(['data: {"event":"message"}\n\n'])),
|
||||
)
|
||||
|
||||
@@ -172,7 +172,7 @@ def test_try_fast_route_returns_none_for_generic_query(monkeypatch):
|
||||
staticmethod(lambda query, agent, session_id=None: False),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.plm_oracle.PLMOracleService.supports',
|
||||
'app.services.integrations.plm.oracle.PLMOracleService.supports',
|
||||
classmethod(lambda cls, query, agent: False),
|
||||
)
|
||||
|
||||
@@ -200,7 +200,7 @@ def test_try_fast_route_plm_skips_when_attachments_present(monkeypatch):
|
||||
staticmethod(lambda query, agent, session_id=None: False),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.plm_oracle.PLMOracleService.supports',
|
||||
'app.services.integrations.plm.oracle.PLMOracleService.supports',
|
||||
classmethod(lambda cls, query, agent: True),
|
||||
)
|
||||
|
||||
@@ -227,7 +227,7 @@ def test_try_fast_route_skips_hr_when_route_not_declared(monkeypatch):
|
||||
staticmethod(lambda query, agent, session_id=None: False),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.plm_oracle.PLMOracleService.supports',
|
||||
'app.services.integrations.plm.oracle.PLMOracleService.supports',
|
||||
classmethod(lambda cls, query, agent: False),
|
||||
)
|
||||
|
||||
@@ -254,7 +254,7 @@ def test_try_fast_route_skips_text2sql_without_route(monkeypatch):
|
||||
staticmethod(lambda query, agent, session_id=None: False),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.plm_oracle.PLMOracleService.supports',
|
||||
'app.services.integrations.plm.oracle.PLMOracleService.supports',
|
||||
classmethod(lambda cls, query, agent: False),
|
||||
)
|
||||
|
||||
|
||||
@@ -1,16 +1,19 @@
|
||||
"""
|
||||
backend/tests/test_chat_user_attachments.py
|
||||
|
||||
用途:验证聊天附件快照的后端白名单清洗与归属安全合并。
|
||||
依赖:chat API 附件辅助函数、pytest monkeypatch。
|
||||
逻辑:覆盖敏感字段过滤、数量/大小边界、无 ChatLog ID 不写入和有效终态合并。
|
||||
用途:验证聊天附件快照的后端白名单清洗、超限显式失败与归属安全合并。
|
||||
依赖:chat API 附件辅助函数、pytest、ValidationError。
|
||||
逻辑:覆盖敏感字段过滤、数量上限显式失败、无效项丢弃、无 ChatLog ID 不写入和有效终态合并。
|
||||
"""
|
||||
|
||||
import pytest
|
||||
|
||||
from app.api.chat import (
|
||||
CHAT_USER_ATTACHMENT_LIMIT,
|
||||
_merge_user_attachments_from_terminal_event,
|
||||
_normalize_user_attachments,
|
||||
)
|
||||
from app.core.errors import ValidationError
|
||||
|
||||
|
||||
def test_normalize_user_attachments_keeps_only_display_whitelist():
|
||||
@@ -34,7 +37,7 @@ def test_normalize_user_attachments_keeps_only_display_whitelist():
|
||||
}]
|
||||
|
||||
|
||||
def test_normalize_user_attachments_limits_items_and_drops_invalid_values():
|
||||
def test_normalize_user_attachments_keeps_all_items_at_limit():
|
||||
valid = {
|
||||
'name': 'file.pdf',
|
||||
'size': 1,
|
||||
@@ -42,16 +45,66 @@ def test_normalize_user_attachments_limits_items_and_drops_invalid_values():
|
||||
'type': 'document',
|
||||
'source': 'local',
|
||||
}
|
||||
items = [valid for _ in range(CHAT_USER_ATTACHMENT_LIMIT + 5)]
|
||||
items[0] = {**valid, 'type': 'executable'}
|
||||
items[1] = {**valid, 'source': 'unknown'}
|
||||
items[2] = {**valid, 'size': -1, 'extension': '../pdf'}
|
||||
|
||||
items = [{**valid, 'name': f'file-{i}.pdf'} for i in range(CHAT_USER_ATTACHMENT_LIMIT)]
|
||||
normalized = _normalize_user_attachments(items)
|
||||
assert len(normalized) == CHAT_USER_ATTACHMENT_LIMIT
|
||||
assert normalized[0]['name'] == 'file-0.pdf'
|
||||
assert normalized[-1]['name'] == f'file-{CHAT_USER_ATTACHMENT_LIMIT - 1}.pdf'
|
||||
|
||||
assert len(normalized) == CHAT_USER_ATTACHMENT_LIMIT - 2
|
||||
assert 'size' not in normalized[0]
|
||||
assert 'extension' not in normalized[0]
|
||||
|
||||
def test_normalize_user_attachments_keeps_more_than_legacy_twenty():
|
||||
valid = {
|
||||
'name': 'file.pdf',
|
||||
'size': 1,
|
||||
'extension': 'pdf',
|
||||
'type': 'document',
|
||||
'source': 'local',
|
||||
}
|
||||
items = [{**valid, 'name': f'file-{i}.pdf'} for i in range(21)]
|
||||
normalized = _normalize_user_attachments(items)
|
||||
assert len(normalized) == 21
|
||||
|
||||
|
||||
def test_normalize_user_attachments_raises_when_over_limit():
|
||||
valid = {
|
||||
'name': 'file.pdf',
|
||||
'size': 1,
|
||||
'extension': 'pdf',
|
||||
'type': 'document',
|
||||
'source': 'local',
|
||||
}
|
||||
items = [valid for _ in range(CHAT_USER_ATTACHMENT_LIMIT + 1)]
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
_normalize_user_attachments(items)
|
||||
err = exc_info.value
|
||||
assert err.code == 'CHAT.USER_ATTACHMENTS_LIMIT_EXCEEDED'
|
||||
assert err.details.get('limit') == CHAT_USER_ATTACHMENT_LIMIT
|
||||
assert err.details.get('count') == CHAT_USER_ATTACHMENT_LIMIT + 1
|
||||
|
||||
|
||||
def test_normalize_user_attachments_drops_invalid_values_without_truncating_valid_tail():
|
||||
valid = {
|
||||
'name': 'file.pdf',
|
||||
'size': 1,
|
||||
'extension': 'pdf',
|
||||
'type': 'document',
|
||||
'source': 'local',
|
||||
}
|
||||
items = [
|
||||
{**valid, 'type': 'executable'},
|
||||
{**valid, 'source': 'unknown'},
|
||||
]
|
||||
# 旧 [:20] 会在处理完前 20 项后丢弃尾部合法项;无 slice 后应保留 tail。
|
||||
items.extend({**valid, 'type': 'executable'} for _ in range(18))
|
||||
items.append({**valid, 'name': 'kept-tail.pdf'})
|
||||
normalized = _normalize_user_attachments(items)
|
||||
assert normalized == [{
|
||||
'name': 'kept-tail.pdf',
|
||||
'type': 'document',
|
||||
'source': 'local',
|
||||
'extension': 'pdf',
|
||||
'size': 1,
|
||||
}]
|
||||
|
||||
|
||||
def test_merge_user_attachments_requires_terminal_chat_log_id(monkeypatch):
|
||||
|
||||
@@ -3,7 +3,7 @@ backend/tests/test_contract_payment_ledger_focus.py
|
||||
|
||||
用途:验收合同台账汇总卡按合同计数,以及点卡片过滤列表。
|
||||
依赖:Flask test client、ContractPaymentContract、ContractPaymentNode、ledger_focus。
|
||||
逻辑:固定业务日 2026-09-10,分别构造即将到期、逾期、待补充、本月应付合同后核对计数与 focus 筛选。
|
||||
逻辑:固定业务日 2026-09-10,分别构造即将到期、逾期、进行中、本月应付合同后核对计数与 focus 筛选。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -11,12 +11,12 @@ from __future__ import annotations
|
||||
from datetime import date
|
||||
|
||||
from app import db
|
||||
from app.models import ContractPaymentContract, ContractPaymentNode, User
|
||||
from app.models import Agent, ContractPaymentContract, ContractPaymentNode, User
|
||||
from app.services.contract_payment.ledger_focus import ledger_focus_counts
|
||||
|
||||
|
||||
def _create_user(*, username: str) -> User:
|
||||
"""创建具备合同付款预警访问权的落库用户。"""
|
||||
"""创建已授予合同付款预警 Agent 的落库用户。"""
|
||||
user = User(
|
||||
username=username,
|
||||
email=f'{username}@example.com',
|
||||
@@ -26,9 +26,22 @@ def _create_user(*, username: str) -> User:
|
||||
employee_id=f'{username.upper()}-EMP',
|
||||
department='采购部',
|
||||
)
|
||||
user.set_feature_permissions({'contract_payment.access': True})
|
||||
user.set_password('password123')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
agent = Agent.query.filter_by(agent_code='contract_payment', is_active=True).first()
|
||||
if not agent:
|
||||
agent = Agent(
|
||||
name='合同付款预警',
|
||||
agent_code='contract_payment',
|
||||
runtime_provider='builtin',
|
||||
conversation_mode='task_chat',
|
||||
type='api',
|
||||
is_active=True,
|
||||
)
|
||||
db.session.add(agent)
|
||||
db.session.flush()
|
||||
user.agents.append(agent)
|
||||
db.session.commit()
|
||||
db.session.refresh(user)
|
||||
db.session.expunge(user)
|
||||
@@ -76,7 +89,8 @@ def _seed_focus_contracts() -> None:
|
||||
_add_node(due, due=today.replace(day=14))
|
||||
overdue = _add_contract(contract_no='HT-FOCUS-OVERDUE')
|
||||
_add_node(overdue, due=date(2026, 8, 20))
|
||||
_add_contract(contract_no='HT-FOCUS-NEEDS')
|
||||
active = _add_contract(contract_no='HT-FOCUS-ACTIVE')
|
||||
_add_node(active, due=date(2026, 11, 1))
|
||||
month = _add_contract(contract_no='HT-FOCUS-MONTH')
|
||||
_add_node(month, due=date(2026, 9, 28))
|
||||
db.session.commit()
|
||||
@@ -87,10 +101,10 @@ def test_ledger_focus_counts_by_contract(app):
|
||||
with app.app_context():
|
||||
_seed_focus_contracts()
|
||||
counts = ledger_focus_counts(session=db.session, today=date(2026, 9, 10))
|
||||
# 关键断言:即将到期 1、逾期 1、待补充 1、本月应付为 9/14 与 9/28 两份。
|
||||
# 关键断言:即将到期 1、逾期 1、进行中 2(11/1 与 9/28)、本月应付为 9/14 与 9/28 两份。
|
||||
assert counts['due'] == 1
|
||||
assert counts['overdue'] == 1
|
||||
assert counts['needs_completion'] == 1
|
||||
assert counts['active'] == 2
|
||||
assert counts['due_this_month'] == 2
|
||||
|
||||
|
||||
@@ -106,12 +120,19 @@ def test_list_contracts_focus_filters_ledger(client, app, monkeypatch):
|
||||
|
||||
headers = _auth_headers(user)
|
||||
overdue = client.get('/api/contract-payment/contracts?focus=overdue', headers=headers)
|
||||
active = client.get('/api/contract-payment/contracts?focus=active', headers=headers)
|
||||
summary = client.get('/api/contract-payment/contracts/summary', headers=headers)
|
||||
empty = client.get('/api/contract-payment/contracts?focus=overdue&keyword=NO-SUCH', headers=headers)
|
||||
# 关键断言:逾期卡只筛出逾期合同;汇总仍看全量台账。
|
||||
# 关键断言:逾期卡只筛出逾期合同;进行中含未到期的 11/1 与本月 9/28;汇总仍看全量台账。
|
||||
assert overdue.status_code == 200
|
||||
data = overdue.get_json()['data']
|
||||
assert data['total'] == 1
|
||||
assert data['items'][0]['contract_no'] == 'HT-FOCUS-OVERDUE'
|
||||
assert {item['contract_no'] for item in active.get_json()['data']['items']} == {
|
||||
'HT-FOCUS-ACTIVE',
|
||||
'HT-FOCUS-MONTH',
|
||||
}
|
||||
assert summary.get_json()['data']['overdue'] == 1
|
||||
assert summary.get_json()['data']['active'] == 2
|
||||
assert 'needs_completion' not in summary.get_json()['data']
|
||||
assert empty.get_json()['data']['total'] == 0
|
||||
@@ -1,19 +1,19 @@
|
||||
"""
|
||||
backend/tests/test_contract_payment_list.py
|
||||
|
||||
用途:验收合同付款台账列表的 keyword 筛选,尤其是按供应商名称模糊匹配。
|
||||
依赖:Flask test client、ContractPaymentContract、用户功能权限。
|
||||
逻辑:构造两份已解析合同,确认供应商片段只命中对应行,且合同号/采购单号检索仍可用。
|
||||
用途:验收合同付款台账列表的 keyword 与申请人筛选。
|
||||
依赖:Flask test client、ContractPaymentContract、Agent 授权。
|
||||
逻辑:构造两份已解析合同,确认供应商/申请人只命中对应行,且合同号/采购单号检索仍可用。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import ContractPaymentContract, User
|
||||
from app.models import Agent, ContractPaymentContract, User
|
||||
|
||||
|
||||
def _create_user(*, username: str) -> User:
|
||||
"""创建具备合同付款预警访问权的落库用户,供列表接口走 legacy header 认证。"""
|
||||
"""创建已授予合同付款预警 Agent 的落库用户,供列表接口走 legacy header 认证。"""
|
||||
user = User(
|
||||
username=username,
|
||||
email=f'{username}@example.com',
|
||||
@@ -23,9 +23,22 @@ def _create_user(*, username: str) -> User:
|
||||
employee_id=f'{username.upper()}-EMP',
|
||||
department='采购部',
|
||||
)
|
||||
user.set_feature_permissions({'contract_payment.access': True})
|
||||
user.set_password('password123')
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
agent = Agent.query.filter_by(agent_code='contract_payment', is_active=True).first()
|
||||
if not agent:
|
||||
agent = Agent(
|
||||
name='合同付款预警',
|
||||
agent_code='contract_payment',
|
||||
runtime_provider='builtin',
|
||||
conversation_mode='task_chat',
|
||||
type='api',
|
||||
is_active=True,
|
||||
)
|
||||
db.session.add(agent)
|
||||
db.session.flush()
|
||||
user.agents.append(agent)
|
||||
db.session.commit()
|
||||
db.session.refresh(user)
|
||||
db.session.expunge(user)
|
||||
@@ -42,7 +55,7 @@ def _auth_headers(user: User) -> dict[str, str]:
|
||||
|
||||
|
||||
def _seed_parsed_contracts() -> None:
|
||||
"""写入两份已进入台账的合同,供应商名称可区分。"""
|
||||
"""写入两份已进入台账的合同,供应商和申请人都可区分。"""
|
||||
db.session.add_all(
|
||||
[
|
||||
ContractPaymentContract(
|
||||
@@ -50,6 +63,7 @@ def _seed_parsed_contracts() -> None:
|
||||
workflow_no='5203-2609020001',
|
||||
purchase_order_no='5203-2609020001',
|
||||
supplier_name='诺亘(上海)工业自动化有限公司',
|
||||
applicant_name='李采购',
|
||||
parse_status='parsed',
|
||||
status='active',
|
||||
),
|
||||
@@ -58,6 +72,7 @@ def _seed_parsed_contracts() -> None:
|
||||
workflow_no='5203-2608270005',
|
||||
purchase_order_no='5203-2608270005',
|
||||
supplier_name='无锡市质谨机电科技有限公司',
|
||||
applicant_name='王申请',
|
||||
parse_status='parsed',
|
||||
status='active',
|
||||
),
|
||||
@@ -96,3 +111,17 @@ def test_list_contracts_keyword_still_matches_contract_and_po(client, app):
|
||||
assert by_po.get_json()['data']['items'][0]['purchase_order_no'] == '5203-2608270005'
|
||||
assert by_contract.get_json()['data']['total'] == 1
|
||||
assert by_contract.get_json()['data']['items'][0]['contract_no'] == 'HT-20260903-30622-0'
|
||||
|
||||
|
||||
def test_list_contracts_filters_by_applicant(client, app):
|
||||
"""关键词命中申请人姓名时只返回对应合同。"""
|
||||
with app.app_context():
|
||||
user = _create_user(username='cp_list_applicant')
|
||||
_seed_parsed_contracts()
|
||||
|
||||
headers = _auth_headers(user)
|
||||
res = client.get('/api/contract-payment/contracts?keyword=李采', headers=headers)
|
||||
# 关键断言:申请人模糊匹配生效,不误伤其他申请人。
|
||||
assert res.get_json()['data']['total'] == 1
|
||||
assert res.get_json()['data']['items'][0]['applicant_name'] == '李采购'
|
||||
assert res.get_json()['data']['items'][0]['contract_no'] == 'HT-20260903-30622-0'
|
||||
@@ -1,31 +1,19 @@
|
||||
"""
|
||||
backend/tests/test_contract_payment_permissions.py
|
||||
|
||||
用途:验收合同付款预警专项权限 `contract_payment.access` 的角色默认值、显式覆盖与 API 拦截。
|
||||
依赖:User 功能权限、Flask test client、contract_payment 蓝图。
|
||||
逻辑:admin 默认可访问;普通用户默认 403;显式授予后可查询台账,但不能触发同步/扫描/发送;关闭 admin 覆盖后同样 403。
|
||||
用途:验收合同付款预警改为 Agent 授权后的 API 拦截。
|
||||
依赖:User、Agent、Flask test client、contract_payment 蓝图。
|
||||
逻辑:admin 无需绑定即可查询;普通用户默认 403;授予 contract_payment Agent 后可查询台账,
|
||||
但不能触发同步/扫描/发送。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import User
|
||||
from app.models import Agent, User
|
||||
|
||||
|
||||
def _make_memory_user(*, role: str, overrides: dict | None = None) -> User:
|
||||
"""构造带功能权限覆盖的内存用户(不落库,仅测 has_feature_permission)。"""
|
||||
user = User(username=f'cp-{role}', role=role)
|
||||
if overrides is not None:
|
||||
user.feature_permissions = overrides
|
||||
return user
|
||||
|
||||
|
||||
def _create_user(
|
||||
*,
|
||||
username: str,
|
||||
role: str = 'user',
|
||||
feature_permissions: dict | None = None,
|
||||
) -> User:
|
||||
def _create_user(*, username: str, role: str = 'user') -> User:
|
||||
"""创建落库用户,供 contract-payment API 走 legacy header 认证。"""
|
||||
user = User(
|
||||
username=username,
|
||||
@@ -36,11 +24,39 @@ def _create_user(
|
||||
employee_id=f'{username.upper()}-EMP',
|
||||
department='采购部',
|
||||
)
|
||||
user.set_feature_permissions(feature_permissions)
|
||||
user.set_password('password123')
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
db.session.refresh(user)
|
||||
return user
|
||||
|
||||
|
||||
def _ensure_contract_payment_agent() -> Agent:
|
||||
"""确保存在启用中的合同付款预警 Agent,供授权绑定。"""
|
||||
agent = Agent.query.filter_by(agent_code='contract_payment', is_active=True).first()
|
||||
if agent:
|
||||
return agent
|
||||
agent = Agent(
|
||||
name='合同付款预警',
|
||||
agent_code='contract_payment',
|
||||
runtime_provider='builtin',
|
||||
conversation_mode='task_chat',
|
||||
type='api',
|
||||
is_active=True,
|
||||
)
|
||||
db.session.add(agent)
|
||||
db.session.commit()
|
||||
db.session.refresh(agent)
|
||||
return agent
|
||||
|
||||
|
||||
def _grant_contract_payment_agent(user: User) -> User:
|
||||
"""把合同付款预警 Agent 授权给指定用户并重新取出,避免会话分离后丢失关系。"""
|
||||
agent = _ensure_contract_payment_agent()
|
||||
if agent not in user.agents:
|
||||
user.agents.append(agent)
|
||||
db.session.commit()
|
||||
db.session.refresh(user)
|
||||
db.session.expunge(user)
|
||||
return user
|
||||
|
||||
@@ -62,49 +78,16 @@ def _json_error(response) -> dict:
|
||||
return body['error']
|
||||
|
||||
|
||||
def test_admin_default_has_contract_payment_access(app):
|
||||
"""admin 角色默认具备 contract_payment.access;普通用户默认无。"""
|
||||
with app.app_context():
|
||||
admin = _make_memory_user(role='admin')
|
||||
user = _make_memory_user(role='user')
|
||||
# 关键断言:不新建角色,仅功能键裁剪工作台访问。
|
||||
assert admin.can_access_contract_payment() is True
|
||||
assert user.can_access_contract_payment() is False
|
||||
|
||||
|
||||
def test_explicit_grant_and_revoke_contract_payment_access(app):
|
||||
"""普通用户可被显式授予;admin 可被显式关闭。"""
|
||||
with app.app_context():
|
||||
granted = _make_memory_user(role='user', overrides={'contract_payment.access': True})
|
||||
revoked_admin = _make_memory_user(role='admin', overrides={'contract_payment.access': False})
|
||||
# 关键断言:显式覆盖优先于角色默认。
|
||||
assert granted.can_access_contract_payment() is True
|
||||
assert revoked_admin.can_access_contract_payment() is False
|
||||
|
||||
|
||||
def test_set_feature_permissions_persists_contract_payment_override(app):
|
||||
"""用户表单保存时只持久化与角色默认值不同的 contract_payment.access。"""
|
||||
with app.app_context():
|
||||
user = User(username='cp-override', role='user')
|
||||
user.set_feature_permissions({'contract_payment.access': True})
|
||||
# 关键断言:未知键被忽略,已知覆盖项写入 JSON。
|
||||
assert user.feature_permissions == {'contract_payment.access': True}
|
||||
assert user.can_access_contract_payment() is True
|
||||
|
||||
admin = User(username='cp-admin-override', role='admin')
|
||||
admin.set_feature_permissions({'contract_payment.access': False})
|
||||
assert admin.feature_permissions == {'contract_payment.access': False}
|
||||
assert admin.can_access_contract_payment() is False
|
||||
|
||||
|
||||
def test_contract_payment_api_forbids_user_without_access(client, app):
|
||||
"""无权限用户查询台账或触发同步均返回 CONTRACT_PAYMENT.FORBIDDEN。"""
|
||||
def test_contract_payment_api_forbids_user_without_agent(client, app):
|
||||
"""未授予 Agent 的普通用户查询台账或触发同步均返回 CONTRACT_PAYMENT.FORBIDDEN。"""
|
||||
with app.app_context():
|
||||
ordinary = _create_user(username='cp_api_denied')
|
||||
_ensure_contract_payment_agent()
|
||||
db.session.expunge(ordinary)
|
||||
|
||||
headers = _auth_headers(ordinary)
|
||||
list_res = client.get('/api/contract-payment/contracts', headers=headers)
|
||||
# 关键断言:登录不足够,专项权限缺失必须 403。
|
||||
# 关键断言:登录不足够,Agent 授权缺失必须 403。
|
||||
assert list_res.status_code == 403
|
||||
assert _json_error(list_res)['code'] == 'CONTRACT_PAYMENT.FORBIDDEN'
|
||||
|
||||
@@ -114,29 +97,36 @@ def test_contract_payment_api_forbids_user_without_access(client, app):
|
||||
|
||||
|
||||
def test_contract_payment_api_allows_granted_user(client, app):
|
||||
"""显式授予后普通用户可以查询台账。"""
|
||||
"""授予 contract_payment Agent 后普通用户可以查询台账。"""
|
||||
with app.app_context():
|
||||
granted = _create_user(
|
||||
username='cp_api_granted',
|
||||
feature_permissions={'contract_payment.access': True},
|
||||
)
|
||||
granted = _grant_contract_payment_agent(_create_user(username='cp_api_granted'))
|
||||
|
||||
headers = _auth_headers(granted)
|
||||
list_res = client.get('/api/contract-payment/contracts', headers=headers)
|
||||
# 关键断言:授予后不再 403,返回标准成功 envelope。
|
||||
# 关键断言:Agent 授权后不再 403,返回标准成功 envelope。
|
||||
assert list_res.status_code == 200
|
||||
body = list_res.get_json()
|
||||
assert body.get('success') is True
|
||||
assert 'items' in (body.get('data') or {})
|
||||
|
||||
|
||||
def test_contract_payment_api_allows_admin_without_agent_binding(client, app):
|
||||
"""平台 admin 即使未绑定该 Agent 也可查询台账。"""
|
||||
with app.app_context():
|
||||
admin = _create_user(username='cp_api_admin', role='admin')
|
||||
_ensure_contract_payment_agent()
|
||||
db.session.expunge(admin)
|
||||
|
||||
headers = _auth_headers(admin)
|
||||
list_res = client.get('/api/contract-payment/contracts', headers=headers)
|
||||
assert list_res.status_code == 200
|
||||
assert list_res.get_json().get('success') is True
|
||||
|
||||
|
||||
def test_contract_payment_jobs_require_admin(client, app):
|
||||
"""已授权的普通用户可查台账,但不能触发同步、扫描或周汇总发送。"""
|
||||
with app.app_context():
|
||||
granted = _create_user(
|
||||
username='cp_api_jobs_denied',
|
||||
feature_permissions={'contract_payment.access': True},
|
||||
)
|
||||
granted = _grant_contract_payment_agent(_create_user(username='cp_api_jobs_denied'))
|
||||
|
||||
headers = _auth_headers(granted)
|
||||
# 关键断言:访问权不等于操作权,手动任务仅管理员。
|
||||
|
||||
@@ -10,7 +10,7 @@ import pytest
|
||||
|
||||
|
||||
def _load_navigation():
|
||||
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "connectors" / "crane" / "crane_navigation.py"
|
||||
module_path = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "connectors" / "crane" / "crane_navigation.py"
|
||||
spec = importlib.util.spec_from_file_location("crane_navigation_test", module_path)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
|
||||
@@ -10,7 +10,7 @@ import pytest
|
||||
|
||||
|
||||
def _load_export():
|
||||
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "connectors" / "crane" / "crane_report_export.py"
|
||||
module_path = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "connectors" / "crane" / "crane_report_export.py"
|
||||
spec = importlib.util.spec_from_file_location("crane_report_export_test", module_path)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
@@ -47,7 +47,7 @@ def test_fill_parameters_skips_warehouse(monkeypatch):
|
||||
select_or_fill=_fake_select,
|
||||
)
|
||||
|
||||
assert calls == [("SHIPPING_NOTICE_RPA_WORKER_CRANE_OWNER_SELECTOR", "Select Owner...", "OWNER1")]
|
||||
assert calls == [("FREIGHT_RPA_WORKER_CRANE_OWNER_SELECTOR", "Select Owner...", "OWNER1")]
|
||||
|
||||
|
||||
def test_build_schedule_description_uses_short_uuid_hex(monkeypatch):
|
||||
@@ -73,7 +73,7 @@ def test_build_schedule_description_hex_len_env():
|
||||
text = module._build_schedule_description(
|
||||
{"source_code": "CRANE_TZR2"},
|
||||
None,
|
||||
env=lambda name, default="": "16" if name == "SHIPPING_NOTICE_RPA_WORKER_CRANE_SCHEDULE_DESCRIPTION_HEX_LEN" else default,
|
||||
env=lambda name, default="": "16" if name == "FREIGHT_RPA_WORKER_CRANE_SCHEDULE_DESCRIPTION_HEX_LEN" else default,
|
||||
)
|
||||
assert len(text) == 16
|
||||
|
||||
@@ -148,7 +148,7 @@ def test_should_run_report_before_schedule_uses_driver_environment_only():
|
||||
assert (
|
||||
module._should_run_report_before_schedule(
|
||||
{"navigation": {}},
|
||||
env=lambda name, default="": "false" if name == "SHIPPING_NOTICE_RPA_WORKER_CRANE_RUN_BEFORE_SCHEDULE" else default,
|
||||
env=lambda name, default="": "false" if name == "FREIGHT_RPA_WORKER_CRANE_RUN_BEFORE_SCHEDULE" else default,
|
||||
)
|
||||
is False
|
||||
)
|
||||
@@ -444,7 +444,7 @@ def test_resolve_download_mode_uses_driver_environment_only():
|
||||
"""下载模式只能由 Driver 环境变量决定。"""
|
||||
module = _load_export()
|
||||
assert module._resolve_download_mode({"navigation": {"download_mode": "file_download"}}, env=lambda name, default="": default) == "scheduled_report"
|
||||
assert module._resolve_download_mode({}, env=lambda name, default="": "file_download" if name == "SHIPPING_NOTICE_RPA_WORKER_CRANE_DOWNLOAD_MODE" else default) == "file_download"
|
||||
assert module._resolve_download_mode({}, env=lambda name, default="": "file_download" if name == "FREIGHT_RPA_WORKER_CRANE_DOWNLOAD_MODE" else default) == "file_download"
|
||||
|
||||
|
||||
def test_wait_and_click_scheduled_download_falls_back_to_directory(tmp_path, monkeypatch):
|
||||
@@ -596,3 +596,34 @@ def test_wait_and_click_scheduled_download_skips_fallback_on_click_failure(tmp_p
|
||||
download_dir=str(tmp_path),
|
||||
)
|
||||
assert fallback_called["value"] is False
|
||||
|
||||
|
||||
def test_row_matches_scheduled_report_normalizes_name_form(monkeypatch):
|
||||
"""行名 InboundDetails.xlsx 与期望名 Inbound Details 应规范化后相等(收料轮询 not found 根因)。"""
|
||||
module = _load_export()
|
||||
texts = ["InboundDetails.xlsx", "2026/9/18 22:02:53", "accf9483fabe", "Download"]
|
||||
|
||||
class _Cell:
|
||||
def __init__(self, text):
|
||||
self._text = text
|
||||
|
||||
def inner_text(self, timeout=None):
|
||||
return self._text
|
||||
|
||||
cells = MagicMock()
|
||||
cells.count.return_value = len(texts)
|
||||
cells.nth.side_effect = lambda i: _Cell(texts[i])
|
||||
row = MagicMock()
|
||||
row.locator.return_value = cells
|
||||
row.is_visible.return_value = True
|
||||
|
||||
assert module._row_matches_scheduled_report(
|
||||
row, description="accf9483fabe", expected_report_name="Inbound Details"
|
||||
) is True
|
||||
# [断言意图] 描述不一致时不得匹配(唯一性由 UUID 保证)
|
||||
assert module._row_matches_scheduled_report(
|
||||
row, description="other", expected_report_name="Inbound Details"
|
||||
) is False
|
||||
assert module._row_matches_scheduled_report(
|
||||
row, description="accf9483fabe", expected_report_name="OnHandDetails.xlsx"
|
||||
) is False
|
||||
@@ -8,7 +8,7 @@ from unittest.mock import MagicMock
|
||||
|
||||
|
||||
def _load_crane_session():
|
||||
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "connectors" / "crane" / "crane_session.py"
|
||||
module_path = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "connectors" / "crane" / "crane_session.py"
|
||||
spec = importlib.util.spec_from_file_location("crane_session_test", module_path)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
@@ -108,15 +108,15 @@ def test_maybe_auto_login_crane_fills_username_password_and_clicks_sign_in(monke
|
||||
module.maybe_auto_login_crane(
|
||||
page,
|
||||
env=lambda name, default="": {
|
||||
"SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME": "crane-user",
|
||||
"SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD": "crane-pass",
|
||||
"FREIGHT_RPA_WORKER_CRANE_USERNAME": "crane-user",
|
||||
"FREIGHT_RPA_WORKER_CRANE_PASSWORD": "crane-pass",
|
||||
}.get(name, default),
|
||||
browser_timeout_ms=5_000,
|
||||
)
|
||||
|
||||
assert calls == [
|
||||
("SHIPPING_NOTICE_RPA_WORKER_CRANE_USERNAME_SELECTOR", "crane-user"),
|
||||
("SHIPPING_NOTICE_RPA_WORKER_CRANE_PASSWORD_SELECTOR", "crane-pass"),
|
||||
("FREIGHT_RPA_WORKER_CRANE_USERNAME_SELECTOR", "crane-user"),
|
||||
("FREIGHT_RPA_WORKER_CRANE_PASSWORD_SELECTOR", "crane-pass"),
|
||||
]
|
||||
|
||||
|
||||
@@ -133,7 +133,7 @@ def test_find_crane_sign_in_button_waits_for_enabled_state(monkeypatch):
|
||||
|
||||
locator = module._find_crane_sign_in_button(
|
||||
page,
|
||||
selector_env="SHIPPING_NOTICE_RPA_WORKER_CRANE_LOGIN_BUTTON_SELECTOR",
|
||||
selector_env="FREIGHT_RPA_WORKER_CRANE_LOGIN_BUTTON_SELECTOR",
|
||||
env=lambda name, default="": default,
|
||||
browser_timeout_ms=3_000,
|
||||
)
|
||||
@@ -144,7 +144,7 @@ def test_find_crane_sign_in_button_waits_for_enabled_state(monkeypatch):
|
||||
|
||||
def test_ensure_crane_session_skips_login_when_session_active(monkeypatch):
|
||||
"""batch 内 session 有效时不应重复 goto + login。"""
|
||||
worker_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "inventory" / "inventory_rpa_worker.py"
|
||||
worker_path = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "inventory" / "inventory_rpa_worker.py"
|
||||
spec = importlib.util.spec_from_file_location("freight_rpa_worker_crane_test", worker_path)
|
||||
assert spec and spec.loader
|
||||
worker = importlib.util.module_from_spec(spec)
|
||||
|
||||
@@ -7,7 +7,7 @@ import pytest
|
||||
|
||||
from app import create_app, db
|
||||
from app.models import Agent, ChatLog, User
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
|
||||
@@ -13,7 +13,7 @@ from types import SimpleNamespace
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
from app.services.file_check import FileCheckService
|
||||
|
||||
|
||||
@@ -59,7 +59,7 @@ def _mock_stream_response(monkeypatch, *, status_code: int = 200, lines: list[by
|
||||
calls["count"] += 1
|
||||
return _Resp()
|
||||
|
||||
monkeypatch.setattr("app.services.dify.requests.post", _post)
|
||||
monkeypatch.setattr("app.services.integrations.dify.requests.post", _post)
|
||||
return calls
|
||||
|
||||
|
||||
@@ -180,7 +180,7 @@ def test_workflow_streaming_503_retries_then_success(monkeypatch):
|
||||
|
||||
return _Resp()
|
||||
|
||||
monkeypatch.setattr("app.services.dify.requests.post", _post)
|
||||
monkeypatch.setattr("app.services.integrations.dify.requests.post", _post)
|
||||
|
||||
result = DifyService.run_workflow_streaming(agent=_Agent(), inputs={"record": "x"})
|
||||
|
||||
@@ -199,7 +199,7 @@ def test_workflow_streaming_401_does_not_retry(monkeypatch):
|
||||
resp.status_code = 401
|
||||
raise requests.HTTPError(response=resp)
|
||||
|
||||
monkeypatch.setattr("app.services.dify.requests.post", _post)
|
||||
monkeypatch.setattr("app.services.integrations.dify.requests.post", _post)
|
||||
|
||||
with pytest.raises(requests.HTTPError):
|
||||
DifyService.run_workflow_streaming(agent=_Agent(), inputs={"record": "x"})
|
||||
@@ -353,7 +353,7 @@ def test_dedupe_exact_doubled_text_fixes_historical_records():
|
||||
def test_chat_stream_error_event_keeps_persisted_chat_log_id(app, monkeypatch):
|
||||
"""连接超时的 error SSE 必须携带持久化主键,供领域 Handler 回写失败状态。"""
|
||||
monkeypatch.setattr(
|
||||
"app.services.dify.requests.post",
|
||||
"app.services.integrations.dify.requests.post",
|
||||
lambda *args, **kwargs: (_ for _ in ()).throw(requests.exceptions.ConnectTimeout("connect timed out")),
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
@@ -402,7 +402,7 @@ def test_chat_stream_read_timeout_after_answer_emits_terminal_event(app, monkeyp
|
||||
yield _sse_lines({"event": "message", "answer": "partial answer"})[0]
|
||||
raise requests.exceptions.ReadTimeout("read timed out")
|
||||
|
||||
monkeypatch.setattr("app.services.dify.requests.post", lambda *args, **kwargs: _ChatResponse())
|
||||
monkeypatch.setattr("app.services.integrations.dify.requests.post", lambda *args, **kwargs: _ChatResponse())
|
||||
monkeypatch.setattr(
|
||||
DifyService,
|
||||
"_persist_stream_chat_record",
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""scripts/rpa/dsv_report_parameters.py 单元测试。"""
|
||||
"""scripts/freight_rpa/dsv_report_parameters.py 单元测试。"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
@@ -7,7 +7,7 @@ from pathlib import Path
|
||||
|
||||
|
||||
def _load_module():
|
||||
path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "connectors" / "dsv" / "dsv_report_parameters.py"
|
||||
path = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "connectors" / "dsv" / "dsv_report_parameters.py"
|
||||
spec = importlib.util.spec_from_file_location("dsv_report_parameters_test", path)
|
||||
assert spec and spec.loader
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
@@ -43,7 +43,7 @@ def test_fill_dsv_owner_filter_defaults_to_reportviewer_owner_input():
|
||||
|
||||
module.fill_dsv_filter_if_needed(
|
||||
_FakePage(),
|
||||
"SHIPPING_NOTICE_RPA_WORKER_DSV_OWNER_SELECTOR",
|
||||
"FREIGHT_RPA_WORKER_DSV_OWNER_SELECTOR",
|
||||
"Owner",
|
||||
"CADU-0000000100",
|
||||
env=lambda name, default="": default,
|
||||
@@ -104,7 +104,7 @@ def test_fill_dsv_warehouse_select_uses_default_ddvalue():
|
||||
|
||||
module.fill_dsv_filter_if_needed(
|
||||
_FakePage(),
|
||||
"SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
|
||||
"FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
|
||||
"Warehouse",
|
||||
"BYAWSATL01",
|
||||
env=lambda name, default="": default,
|
||||
@@ -290,7 +290,7 @@ def test_fill_dsv_filter_if_needed_jda_report_uses_template_multi_value():
|
||||
|
||||
module.fill_dsv_filter_if_needed(
|
||||
_FakePage(),
|
||||
"SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
|
||||
"FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
|
||||
"Warehouse",
|
||||
"RTM",
|
||||
env=lambda name, default="": default,
|
||||
|
||||
@@ -0,0 +1,217 @@
|
||||
"""
|
||||
tests/test_effective_order_view.py
|
||||
|
||||
用途:验证「冻结快照 + 冻结后人工修正」的有效订单值视图。
|
||||
依赖:pytest、effective_order_view、task_order_field_editor、订单 Schema/快照模型。
|
||||
逻辑:覆盖行级修正对位叠加、快照不可变、整行替换后的保守跳过与 Notice 行事实投影。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingNotice,
|
||||
ShippingOrderExtraction,
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderLine,
|
||||
ShippingOrderSchema,
|
||||
ShippingOrderSchemaVersion,
|
||||
ShippingOrderSnapshot,
|
||||
ShippingOrderSnapshotLine,
|
||||
ShippingOrderTask,
|
||||
User,
|
||||
)
|
||||
from app.services.shipping_notice.effective_order_view import (
|
||||
effective_line_facts_for_notice,
|
||||
effective_order_field_values,
|
||||
)
|
||||
from app.services.shipping_notice.order_field_purposes import task_line_purpose_values
|
||||
from app.services.shipping_notice.task_order_field_editor import (
|
||||
replace_current_line_field_value,
|
||||
replace_current_line_fields,
|
||||
)
|
||||
|
||||
|
||||
def _seed_frozen_order():
|
||||
"""最小冻结订单夹具:OT + accepted Extraction(两行三字段)+ 冻结快照。"""
|
||||
user = User(username='eff-view-user', email='eff-view@test.local', role='user', status='active')
|
||||
db.session.add(user)
|
||||
schema = ShippingOrderSchema(schema_code='EFFVIEW', display_name='EffView')
|
||||
db.session.add(schema)
|
||||
db.session.flush()
|
||||
version = ShippingOrderSchemaVersion(
|
||||
schema_id=schema.id, version=1, status='published',
|
||||
definition_json={'fields': [
|
||||
{'field_id': 'f-part', 'field_code': 'part_number', 'scope': 'line', 'value_type': 'string', 'field_category': 'order_line', 'sequence': 1, 'enabled': True},
|
||||
{'field_id': 'f-rsv', 'field_code': 'reservation_id', 'scope': 'line', 'value_type': 'string', 'field_category': 'order_line', 'sequence': 2, 'enabled': True},
|
||||
{'field_id': 'f-qty', 'field_code': 'qty', 'scope': 'line', 'value_type': 'decimal', 'field_category': 'order_line', 'sequence': 3, 'enabled': True},
|
||||
]},
|
||||
)
|
||||
db.session.add(version)
|
||||
db.session.flush()
|
||||
order = ShippingOrderTask(task_no='OT-EFFVIEW-1', source_type='direct_pdf', user_id=user.id)
|
||||
db.session.add(order)
|
||||
db.session.flush()
|
||||
extraction = ShippingOrderExtraction(
|
||||
task_id=order.id, schema_version_id=version.id, input_snapshot_hash='a' * 64, status='accepted',
|
||||
)
|
||||
db.session.add(extraction)
|
||||
db.session.flush()
|
||||
snapshot = ShippingOrderSnapshot(
|
||||
task_id=order.id, extraction_id=extraction.id, schema_version_id=version.id,
|
||||
order_data_version=1,
|
||||
rule_versions_json={'fulfillment_rule': {'required_field_ids': {
|
||||
'part_number': 'f-part', 'reservation_id': 'f-rsv', 'qty': 'f-qty',
|
||||
}}},
|
||||
header_values_json={},
|
||||
)
|
||||
db.session.add(snapshot)
|
||||
db.session.flush()
|
||||
snap_lines = []
|
||||
for position, part in enumerate(('D4-A08AR12000002-', 'D4-B07BR07000001')):
|
||||
line = ShippingOrderLine(extraction_id=extraction.id, position=position, line_no=position + 1)
|
||||
db.session.add(line)
|
||||
db.session.flush()
|
||||
for field_id, value in (('f-part', part), ('f-rsv', f'RSV-{position + 1}'), ('f-qty', '10')):
|
||||
decision = ShippingOrderFieldDecision(
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=field_id,
|
||||
decision_status='accepted', resolved_value_json=value,
|
||||
)
|
||||
db.session.add(decision)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderFieldValue(
|
||||
extraction_id=extraction.id, line_id=line.id, field_id=field_id, decision_id=decision.id,
|
||||
value_text=str(value), value_json=value,
|
||||
))
|
||||
snap_line = ShippingOrderSnapshotLine(
|
||||
snapshot_id=snapshot.id, position=position, line_no=position + 1,
|
||||
part_number=part, reservation_id=f'RSV-{position + 1}', qty=Decimal('10'),
|
||||
field_values_json={'f-part': part, 'f-rsv': f'RSV-{position + 1}', 'f-qty': '10'},
|
||||
)
|
||||
db.session.add(snap_line)
|
||||
db.session.flush()
|
||||
snap_lines.append(snap_line)
|
||||
order.current_order_extraction_id = extraction.id
|
||||
order.order_snapshot_id = snapshot.id
|
||||
db.session.flush()
|
||||
return SimpleNamespace(user=user, order=order, extraction=extraction, snapshot=snapshot, snap_lines=snap_lines)
|
||||
|
||||
|
||||
def test_edited_part_number_flows_into_effective_values(app):
|
||||
"""冻结后人工修正料号,有效视图必须返回修正值(匹配/Excel 的读取口径)。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
replace_current_line_field_value(
|
||||
task=fixture.order, position=0, field_code='part_number', value='D4-A08AR12000002',
|
||||
)
|
||||
_header, lines = effective_order_field_values(fixture.order)
|
||||
# 断言:第 0 行为修正值、第 1 行保持冻结值,证明对位叠加只影响被改行。
|
||||
assert lines[0]['f-part'] == 'D4-A08AR12000002'
|
||||
assert lines[1]['f-part'] == 'D4-B07BR07000001'
|
||||
|
||||
|
||||
def test_snapshot_stays_frozen_after_edit(app):
|
||||
"""有效视图不得回写快照:冻结事实仍是审计锚点。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
replace_current_line_field_value(
|
||||
task=fixture.order, position=0, field_code='part_number', value='D4-A08AR12000002',
|
||||
)
|
||||
# 断言:快照强类型列与 field_values_json 均保持冻结原值。
|
||||
assert fixture.snap_lines[0].part_number == 'D4-A08AR12000002-'
|
||||
assert fixture.snap_lines[0].field_values_json['f-part'] == 'D4-A08AR12000002-'
|
||||
|
||||
|
||||
def test_line_set_replacement_skips_line_overlay(app):
|
||||
"""整行替换后 position 不再可比:行级叠加保守跳过,返回冻结行值。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
# 注:替换行不带 qty——本测试只验证行集替换守卫;decimal 经整行替换路径的可持久化
|
||||
# 已由 test_line_set_replacement_with_decimal_persists_without_json_error 单独覆盖。
|
||||
replace_current_line_fields(task=fixture.order, lines=[
|
||||
{'part_number': 'D4-A08AR12000002', 'reservation_id': 'RSV-1'},
|
||||
])
|
||||
_header, lines = effective_order_field_values(fixture.order)
|
||||
# 断言:行级叠加被守卫跳过(行集维度属后续特性),值仍来自冻结快照两行原样。
|
||||
assert [row['f-part'] for row in lines] == ['D4-A08AR12000002-', 'D4-B07BR07000001']
|
||||
|
||||
|
||||
def test_effective_line_facts_for_notice(app):
|
||||
"""Notice 行物化事实按冻结规则映射强类型键并携带修正值。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
replace_current_line_field_value(
|
||||
task=fixture.order, position=0, field_code='part_number', value='D4-A08AR12000002',
|
||||
)
|
||||
facts = effective_line_facts_for_notice(fixture.order)
|
||||
first = facts[int(fixture.snap_lines[0].id)]
|
||||
# 断言:料号为修正值,数量被安全转为 Decimal,字段值字典完整。
|
||||
assert first['part_number'] == 'D4-A08AR12000002'
|
||||
assert first['reservation_id'] == 'RSV-1'
|
||||
assert first['qty'] == Decimal('10')
|
||||
assert first['field_values']['f-rsv'] == 'RSV-1'
|
||||
|
||||
|
||||
def test_decimal_edit_persists_without_json_error(app):
|
||||
"""数量(decimal 字段)人工编辑必须可持久化:value_json 存字符串、value_decimal 存 Decimal。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
replace_current_line_field_value(
|
||||
task=fixture.order, position=0, field_code='qty', value='12.5',
|
||||
)
|
||||
rows = [
|
||||
item for item in ShippingOrderFieldValue.query.filter_by(
|
||||
extraction_id=fixture.extraction.id,
|
||||
).all()
|
||||
if item.value_json is not None
|
||||
]
|
||||
# 夹具两行均预置了 f-qty FieldValue(未编辑行 value_json='10'),须限定被编辑的第 0 行再断言。
|
||||
edited_line = ShippingOrderLine.query.filter_by(
|
||||
extraction_id=fixture.extraction.id, position=0,
|
||||
).one()
|
||||
qty_rows = [item for item in rows if item.field_id == 'f-qty' and item.line_id == edited_line.id]
|
||||
# 断言:JSON 列存规范字符串(与机器路径 _json_value 对齐),类型列保留 Decimal。
|
||||
assert qty_rows, 'qty FieldValue 必须存在'
|
||||
assert all(item.value_json == '12.5' for item in qty_rows)
|
||||
assert any(item.value_decimal == Decimal('12.5') for item in qty_rows)
|
||||
|
||||
|
||||
def test_line_set_replacement_with_decimal_persists_without_json_error(app):
|
||||
"""整行替换带 decimal 字段必须同样可持久化:新当前 Extraction 的 qty JSON 列存字符串、类型列存 Decimal。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
replace_current_line_fields(task=fixture.order, lines=[
|
||||
{'part_number': 'D4-A08AR12000002', 'reservation_id': 'RSV-1', 'qty': '12.5'},
|
||||
])
|
||||
rows = ShippingOrderFieldValue.query.filter_by(
|
||||
extraction_id=fixture.order.current_order_extraction_id,
|
||||
field_id='f-qty',
|
||||
).all()
|
||||
line_qty_rows = [item for item in rows if item.line_id is not None]
|
||||
# 断言:整行替换路径的 Decision/FieldValue 均经 _json_value 落库且不得抛序列化错误。
|
||||
assert line_qty_rows, '替换行集的 qty FieldValue 必须存在'
|
||||
assert all(item.value_json == '12.5' for item in line_qty_rows)
|
||||
assert all(item.value_decimal == Decimal('12.5') for item in line_qty_rows)
|
||||
|
||||
|
||||
def test_matching_purpose_values_use_effective_view(app):
|
||||
"""库存匹配用途投影必须读到修正后的料号(修复改值不进匹配的断层)。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
replace_current_line_field_value(
|
||||
task=fixture.order, position=0, field_code='part_number', value='D4-A08AR12000002',
|
||||
)
|
||||
notice = ShippingNotice(
|
||||
task_no='SN-EFFVIEW-1', source_type='manual', user_id=fixture.user.id,
|
||||
order_task_id=fixture.order.id,
|
||||
)
|
||||
db.session.add(notice)
|
||||
db.session.flush()
|
||||
purpose_values = task_line_purpose_values(notice)
|
||||
# 断言:第 0 行用途值为修正料号,第 1 行保持冻结值。
|
||||
assert purpose_values[0]['part_number'] == 'D4-A08AR12000002'
|
||||
assert purpose_values[1]['part_number'] == 'D4-B07BR07000001'
|
||||
@@ -2,7 +2,7 @@
|
||||
|
||||
依赖:正文补充解析器与合并服务。
|
||||
逻辑:正文只补 Reservation/来源字段,PDF 数量始终保持权威;关联优先 PO+料号,
|
||||
其次 PO+预约号,歧义稳定进入复核。
|
||||
其次 PO+预约号;无同 PO 时仅 PO 缺失行可料号兜底;错 PO 禁止补充。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -23,7 +23,7 @@ SCHEMA = {'fields': [
|
||||
{'field_id': 'qty', 'field_code': 'qty'},
|
||||
{
|
||||
'field_id': 'reservation', 'field_code': 'reservation_id', 'scope': 'line',
|
||||
'aliases': ['Reservation ID', 'External reservation ID', 'Reservation Number'],
|
||||
'aliases': ['Reservation ID', 'External reservation ID', 'Reservation Number', 'IR#'],
|
||||
},
|
||||
{'field_id': 'allocation', 'field_code': 'allocation_id'},
|
||||
{'field_id': 'source', 'field_code': 'inventory_source_hint', 'scope': 'line', 'aliases': ['Source Type']},
|
||||
@@ -213,7 +213,12 @@ def test_email_supplement_pdf_value_conflict_keeps_pdf_and_requires_review():
|
||||
)[0]
|
||||
|
||||
assert _value(merged['lines'][0]['fields'], 'reservation') == 'PDF-33873'
|
||||
assert {'severity': 'blocking', 'reason': 'supplement_field_conflict', 'field': 'reservation_id'} in merged['conflicts']
|
||||
assert any(
|
||||
item.get('severity') == 'blocking'
|
||||
and item.get('reason') == 'supplement_field_conflict'
|
||||
and item.get('field') == 'reservation_id'
|
||||
for item in merged['conflicts']
|
||||
)
|
||||
|
||||
|
||||
@pytest.mark.pure_unit
|
||||
@@ -337,12 +342,12 @@ def test_email_supplement_cross_adjudicates_pn_and_ampn_against_both_order_part_
|
||||
order['lines'][0]['fields'][0]['observations'][0]['value'] = value
|
||||
supplement = {'document_id': 44, 'rows': [{
|
||||
'po_number': '4518738152', mail_field: value,
|
||||
'reservation_id': f'30000{index}', 'evidence': {},
|
||||
'reservation_id': f'300000000{index}', 'evidence': {},
|
||||
}]}
|
||||
merged = merge_email_supplements(
|
||||
orders=[order], supplements_by_intake={1: supplement}, schema_definition=SCHEMA,
|
||||
)
|
||||
assert _value(merged[0]['lines'][0]['fields'], 'reservation') == f'30000{index}'
|
||||
assert _value(merged[0]['lines'][0]['fields'], 'reservation') == f'300000000{index}'
|
||||
assert merged[0]['_hxops_email_supplement_relation'] == 'po_mpn'
|
||||
|
||||
|
||||
@@ -447,17 +452,13 @@ def test_email_supplement_po_fallback_requires_one_reservation():
|
||||
assert any(item.get('reason') == 'supplement_relation_ambiguous' for item in result['conflicts'])
|
||||
|
||||
|
||||
def test_email_supplement_unique_mpn_fallback_handles_mistyped_email_po():
|
||||
"""邮件 PO 与 PDF 不一致时,唯一完全匹配 MPN 仍可保守补齐预约号。"""
|
||||
def test_email_supplement_unique_mpn_fallback_rejects_mistyped_email_po():
|
||||
"""邮件 PO 有值且与 PDF 不一致时禁止 mpn_fallback,哪怕料号唯一命中。"""
|
||||
order = _order()
|
||||
order['header_fields'][0]['observations'][0]['value'] = '4518838152'
|
||||
supplement = {
|
||||
'document_id': 44,
|
||||
'rows': [
|
||||
{
|
||||
'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000002',
|
||||
'reservation_id': '2000484577', 'evidence': {},
|
||||
},
|
||||
{
|
||||
'customer_po_number': '4518738152', 'part_number': 'D4-A08AR12000002',
|
||||
'reservation_id': '2000484577', 'evidence': {},
|
||||
@@ -472,10 +473,121 @@ def test_email_supplement_unique_mpn_fallback_handles_mistyped_email_po():
|
||||
orders=[order], supplements_by_intake={1: supplement}, schema_definition=SCHEMA,
|
||||
)[0]
|
||||
|
||||
assert not any(item['field_id'] == 'reservation' for item in result['lines'][0]['fields'])
|
||||
assert result.get('_hxops_email_supplement_relation') is None
|
||||
|
||||
|
||||
def test_email_supplement_mpn_fallback_when_po_absent_and_part_unique():
|
||||
"""PO 列缺失时,唯一料号命中仍可保守补齐预约号与库存源线索。"""
|
||||
order = _order()
|
||||
result = merge_email_supplements(
|
||||
orders=[order],
|
||||
supplements_by_intake={1: {'document_id': 44, 'rows': [{
|
||||
'part_number': 'D4-A08AR12000002',
|
||||
'reservation_id': '2000484577',
|
||||
'inventory_source_hint': 'DBS SIN',
|
||||
'evidence': {},
|
||||
}]}},
|
||||
schema_definition=SCHEMA,
|
||||
)[0]
|
||||
assert _value(result['lines'][0]['fields'], 'reservation') == '2000484577'
|
||||
assert _value(result['lines'][0]['fields'], 'source') == 'DBS SIN'
|
||||
assert result['_hxops_email_supplement_relation'] == 'mpn_fallback'
|
||||
|
||||
|
||||
def test_email_supplement_single_line_po_absent_still_requires_part_match():
|
||||
"""双边各一行且 PO 缺失时仍须料号对上;对不上不得广播预约号。"""
|
||||
order = _order()
|
||||
result = merge_email_supplements(
|
||||
orders=[order],
|
||||
supplements_by_intake={1: {'document_id': 44, 'rows': [{
|
||||
'part_number': 'OTHER-PART-0001',
|
||||
'reservation_id': '2000484577',
|
||||
'evidence': {},
|
||||
}]}},
|
||||
schema_definition=SCHEMA,
|
||||
)[0]
|
||||
assert not any(item['field_id'] == 'reservation' for item in result['lines'][0]['fields'])
|
||||
assert result.get('_hxops_email_supplement_relation') is None
|
||||
|
||||
|
||||
def test_email_supplement_po_absent_unique_reservation_per_part_merges_rows():
|
||||
"""多行 PO 缺失时按料号唯一预约号逐行补充;同料号多预约则歧义。"""
|
||||
order = {
|
||||
'_hxops_intake_id': 1,
|
||||
'header_fields': [{'field_id': 'po', 'observations': [{'value': '4518738152'}]}],
|
||||
'lines': [
|
||||
{'fields': [
|
||||
{'field_id': 'part', 'observations': [{'value': 'D4-A08AR12000002'}]},
|
||||
{'field_id': 'qty', 'observations': [{'value': 1}]},
|
||||
]},
|
||||
{'fields': [
|
||||
{'field_id': 'part', 'observations': [{'value': 'D4-A08AR12000003'}]},
|
||||
{'field_id': 'qty', 'observations': [{'value': 2}]},
|
||||
]},
|
||||
],
|
||||
'conflicts': [],
|
||||
}
|
||||
merged = merge_email_supplements(
|
||||
orders=[order],
|
||||
supplements_by_intake={1: {'document_id': 44, 'rows': [
|
||||
{'part_number': 'D4-A08AR12000002', 'reservation_id': '2000484577', 'evidence': {}},
|
||||
{'part_number': 'D4-A08AR12000003', 'reservation_id': '2000484578', 'evidence': {}},
|
||||
]}},
|
||||
schema_definition=SCHEMA,
|
||||
)[0]
|
||||
assert merged['_hxops_email_supplement_relation'] == 'mpn_fallback'
|
||||
assert _value(merged['lines'][0]['fields'], 'reservation') == '2000484577'
|
||||
assert _value(merged['lines'][1]['fields'], 'reservation') == '2000484578'
|
||||
|
||||
ambiguous = merge_email_supplements(
|
||||
orders=[order],
|
||||
supplements_by_intake={1: {'document_id': 44, 'rows': [
|
||||
{'part_number': 'D4-A08AR12000002', 'reservation_id': '2000484577', 'evidence': {}},
|
||||
{'part_number': 'D4-A08AR12000002', 'reservation_id': '2000484579', 'evidence': {}},
|
||||
{'part_number': 'D4-A08AR12000003', 'reservation_id': '2000484578', 'evidence': {}},
|
||||
]}},
|
||||
schema_definition=SCHEMA,
|
||||
)[0]
|
||||
assert any(item.get('reason') == 'supplement_relation_ambiguous' for item in ambiguous['conflicts'])
|
||||
assert not any(item['field_id'] == 'reservation' for item in ambiguous['lines'][0]['fields'])
|
||||
assert not any(item['field_id'] == 'reservation' for item in ambiguous['lines'][1]['fields'])
|
||||
|
||||
|
||||
def test_email_supplement_normalizes_reservation_short_numeric_suffix_on_merge():
|
||||
"""同 PO 命中后,IR# 形态 35354-1 写入订单行时归一为 35354。"""
|
||||
result = merge_email_supplements(
|
||||
orders=[_order()],
|
||||
supplements_by_intake={1: {'document_id': 44, 'rows': [{
|
||||
'customer_po_number': '4518738152',
|
||||
'part_number': 'D4-A08AR12000002',
|
||||
'reservation_id': '35354-1',
|
||||
'evidence': {},
|
||||
}]}},
|
||||
schema_definition=SCHEMA,
|
||||
)[0]
|
||||
assert _value(result['lines'][0]['fields'], 'reservation') == '35354'
|
||||
assert result['_hxops_email_supplement_relation'] == 'po_mpn'
|
||||
|
||||
|
||||
def test_email_supplement_html_ir_hash_suffix_survives_parse_and_merge():
|
||||
"""解析 IR#=35354-1 不得因非法形态丢列,合并后预约号为 35354。"""
|
||||
supplement = parse_email_allocation_tables(
|
||||
content_hash='i' * 64,
|
||||
html_tables=['''<table><tr><th>PO#</th><th>MPN</th><th>IR#</th></tr>
|
||||
<tr><td>4518738152</td><td>D4-A08AR12000002</td><td>35354-1</td></tr></table>'''],
|
||||
schema_definition=SCHEMA,
|
||||
)
|
||||
assert supplement['rows'][0]['reservation_id'] == '35354'
|
||||
assert 'email_supplement_field_invalid' not in supplement.get('issues', [])
|
||||
merged = merge_email_supplements(
|
||||
orders=[_order()],
|
||||
supplements_by_intake={1: {**supplement, 'document_id': 44}},
|
||||
schema_definition=SCHEMA,
|
||||
)[0]
|
||||
assert _value(merged['lines'][0]['fields'], 'reservation') == '35354'
|
||||
|
||||
|
||||
def test_email_supplement_plain_text_vertical_table_is_parsed_without_guessing_body_text():
|
||||
"""Outlook 展平的纵向表头可恢复补充行,尾部邮件正文不会被误当数据。"""
|
||||
supplement = parse_email_allocation_text(
|
||||
@@ -508,6 +620,43 @@ def test_email_supplement_requires_frozen_schema_alias_for_order_headers():
|
||||
assert result == {'version': 'email-supplement.v1', 'rows': [], 'issues': ['email_supplement_po_header_missing']}
|
||||
|
||||
|
||||
def test_email_supplement_parses_without_po_when_mpn_and_reservation_present():
|
||||
"""无 PO 表头但有 MPN + External reservation ID 时仍须产出补充行(本单回归)。"""
|
||||
html = '''<table><tr>
|
||||
<th>MPN</th><th>Source type</th><th>External reservation ID</th>
|
||||
</tr><tr>
|
||||
<td>D4-A08AR12000002</td><td>VMI-SIN</td><td>3000092917</td>
|
||||
</tr></table>'''
|
||||
supplement = parse_email_allocation_tables(
|
||||
content_hash='j' * 64, html_tables=[html], schema_definition=SCHEMA,
|
||||
)
|
||||
assert len(supplement['rows']) == 1
|
||||
assert supplement['rows'][0]['part_number'] == 'D4-A08AR12000002'
|
||||
assert supplement['rows'][0]['reservation_id'] == '3000092917'
|
||||
assert supplement['rows'][0]['inventory_source_hint'] == 'VMI-SIN'
|
||||
assert 'email_supplement_po_header_missing' in supplement['issues']
|
||||
merged = merge_email_supplements(
|
||||
orders=[_order()],
|
||||
supplements_by_intake={1: {**supplement, 'document_id': 44}},
|
||||
schema_definition=SCHEMA,
|
||||
)[0]
|
||||
assert _value(merged['lines'][0]['fields'], 'reservation') == '3000092917'
|
||||
assert _value(merged['lines'][0]['fields'], 'source') == 'VMI-SIN'
|
||||
assert merged['_hxops_email_supplement_relation'] == 'mpn_fallback'
|
||||
|
||||
|
||||
def test_email_supplement_still_skips_table_without_po_or_part_or_reservation():
|
||||
"""无 PO 且无料号/预约号可映射列时仍整表跳过,避免无身份噪声行。"""
|
||||
result = parse_email_allocation_tables(
|
||||
content_hash='k' * 64,
|
||||
schema_definition=SCHEMA,
|
||||
html_tables=['''<table><tr><th>Location ID</th><th>Supplier code</th></tr>
|
||||
<tr><td>941.76</td><td>0000000100</td></tr></table>'''],
|
||||
)
|
||||
assert result['rows'] == []
|
||||
assert 'email_supplement_po_header_missing' in result['issues']
|
||||
|
||||
|
||||
def test_email_supplement_inventec_po_date_two_digit_year_keeps_source_location():
|
||||
"""Inventec 分配表 PO Date=12-Jun-26 时仍须保留 Source Location / 预约号。
|
||||
|
||||
|
||||
@@ -297,7 +297,10 @@ def test_file_check_tool_accepts_any_valid_task(app, client, monkeypatch):
|
||||
def start(self):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
|
||||
def _enqueue(*_args, **_kwargs):
|
||||
return 1
|
||||
|
||||
monkeypatch.setattr('app.api.file_check_tools.enqueue', _enqueue)
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
admin = _mk_admin()
|
||||
@@ -382,7 +385,10 @@ def test_file_check_tool_start_records_chat_log_bind_context(app, client, monkey
|
||||
def start(self):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
|
||||
def _enqueue(*_args, **_kwargs):
|
||||
return 1
|
||||
|
||||
monkeypatch.setattr('app.api.file_check_tools.enqueue', _enqueue)
|
||||
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
@@ -619,7 +625,10 @@ def test_file_check_tool_running_conflict_is_per_task(app, client, monkeypatch):
|
||||
def start(self):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
|
||||
def _enqueue(*_args, **_kwargs):
|
||||
return 1
|
||||
|
||||
monkeypatch.setattr('app.api.file_check_tools.enqueue', _enqueue)
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
admin = _mk_admin()
|
||||
@@ -1224,18 +1233,13 @@ def test_file_check_tool_excel_download_uses_signed_token(app, client):
|
||||
|
||||
|
||||
def test_file_check_tool_runs_disabled_schedule_immediately(app, client, monkeypatch):
|
||||
started_threads = []
|
||||
enqueued = []
|
||||
|
||||
class _Thread:
|
||||
def __init__(self, *, target, daemon, name):
|
||||
self.target = target
|
||||
self.daemon = daemon
|
||||
self.name = name
|
||||
def _enqueue(*args, **kwargs):
|
||||
enqueued.append({"args": args, "kwargs": kwargs})
|
||||
return 1
|
||||
|
||||
def start(self):
|
||||
started_threads.append(self.name)
|
||||
|
||||
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
|
||||
monkeypatch.setattr('app.api.file_check_tools.enqueue', _enqueue)
|
||||
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
@@ -1254,7 +1258,7 @@ def test_file_check_tool_runs_disabled_schedule_immediately(app, client, monkeyp
|
||||
assert data['ok'] is True
|
||||
assert data['run']['task_id'] == task_id
|
||||
assert data['run']['status'] == 'running'
|
||||
assert started_threads == [f"file-check-run-{data['run']['run_id']}"]
|
||||
assert enqueued and enqueued[0]['kwargs'].get('domain') == 'file_check'
|
||||
|
||||
|
||||
def test_serialize_file_judgement_reads_file_key():
|
||||
@@ -1816,7 +1820,10 @@ def test_file_check_turn_registry_binds_run_without_http_turn_id(app, client, mo
|
||||
def start(self):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
|
||||
def _enqueue(*_args, **_kwargs):
|
||||
return 1
|
||||
|
||||
monkeypatch.setattr('app.api.file_check_tools.enqueue', _enqueue)
|
||||
|
||||
with app.app_context():
|
||||
app.config['INTEGRATION_API_KEY'] = 'secret'
|
||||
@@ -1860,7 +1867,7 @@ def test_file_check_turn_registry_binds_run_without_http_turn_id(app, client, mo
|
||||
) == run_id
|
||||
|
||||
chat_log_id = None
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
|
||||
result = DifyService._persist_stream_chat_record(
|
||||
data={'conversation_id': 'sess-registry-001'},
|
||||
@@ -1998,7 +2005,10 @@ def _stub_file_check_thread(monkeypatch):
|
||||
def start(self):
|
||||
return None
|
||||
|
||||
monkeypatch.setattr('app.api.file_check_tools.threading.Thread', _Thread)
|
||||
def _enqueue(*_args, **_kwargs):
|
||||
return 1
|
||||
|
||||
monkeypatch.setattr('app.api.file_check_tools.enqueue', _enqueue)
|
||||
|
||||
|
||||
def _file_check_agent_proxy(task_id: int):
|
||||
@@ -2049,7 +2059,7 @@ def test_chat_tool_runs_tool_first_then_chat_log(app, client, monkeypatch):
|
||||
assert res.status_code == 200
|
||||
run_id = res.get_json()['run']['run_id']
|
||||
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
|
||||
with app.app_context():
|
||||
result = DifyService._persist_stream_chat_record(
|
||||
@@ -2094,7 +2104,7 @@ def test_chat_tool_runs_chat_log_first_then_tool(app, client, monkeypatch):
|
||||
admin_id = admin.id
|
||||
|
||||
from app.services.file_check_tools.chat_tool_run_binding import register_pending_turn
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
|
||||
with app.app_context():
|
||||
register_pending_turn(
|
||||
@@ -2219,7 +2229,7 @@ def test_chat_tool_runs_same_message_does_not_cross_runs(app, client, monkeypatc
|
||||
run_b = res_b.get_json()['run']['run_id']
|
||||
assert run_b == run_a
|
||||
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
|
||||
with app.app_context():
|
||||
result_b = DifyService._persist_stream_chat_record(
|
||||
@@ -2279,7 +2289,7 @@ def test_chat_tool_runs_without_turn_id_same_message_skips_ambiguous_bind(app, c
|
||||
from app.models import ChatToolRun
|
||||
from app.services.file_check_tools.chat_tool_run_binding import register_pending_turn
|
||||
from app.services.file_check_tools.chat_turn_registry import clear_registry_for_tests
|
||||
from app.services.dify import DifyService
|
||||
from app.services.integrations.dify import DifyService
|
||||
|
||||
with app.app_context():
|
||||
register_pending_turn(
|
||||
|
||||
@@ -30,6 +30,67 @@ def test_receipt_callback_archives_once_without_inventory_file(app, monkeypatch)
|
||||
assert ShippingInventoryFile.query.count() == 0
|
||||
|
||||
|
||||
def test_ingest_success_advances_transfer_waiting_job(app, monkeypatch):
|
||||
"""收料回调 success 落归档后,必须推进调拨 waiting 来源任务(B3 接线)。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun, TransferSourceJob, TransferRun
|
||||
from app.services.shipping_notice.receipt_report_storage import ingest_receipt_callback
|
||||
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-CB2', name='Receipt callback 2', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-CB2', schedule_task_id=task.id, status='running')
|
||||
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-callback-bridge', status='awaiting_rpa', config_snapshot_json={})
|
||||
db.session.add(unit)
|
||||
transfer_run = TransferRun(run_no='RUN-BRIDGE-E2E', business_date='2026-09-17', status='preparing_files', trigger_type='manual')
|
||||
db.session.add(transfer_run); db.session.flush()
|
||||
job = TransferSourceJob(run_id=transfer_run.id, source_code=source.source_code, status='waiting_rpa_callback')
|
||||
db.session.add(job); db.session.commit()
|
||||
monkeypatch.setattr('app.services.shipping_notice.receipt_report_storage._read_receipt_callback_file', lambda _path: b'receipt-bytes')
|
||||
monkeypatch.setattr('app.services.shipping_notice.receipt_report_storage.file_asset_storage.upload_bytes', lambda **_kwargs: None)
|
||||
payload = {'schema_version': 'shipping_receipt_rpa.v1', 'callback_id': unit.callback_id, 'status': 'success', 'file_path': 'Z:/receipt.xlsx', 'original_filename': 'receipt.xlsx', 'sha256': hashlib.sha256(b'receipt-bytes').hexdigest()}
|
||||
|
||||
result = ingest_receipt_callback(payload)
|
||||
# [断言意图] 桥接发生:收料归档后调拨任务状态推进 file_ready,file_no 为归档文件 id
|
||||
db.session.expire_all()
|
||||
advanced = db.session.get(TransferSourceJob, job.id)
|
||||
assert advanced.status == "file_ready"
|
||||
assert advanced.file_no == str(result["file_id"])
|
||||
|
||||
|
||||
def test_ingest_failed_advance_is_durable(app):
|
||||
"""failed 回调推进调拨任务后必须已 commit——rollback 不得丢弃该推进(B3 持久性)。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptRpaUnitRun, TransferSourceJob, TransferRun
|
||||
from app.services.shipping_notice.receipt_report_storage import ingest_receipt_callback
|
||||
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-CB3', name='Receipt callback 3', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-CB3', schedule_task_id=task.id, status='running')
|
||||
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-callback-bridge-durable', status='awaiting_rpa', config_snapshot_json={})
|
||||
db.session.add(unit)
|
||||
transfer_run = TransferRun(run_no='RUN-BRIDGE-E2E-FAIL', business_date='2026-09-17', status='preparing_files', trigger_type='manual')
|
||||
db.session.add(transfer_run); db.session.flush()
|
||||
job = TransferSourceJob(run_id=transfer_run.id, source_code=source.source_code, status='waiting_rpa_callback')
|
||||
db.session.add(job); db.session.commit()
|
||||
payload = {'schema_version': 'shipping_receipt_rpa.v1', 'callback_id': unit.callback_id, 'status': 'failed', 'error_code': 'RPA_TEST_FAIL', 'error_message': 'boom'}
|
||||
|
||||
result = ingest_receipt_callback(payload)
|
||||
assert result['status'] == 'failed'
|
||||
# [断言意图] 推进必须已落库而非仅 flush:rollback 丢弃会话内未提交变更,
|
||||
# 只有真正 commit 过的推进才能在 expire_all 后被新查询读到。
|
||||
db.session.rollback()
|
||||
db.session.expire_all()
|
||||
advanced = db.session.get(TransferSourceJob, job.id)
|
||||
assert advanced.status == 'failed'
|
||||
assert advanced.error_code == 'RPA_TEST_FAIL'
|
||||
|
||||
|
||||
def test_receipt_callback_rejects_file_outside_receipt_drop_root(app, tmp_path):
|
||||
"""Callback cannot read arbitrary local xlsx files outside the receipt-only drop root."""
|
||||
from app.core.errors import ValidationError
|
||||
@@ -38,7 +99,7 @@ def test_receipt_callback_rejects_file_outside_receipt_drop_root(app, tmp_path):
|
||||
with app.app_context():
|
||||
allowed_root = tmp_path / 'receipt-drop'
|
||||
allowed_root.mkdir()
|
||||
app.config['SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR'] = str(allowed_root)
|
||||
app.config['FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR'] = str(allowed_root)
|
||||
outside = tmp_path / 'outside.xlsx'
|
||||
outside.write_bytes(b'not-a-real-xlsx')
|
||||
|
||||
|
||||
@@ -63,3 +63,109 @@ def test_receipt_notification_failure_is_audited(app, monkeypatch):
|
||||
# 审计结果遵循统一枚举;业务投递状态仍保留为 failed。
|
||||
assert audit.result == 'failure'
|
||||
assert audit.after_snapshot_json['error_code'] == 'WECOM_USER_UNBOUND'
|
||||
|
||||
|
||||
def _make_receipt_run_fixture(db, task_no: str, run_no: str, callback_id: str, *, awaiting: bool = True):
|
||||
"""构造一个收料排程任务+run+成功单元+归档文件的最小通知夹具。"""
|
||||
from app.models import (
|
||||
ScheduleRun, ScheduleTask, ShippingInventorySource, ShippingReceiptReportFile,
|
||||
ShippingReceiptRpaUnitRun,
|
||||
)
|
||||
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no=task_no, name=f'Receipt notify {task_no}', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no=run_no, schedule_task_id=task.id, status='running', response_summary_json={'awaiting_receipt_rpa': True} if awaiting else None)
|
||||
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=callback_id, status='success', config_snapshot_json={})
|
||||
db.session.add(unit); db.session.flush()
|
||||
report_file = ShippingReceiptReportFile(unit_run_id=unit.id, storage_provider='minio', storage_bucket='test', storage_key=f'{callback_id}.xlsx', original_filename='receipt.xlsx', file_size=12, sha256='c' * 64)
|
||||
db.session.add(report_file)
|
||||
db.session.commit()
|
||||
return task, run, report_file
|
||||
|
||||
|
||||
def _patch_unified_wecom(monkeypatch, *, enabled_events: bool):
|
||||
"""拦截通用排程出口的企微调用,返回可断言的捕获列表。"""
|
||||
textcards: list[tuple[str, str]] = []
|
||||
media_uploads: list[str] = []
|
||||
file_sends: list[str] = []
|
||||
|
||||
def _fake_send_textcard(_userid, _title, description, _jump_url):
|
||||
textcards.append((_title, description))
|
||||
return {'errcode': 0}
|
||||
|
||||
monkeypatch.setattr('app.services.wecom_notify.send_wecom_textcard_message', _fake_send_textcard)
|
||||
if enabled_events:
|
||||
monkeypatch.setattr('app.services.wecom_notify._get_enabled_events', lambda: {'schedule_completed'})
|
||||
monkeypatch.setattr('app.services.wecom_notify.upload_wecom_temp_media', lambda _data, filename: media_uploads.append(filename) or f'media-{len(media_uploads)}')
|
||||
monkeypatch.setattr('app.services.wecom_notify.send_wecom_file_message', lambda _userid, media_id: file_sends.append(media_id) or {'errcode': 0})
|
||||
monkeypatch.setattr('app.services.file_assets.storage.file_asset_storage.get_bytes', lambda _key: b'receipt-data')
|
||||
return textcards, media_uploads, file_sends
|
||||
|
||||
|
||||
def test_receipt_run_notification_is_one_shot_at_finalize(app, monkeypatch):
|
||||
"""收料 run 终态后经通用排程出口一次性发 textcard+全部收料文件;重复归集不重发。"""
|
||||
from app import db
|
||||
from app.models import User
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import finalize_receipt_schedule_run_if_complete
|
||||
|
||||
with app.app_context():
|
||||
recipient = User(username='receipt-one-shot', email='one-shot@example.com', role='user', status='active', wecom_userid='one-shot-user')
|
||||
db.session.add(recipient); db.session.flush()
|
||||
task, run, _report_file = _make_receipt_run_fixture(db, 'SCH-RECEIPT-ONESHOT', 'RUN-RECEIPT-ONESHOT', 'receipt-oneshot-callback')
|
||||
task.notify_enabled = True
|
||||
task.notify_user_ids_json = [recipient.id]
|
||||
db.session.commit()
|
||||
|
||||
app.config['WECOM_NOTIFY_ENABLED'] = True
|
||||
app.config['WECOM_PUBLIC_BASE_URL'] = 'https://hxops.example.com'
|
||||
textcards, media_uploads, file_sends = _patch_unified_wecom(monkeypatch, enabled_events=True)
|
||||
|
||||
outcome = finalize_receipt_schedule_run_if_complete(run.id)
|
||||
|
||||
# [断言意图] 一次性出口:单条 textcard + 单文件消息,与库存排程同通道同门禁。
|
||||
assert outcome == {'finalized': True, 'status': 'success'}
|
||||
assert len(textcards) == 1
|
||||
assert '收料报表文件 1 份:已随本通知发送' in textcards[0][1]
|
||||
assert media_uploads == ['receipt.xlsx']
|
||||
assert file_sends == ['media-1']
|
||||
assert run.wecom_notified is True
|
||||
|
||||
# [断言意图] awaiting 标志清零后再次归集必须短路,绝不二次打扰接收人。
|
||||
outcome_again = finalize_receipt_schedule_run_if_complete(run.id)
|
||||
assert outcome_again == {'finalized': False, 'reason': 'not_awaiting_receipt_callback'}
|
||||
assert len(textcards) == 1 and len(file_sends) == 1
|
||||
|
||||
|
||||
def test_receipt_run_notification_follows_inventory_gates(app, monkeypatch):
|
||||
"""收料通知与库存共用门禁:事件未启用或接收人未绑定企微时不发送并记录原因。"""
|
||||
from app import db
|
||||
from app.models import User
|
||||
from app.services.schedule.scheduler_service import _notify_schedule_run_wecom
|
||||
|
||||
with app.app_context():
|
||||
app.config['WECOM_NOTIFY_ENABLED'] = True
|
||||
textcards, _media_uploads, file_sends = _patch_unified_wecom(monkeypatch, enabled_events=False)
|
||||
|
||||
bound_user = User(username='receipt-gate-bound', email='gate-bound@example.com', role='user', status='active', wecom_userid='gate-bound-user')
|
||||
unbound_user = User(username='receipt-gate-unbound', email='gate-unbound@example.com', role='user', status='active')
|
||||
db.session.add_all([bound_user, unbound_user]); db.session.flush()
|
||||
task_a, run_a, _f = _make_receipt_run_fixture(db, 'SCH-RECEIPT-GATE-A', 'RUN-RECEIPT-GATE-A', 'receipt-gate-a')
|
||||
task_a.notify_user_ids_json = [bound_user.id]
|
||||
task_b, run_b, _g = _make_receipt_run_fixture(db, 'SCH-RECEIPT-GATE-B', 'RUN-RECEIPT-GATE-B', 'receipt-gate-b')
|
||||
task_b.notify_user_ids_json = [unbound_user.id]
|
||||
db.session.commit()
|
||||
|
||||
# [断言意图] ①schedule_completed 不在 WECOM_NOTIFY_EVENTS 内 → 整体拦截并留因。
|
||||
app.config['WECOM_NOTIFY_EVENTS'] = ''
|
||||
_notify_schedule_run_wecom(task_a, run_a)
|
||||
assert textcards == [] and file_sends == []
|
||||
assert run_a.wecom_notify_error == 'event schedule_completed disabled'
|
||||
|
||||
# [断言意图] ②事件放行但接收人无 wecom_userid → 不发送并留因,与库存口径一致。
|
||||
app.config['WECOM_NOTIFY_EVENTS'] = 'schedule_completed'
|
||||
_notify_schedule_run_wecom(task_b, run_b)
|
||||
assert textcards == [] and file_sends == []
|
||||
assert run_b.wecom_notify_error == 'no wecom_userid bound users in notify list'
|
||||
|
||||
@@ -19,9 +19,9 @@ def test_receipt_schedule_expands_dbs_warehouses_and_crane_once(app, monkeypatch
|
||||
parsing_profile=dbs.parsing_profile, excel_template=dbs.excel_template,
|
||||
warehouse_resolution_mode='fixed', fixed_warehouse_id='CRANE', report_path_json={}, query_parameters_json=[], enabled=True,
|
||||
)
|
||||
db.session.add_all([crane, ShippingReceiptReportConfig(inventory_source_id=dbs.id, enabled=True, report_path_json={'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inbound', 'report_name': 'Receipt Detail'}, warehouse_ids_json=['A', 'B']),])
|
||||
db.session.add_all([crane, ShippingReceiptReportConfig(inventory_source_id=dbs.id, report_path_json={'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inbound', 'report_name': 'Receipt Detail'}, query_parameters_json=[{'name': 'Warehouse', 'mode': 'multi_text', 'values': ['A', 'B'], 'required': False, 'select_all': False}]),])
|
||||
db.session.flush()
|
||||
db.session.add(ShippingReceiptReportConfig(inventory_source_id=crane.id, enabled=True, report_path_json={'report_name': 'Inbound Details'}, warehouse_ids_json=[]))
|
||||
db.session.add(ShippingReceiptReportConfig(inventory_source_id=crane.id, report_path_json={'report_name': 'Inbound Details'}, query_parameters_json=[]))
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-1', name='Receipt', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *', job_params={'source_codes': [dbs.source_code, crane.source_code]})
|
||||
db.session.add(task); db.session.flush()
|
||||
run = ScheduleRun(run_no='RUN-RECEIPT-1', schedule_task_id=task.id, status='running')
|
||||
@@ -45,10 +45,12 @@ def test_receipt_schedule_expands_dbs_warehouses_and_crane_once(app, monkeypatch
|
||||
}
|
||||
assert dbs_unit['report_path_json']['report_name'] == 'Receipt Detail'
|
||||
assert dbs_unit['warehouse_id'] == 'A'
|
||||
# 关键断言:单元快照必须剥离 Warehouse 条件,Worker 才能按 warehouse_id 自动追加不重复。
|
||||
assert all(item['name'] != 'Warehouse' for item in dbs_unit['query_parameters_json'])
|
||||
|
||||
|
||||
def test_receipt_schedule_options_only_return_enabled_configured_sources(app):
|
||||
"""动态排程选项只暴露库存站点已启用且收料配置也启用的站点。"""
|
||||
"""动态排程选项只暴露库存站点已启用且已配置收料的站点。"""
|
||||
from app import db
|
||||
from app.models import ShippingInventorySource, ShippingReceiptReportConfig
|
||||
from app.services.schedule.job_options import list_job_options
|
||||
@@ -56,9 +58,9 @@ def test_receipt_schedule_options_only_return_enabled_configured_sources(app):
|
||||
with app.app_context():
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
db.session.add(ShippingReceiptReportConfig(
|
||||
inventory_source_id=source.id, enabled=True,
|
||||
inventory_source_id=source.id,
|
||||
report_path_json={'program_group': 'Bison', 'program_label': 'AWSBI', 'report_group': 'Inbound', 'report_name': 'Receipt Detail'},
|
||||
warehouse_ids_json=['A'],
|
||||
query_parameters_json=[{'name': 'Warehouse', 'mode': 'single', 'values': ['A'], 'required': False, 'select_all': False}],
|
||||
))
|
||||
db.session.commit()
|
||||
|
||||
@@ -74,7 +76,7 @@ def test_stale_receipt_callback_run_is_failed_without_automatic_retry(app):
|
||||
from app.services.schedule.freight_receipt_rpa_finalize import recover_stale_receipt_rpa_schedule_runs
|
||||
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_RPA_RECEIPT_TIMEOUT_SECONDS'] = 60
|
||||
app.config['FREIGHT_RPA_RECEIPT_TIMEOUT_SECONDS'] = 60
|
||||
source = ShippingInventorySource.query.filter_by(source_code='DSV360_AWSDU').one()
|
||||
task = ScheduleTask(schedule_no='SCH-RECEIPT-TIMEOUT', name='Receipt timeout', schedule_type='platform_job', platform_api_path='freight-receipt-rpa', owner_user_id=1, cron_expr='0 8 * * *')
|
||||
db.session.add(task); db.session.flush()
|
||||
@@ -98,7 +100,7 @@ def test_receipt_trigger_is_published_atomically(app, tmp_path):
|
||||
from app.services.shipping_notice.receipt_rpa import write_receipt_export_batch_trigger
|
||||
|
||||
with app.app_context():
|
||||
app.config['SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR'] = str(tmp_path)
|
||||
app.config['FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR'] = str(tmp_path)
|
||||
written = write_receipt_export_batch_trigger('RUN-ATOMIC', [{'callback_id': 'receipt:atomic'}])
|
||||
|
||||
assert written is not None
|
||||
|
||||
@@ -7,18 +7,18 @@ from pathlib import Path
|
||||
|
||||
def test_receipt_worker_isolated_from_inventory_worker_and_uses_receipt_contract():
|
||||
"""收料 Worker 只消费 v1 receipt trigger、专用目录和独立 callback。"""
|
||||
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
|
||||
assert 'SHIPPING_NOTICE_RPA_SHARED_RECEIPT_TRIGGER_DIR' in text
|
||||
assert 'SHIPPING_NOTICE_RPA_SHARED_RECEIPT_DROP_DIR' in text
|
||||
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
|
||||
assert 'FREIGHT_RPA_SHARED_RECEIPT_TRIGGER_DIR' in text
|
||||
assert 'FREIGHT_RPA_SHARED_RECEIPT_DROP_DIR' in text
|
||||
assert 'shipping_receipt_rpa.v1' in text
|
||||
assert '/api/shipping-notice/rpa/receipt-batch-ready' in text
|
||||
assert 'freight_rpa_worker' not in text
|
||||
assert 'SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR' not in text
|
||||
assert 'FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR' not in text
|
||||
|
||||
|
||||
def test_receipt_crane_driver_forces_inbound_details_match_name():
|
||||
"""收料 Crane 必须将固定报表名传给轮询匹配,不能落回库存文件名默认值。"""
|
||||
root = Path(__file__).resolve().parents[2] / 'scripts' / 'rpa'
|
||||
root = Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa'
|
||||
receipt_driver = (root / 'receipt' / 'receipt_crane_export.py').read_text(encoding='utf-8')
|
||||
crane_driver = (root / 'connectors' / 'crane' / 'crane_report_export.py').read_text(encoding='utf-8')
|
||||
assert "'scheduled_report_name': 'Inbound Details'" in receipt_driver
|
||||
@@ -27,7 +27,7 @@ def test_receipt_crane_driver_forces_inbound_details_match_name():
|
||||
|
||||
def test_receipt_crane_driver_forces_inbound_details_entry_route():
|
||||
"""复用 Profile 的门户首页时,收料不能误走库存 On Hand Details 路由。"""
|
||||
root = Path(__file__).resolve().parents[2] / 'scripts' / 'rpa'
|
||||
root = Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa'
|
||||
module_path = root / 'receipt' / 'receipt_crane_export.py'
|
||||
sys.path.insert(0, str(root))
|
||||
spec = importlib.util.spec_from_file_location('freight_receipt_crane_export_test', module_path)
|
||||
@@ -41,3 +41,59 @@ def test_receipt_crane_driver_forces_inbound_details_entry_route():
|
||||
assert module._inbound_details_entry_url('https://wms-portal.craneww.com/') == (
|
||||
'https://wms-portal.craneww.com/#/inbound-details-query'
|
||||
)
|
||||
|
||||
|
||||
def test_receipt_worker_uses_common_trigger_consumer():
|
||||
"""收料 Worker 必须复用公共 claim/归档原语,不再自建目录搬移实现。"""
|
||||
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
|
||||
assert 'claim_trigger' in text
|
||||
assert 'archive_trigger' in text
|
||||
assert "path.replace(claimed)" not in text # 领取逻辑收敛到公共模块
|
||||
|
||||
|
||||
def test_receipt_worker_logs_full_lifecycle_and_banner():
|
||||
"""收料 Worker 必须启用文件日志、完整启动 banner,且成功/失败单元都留痕。"""
|
||||
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
|
||||
assert 'configure_file_logging' in text
|
||||
assert 'maybe_rotate_open_log' in text
|
||||
assert 'mock=' in text and 'api_base=' in text and 'auth_key=' in text # banner 对齐库存字段
|
||||
assert '[receipt-unit] success' in text # 成功单元留痕(此前成功路径零输出)
|
||||
assert '[receipt-unit] failed' in text
|
||||
assert '[receipt-trigger] claimed' in text and '[receipt-trigger] archived' in text
|
||||
|
||||
|
||||
def test_receipt_worker_reports_heartbeat_with_dedicated_identity():
|
||||
"""收料 Worker 必须接心跳(对齐库存),且 ps1 以独立 WORKER_ID 上报避免监控身份抖动。"""
|
||||
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
|
||||
assert 'start_heartbeat_loop' in text and 'maybe_send_heartbeat' in text
|
||||
ps1 = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'start_receipt_worker.ps1').read_text(encoding='utf-8')
|
||||
assert 'FREIGHT_RPA_WORKER_ID' in ps1 and '-receipt' in ps1
|
||||
|
||||
|
||||
def test_receipt_register_script_mirrors_inventory_with_distinct_identity():
|
||||
"""收料计划任务注册脚本与库存同构(AtLogOn+Interactive+headless),任务名独立可同机并存。"""
|
||||
root = Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa'
|
||||
receipt = (root / 'receipt' / 'register_receipt_worker_tasks.ps1').read_text(encoding='utf-8')
|
||||
inventory = (root / 'inventory' / 'register_inventory_worker_tasks.ps1').read_text(encoding='utf-8')
|
||||
# [断言意图] 任务名赋值行必须指向 Receipt;docstring 允许提及库存任务名(并排设计说明),功能段不得引用
|
||||
assert '$TestTask = "HXOPS Receipt RPA Worker TEST"' in receipt
|
||||
assert '$ProdTask = "HXOPS Receipt RPA Worker PROD"' in receipt
|
||||
assert 'HXOPS Inventory RPA Worker TEST' in inventory and 'HXOPS Receipt RPA Worker' not in inventory
|
||||
# [断言意图] 动作必须指向收料启动脚本,且不得把库存启动脚本带进收料注册
|
||||
assert 'start_receipt_worker.ps1' in receipt and 'start_inventory_worker.ps1' not in receipt
|
||||
# [断言意图] 形状约束与库存同款:AtLogOn + Interactive + headless + 隐藏控制台
|
||||
assert 'AtLogOn' in receipt and 'Interactive' in receipt and 'Headless' in receipt and 'WindowStyle Hidden' in receipt
|
||||
|
||||
|
||||
def test_receipt_worker_supports_opt_in_session_reuse():
|
||||
"""收料 Worker 支持可选跨批次会话复用:ps1 注入开关,worker 按 env 切换持久/一次性 Profile。"""
|
||||
text = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'receipt_rpa_worker.py').read_text(encoding='utf-8')
|
||||
# [断言意图] 开关经 env 读取(默认 false 保持一次性 Profile 行为不变)
|
||||
assert "env('FREIGHT_RPA_WORKER_SESSION_REUSE', 'false')" in text
|
||||
# [断言意图] 复用模式使用持久 receipt_session 目录,且该目录不做批次后删除(跨批次复用登录态)
|
||||
assert "profile_root / 'receipt_session'" in text
|
||||
assert 'not reuse_session' in text
|
||||
ps1 = (Path(__file__).resolve().parents[2] / 'scripts' / 'freight_rpa' / 'receipt' / 'start_receipt_worker.ps1').read_text(encoding='utf-8')
|
||||
# [断言意图] 启动脚本提供 -SessionReuse 开关并注入对应 env
|
||||
assert '[switch]$SessionReuse' in ps1
|
||||
assert 'FREIGHT_RPA_WORKER_SESSION_REUSE' in ps1
|
||||
@@ -10,7 +10,7 @@ from pathlib import Path
|
||||
|
||||
|
||||
def _load_freight_rpa_heartbeat_module():
|
||||
rpa_dir = Path(__file__).resolve().parents[2] / "scripts" / "rpa"
|
||||
rpa_dir = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa"
|
||||
if str(rpa_dir) not in sys.path:
|
||||
sys.path.insert(0, str(rpa_dir))
|
||||
module_path = rpa_dir / "common" / "rpa_heartbeat.py"
|
||||
@@ -24,7 +24,7 @@ def _load_freight_rpa_heartbeat_module():
|
||||
def test_build_heartbeat_payload_includes_shared_scope_id(monkeypatch):
|
||||
module = _load_freight_rpa_heartbeat_module()
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", "hxops-rpa-test-data")
|
||||
monkeypatch.setenv("FREIGHT_RPA_SHARED_SCOPE_ID", "hxops-rpa-test-data")
|
||||
payload = module.build_heartbeat_payload(
|
||||
trigger_dir=r"C:\HxopsRpaTest\data\inventory_triggers",
|
||||
drop_dir=r"C:\HxopsRpaTest\data\inventory_drop",
|
||||
@@ -35,15 +35,15 @@ def test_build_heartbeat_payload_includes_shared_scope_id(monkeypatch):
|
||||
|
||||
def test_resolve_shared_scope_id_from_trigger_path(monkeypatch):
|
||||
module = _load_freight_rpa_heartbeat_module()
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", raising=False)
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", raising=False)
|
||||
monkeypatch.delenv("FREIGHT_RPA_SHARED_SCOPE_ID", raising=False)
|
||||
monkeypatch.delenv("FREIGHT_RPA_SHARED_SCOPE_ID", raising=False)
|
||||
monkeypatch.setenv(
|
||||
"SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR",
|
||||
"FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR",
|
||||
r"C:\HxopsRpaTest\data\inventory_triggers",
|
||||
)
|
||||
assert module._resolve_shared_scope_id() == ""
|
||||
monkeypatch.setenv(
|
||||
"SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR",
|
||||
"FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR",
|
||||
r"C:\mount\hxops-rpa-test-data\inventory_triggers",
|
||||
)
|
||||
assert module._resolve_shared_scope_id() == "hxops-rpa-test-data"
|
||||
@@ -54,7 +54,7 @@ def test_write_shared_mount_sentinel_writes_scope_file(tmp_path, monkeypatch):
|
||||
|
||||
trigger_dir = tmp_path / "inventory_triggers"
|
||||
trigger_dir.mkdir()
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", "hxops-rpa-test-data")
|
||||
monkeypatch.setenv("FREIGHT_RPA_SHARED_SCOPE_ID", "hxops-rpa-test-data")
|
||||
module.write_shared_mount_sentinel(trigger_dir=trigger_dir, hostname="WIN-RPA-01")
|
||||
|
||||
sentinel = trigger_dir / ".hxops_rpa_shared_mount"
|
||||
@@ -78,7 +78,7 @@ def test_maybe_send_heartbeat_does_not_block_trigger_loop_when_http_stalls(tmp_p
|
||||
return False
|
||||
|
||||
monkeypatch.setattr(module, "post_heartbeat", stalled_post)
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_SECONDS", "15")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_HEARTBEAT_SECONDS", "15")
|
||||
started = time.monotonic()
|
||||
sent_at = module.maybe_send_heartbeat(
|
||||
trigger_dir=tmp_path,
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
"""scripts/rpa/freight_rpa_worker.py tests.
|
||||
"""scripts/freight_rpa/freight_rpa_worker.py tests.
|
||||
|
||||
覆盖货代 RPA worker 对真实库存导出 trigger JSON 的消费路径:
|
||||
1. 读取 inventory_export_SN-20260629-2EDADC77.json。
|
||||
@@ -15,6 +15,7 @@ import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
@@ -27,7 +28,7 @@ def _repo_root() -> Path:
|
||||
|
||||
|
||||
def _load_freight_rpa_worker():
|
||||
module_path = _repo_root() / "scripts" / "rpa" / "inventory" / "inventory_rpa_worker.py"
|
||||
module_path = _repo_root() / "scripts" / "freight_rpa" / "inventory" / "inventory_rpa_worker.py"
|
||||
spec = importlib.util.spec_from_file_location("inventory_rpa_worker_under_test", module_path)
|
||||
assert spec is not None
|
||||
assert spec.loader is not None
|
||||
@@ -162,7 +163,7 @@ def test_batch_inventory_callback_preserves_each_source_v2_identity(monkeypatch,
|
||||
"inventory_sources": [source],
|
||||
}), encoding="utf-8")
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "true")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "true")
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
|
||||
|
||||
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
@@ -216,7 +217,7 @@ def test_batch_crane_trigger_allows_dynamic_warehouse_identity(monkeypatch, tmp_
|
||||
"inventory_sources": [source],
|
||||
}), encoding="utf-8")
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "true")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "true")
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
|
||||
|
||||
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
@@ -300,7 +301,7 @@ def test_batch_scheduled_trigger_skips_per_source_task_identity(monkeypatch, tmp
|
||||
}],
|
||||
}), encoding="utf-8")
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "true")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "true")
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
|
||||
|
||||
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
@@ -359,7 +360,7 @@ def test_batch_configuration_test_skips_per_source_task_identity(monkeypatch, tm
|
||||
}],
|
||||
}), encoding="utf-8")
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "true")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "true")
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, body: callbacks.append((path, body)))
|
||||
|
||||
worker._handle_inventory_batch_trigger(trigger_path, drop_dir, processed_dir)
|
||||
@@ -432,11 +433,11 @@ def test_env_strips_wrapping_quotes(monkeypatch):
|
||||
"""RPA 读取 .env 风格账号密码时,应自动剥掉外层成对引号。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME", '"user@example.com"')
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD", "'secret-pass'")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_DSV_USERNAME", '"user@example.com"')
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_DSV_PASSWORD", "'secret-pass'")
|
||||
|
||||
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME") == "user@example.com"
|
||||
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD") == "secret-pass"
|
||||
assert worker._env("FREIGHT_RPA_WORKER_DSV_USERNAME") == "user@example.com"
|
||||
assert worker._env("FREIGHT_RPA_WORKER_DSV_PASSWORD") == "secret-pass"
|
||||
|
||||
|
||||
def test_worker_accepts_business_connector_without_site_id():
|
||||
@@ -511,7 +512,7 @@ def test_dsv_sso_blank_transition_refreshes_once_before_portal_wait(monkeypatch)
|
||||
clock['value'] += 3.0
|
||||
return clock['value']
|
||||
|
||||
monkeypatch.setenv('SHIPPING_NOTICE_RPA_WORKER_DSV_SSO_RELOAD_AFTER_MS', '5000')
|
||||
monkeypatch.setenv('FREIGHT_RPA_WORKER_DSV_SSO_RELOAD_AFTER_MS', '5000')
|
||||
monkeypatch.setattr(session.time, 'monotonic', monotonic)
|
||||
monkeypatch.setattr(session.time, 'sleep', lambda _seconds: None)
|
||||
monkeypatch.setattr(session, '_debug_dsv_stage', lambda *_args, **_kwargs: None)
|
||||
@@ -533,7 +534,7 @@ def test_dsv_sso_return_timeout_is_explicit(monkeypatch):
|
||||
worker = _load_freight_rpa_worker()
|
||||
session = worker.dsv_session
|
||||
import dsv_auth
|
||||
monkeypatch.setenv('SHIPPING_NOTICE_RPA_WORKER_DSV_SSO_RETURN_TIMEOUT_MS', '30000')
|
||||
monkeypatch.setenv('FREIGHT_RPA_WORKER_DSV_SSO_RETURN_TIMEOUT_MS', '30000')
|
||||
|
||||
class _Page:
|
||||
url = 'https://auth.dbschenker.com/as/authorization.ping'
|
||||
@@ -569,9 +570,9 @@ def test_worker_uses_profile_envelope_only_within_execution_scope(monkeypatch):
|
||||
worker = _load_freight_rpa_worker()
|
||||
key = Fernet.generate_key()
|
||||
cipher = Fernet(key)
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_CREDENTIAL_KEY", key.decode("ascii"))
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME", raising=False)
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD", raising=False)
|
||||
monkeypatch.setenv("FREIGHT_RPA_CREDENTIAL_KEY", key.decode("ascii"))
|
||||
monkeypatch.delenv("FREIGHT_RPA_WORKER_DSV_USERNAME", raising=False)
|
||||
monkeypatch.delenv("FREIGHT_RPA_WORKER_DSV_PASSWORD", raising=False)
|
||||
monkeypatch.delenv("FREIGHT_RPA_DSV_USERNAME", raising=False)
|
||||
monkeypatch.delenv("FREIGHT_RPA_DSV_PASSWORD", raising=False)
|
||||
source = {
|
||||
@@ -582,43 +583,40 @@ def test_worker_uses_profile_envelope_only_within_execution_scope(monkeypatch):
|
||||
},
|
||||
}
|
||||
with worker._profile_credentials(source):
|
||||
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME") == "test-user"
|
||||
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD") == "test-password"
|
||||
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME") == ""
|
||||
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD") == ""
|
||||
assert worker._env("FREIGHT_RPA_WORKER_DSV_USERNAME") == "test-user"
|
||||
assert worker._env("FREIGHT_RPA_WORKER_DSV_PASSWORD") == "test-password"
|
||||
assert worker._env("FREIGHT_RPA_WORKER_DSV_USERNAME") == ""
|
||||
assert worker._env("FREIGHT_RPA_WORKER_DSV_PASSWORD") == ""
|
||||
|
||||
|
||||
def test_worker_prefers_canonical_rpa_env_over_legacy_name(monkeypatch):
|
||||
"""新旧 RPA 变量同时存在时必须使用统一的新命名空间,避免旧部署值覆盖新配置。"""
|
||||
def test_worker_ignores_legacy_rpa_name_without_compat(monkeypatch):
|
||||
"""无兼容层:历史旧名(FREIGHT_RPA_MOCK)不作为 FREIGHT_RPA_WORKER_MOCK 的回退,也不发弃用警告。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")
|
||||
monkeypatch.delenv("FREIGHT_RPA_WORKER_MOCK", raising=False)
|
||||
monkeypatch.setenv("FREIGHT_RPA_MOCK", "true")
|
||||
|
||||
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_MOCK") == "false"
|
||||
|
||||
|
||||
def test_worker_reads_legacy_rpa_env_during_migration(monkeypatch):
|
||||
"""规范变量缺失时允许读取旧名称,保障 Windows Worker 分阶段迁移不中断。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", raising=False)
|
||||
monkeypatch.setenv("FREIGHT_RPA_MOCK", "true")
|
||||
|
||||
with pytest.warns(DeprecationWarning, match="FREIGHT_RPA_MOCK is deprecated"):
|
||||
assert worker._env("SHIPPING_NOTICE_RPA_WORKER_MOCK") == "true"
|
||||
with warnings.catch_warnings(record=True) as caught:
|
||||
warnings.simplefilter("always")
|
||||
# 断言 1:仅设置历史旧名时,规范名直读为空、带默认值读回默认值(旧名不被咨询)。
|
||||
assert worker._env("FREIGHT_RPA_WORKER_MOCK") == ""
|
||||
assert worker._env("FREIGHT_RPA_WORKER_MOCK", "false") == "false"
|
||||
# 断言 2:读取过程不产生任何 DeprecationWarning(兼容层已删除)。
|
||||
assert not any(issubclass(item.category, DeprecationWarning) for item in caught)
|
||||
|
||||
|
||||
def test_configure_file_logging_tees_stdout_and_stderr(monkeypatch, tmp_path, capsys):
|
||||
"""配置 SHIPPING_NOTICE_RPA_WORKER_LOG_FILE 后,stdout/stderr 应同时写入日志文件并带行首时间戳。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
"""配置 FREIGHT_RPA_WORKER_LOG_FILE 后,stdout/stderr 应同时写入日志文件并带行首时间戳。"""
|
||||
# 等价迁移:文件日志实现已提取至公共 worker_logging 模块,本用例改测公共接口。
|
||||
worker_logging = _load_worker_logging()
|
||||
log_path = tmp_path / "logs" / "worker.log"
|
||||
timestamp_pattern = re.compile(r"^\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2} ")
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_FILE", str(log_path))
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_LOG_FILE", str(log_path))
|
||||
original_stdout = sys.stdout
|
||||
original_stderr = sys.stderr
|
||||
|
||||
try:
|
||||
resolved = worker._configure_file_logging()
|
||||
resolved = worker_logging.configure_file_logging()
|
||||
print("hello stdout")
|
||||
print("hello stderr", file=sys.stderr)
|
||||
finally:
|
||||
@@ -644,16 +642,17 @@ def test_configure_file_logging_tees_stdout_and_stderr(monkeypatch, tmp_path, ca
|
||||
|
||||
|
||||
def test_rotate_log_file_when_size_reaches_limit(monkeypatch, tmp_path):
|
||||
"""日志超过 SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES 时,应滚动为 .1 并保留旧备份序列。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
"""日志超过 FREIGHT_RPA_WORKER_LOG_MAX_BYTES 时,应滚动为 .1 并保留旧备份序列。"""
|
||||
# 等价迁移:轮转实现已提取至公共 worker_logging 模块,本用例改测公共接口。
|
||||
worker_logging = _load_worker_logging()
|
||||
log_path = tmp_path / "worker.log"
|
||||
log_path.write_text("current-log", encoding="utf-8")
|
||||
Path(f"{log_path}.1").write_text("old-1", encoding="utf-8")
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", "1")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT", "2")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_LOG_MAX_BYTES", "1")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_LOG_BACKUP_COUNT", "2")
|
||||
|
||||
worker._rotate_log_file_if_needed(log_path)
|
||||
worker_logging.rotate_log_file_if_needed(log_path)
|
||||
|
||||
assert not log_path.exists()
|
||||
assert Path(f"{log_path}.1").read_text(encoding="utf-8") == "current-log"
|
||||
@@ -662,21 +661,44 @@ def test_rotate_log_file_when_size_reaches_limit(monkeypatch, tmp_path):
|
||||
|
||||
def test_rotate_log_file_deletes_current_when_backup_count_zero(monkeypatch, tmp_path):
|
||||
"""备份数量为 0 时,超过大小的当前日志应直接删除。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
# 等价迁移:轮转实现已提取至公共 worker_logging 模块,本用例改测公共接口。
|
||||
worker_logging = _load_worker_logging()
|
||||
log_path = tmp_path / "worker.log"
|
||||
log_path.write_text("current-log", encoding="utf-8")
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_MAX_BYTES", "1")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_LOG_BACKUP_COUNT", "0")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_LOG_MAX_BYTES", "1")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_LOG_BACKUP_COUNT", "0")
|
||||
|
||||
worker._rotate_log_file_if_needed(log_path)
|
||||
worker_logging.rotate_log_file_if_needed(log_path)
|
||||
|
||||
assert not log_path.exists()
|
||||
|
||||
|
||||
def _load_worker_logging():
|
||||
"""加载 scripts/freight_rpa/common/worker_logging.py 供单测直接断言。
|
||||
|
||||
历史背景:文件日志实现(tee/轮转/时间戳)原内置于 inventory_rpa_worker.py,
|
||||
已提取为公共模块;Worker 内部私有名(_configure_file_logging 等)已删除,
|
||||
日志行为用例统一改测公共接口,行为断言保持等价。
|
||||
"""
|
||||
common_dir = _repo_root() / "scripts" / "freight_rpa" / "common"
|
||||
if str(common_dir) not in sys.path:
|
||||
sys.path.insert(0, str(common_dir))
|
||||
module_path = common_dir / "worker_logging.py"
|
||||
spec = importlib.util.spec_from_file_location("worker_logging_under_test", module_path)
|
||||
assert spec is not None
|
||||
assert spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
# 模块顶层 `from rpa_common import _env` 依赖 sys.path,须先登记再执行;
|
||||
# _ACTIVE_* 运行态按用例独立加载实例,避免跨用例状态串扰。
|
||||
sys.modules[spec.name] = module
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def _load_worker_disk_cleanup():
|
||||
"""加载 scripts/rpa/common/worker_disk_cleanup.py 供单测直接断言。"""
|
||||
module_path = _repo_root() / "scripts" / "rpa" / "common" / "worker_disk_cleanup.py"
|
||||
"""加载 scripts/freight_rpa/common/worker_disk_cleanup.py 供单测直接断言。"""
|
||||
module_path = _repo_root() / "scripts" / "freight_rpa" / "common" / "worker_disk_cleanup.py"
|
||||
spec = importlib.util.spec_from_file_location("worker_disk_cleanup_under_test", module_path)
|
||||
assert spec is not None
|
||||
assert spec.loader is not None
|
||||
@@ -762,8 +784,8 @@ def test_worker_disk_cleanup_deletes_expired_archives_and_keeps_active(monkeypat
|
||||
(orphan_run / "Cookies").write_text("drop", encoding="utf-8")
|
||||
os.utime(orphan_run, (now - (48 * 3600), now - (48 * 3600)))
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS", "7")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS", "24")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_DISK_RETENTION_DAYS", "7")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS", "24")
|
||||
|
||||
stats = cleanup.run_worker_disk_cleanup(
|
||||
inventory_trigger_dir=inv_trigger,
|
||||
@@ -810,8 +832,8 @@ def test_worker_disk_cleanup_skips_when_retention_disabled(monkeypatch, tmp_path
|
||||
orphan_run.mkdir()
|
||||
os.utime(orphan_run, (now - (48 * 3600), now - (48 * 3600)))
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DISK_RETENTION_DAYS", "0")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS", "24")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_DISK_RETENTION_DAYS", "0")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_ORPHAN_PROFILE_MAX_AGE_HOURS", "24")
|
||||
|
||||
cleanup.run_worker_disk_cleanup(
|
||||
inventory_trigger_dir=inv_trigger,
|
||||
@@ -823,8 +845,41 @@ def test_worker_disk_cleanup_skips_when_retention_disabled(monkeypatch, tmp_path
|
||||
assert not orphan_run.exists()
|
||||
|
||||
|
||||
def test_open_browser_uses_shipping_notice_profile_fallback(monkeypatch):
|
||||
"""未配置 profile 根目录时,应回退到 shipping_notice/freight_rpa/browser_profile。"""
|
||||
def test_cleanup_orphan_runtime_profiles_removes_receipt_prefix(tmp_path):
|
||||
"""
|
||||
崩溃残留的 receipt_* 临时 Profile 超期必须被清理;_session 目录保留。
|
||||
|
||||
断言意图:收料 Worker 的一次性 Profile 以 receipt_ 前缀创建,异常中断后
|
||||
残留目录同样按孤儿 Profile 规则清理;会话复用目录按名豁免(与年龄无关);
|
||||
未超期的 receipt_* Profile 正在使用中,前缀匹配不得误删。
|
||||
"""
|
||||
cleanup = _load_worker_disk_cleanup()
|
||||
root = tmp_path / "browser_profile"
|
||||
stale_receipt = root / "receipt_abcd1234"
|
||||
stale_receipt.mkdir(parents=True)
|
||||
(stale_receipt / "Cookies").write_text("drop", encoding="utf-8")
|
||||
young_receipt = root / "receipt_fresh5678"
|
||||
young_receipt.mkdir()
|
||||
session_dir = root / "dsv_session"
|
||||
session_dir.mkdir()
|
||||
now = time.time()
|
||||
old = now - 10 * 24 * 3600
|
||||
os.utime(stale_receipt, (old, old))
|
||||
os.utime(young_receipt, (now - 3600, now - 3600))
|
||||
os.utime(session_dir, (old, old))
|
||||
stats = cleanup.DiskCleanupStats()
|
||||
|
||||
# cutoff 对齐真实调用语义:run_worker_disk_cleanup 传入 now - 孤儿最大存活(默认 24h)
|
||||
cleanup.cleanup_orphan_runtime_profiles(root, cutoff_unix=now - 24 * 3600, stats=stats)
|
||||
|
||||
# 过期 receipt_* 目录树删除;未过期 receipt_* 与 _session 结尾目录即使过期也保留
|
||||
assert not stale_receipt.exists() and session_dir.exists()
|
||||
assert young_receipt.exists()
|
||||
assert stats.deleted_dirs == 1
|
||||
|
||||
|
||||
def test_open_browser_uses_freight_rpa_common_profile_fallback(monkeypatch):
|
||||
"""未配置 profile 根目录时,应回退到 freight_rpa/common 布局的 browser_profile。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
observed: dict[str, object] = {}
|
||||
|
||||
@@ -848,12 +903,11 @@ def test_open_browser_uses_shipping_notice_profile_fallback(monkeypatch):
|
||||
def start(self):
|
||||
return _FakePlaywright()
|
||||
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", raising=False)
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "false")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "true")
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL", raising=False)
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH", raising=False)
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", raising=False)
|
||||
monkeypatch.delenv("FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR", raising=False)
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_SESSION_REUSE", "false")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_HEADLESS", "true")
|
||||
monkeypatch.delenv("FREIGHT_RPA_WORKER_BROWSER_CHANNEL", raising=False)
|
||||
monkeypatch.delenv("FREIGHT_RPA_WORKER_BROWSER_EXECUTABLE_PATH", raising=False)
|
||||
monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object))
|
||||
|
||||
temp_roots: list[Path] = []
|
||||
@@ -872,7 +926,8 @@ def test_open_browser_uses_shipping_notice_profile_fallback(monkeypatch):
|
||||
|
||||
assert context is not None
|
||||
assert page is not None
|
||||
expected_root = _repo_root() / "backend" / "data" / "shipping_notice" / "freight_rpa" / "browser_profile"
|
||||
# 断言意图:bare-run 默认值必须等于 freight_rpa 三层布局的 common/browser_profile
|
||||
expected_root = _repo_root() / "backend" / "data" / "freight_rpa" / "common" / "browser_profile"
|
||||
assert temp_roots == [expected_root]
|
||||
assert runtime_profile_dir == expected_root / "run_unit"
|
||||
assert runtime_profile_dir.parent == expected_root
|
||||
@@ -888,7 +943,7 @@ def test_browser_profile_root_resolves_backend_relative_shipping_notice(monkeypa
|
||||
"""profile 根目录配置为 data/shipping_notice 时,应按 backend 根目录解析。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
monkeypatch.setenv(
|
||||
"SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR",
|
||||
"FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR",
|
||||
"data/shipping_notice/freight_rpa/browser_profile",
|
||||
)
|
||||
|
||||
@@ -897,30 +952,32 @@ def test_browser_profile_root_resolves_backend_relative_shipping_notice(monkeypa
|
||||
assert worker._browser_profile_root() == expected.resolve()
|
||||
|
||||
|
||||
def test_browser_profile_root_remaps_legacy_freight_rpa_path(monkeypatch):
|
||||
"""本机残留旧 profile 路径时,应强制迁到 shipping_notice 命名空间。"""
|
||||
def test_browser_profile_root_keeps_freight_rpa_layout_without_remap(monkeypatch, capsys):
|
||||
"""profile 配置为 freight_rpa 布局路径时,应按字面解析:不改写、不告警(无兼容层红线)。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
monkeypatch.setenv(
|
||||
"SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR",
|
||||
"backend/data/freight_rpa/browser_profile",
|
||||
"FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR",
|
||||
"data/freight_rpa/browser_profile",
|
||||
)
|
||||
|
||||
expected = _repo_root() / "backend" / "data" / "shipping_notice" / "freight_rpa" / "browser_profile"
|
||||
# 断言意图:迁移期 remap 已删除,旧布局形状的配置值必须原样落到 backend 根下
|
||||
expected = _repo_root() / "backend" / "data" / "freight_rpa" / "browser_profile"
|
||||
|
||||
assert worker._browser_profile_root() == expected.resolve()
|
||||
# 断言意图:不得再输出 legacy 改写告警
|
||||
assert "legacy" not in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_browser_profile_root_remaps_absolute_legacy_freight_rpa_path(monkeypatch):
|
||||
"""本机环境变量保存绝对旧路径时,也应迁到 shipping_notice 命名空间。"""
|
||||
def test_browser_profile_root_keeps_absolute_freight_rpa_layout_without_remap(monkeypatch, capsys):
|
||||
"""绝对 freight_rpa 路径同样按字面解析,证明 remap 分支已完全移除。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
monkeypatch.setenv(
|
||||
"SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR",
|
||||
str(_repo_root() / "backend" / "data" / "freight_rpa" / "browser_profile"),
|
||||
)
|
||||
profile_dir = _repo_root() / "backend" / "data" / "freight_rpa" / "browser_profile"
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR", str(profile_dir))
|
||||
|
||||
expected = _repo_root() / "backend" / "data" / "shipping_notice" / "freight_rpa" / "browser_profile"
|
||||
|
||||
assert worker._browser_profile_root() == expected.resolve()
|
||||
# 断言意图:绝对路径不再被强制迁往 shipping_notice 命名空间
|
||||
assert worker._browser_profile_root() == profile_dir.resolve()
|
||||
# 断言意图:不得再输出 legacy 改写告警
|
||||
assert "legacy" not in capsys.readouterr().out
|
||||
|
||||
|
||||
def test_inventory_export_trigger_2edadc77_reports_success(monkeypatch, tmp_path):
|
||||
@@ -944,7 +1001,7 @@ def test_inventory_export_trigger_2edadc77_reports_success(monkeypatch, tmp_path
|
||||
out_file.write_bytes(b"fake inventory content")
|
||||
return out_file
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "false")
|
||||
monkeypatch.setattr(worker, "_download_inventory_with_browser", fake_download_inventory_with_browser)
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload)))
|
||||
|
||||
@@ -1002,8 +1059,8 @@ def test_inventory_export_trigger_2edadc77_mock_writes_inventory_excel(monkeypat
|
||||
processed_dir = trigger_dir / "processed"
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "true")
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_SAMPLE_INVENTORY", raising=False)
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "true")
|
||||
monkeypatch.delenv("FREIGHT_RPA_WORKER_SAMPLE_INVENTORY", raising=False)
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload)))
|
||||
|
||||
worker._handle_inventory_trigger(trigger_path, drop_dir, processed_dir)
|
||||
@@ -1064,7 +1121,7 @@ def test_inventory_export_no_inventory_posts_skipped_callback(monkeypatch, tmp_p
|
||||
def raise_no_inventory(_trigger: dict, _drop: Path):
|
||||
raise worker.NoInventoryDataError("DSV report has no inventory data")
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "false")
|
||||
monkeypatch.setattr(worker, "_download_inventory_with_browser", raise_no_inventory)
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload)))
|
||||
|
||||
@@ -1129,7 +1186,7 @@ def test_real_upload_requires_connection_config_enabled(monkeypatch, tmp_path):
|
||||
worker = _load_freight_rpa_worker()
|
||||
workbook = tmp_path / "shipment.xlsx"
|
||||
workbook.write_bytes(b"test")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED", "true")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_UPLOAD_ENABLED", "true")
|
||||
|
||||
with pytest.raises(RuntimeError, match="not enabled for this connection"):
|
||||
worker._upload_shipment_with_browser(workbook, connector_type="dbs", upload_source={"upload_config_json": {"enabled": False}})
|
||||
@@ -1140,8 +1197,8 @@ def test_dsv_upload_returns_result_page_evidence(monkeypatch, tmp_path):
|
||||
worker = _load_freight_rpa_worker()
|
||||
workbook = tmp_path / "shipment.xlsx"
|
||||
workbook.write_bytes(b"test")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED", "true")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT", "true")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_UPLOAD_ENABLED", "true")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT", "true")
|
||||
events: list[tuple[str, object]] = []
|
||||
|
||||
class _Locator:
|
||||
@@ -1187,7 +1244,7 @@ def test_dsv_upload_returns_result_page_evidence(monkeypatch, tmp_path):
|
||||
runtime_profile = tmp_path / "profile"
|
||||
runtime_profile.mkdir()
|
||||
monkeypatch.setattr(worker, "_ensure_dsv_session", lambda _page, url: events.append(("session", url)))
|
||||
monkeypatch.setattr(worker, "_open_browser", lambda _dir: (_Playwright(), _Context(), _Page(), runtime_profile))
|
||||
monkeypatch.setattr(worker, "_open_browser", lambda _dir, **_kwargs: (_Playwright(), _Context(), _Page(), runtime_profile))
|
||||
|
||||
def fake_result(_page, filename):
|
||||
return {"reference": "", "success_evidence": {"kind": "dsv_upload_success_dom", "selector": ".alert.alert-success", "filename": filename, "reference": None, "observed_at": "2026-01-01T00:00:00Z", "page_url": "https://s360.dbschenker.com/main/portal/frame/WMSUpload2", "dom_snippet": "<div/>", "dom_sha256": "abc"}}
|
||||
@@ -1217,8 +1274,8 @@ def test_dsv_upload_uses_upload_entry_url_after_login(monkeypatch, tmp_path):
|
||||
worker = _load_freight_rpa_worker()
|
||||
workbook = tmp_path / "shipment.xlsx"
|
||||
workbook.write_bytes(b"test")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_ENABLED", "true")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT", "true")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_UPLOAD_ENABLED", "true")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_UPLOAD_CONFIRM_SUBMIT", "true")
|
||||
events: list[tuple[str, object]] = []
|
||||
|
||||
class _Locator:
|
||||
@@ -1256,7 +1313,7 @@ def test_dsv_upload_uses_upload_entry_url_after_login(monkeypatch, tmp_path):
|
||||
runtime_profile = tmp_path / "profile"
|
||||
runtime_profile.mkdir()
|
||||
monkeypatch.setattr(worker, "_ensure_dsv_session", lambda _page, url: events.append(("session", url)))
|
||||
monkeypatch.setattr(worker, "_open_browser", lambda _dir: (_Playwright(), _Context(), _Page(), runtime_profile))
|
||||
monkeypatch.setattr(worker, "_open_browser", lambda _dir, **_kwargs: (_Playwright(), _Context(), _Page(), runtime_profile))
|
||||
monkeypatch.setattr(worker, "_wait_for_dsv_upload_result", lambda _page, _filename: {"reference": "", "success_evidence": {}})
|
||||
|
||||
assert worker._upload_shipment_with_browser(
|
||||
@@ -1348,7 +1405,7 @@ def test_dsv_upload_history_requires_green_status_and_reference(monkeypatch):
|
||||
return clock["value"]
|
||||
|
||||
monkeypatch.setattr(worker.time, "monotonic", monotonic)
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_TIMEOUT_MS", "1000")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_BROWSER_TIMEOUT_MS", "1000")
|
||||
|
||||
with pytest.raises(RuntimeError, match="did not confirm a green success status"):
|
||||
worker._wait_for_dsv_upload_history_receipt(_Page(), "shipment.xlsx")
|
||||
@@ -1484,7 +1541,7 @@ def test_real_upload_failure_reports_failed_callback(monkeypatch, tmp_path):
|
||||
"task_no": "SN-UPLOAD-FAIL", "file_path": str(queue_file), "attempt_id": 8, "callback_id": "rpa:8",
|
||||
}), encoding="utf-8")
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "false")
|
||||
monkeypatch.setattr(worker, "_upload_shipment_with_browser", lambda *_args, **_kwargs: (_ for _ in ()).throw(RuntimeError("success marker missing")))
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload)))
|
||||
|
||||
@@ -1507,7 +1564,7 @@ def test_upload_empty_queue_path_reports_failed_callback(monkeypatch, tmp_path):
|
||||
"task_no": "SN-UPLOAD-EMPTY", "attempt_id": 9, "callback_id": "rpa:9",
|
||||
}), encoding="utf-8")
|
||||
callbacks: list[tuple[str, dict]] = []
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "false")
|
||||
monkeypatch.setattr(worker, "_post_callback", lambda path, payload: callbacks.append((path, payload)))
|
||||
|
||||
worker._handle_upload_trigger(trigger_path, trigger_dir / "processed")
|
||||
@@ -1573,12 +1630,11 @@ def test_open_browser_uses_fresh_runtime_profile_under_configured_root(monkeypat
|
||||
def start(self):
|
||||
return _FakePlaywright()
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "false")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_CHANNEL", "msedge")
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_EXECUTABLE_PATH", raising=False)
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", raising=False)
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_SESSION_REUSE", "false")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_HEADLESS", "false")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_BROWSER_CHANNEL", "msedge")
|
||||
monkeypatch.delenv("FREIGHT_RPA_WORKER_BROWSER_EXECUTABLE_PATH", raising=False)
|
||||
monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object))
|
||||
|
||||
_playwright, context, page, runtime_profile_dir = worker._open_browser(tmp_path / "downloads")
|
||||
@@ -1621,9 +1677,8 @@ def test_open_browser_reuses_session_profile_per_connector_and_rpa_profile(monke
|
||||
def start(self):
|
||||
return _FakePlaywright()
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "true")
|
||||
monkeypatch.delenv("SHIPPING_NOTICE_RPA_WORKER_DSV_SESSION_REUSE", raising=False)
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_SESSION_REUSE", "true")
|
||||
monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object))
|
||||
|
||||
_playwright, context, page, profile_dir = worker._open_browser(
|
||||
@@ -1665,8 +1720,8 @@ def test_open_browser_reuses_dsv_session_profile_only_when_explicitly_enabled(mo
|
||||
def start(self):
|
||||
return _FakePlaywright()
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_SESSION_REUSE", "true")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR", str(tmp_path / "profile"))
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_SESSION_REUSE", "true")
|
||||
monkeypatch.setattr(worker, "_require_playwright", lambda: (_FakeStarter, object))
|
||||
|
||||
_playwright, context, page, profile_dir = worker._open_browser(
|
||||
@@ -1791,6 +1846,190 @@ def test_fill_dsv_username_reuses_detected_email_locator(monkeypatch):
|
||||
assert locator.value == "user@example.com"
|
||||
|
||||
|
||||
def test_maybe_switch_dsv_locale_to_zh_cn_skips_when_already_zh(monkeypatch):
|
||||
"""已是中文简体时不重复点语言下拉。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
auth_globals = worker._maybe_switch_dsv_locale_to_zh_cn.__globals__
|
||||
clicks = {"value": 0}
|
||||
|
||||
class _FakeLocator:
|
||||
def __init__(self, text: str = "") -> None:
|
||||
self.first = self
|
||||
self._text = text
|
||||
|
||||
def wait_for(self, *args, **kwargs) -> None:
|
||||
return None
|
||||
|
||||
def inner_text(self, *args, **kwargs) -> str:
|
||||
return self._text
|
||||
|
||||
def click(self, *args, **kwargs) -> None:
|
||||
clicks["value"] += 1
|
||||
|
||||
class _FakeFrame:
|
||||
def locator(self, selector: str) -> _FakeLocator:
|
||||
if selector == "#lanNavSel":
|
||||
return _FakeLocator("中文简体")
|
||||
return _FakeLocator("")
|
||||
|
||||
class _FakePage:
|
||||
frames = [_FakeFrame()]
|
||||
|
||||
def locator(self, selector: str) -> _FakeLocator:
|
||||
return _FakeFrame().locator(selector)
|
||||
|
||||
monkeypatch.setitem(auth_globals, "_dsv_switch_zh_cn_enabled", lambda: True)
|
||||
assert worker._maybe_switch_dsv_locale_to_zh_cn(_FakePage()) is True
|
||||
assert clicks["value"] == 0
|
||||
|
||||
|
||||
def test_maybe_switch_dsv_locale_to_zh_cn_clicks_english_to_simplified(monkeypatch):
|
||||
"""English 时点 #kc_locale 再选中文简体,并在标签变为中文后返回 True。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
auth_globals = worker._maybe_switch_dsv_locale_to_zh_cn.__globals__
|
||||
state = {"label": "English", "opened": False, "clicks": []}
|
||||
|
||||
class _FakeLocator:
|
||||
def __init__(self, kind: str) -> None:
|
||||
self.first = self
|
||||
self._kind = kind
|
||||
|
||||
def wait_for(self, *args, **kwargs) -> None:
|
||||
return None
|
||||
|
||||
def inner_text(self, *args, **kwargs) -> str:
|
||||
return state["label"]
|
||||
|
||||
def click(self, *args, **kwargs) -> None:
|
||||
state["clicks"].append(self._kind)
|
||||
if self._kind == "toggle":
|
||||
state["opened"] = True
|
||||
if self._kind == "zh":
|
||||
state["label"] = "中文简体"
|
||||
|
||||
class _FakeFrame:
|
||||
def locator(self, selector: str) -> _FakeLocator:
|
||||
if selector == "#lanNavSel":
|
||||
return _FakeLocator("label")
|
||||
if selector == "#kc_locale":
|
||||
return _FakeLocator("toggle")
|
||||
if "中文简体" in selector:
|
||||
if not state["opened"]:
|
||||
raise RuntimeError("menu closed")
|
||||
return _FakeLocator("zh")
|
||||
raise RuntimeError(f"unexpected selector {selector}")
|
||||
|
||||
class _FakePage:
|
||||
frames = [_FakeFrame()]
|
||||
|
||||
def locator(self, selector: str) -> _FakeLocator:
|
||||
return _FakeFrame().locator(selector)
|
||||
|
||||
monkeypatch.setitem(auth_globals, "_dsv_switch_zh_cn_enabled", lambda: True)
|
||||
monkeypatch.setattr(auth_globals["time"], "sleep", lambda seconds: None)
|
||||
ticks = {"value": 0.0}
|
||||
|
||||
def fake_monotonic() -> float:
|
||||
current = ticks["value"]
|
||||
ticks["value"] += 0.5
|
||||
return current
|
||||
|
||||
monkeypatch.setattr(auth_globals["time"], "monotonic", fake_monotonic)
|
||||
|
||||
assert worker._maybe_switch_dsv_locale_to_zh_cn(_FakePage()) is True
|
||||
assert state["clicks"] == ["toggle", "zh"]
|
||||
assert state["label"] == "中文简体"
|
||||
|
||||
|
||||
def test_maybe_switch_dsv_locale_to_zh_cn_disabled_by_env(monkeypatch):
|
||||
"""环境变量关闭时不尝试切语言。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
auth_globals = worker._maybe_switch_dsv_locale_to_zh_cn.__globals__
|
||||
monkeypatch.setitem(auth_globals, "_dsv_switch_zh_cn_enabled", lambda: False)
|
||||
assert worker._maybe_switch_dsv_locale_to_zh_cn(object()) is False
|
||||
|
||||
|
||||
def test_is_dsv_password_method_label_matches_english_subtitle_row():
|
||||
"""
|
||||
英文 MFA 页「Password + Enter your password to sign in.」整行须识别为密码方式;
|
||||
Passkey / Mobile App / E-Mail Code 不得误判(对应 2026-09-16 worker 失败页)。
|
||||
"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
assert worker._is_dsv_password_method_label("Password") is True
|
||||
assert worker._is_dsv_password_method_label("Password\nEnter your password to sign in.") is True
|
||||
assert worker._is_dsv_password_method_label("密码") is True
|
||||
assert worker._is_dsv_password_method_label("Passkey\nUse this device to sign in.") is False
|
||||
assert worker._is_dsv_password_method_label("Mobile App (iPhone 11)\nUse your PingID app to sign in.") is False
|
||||
assert worker._is_dsv_password_method_label("E-Mail Code\nEnter a 6-digit code sent to your inbox.") is False
|
||||
assert worker._is_dsv_password_method_label("Forgot password") is False
|
||||
|
||||
|
||||
def test_click_dsv_password_method_clicks_english_choose_sign_in_row(monkeypatch):
|
||||
"""
|
||||
当页面只有带副标题的 Password 行(无旧 mfaForm 精确标题)时,仍应点击并确认过渡。
|
||||
"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
auth_globals = worker._click_dsv_password_method.__globals__
|
||||
clicked = {"value": False}
|
||||
|
||||
class _FakeLocator:
|
||||
def __init__(self, text: str = "") -> None:
|
||||
self.first = self
|
||||
self._text = text
|
||||
|
||||
def all(self):
|
||||
return [self] if self._text else []
|
||||
|
||||
def inner_text(self, *args, **kwargs) -> str:
|
||||
return self._text
|
||||
|
||||
def wait_for(self, *args, **kwargs) -> None:
|
||||
if not self._text:
|
||||
raise RuntimeError("not visible")
|
||||
|
||||
def scroll_into_view_if_needed(self, *args, **kwargs) -> None:
|
||||
return None
|
||||
|
||||
def click(self, *args, **kwargs) -> None:
|
||||
clicked["value"] = True
|
||||
|
||||
def evaluate(self, *args, **kwargs) -> None:
|
||||
clicked["value"] = True
|
||||
|
||||
class _FakeFrame:
|
||||
def evaluate(self, script: str, *args, **kwargs):
|
||||
# 脚本路径故意失败,迫使走 Playwright 行点击兜底
|
||||
return False
|
||||
|
||||
def locator(self, selector: str) -> _FakeLocator:
|
||||
if "listitem" in selector or "mb-2" in selector or "device-list" in selector:
|
||||
return _FakeLocator("Password\nEnter your password to sign in.")
|
||||
return _FakeLocator("")
|
||||
|
||||
class _FakePage:
|
||||
frames = [_FakeFrame()]
|
||||
url = "https://auth.dbschenker.com/as/mock/resume/as/authorization.ping"
|
||||
|
||||
def locator(self, selector: str) -> _FakeLocator:
|
||||
return _FakeFrame().locator(selector)
|
||||
|
||||
monkeypatch.setattr(auth_globals["time"], "sleep", lambda seconds: None)
|
||||
ticks = {"value": 0.0}
|
||||
|
||||
def fake_monotonic() -> float:
|
||||
current = ticks["value"]
|
||||
ticks["value"] += 0.1
|
||||
return current
|
||||
|
||||
monkeypatch.setattr(auth_globals["time"], "monotonic", fake_monotonic)
|
||||
monkeypatch.setitem(auth_globals, "_find_dsv_password_locator", lambda *args, **kwargs: object())
|
||||
monkeypatch.setitem(auth_globals, "_wait_for_visible_selector", lambda *args, **kwargs: object())
|
||||
monkeypatch.setitem(auth_globals, "_looks_like_dsv_login_method_page", lambda page: False)
|
||||
|
||||
assert worker._click_dsv_password_method(_FakePage()) is True
|
||||
assert clicked["value"] is True
|
||||
|
||||
|
||||
def test_click_dsv_password_method_ignores_forgot_password_link(monkeypatch):
|
||||
"""密码页的“忘记密码/Forgot password”链接不能被当成密码登录方式点击。"""
|
||||
worker = _load_freight_rpa_worker()
|
||||
@@ -1988,7 +2227,7 @@ def test_has_dsv_password_upgrade_prompt_skips_portal_page_scan(monkeypatch):
|
||||
|
||||
def test_ensure_dsv_session_retries_entry_after_home_not_ready(monkeypatch):
|
||||
"""登录后 home-not-ready 且 session 仍在 entry 站点时,应回 entry 重试一次。"""
|
||||
module_path = _repo_root() / "scripts" / "rpa" / "connectors" / "dsv" / "dsv_report_export.py"
|
||||
module_path = _repo_root() / "scripts" / "freight_rpa" / "connectors" / "dsv" / "dsv_report_export.py"
|
||||
spec = importlib.util.spec_from_file_location("dsv_report_export_retry_test", module_path)
|
||||
assert spec is not None and spec.loader is not None
|
||||
dsv_report_export = importlib.util.module_from_spec(spec)
|
||||
@@ -2188,7 +2427,7 @@ def test_fill_dsv_owner_filter_defaults_to_reportviewer_owner_input():
|
||||
|
||||
worker._fill_dsv_filter_if_needed(
|
||||
_FakePage(),
|
||||
"SHIPPING_NOTICE_RPA_WORKER_DSV_OWNER_SELECTOR",
|
||||
"FREIGHT_RPA_WORKER_DSV_OWNER_SELECTOR",
|
||||
"Owner",
|
||||
"CADU-0000000100",
|
||||
)
|
||||
@@ -2224,7 +2463,7 @@ def test_fill_dsv_filter_if_needed_accepts_report_name_kwarg():
|
||||
|
||||
worker._fill_dsv_filter_if_needed(
|
||||
_FakePage(),
|
||||
"SHIPPING_NOTICE_RPA_WORKER_DSV_OWNER_SELECTOR",
|
||||
"FREIGHT_RPA_WORKER_DSV_OWNER_SELECTOR",
|
||||
"Owner",
|
||||
"CADU-0000000100",
|
||||
report_name="On Hand Inventory by Location",
|
||||
@@ -2380,26 +2619,26 @@ def test_inventory_export_trigger_2edadc77_downloads_real_file(monkeypatch, tmp_
|
||||
"""
|
||||
手动集成测试:使用真实浏览器 Driver 从 DSV360 导出库存文件。
|
||||
|
||||
默认跳过;仅当 SHIPPING_NOTICE_RPA_WORKER_E2E=true 时执行。执行前需准备账号密码:
|
||||
- SHIPPING_NOTICE_RPA_WORKER_MOCK=false
|
||||
- SHIPPING_NOTICE_RPA_WORKER_HEADLESS=false(建议首次调试)
|
||||
- SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR=<运行时 profile 根目录,可选;每次执行会自动创建全新子目录>
|
||||
- SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME / SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD
|
||||
默认跳过;仅当 FREIGHT_RPA_WORKER_E2E=true 时执行。执行前需准备账号密码:
|
||||
- FREIGHT_RPA_WORKER_MOCK=false
|
||||
- FREIGHT_RPA_WORKER_HEADLESS=false(建议首次调试)
|
||||
- FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR=<运行时 profile 根目录,可选;每次执行会自动创建全新子目录>
|
||||
- FREIGHT_RPA_WORKER_DSV_USERNAME / FREIGHT_RPA_WORKER_DSV_PASSWORD
|
||||
"""
|
||||
if str(os.getenv("SHIPPING_NOTICE_RPA_WORKER_E2E") or "").strip().lower() != "true":
|
||||
pytest.skip("set SHIPPING_NOTICE_RPA_WORKER_E2E=true to run real freight RPA export")
|
||||
if str(os.getenv("FREIGHT_RPA_WORKER_E2E") or "").strip().lower() != "true":
|
||||
pytest.skip("set FREIGHT_RPA_WORKER_E2E=true to run real freight RPA export")
|
||||
|
||||
worker = _load_freight_rpa_worker()
|
||||
trigger = _build_inventory_export_trigger("SN-20260629-2EDADC77")
|
||||
drop_dir = tmp_path / "drop"
|
||||
drop_dir.mkdir()
|
||||
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_MOCK", "false")
|
||||
if not os.getenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS"):
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_HEADLESS", "false")
|
||||
if not os.getenv("SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR"):
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_MOCK", "false")
|
||||
if not os.getenv("FREIGHT_RPA_WORKER_HEADLESS"):
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_HEADLESS", "false")
|
||||
if not os.getenv("FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR"):
|
||||
monkeypatch.setenv(
|
||||
"SHIPPING_NOTICE_RPA_WORKER_BROWSER_PROFILE_DIR",
|
||||
"FREIGHT_RPA_WORKER_BROWSER_PROFILE_DIR",
|
||||
str(tmp_path / "browser_profile"),
|
||||
)
|
||||
|
||||
@@ -2409,3 +2648,45 @@ def test_inventory_export_trigger_2edadc77_downloads_real_file(monkeypatch, tmp_
|
||||
assert out_file.parent == drop_dir
|
||||
assert out_file.suffix.lower() in {".xlsx", ".xls", ".csv"}
|
||||
assert out_file.stat().st_size > 0
|
||||
|
||||
|
||||
def test_ensure_dsv_session_continues_auto_login_after_goto_abort(monkeypatch):
|
||||
"""未登录时 goto 被 SSO 重定向以 ERR_ABORTED 中止:应继续自动登录,而不是判死整个源。"""
|
||||
module_path = _repo_root() / "scripts" / "freight_rpa" / "connectors" / "dsv" / "dsv_report_export.py"
|
||||
spec = importlib.util.spec_from_file_location("dsv_report_export_abort_test", module_path)
|
||||
assert spec is not None and spec.loader is not None
|
||||
dsv_report_export = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(dsv_report_export)
|
||||
|
||||
class _FakeGotoAbort(Exception):
|
||||
pass
|
||||
|
||||
login_calls: list[str] = []
|
||||
goto_calls: list[str] = []
|
||||
|
||||
monkeypatch.setattr(dsv_report_export, "_is_dsv_session_active", lambda page, entry_url: False)
|
||||
monkeypatch.setattr(
|
||||
dsv_report_export,
|
||||
"_goto_dsv_entry_url",
|
||||
lambda page, entry_url: (goto_calls.append(entry_url), (_ for _ in ()).throw(_FakeGotoAbort("Page.goto: net::ERR_ABORTED at https://s360.dbschenker.com/main/portal")))[0],
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
dsv_report_export,
|
||||
"_maybe_auto_login_dsv",
|
||||
lambda page: login_calls.append("login"),
|
||||
)
|
||||
monkeypatch.setattr(dsv_report_export, "_is_dsv_on_entry_site", lambda page, entry_url: True)
|
||||
monkeypatch.setattr(
|
||||
dsv_report_export,
|
||||
"_wait_for_dsv_home_ready",
|
||||
lambda page, timeout_ms=None: None,
|
||||
)
|
||||
monkeypatch.setattr(dsv_report_export, "_wait_for_dsv_reports_nav_stable", lambda page, timeout_ms=None: None)
|
||||
|
||||
entry_url = "https://s360.dbschenker.com/"
|
||||
dsv_report_export._ensure_dsv_session(object(), entry_url)
|
||||
|
||||
# [断言意图] goto 被中止后必须继续自动登录(正是未登录才会被 SSO 重定向打断);
|
||||
# 登录成功后直接等待首页就绪,不重复 goto entry(该二次跳转仅在 home-not-ready 分支出现)
|
||||
assert goto_calls == [entry_url]
|
||||
assert login_calls == ["login"]
|
||||
@@ -34,7 +34,7 @@ _RPA_MODULE_PATHS = {
|
||||
|
||||
def _load_rpa_module(module_name: str):
|
||||
rel = _RPA_MODULE_PATHS.get(module_name, f"{module_name}.py")
|
||||
module_path = Path(__file__).resolve().parents[2] / "scripts" / "rpa" / rel
|
||||
module_path = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / rel
|
||||
scripts_dir = str(module_path.parent)
|
||||
if scripts_dir not in sys.path:
|
||||
sys.path.insert(0, scripts_dir)
|
||||
@@ -59,12 +59,12 @@ def test_fill_report_parameter_multi_select(monkeypatch):
|
||||
page,
|
||||
{
|
||||
"name": "Warehouse",
|
||||
"selector_env": "SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
|
||||
"selector_env": "FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
|
||||
"mode": "multi_select",
|
||||
"values": ["WH1", "WH2"],
|
||||
},
|
||||
)
|
||||
assert calls == [("SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", "Warehouse", ["WH1", "WH2"])]
|
||||
assert calls == [("FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR", "Warehouse", ["WH1", "WH2"])]
|
||||
|
||||
|
||||
def test_fill_report_parameter_multi_select_with_select_all(monkeypatch):
|
||||
@@ -96,7 +96,7 @@ def test_fill_report_parameter_multi_select_with_select_all(monkeypatch):
|
||||
)
|
||||
assert calls == [
|
||||
{
|
||||
"selector_env": "SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
|
||||
"selector_env": "FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
|
||||
"label": "Warehouse",
|
||||
"values": ["RTM"],
|
||||
"selectors": None,
|
||||
@@ -136,7 +136,7 @@ def test_fill_report_parameter_multi_select_jda_report_passes_template_selectors
|
||||
)
|
||||
assert calls == [
|
||||
{
|
||||
"selector_env": "SHIPPING_NOTICE_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
|
||||
"selector_env": "FREIGHT_RPA_WORKER_DSV_WAREHOUSE_SELECTOR",
|
||||
"label": "Warehouse",
|
||||
"values": ["RTM"],
|
||||
"selectors": None,
|
||||
@@ -418,8 +418,8 @@ def test_dsv_existing_portal_session_skips_all_auth_probes(monkeypatch):
|
||||
"""持久化 Profile 已恢复 Portal 时,不得先等待用户名或认证页面。"""
|
||||
flow = _load_dsv_auth_login_flow()
|
||||
page = MagicMock()
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_USERNAME", "user")
|
||||
monkeypatch.setenv("SHIPPING_NOTICE_RPA_WORKER_DSV_PASSWORD", "password")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_DSV_USERNAME", "user")
|
||||
monkeypatch.setenv("FREIGHT_RPA_WORKER_DSV_PASSWORD", "password")
|
||||
selector_wait = MagicMock()
|
||||
auth_ready = MagicMock()
|
||||
monkeypatch.setattr(flow, "_has_existing_dsv_portal_session", lambda _page: True)
|
||||
|
||||
@@ -91,7 +91,7 @@ def test_fetch_gate_positions_batched(app):
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
status='waiting_review',
|
||||
stage='step5_match_inventory',
|
||||
stage='inventory_matching',
|
||||
progress_version=1,
|
||||
)
|
||||
ot_b = ShippingOrderTask(
|
||||
@@ -345,7 +345,7 @@ def test_sql_todo_category_prefers_gate_inventory_sufficiency(app):
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
status='waiting_review',
|
||||
stage='step5_match_inventory',
|
||||
stage='inventory_matching',
|
||||
progress_version=1,
|
||||
)
|
||||
db.session.add(ot)
|
||||
@@ -412,3 +412,102 @@ def test_user_mode_review_status_must_human():
|
||||
review_status=rs,
|
||||
lifecycle_stage=None,
|
||||
) == 'must_human'
|
||||
|
||||
|
||||
def test_sql_todo_category_review_gate_blocked_is_review(app):
|
||||
"""订单复核 Gate 阻断必须进 review,不得落入 in_progress。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.models import ShippingOrderTask, ShippingProcessExecution
|
||||
from app.services.shipping_notice.query_service import _order_task_todo_category_sql_expr
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
user, _agent, session, _intake, _document = _seed_run_input(suffix='SQL-REVIEW-BLOCK')
|
||||
ot = ShippingOrderTask(
|
||||
task_no='OT-SQL-REVIEW-BLOCK',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
status='waiting_review',
|
||||
stage='order_review',
|
||||
progress_version=1,
|
||||
)
|
||||
db.session.add(ot)
|
||||
db.session.flush()
|
||||
db.session.add(
|
||||
ShippingProcessExecution(
|
||||
execution_no='SPE-SQL-REVIEW-BLOCK',
|
||||
task_id=int(ot.id),
|
||||
status='blocked',
|
||||
current_gate_code='order_field_extraction',
|
||||
)
|
||||
)
|
||||
db.session.commit()
|
||||
cat = (
|
||||
db.session.query(_order_task_todo_category_sql_expr())
|
||||
.filter(ShippingOrderTask.id == ot.id)
|
||||
.scalar()
|
||||
)
|
||||
assert cat == 'review'
|
||||
|
||||
|
||||
def test_sql_todo_category_running_inventory_prep_is_in_progress(app):
|
||||
"""库存准备 Execution=active 才是系统处理中。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.models import ShippingOrderTask, ShippingProcessExecution
|
||||
from app.services.shipping_notice.query_service import _order_task_todo_category_sql_expr
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
user, _agent, session, _intake, _document = _seed_run_input(suffix='SQL-RUNNING')
|
||||
ot = ShippingOrderTask(
|
||||
task_no='OT-SQL-RUNNING-PREP',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
status='processing',
|
||||
stage='notification_preparation',
|
||||
progress_version=1,
|
||||
)
|
||||
db.session.add(ot)
|
||||
db.session.flush()
|
||||
db.session.add(
|
||||
ShippingProcessExecution(
|
||||
execution_no='SPE-SQL-RUNNING-PREP',
|
||||
task_id=int(ot.id),
|
||||
status='active',
|
||||
current_gate_code='inventory_preparation',
|
||||
)
|
||||
)
|
||||
db.session.commit()
|
||||
cat = (
|
||||
db.session.query(_order_task_todo_category_sql_expr())
|
||||
.filter(ShippingOrderTask.id == ot.id)
|
||||
.scalar()
|
||||
)
|
||||
assert cat == 'in_progress'
|
||||
|
||||
|
||||
def test_sql_todo_category_without_gate_is_not_in_progress(app):
|
||||
"""无 Gate 的 OT 不得进入处理中桶。"""
|
||||
with app.app_context():
|
||||
from app import db
|
||||
from app.models import ShippingOrderTask
|
||||
from app.services.shipping_notice.query_service import _order_task_todo_category_sql_expr
|
||||
from tests.test_shipping_order_extraction_runs import _seed_run_input
|
||||
|
||||
user, _agent, session, _intake, _document = _seed_run_input(suffix='SQL-NO-GATE')
|
||||
ot = ShippingOrderTask(
|
||||
task_no='OT-SQL-NO-GATE',
|
||||
user_id=user.id,
|
||||
conversation_id=session.session_id,
|
||||
status='waiting_review',
|
||||
stage='order_review',
|
||||
progress_version=1,
|
||||
)
|
||||
db.session.add(ot)
|
||||
db.session.commit()
|
||||
cat = (
|
||||
db.session.query(_order_task_todo_category_sql_expr())
|
||||
.filter(ShippingOrderTask.id == ot.id)
|
||||
.scalar()
|
||||
)
|
||||
assert cat == 'exception'
|
||||
@@ -9,7 +9,7 @@ def test_internal_job_shipping_inventory_rpa_writes_trigger(client, app, tmp_pat
|
||||
"""POST /api/internal/jobs/shipping-inventory-rpa 应写入 batch trigger。"""
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
|
||||
with app.app_context():
|
||||
from app import db
|
||||
|
||||
@@ -126,7 +126,7 @@ def _published_template(*, code: str) -> ShippingExcelTemplate:
|
||||
def test_configuration_test_callback_isolated_from_production_inventory(app, tmp_path):
|
||||
"""测试文件只能生成测试分析,重复发起复用运行,禁止创建生产库存快照。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
@@ -150,8 +150,8 @@ def test_configuration_test_callback_maps_windows_drop_path_to_shared_mount(app,
|
||||
drop_dir = tmp_path / 'inventory_drop'
|
||||
drop_dir.mkdir()
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['SHIPPING_NOTICE_RPA_SHARED_INVENTORY_DROP_DIR'] = str(drop_dir)
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_SHARED_INVENTORY_DROP_DIR'] = str(drop_dir)
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
@@ -170,7 +170,7 @@ def test_configuration_test_callback_maps_windows_drop_path_to_shared_mount(app,
|
||||
|
||||
def test_empty_configuration_export_is_successful_but_marks_data_validation_pending(app, tmp_path):
|
||||
"""已绑定发布方案的空库存结果是有效连接证据,不能被误写为 RPA 失败。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
@@ -211,7 +211,7 @@ def test_empty_configuration_export_is_successful_but_marks_data_validation_pend
|
||||
|
||||
def test_empty_configuration_export_without_published_profile_is_rejected(app):
|
||||
"""没有受控解析定义时,空结果不能被用作站点可用性的替代证据。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
@@ -228,7 +228,7 @@ def test_empty_configuration_export_without_published_profile_is_rejected(app):
|
||||
|
||||
def test_configuration_test_automatically_verifies_compatible_bound_profile(app, tmp_path):
|
||||
"""当前绑定方案的核心栏位仍在时,历史无关列缺失也必须直接成为验证证据。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
@@ -248,7 +248,7 @@ def test_configuration_test_automatically_verifies_compatible_bound_profile(app,
|
||||
|
||||
def test_verified_current_profile_automatically_enables_ready_source(app, tmp_path):
|
||||
"""当前解析验证通过且必要条件齐全时,站点无需人工确认即可自动启用。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
@@ -270,7 +270,7 @@ def test_verified_current_profile_automatically_enables_ready_source(app, tmp_pa
|
||||
|
||||
def test_verified_current_profile_keeps_source_disabled_without_template(app, tmp_path):
|
||||
"""解析测试通过不绕过发货模板门禁,条件不完整的站点必须保持停用。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
@@ -291,7 +291,7 @@ def test_verified_current_profile_keeps_source_disabled_without_template(app, tm
|
||||
|
||||
def test_empty_export_automatically_enables_ready_fixed_source(app, tmp_path):
|
||||
"""固定仓查询成功但无库存时,也能在完整门禁下自动启用站点。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
@@ -314,7 +314,7 @@ def test_empty_export_automatically_enables_ready_fixed_source(app, tmp_path):
|
||||
|
||||
def test_batch_configuration_test_groups_profiles_and_isolates_site_results(app, tmp_path):
|
||||
"""同连接站点一次投递,混合成功、空库存及失败后仍独立汇总为部分失败。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
) as write_trigger:
|
||||
@@ -356,7 +356,7 @@ def test_batch_configuration_test_groups_profiles_and_isolates_site_results(app,
|
||||
|
||||
def test_retry_batch_only_retriggers_failed_sites(app, tmp_path):
|
||||
"""批次重试只新建失败站点运行,成功和空库存结果不会被重复导出。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
@@ -378,7 +378,7 @@ def test_retry_batch_only_retriggers_failed_sites(app, tmp_path):
|
||||
|
||||
def test_batch_callback_marks_changed_source_stale_and_ignores_unknown_run(app, tmp_path):
|
||||
"""配置变更后的旧批次回调必须失效,未知运行号不能污染同批次状态。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
@@ -406,7 +406,7 @@ def test_batch_callback_marks_changed_source_stale_and_ignores_unknown_run(app,
|
||||
|
||||
def test_latest_active_batch_restores_only_unfinished_validation(app, tmp_path):
|
||||
"""页面刷新只能恢复仍在执行的批次,已结束批次不会反复占用进度面板。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
@@ -428,7 +428,7 @@ def test_latest_active_batch_restores_only_unfinished_validation(app, tmp_path):
|
||||
|
||||
def test_batch_progress_marks_only_claimed_current_run_processing(app, tmp_path):
|
||||
"""Worker 领取回调只更新本批次当前运行,终态运行不得被重新打开。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
@@ -461,7 +461,7 @@ def test_batch_progress_marks_only_claimed_current_run_processing(app, tmp_path)
|
||||
def test_latest_configuration_test_recovers_only_current_configuration(app, tmp_path):
|
||||
"""重开配置抽屉只能恢复当前版本测试;站点改动后可发起独立新测试而不复用旧运行。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
@@ -482,8 +482,8 @@ def test_latest_configuration_test_recovers_only_current_configuration(app, tmp_
|
||||
def test_configuration_test_timeout_marks_run_failed(app, tmp_path):
|
||||
"""RPA 长时间未回调时,读取最近运行应服务端收口为失败而非让前端无限轮询。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS'] = 1
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS'] = 1
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
@@ -511,8 +511,8 @@ def test_configuration_test_timeout_marks_run_failed(app, tmp_path):
|
||||
|
||||
def test_batch_configuration_test_timeout_scales_with_shared_worker_queue(app, tmp_path):
|
||||
"""同连接批量站点在 Worker 串行等待时,不得按单站时限提前失败。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['SHIPPING_NOTICE_RPA_INVENTORY_TIMEOUT_SECONDS'] = 10
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_INVENTORY_TIMEOUT_SECONDS'] = 10
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
@@ -538,7 +538,7 @@ def test_batch_configuration_test_timeout_scales_with_shared_worker_queue(app, t
|
||||
def test_confirming_test_profile_binds_only_compatible_published_profile(app, tmp_path):
|
||||
"""确认本次测试推荐的已发布方案后,才绑定库存站点并形成有效测试证据。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
@@ -581,7 +581,7 @@ def test_confirming_test_profile_binds_only_compatible_published_profile(app, tm
|
||||
def test_rpa_profile_change_stales_completed_configuration_test(app, tmp_path):
|
||||
"""连接凭据或登录配置变更后,旧测试不得继续作为当前库存站点的启用证据。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
@@ -611,7 +611,7 @@ def test_rpa_profile_change_stales_completed_configuration_test(app, tmp_path):
|
||||
def test_configuration_test_rejects_enabled_source_and_stale_confirmation(app, tmp_path):
|
||||
"""正式运行中的站点不能发起测试;站点配置变化后旧测试不得绑定。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
@@ -654,7 +654,7 @@ def test_configuration_test_rejects_enabled_source_and_stale_confirmation(app, t
|
||||
def test_failed_callback_and_unrelated_profile_never_bind_source(app, tmp_path):
|
||||
"""失败回调和非推荐方案均不得产生生产快照或修改站点解析方案。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context(), patch(
|
||||
'app.services.shipping_notice.rpa.write_inventory_export_batch_trigger', return_value='trigger.json',
|
||||
):
|
||||
|
||||
@@ -114,7 +114,7 @@ def _excel_template_id() -> int:
|
||||
|
||||
def test_published_parsing_profile_can_be_shared_by_sources(app):
|
||||
"""同一 published Profile 应可绑定多个库存源,避免重复维护相同模板。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
parsing = _published_profile()
|
||||
login = shipping_inventory_service.save_profile({
|
||||
@@ -132,7 +132,7 @@ def test_published_parsing_profile_can_be_shared_by_sources(app):
|
||||
|
||||
def test_source_rejects_draft_parsing_profile(app):
|
||||
"""库存源只能绑定 published Profile,避免运行期读取可变草稿。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
order_schema_service.initialize_schema({'display_name': '库存匹配字段'}, actor_id=None)
|
||||
field = order_schema_service.save_field({'field_code': 'part_number', 'scope': 'line', 'value_type': 'string'}, actor_id=None)
|
||||
@@ -175,7 +175,7 @@ def test_csv_parsing_profile_rejects_worksheet_configuration(app):
|
||||
|
||||
def test_new_published_version_does_not_retire_bound_version(app):
|
||||
"""发布新版本不得使现有库存源绑定的旧 published 版本失效。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
first = _published_profile()
|
||||
field_id = order_schema_service.get_state()['fields'][0]['id']
|
||||
@@ -195,7 +195,7 @@ def test_new_published_version_does_not_retire_bound_version(app):
|
||||
|
||||
def test_referenced_published_profile_cannot_be_retired(app):
|
||||
"""已绑定库存源的解析 Profile 必须先迁移 Source,不能直接退役。"""
|
||||
app.config['SHIPPING_NOTICE_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
app.config['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
|
||||
with app.app_context():
|
||||
parsing = _published_profile()
|
||||
login = shipping_inventory_service.save_profile({
|
||||
|
||||
@@ -12,7 +12,7 @@ from pathlib import Path
|
||||
|
||||
def _load_worker():
|
||||
module_path = (
|
||||
Path(__file__).resolve().parents[2] / "scripts" / "rpa" / "inventory" / "inventory_rpa_worker.py"
|
||||
Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "inventory" / "inventory_rpa_worker.py"
|
||||
)
|
||||
scripts_dir = str(module_path.parent)
|
||||
if scripts_dir not in sys.path:
|
||||
|
||||
@@ -281,3 +281,42 @@ def test_sample_analysis_rejects_invalid_file(app, tmp_path):
|
||||
with pytest.raises(ValidationError) as exc_info:
|
||||
inventory_structure_analysis.create_sample_upload(upload, actor_id=None)
|
||||
assert exc_info.value.code == 'SHIPPING.INVENTORY_STRUCTURE_ANALYSIS_INVALID'
|
||||
|
||||
|
||||
def test_profile_draft_purpose_passthrough_creates_movement_profile(app, tmp_path):
|
||||
"""purpose='movement' 必须透传到解析规则:异动草稿不依赖库存字段目录与匹配键。"""
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
analysis = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
|
||||
# 关键断言:movement 映射直接用定死领域字段码作键,不需要订单匹配键。
|
||||
profile = inventory_structure_analysis.create_profile_draft(analysis['id'], {
|
||||
'profile_code': 'MOVE_STD', 'display_name': '收料异动标准', 'purpose': 'movement',
|
||||
'sheet_name': 'Inventory', 'header_row_index': 3,
|
||||
'field_mapping': {'doc_no': 'Supplier Sku', 'material_code': 'Reservation ID',
|
||||
'quantity': 'Qty Available', 'movement_date': 'Warehouse ID'},
|
||||
'match_keys': None,
|
||||
}, actor_id=None)
|
||||
assert profile['purpose'] == 'movement'
|
||||
assert profile['definition']['match_keys'] == []
|
||||
assert set(profile['definition']['field_mapping']) == {'doc_no', 'material_code', 'quantity', 'movement_date'}
|
||||
|
||||
|
||||
def test_publish_movement_profile_skips_order_match_key_contract(app, tmp_path):
|
||||
"""发布 movement 规则不需要订单匹配键:其端点契约是定死异动字段,不是订单 Schema。"""
|
||||
from app.services.shipping_notice import inventory_parsing_profile
|
||||
|
||||
app.config['SHIPPING_NOTICE_STORAGE_ROOT'] = str(tmp_path / 'shipping')
|
||||
with app.app_context():
|
||||
analysis = inventory_structure_analysis.create_sample_upload(_inventory_upload(), actor_id=None)
|
||||
profile = inventory_structure_analysis.create_profile_draft(analysis['id'], {
|
||||
'profile_code': 'MOVE_PUB', 'display_name': '收料异动发布', 'purpose': 'movement',
|
||||
'sheet_name': 'Inventory', 'header_row_index': 3,
|
||||
'field_mapping': {'doc_no': 'Supplier Sku', 'material_code': 'Reservation ID',
|
||||
'quantity': 'Qty Available', 'movement_date': 'Warehouse ID'},
|
||||
'match_keys': None,
|
||||
}, actor_id=None)
|
||||
# 关键断言:movement 草稿必须能直接发布(有样本证据即可),match_keys 为空是合法契约。
|
||||
published = inventory_parsing_profile.publish(profile['id'], actor_id=None)
|
||||
assert published['status'] == 'published'
|
||||
assert published['checksum']
|
||||
assert published['definition']['match_keys'] == []
|
||||
@@ -0,0 +1,65 @@
|
||||
"""
|
||||
tests/test_line_closure_export.py
|
||||
|
||||
用途:验证滚动导出资格对已结案行的剔除(含"有库存的结案行也不导出"边缘场景)。
|
||||
依赖:pytest、reservation_service、fulfillment_workflow、核验/预约模型、行级履约决定。
|
||||
逻辑:两行均有可用预约,结案其一后,导出资格集合只保留未结案行。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingInventoryVerification,
|
||||
ShippingInventoryVerificationLine,
|
||||
ShippingReservation,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_workflow import exportable_snapshot_line_ids
|
||||
from app.services.shipping_notice.reservation_service import current_available_snapshot_line_ids
|
||||
from tests.test_effective_order_view import _seed_frozen_order
|
||||
from tests.test_line_closure_fulfillment import _seed_close_decision
|
||||
|
||||
|
||||
def _seed_available_reservations(fixture):
|
||||
"""两行各建一条 available 预约 + 一轮 completed 核验。"""
|
||||
verification = ShippingInventoryVerification(task_id=fixture.order.id, status='completed')
|
||||
db.session.add(verification)
|
||||
db.session.flush()
|
||||
for index, snap_line in enumerate(fixture.snap_lines):
|
||||
reservation = ShippingReservation(
|
||||
task_id=fixture.order.id, snapshot_line_id=snap_line.id,
|
||||
reservation_id=f'RSV-CLOSE-{index}', po_number_normalized='PO-CLOSE',
|
||||
part_number=snap_line.part_number, required_qty=Decimal('10'), status='available',
|
||||
)
|
||||
db.session.add(reservation)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingInventoryVerificationLine(
|
||||
verification_id=verification.id, reservation_id=reservation.id,
|
||||
required_qty=Decimal('10'), available_qty=Decimal('10'), status='available',
|
||||
))
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def test_closed_line_with_inventory_is_not_exportable(app):
|
||||
"""结案行即使库存充足、核验 available 也不得进入导出资格集合。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
_seed_available_reservations(fixture)
|
||||
_seed_close_decision(fixture, 1)
|
||||
_verification, available = current_available_snapshot_line_ids(
|
||||
fixture.order, closed_snapshot_line_ids={int(fixture.snap_lines[1].id)},
|
||||
)
|
||||
# 断言:仅未结案的第 0 行可导出。
|
||||
assert available == {int(fixture.snap_lines[0].id)}
|
||||
|
||||
|
||||
def test_exportable_snapshot_line_ids_excludes_closed(app):
|
||||
"""滚动导出入口(exportable_snapshot_line_ids)自动剔除结案行。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
_seed_available_reservations(fixture)
|
||||
_seed_close_decision(fixture, 1)
|
||||
# 断言:导出集合不含结案行(该行预约仍 available,验证 closed 过滤优先)。
|
||||
assert exportable_snapshot_line_ids(fixture.order) == {int(fixture.snap_lines[0].id)}
|
||||
@@ -0,0 +1,141 @@
|
||||
"""
|
||||
tests/test_line_closure_fulfillment.py
|
||||
|
||||
用途:验证行结案(close_unfulfillable)在满足性聚合与整单门禁中的豁免语义。
|
||||
依赖:pytest、fulfillment_workflow、行级履约决定模型、冻结订单夹具。
|
||||
逻辑:两行订单关闭短缺行后整单应判定满足;全部行结案时整单不通过(无剩余履约内容)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
ShippingNoticeLineInventoryMatch,
|
||||
ShippingOrderReviewCase,
|
||||
ShippingOrderReviewLineDecision,
|
||||
)
|
||||
from app.services.shipping_notice.fulfillment_workflow import (
|
||||
_closed_snapshot_line_ids_for_task,
|
||||
_recompute_task_match_aggregate,
|
||||
match_completed,
|
||||
)
|
||||
from tests.test_effective_order_view import _seed_frozen_order
|
||||
|
||||
|
||||
def _seed_match_facts(fixture):
|
||||
"""第 0 行 matched+ready,第 1 行 not_found 短缺(历史阻塞点)。"""
|
||||
for snap_line, result, shortage in (
|
||||
(fixture.snap_lines[0], 'matched', '0'),
|
||||
(fixture.snap_lines[1], 'not_found', '10'),
|
||||
):
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
task_id=fixture.order.id, snapshot_line_id=snap_line.id, line_no=snap_line.line_no,
|
||||
line_index=snap_line.position, match_result=result, inventory_status='ready',
|
||||
required_qty='10', available_qty='10' if result == 'matched' else '0',
|
||||
shortage_qty=shortage, reservation_id=snap_line.reservation_id,
|
||||
part_number=snap_line.part_number, is_current=True,
|
||||
))
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def _seed_close_decision(fixture, line_index, *, case_no='SNRC-CLOSE-1', version=1):
|
||||
"""给已确认 Case 补一条活动结案决定(FK 不强制,挂哨兵父 id 即可)。"""
|
||||
case = ShippingOrderReviewCase.query.filter_by(case_no=case_no).first()
|
||||
if case is None:
|
||||
case = ShippingOrderReviewCase(
|
||||
case_no=case_no, run_id=901, unit_id=902, document_id=903,
|
||||
owner_user_id=fixture.user.id, status='confirmed', confirmed_task_id=fixture.order.id,
|
||||
)
|
||||
db.session.add(case)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderReviewLineDecision(
|
||||
review_case_id=case.id, draft_line_id=f'line-{line_index}', line_index=line_index,
|
||||
decision_version=version, decision_code='close_unfulfillable', decision_source='user',
|
||||
line_status='closed_unfulfillable', is_active=True, reason='该行不再发货',
|
||||
actor_user_id=fixture.user.id, snapshot_json={},
|
||||
))
|
||||
db.session.flush()
|
||||
|
||||
|
||||
def test_closed_line_ids_helper_mirrors_release_query(app):
|
||||
"""结案行集合必须与放行同款:活动决定 + line_index 映射快照行。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
_seed_close_decision(fixture, 1)
|
||||
# 断言:仅第 1 行(line_index=1)进入结案集合。
|
||||
assert _closed_snapshot_line_ids_for_task(fixture.order) == {int(fixture.snap_lines[1].id)}
|
||||
|
||||
|
||||
def test_aggregate_exempts_closed_shortage_line(app):
|
||||
"""关闭短缺行后聚合应判满足:closed 行不阻断、不进缺货列表。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
_seed_match_facts(fixture)
|
||||
_seed_close_decision(fixture, 1)
|
||||
status, shortages = _recompute_task_match_aggregate(fixture.order)
|
||||
payload = fixture.order.step_payload_json or {}
|
||||
line_results = payload['current_match_projection']['line_results']
|
||||
# 断言:整单满足、缺货列表为空、结案行状态为 closed 而非 shortage。
|
||||
assert status == 'fulfillable'
|
||||
assert shortages == []
|
||||
assert line_results[1]['line_status'] == 'closed'
|
||||
|
||||
|
||||
def test_match_completed_passes_with_closed_line(app):
|
||||
"""整单满足性门禁对结案行豁免:一行 matched + 一行 closed 即通过。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
_seed_match_facts(fixture)
|
||||
# 断言:结案前整单不通过(历史阻塞行为)。
|
||||
assert match_completed(fixture.order) is False
|
||||
_seed_close_decision(fixture, 1)
|
||||
# 断言:结案后整单通过(本任务修复目标)。
|
||||
assert match_completed(fixture.order) is True
|
||||
|
||||
|
||||
def test_all_lines_closed_fails_match_completed(app):
|
||||
"""全部行结案=无剩余履约内容:整单满足性不通过(此类单应走作废流程)。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
_seed_match_facts(fixture)
|
||||
_seed_close_decision(fixture, 1, version=1)
|
||||
_seed_close_decision(fixture, 0, version=1)
|
||||
# 断言:无任何待履约行时 match_completed 返回 False,避免自动建空通知。
|
||||
assert match_completed(fixture.order) is False
|
||||
|
||||
|
||||
def test_all_lines_closed_aggregate_is_unfulfillable(app):
|
||||
"""全结案聚合口径锁定:结案行不计满足 ⇒ 整单 unfulfillable(与 match_completed 一致)。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
_seed_match_facts(fixture)
|
||||
_seed_close_decision(fixture, 1, version=1)
|
||||
_seed_close_decision(fixture, 0, version=1)
|
||||
status, shortages = _recompute_task_match_aggregate(fixture.order)
|
||||
# 断言:无 ok 也无 block(无可履约内容)⇒ unfulfillable,且不产生缺货列表。
|
||||
assert status == 'unfulfillable'
|
||||
assert shortages == []
|
||||
|
||||
|
||||
def test_closed_status_precedence_over_ok(app):
|
||||
"""分类优先级锁定:matched+ready 行结案后记 closed(非 ok),且不再贡献整单满足。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
# 仅第 0 行有匹配事实(matched+ready)且已结案:聚合视角为单行订单。
|
||||
snap_line = fixture.snap_lines[0]
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
task_id=fixture.order.id, snapshot_line_id=snap_line.id, line_no=snap_line.line_no,
|
||||
line_index=snap_line.position, match_result='matched', inventory_status='ready',
|
||||
required_qty='10', available_qty='10', shortage_qty='0',
|
||||
reservation_id=snap_line.reservation_id, part_number=snap_line.part_number,
|
||||
is_current=True,
|
||||
))
|
||||
db.session.flush()
|
||||
_seed_close_decision(fixture, 0)
|
||||
status, shortages = _recompute_task_match_aggregate(fixture.order)
|
||||
payload = fixture.order.step_payload_json or {}
|
||||
line_results = payload['current_match_projection']['line_results']
|
||||
# 断言:结案分类优先于匹配满足;无 ok 无 block ⇒ 整单 unfulfillable。
|
||||
assert line_results[0]['line_status'] == 'closed'
|
||||
assert status == 'unfulfillable'
|
||||
assert shortages == []
|
||||
@@ -0,0 +1,63 @@
|
||||
"""
|
||||
tests/test_line_closure_gate_sync.py
|
||||
|
||||
用途:验证结案决定落库后的 Gate 重算联动(对齐放行路径),含 trigger 透传。
|
||||
依赖:pytest、order_review_fulfillment_decision_service、fulfillment_workflow、匹配事实夹具。
|
||||
逻辑:结案使聚合转为满足后,_sync 必须重算任务履约态并以 line_fulfillment_closed 触发编排。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from types import SimpleNamespace
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingProcessExecution
|
||||
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||||
_sync_confirmed_task_fulfillment_gates,
|
||||
)
|
||||
from tests.test_effective_order_view import _seed_frozen_order
|
||||
from tests.test_line_closure_fulfillment import _seed_close_decision, _seed_match_facts
|
||||
|
||||
|
||||
def test_close_decision_syncs_gates_with_closed_trigger(app, monkeypatch):
|
||||
"""结案行豁免使整单满足后,Gate 同步须重算并以 line_fulfillment_closed 触发编排。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
_seed_match_facts(fixture)
|
||||
_seed_close_decision(fixture, 1)
|
||||
# 计划自审补齐:submit_auto_progress 仅在 OT 绑定活动 Execution 时触发,
|
||||
# 冻结订单夹具默认不带执行实例,须按结案现场补一条 blocked 的最小执行。
|
||||
execution = ShippingProcessExecution(
|
||||
execution_no='EXE-CLOSE-GATE-SYNC', task_id=int(fixture.order.id),
|
||||
status='blocked', current_gate_code='inventory_sufficiency', lock_version=1,
|
||||
)
|
||||
db.session.add(execution)
|
||||
db.session.flush()
|
||||
fixture.order.active_process_execution_id = int(execution.id)
|
||||
db.session.flush()
|
||||
calls = []
|
||||
|
||||
def _capture_progress(*args, **kwargs):
|
||||
calls.append(('submit_auto_progress', kwargs.get('trigger')))
|
||||
|
||||
def _capture_enqueue(*args, **kwargs):
|
||||
calls.append(('enqueue_post_ot_auto_fulfill_job', kwargs.get('trigger')))
|
||||
|
||||
# 拦截编排出口:函数内为局部 import,直接 patch 源模块属性即可生效。
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.auto_progress_controller.submit_auto_progress',
|
||||
_capture_progress,
|
||||
)
|
||||
monkeypatch.setattr(
|
||||
'app.services.shipping_notice.line_auto_fulfill_coordinator.enqueue_post_ot_auto_fulfill_job',
|
||||
_capture_enqueue,
|
||||
)
|
||||
fake_case = SimpleNamespace(confirmed_task_id=fixture.order.id)
|
||||
_sync_confirmed_task_fulfillment_gates(
|
||||
case=fake_case, actor_id=fixture.user.id, trigger='line_fulfillment_closed',
|
||||
)
|
||||
payload = fixture.order.step_payload_json or {}
|
||||
# 断言:任务履约态被重算为满足,且两个编排出口都带结案 trigger。
|
||||
assert payload['current_match_projection']['match_status'] == 'fulfillable'
|
||||
assert ('submit_auto_progress', 'line_fulfillment_closed') in calls
|
||||
assert ('enqueue_post_ot_auto_fulfill_job', 'line_fulfillment_closed') in calls
|
||||
@@ -1,7 +1,7 @@
|
||||
from types import SimpleNamespace
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
from app.services.oa_leave_workflow import OALeaveWorkflowService
|
||||
from app.services.integrations.oa.leave_workflow import OALeaveWorkflowService
|
||||
|
||||
|
||||
WORKFLOW_NS = 'http://webservices.workflow.weaver'
|
||||
|
||||
+211
-106
@@ -1,106 +1,211 @@
|
||||
"""Tests for OA userInfo_view → wecom_userid sync."""
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
import pytest
|
||||
|
||||
from app.models import User
|
||||
from app.services.oa_wecom_sync import sync_wecom_userids_from_oa
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def oa_rows_for_local_user():
|
||||
return [
|
||||
{'workcode': '26030025', 'wecom_userid': '21784', 'name': 'sophie'},
|
||||
]
|
||||
|
||||
|
||||
def test_sync_wecom_userids_from_oa_dry_run(app, oa_rows_for_local_user):
|
||||
with app.app_context():
|
||||
user = User(
|
||||
username='26030025',
|
||||
email='26030025@test.local',
|
||||
employee_id='26030025',
|
||||
real_name='sophie',
|
||||
role='user',
|
||||
status='active',
|
||||
)
|
||||
user.set_password('test123')
|
||||
from app import db
|
||||
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
with patch(
|
||||
'app.services.oa_wecom_sync.fetch_oa_wecom_bindings_for_workcodes',
|
||||
return_value=oa_rows_for_local_user,
|
||||
) as fetch_mock:
|
||||
summary = sync_wecom_userids_from_oa(apply=False)
|
||||
|
||||
fetch_mock.assert_called_once_with(['26030025'])
|
||||
assert summary['local_candidates'] == 1
|
||||
assert summary['wecom_users'] == 1
|
||||
assert summary['local_matched'] == 1
|
||||
assert summary['would_update'] == 1
|
||||
assert summary['local_missing'] == 0
|
||||
assert summary['pending_updates'][0]['wecom_userid'] == '21784'
|
||||
|
||||
db.session.refresh(user)
|
||||
assert user.wecom_userid is None
|
||||
|
||||
|
||||
def test_sync_wecom_userids_from_oa_apply(app, oa_rows_for_local_user):
|
||||
with app.app_context():
|
||||
user = User(
|
||||
username='26030025',
|
||||
email='26030025@test.local',
|
||||
employee_id='26030025',
|
||||
real_name='sophie',
|
||||
role='user',
|
||||
status='active',
|
||||
)
|
||||
user.set_password('test123')
|
||||
from app import db
|
||||
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
with patch(
|
||||
'app.services.oa_wecom_sync.fetch_oa_wecom_bindings_for_workcodes',
|
||||
return_value=oa_rows_for_local_user,
|
||||
):
|
||||
summary = sync_wecom_userids_from_oa(apply=True)
|
||||
|
||||
assert summary['updated'] == 1
|
||||
db.session.refresh(user)
|
||||
assert user.wecom_userid == '21784'
|
||||
|
||||
|
||||
def test_sync_wecom_userids_from_oa_local_not_in_oa(app):
|
||||
with app.app_context():
|
||||
user = User(
|
||||
username='missing_oa',
|
||||
email='missing_oa@test.local',
|
||||
employee_id='99999999',
|
||||
real_name='missing',
|
||||
role='user',
|
||||
status='active',
|
||||
)
|
||||
user.set_password('test123')
|
||||
from app import db
|
||||
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
|
||||
with patch(
|
||||
'app.services.oa_wecom_sync.fetch_oa_wecom_bindings_for_workcodes',
|
||||
return_value=[],
|
||||
) as fetch_mock:
|
||||
summary = sync_wecom_userids_from_oa(apply=False)
|
||||
|
||||
fetch_mock.assert_called_once_with(['99999999'])
|
||||
assert summary['local_candidates'] == 1
|
||||
assert summary['wecom_users'] == 0
|
||||
assert summary['local_matched'] == 0
|
||||
assert summary['local_missing'] == 1
|
||||
|
||||
"""Tests for OA userInfo_view → wecom_userid sync."""
|
||||
|
||||
|
||||
|
||||
from unittest.mock import patch
|
||||
|
||||
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
|
||||
from app.models import User
|
||||
|
||||
from app.services.integrations.oa.wecom_sync import sync_wecom_userids_from_oa
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
|
||||
def oa_rows_for_local_user():
|
||||
|
||||
return [
|
||||
|
||||
{'workcode': '26030025', 'wecom_userid': '21784', 'name': 'sophie'},
|
||||
|
||||
]
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def test_sync_wecom_userids_from_oa_dry_run(app, oa_rows_for_local_user):
|
||||
|
||||
with app.app_context():
|
||||
|
||||
user = User(
|
||||
|
||||
username='26030025',
|
||||
|
||||
email='26030025@test.local',
|
||||
|
||||
employee_id='26030025',
|
||||
|
||||
real_name='sophie',
|
||||
|
||||
role='user',
|
||||
|
||||
status='active',
|
||||
|
||||
)
|
||||
|
||||
user.set_password('test123')
|
||||
|
||||
from app import db
|
||||
|
||||
|
||||
|
||||
db.session.add(user)
|
||||
|
||||
db.session.commit()
|
||||
|
||||
|
||||
|
||||
with patch(
|
||||
|
||||
'app.services.integrations.oa.wecom_sync.fetch_oa_wecom_bindings_for_workcodes',
|
||||
|
||||
return_value=oa_rows_for_local_user,
|
||||
|
||||
) as fetch_mock:
|
||||
|
||||
summary = sync_wecom_userids_from_oa(apply=False)
|
||||
|
||||
|
||||
|
||||
fetch_mock.assert_called_once_with(['26030025'])
|
||||
|
||||
assert summary['local_candidates'] == 1
|
||||
|
||||
assert summary['wecom_users'] == 1
|
||||
|
||||
assert summary['local_matched'] == 1
|
||||
|
||||
assert summary['would_update'] == 1
|
||||
|
||||
assert summary['local_missing'] == 0
|
||||
|
||||
assert summary['pending_updates'][0]['wecom_userid'] == '21784'
|
||||
|
||||
|
||||
|
||||
db.session.refresh(user)
|
||||
|
||||
assert user.wecom_userid is None
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def test_sync_wecom_userids_from_oa_apply(app, oa_rows_for_local_user):
|
||||
|
||||
with app.app_context():
|
||||
|
||||
user = User(
|
||||
|
||||
username='26030025',
|
||||
|
||||
email='26030025@test.local',
|
||||
|
||||
employee_id='26030025',
|
||||
|
||||
real_name='sophie',
|
||||
|
||||
role='user',
|
||||
|
||||
status='active',
|
||||
|
||||
)
|
||||
|
||||
user.set_password('test123')
|
||||
|
||||
from app import db
|
||||
|
||||
|
||||
|
||||
db.session.add(user)
|
||||
|
||||
db.session.commit()
|
||||
|
||||
|
||||
|
||||
with patch(
|
||||
|
||||
'app.services.integrations.oa.wecom_sync.fetch_oa_wecom_bindings_for_workcodes',
|
||||
|
||||
return_value=oa_rows_for_local_user,
|
||||
|
||||
):
|
||||
|
||||
summary = sync_wecom_userids_from_oa(apply=True)
|
||||
|
||||
|
||||
|
||||
assert summary['updated'] == 1
|
||||
|
||||
db.session.refresh(user)
|
||||
|
||||
assert user.wecom_userid == '21784'
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def test_sync_wecom_userids_from_oa_local_not_in_oa(app):
|
||||
|
||||
with app.app_context():
|
||||
|
||||
user = User(
|
||||
|
||||
username='missing_oa',
|
||||
|
||||
email='missing_oa@test.local',
|
||||
|
||||
employee_id='99999999',
|
||||
|
||||
real_name='missing',
|
||||
|
||||
role='user',
|
||||
|
||||
status='active',
|
||||
|
||||
)
|
||||
|
||||
user.set_password('test123')
|
||||
|
||||
from app import db
|
||||
|
||||
|
||||
|
||||
db.session.add(user)
|
||||
|
||||
db.session.commit()
|
||||
|
||||
|
||||
|
||||
with patch(
|
||||
|
||||
'app.services.integrations.oa.wecom_sync.fetch_oa_wecom_bindings_for_workcodes',
|
||||
|
||||
return_value=[],
|
||||
|
||||
) as fetch_mock:
|
||||
|
||||
summary = sync_wecom_userids_from_oa(apply=False)
|
||||
|
||||
|
||||
|
||||
fetch_mock.assert_called_once_with(['99999999'])
|
||||
|
||||
assert summary['local_candidates'] == 1
|
||||
|
||||
assert summary['wecom_users'] == 0
|
||||
|
||||
assert summary['local_matched'] == 0
|
||||
|
||||
assert summary['local_missing'] == 1
|
||||
|
||||
|
||||
@@ -29,6 +29,14 @@ RESERVATION_DEFINITION = {
|
||||
],
|
||||
}
|
||||
|
||||
LN_RESERVATION_DEFINITION = {
|
||||
'reservation_id_region': {'region': {'x0': .1, 'y0': .1, 'x1': .9, 'y1': .2}, 'page_no': 1},
|
||||
'fields': DEFINITION['fields'] + [
|
||||
{'field_id': 'line-reservation', 'field_code': 'reservation_id', 'scope': 'line', 'required': True},
|
||||
{'field_id': 'ln', 'field_code': 'customer_po_line_no', 'scope': 'line'},
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def _row(po: str, part: str) -> dict:
|
||||
return {'status': 'parsed', 'issues': [], 'fields': [
|
||||
@@ -38,6 +46,12 @@ def _row(po: str, part: str) -> dict:
|
||||
]}
|
||||
|
||||
|
||||
def _ln_row(po: str, part: str, ln: str) -> dict:
|
||||
row = _row(po, part)
|
||||
row['fields'].append({'field_id': 'ln', 'value': ln, 'quote': ln})
|
||||
return row
|
||||
|
||||
|
||||
def _page_glyphs(*lines: str) -> list[dict]:
|
||||
"""构造跨页 Reservation 路由回归所需的最小坐标文字。"""
|
||||
glyphs = []
|
||||
@@ -152,6 +166,63 @@ def test_approved_pdf_marks_conflicting_reservation_region_for_review():
|
||||
assert (orders or [])[0]['reservation_region_status'] == 'needs_review'
|
||||
|
||||
|
||||
def test_approved_pdf_maps_reservation_by_printed_ln_when_ln_non_contiguous():
|
||||
"""PO_6075309 回归:LN=1/2/4/5 非连续时 L#n 必须按 LN 值落行,整单不转复核。
|
||||
|
||||
关键断言:L#4/L#5 分别写入 LN=4/LN=5 行(旧位置序会把 L#4 错配到 LN=5 并把
|
||||
L#5 误报 line_out_of_range);行级 reservation 已全部归属后 source_missing_fields
|
||||
不得残留 line_index 0 的假缺失(``or -1`` falsy bug)。
|
||||
"""
|
||||
orders, reason = _build_approved_profile_order_result(
|
||||
unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA,
|
||||
definition=LN_RESERVATION_DEFINITION,
|
||||
table={'rows': [
|
||||
_ln_row('PO-1', 'P-1', '1'), _ln_row('PO-1', 'P-2', '2'),
|
||||
_ln_row('PO-1', 'P-4', '4'), _ln_row('PO-1', 'P-5', '5'),
|
||||
]},
|
||||
reservation_region_candidates=[
|
||||
{'value': '1000159370', 'scope': 'line', 'line_no': 1, 'raw_text': 'Reservation L#1: 1000159370'},
|
||||
{'value': '1000159366', 'scope': 'line', 'line_no': 2, 'raw_text': 'Reservation L#2: 1000159366'},
|
||||
{'value': '1000159379', 'scope': 'line', 'line_no': 4, 'raw_text': 'Reservation L#4: 1000159379'},
|
||||
{'value': '1000159236', 'scope': 'line', 'line_no': 5, 'raw_text': 'Reservation L#5: 1000159236'},
|
||||
],
|
||||
)
|
||||
|
||||
assert reason is None
|
||||
order = (orders or [])[0]
|
||||
assert order.get('reservation_region_status') != 'needs_review'
|
||||
assert 'source_missing_fields' not in order
|
||||
expected_by_ln = {'1': '1000159370', '2': '1000159366', '4': '1000159379', '5': '1000159236'}
|
||||
for line in order['lines']:
|
||||
ln = next(item['observations'][0]['value'] for item in line['fields'] if item['field_id'] == 'ln')
|
||||
assert any(
|
||||
item['field_id'] == 'line-reservation' and item['observations'][0]['value'] == expected_by_ln[ln]
|
||||
for item in line['fields']
|
||||
)
|
||||
|
||||
|
||||
def test_approved_pdf_keeps_reservation_review_when_referenced_ln_row_is_missing():
|
||||
"""被引用的印刷行号在解析行中不存在时必须转复核,不得按位置静默写入。"""
|
||||
orders, reason = _build_approved_profile_order_result(
|
||||
unit=SimpleNamespace(document_id=9), intake={'intake_no': 'SNI-1'}, schema=SCHEMA,
|
||||
definition=LN_RESERVATION_DEFINITION,
|
||||
table={'rows': [_ln_row('PO-1', 'P-1', '1'), _ln_row('PO-1', 'P-2', '2')]},
|
||||
reservation_region_candidates=[
|
||||
{'value': '1000159236', 'scope': 'line', 'line_no': 5, 'raw_text': 'Reservation L#5: 1000159236'},
|
||||
],
|
||||
)
|
||||
|
||||
assert reason is None
|
||||
order = (orders or [])[0]
|
||||
assert order['reservation_region_status'] == 'needs_review'
|
||||
assert order['reservation_region_review_reasons'] == ['line_out_of_range']
|
||||
# LN=1/LN=2 行无对应候选,reservation 保持缺失供人工补录。
|
||||
assert all(
|
||||
not any(item['field_id'] == 'line-reservation' for item in line['fields'])
|
||||
for line in order['lines']
|
||||
)
|
||||
|
||||
|
||||
def test_enabled_reservation_region_reads_vendor_comments_across_pages():
|
||||
"""已标注专区时,正式路由不能使用旧 page_no/region,必须跨页按文本锚点读取。"""
|
||||
result = _reservation_region_candidates(
|
||||
|
||||
@@ -0,0 +1,298 @@
|
||||
"""
|
||||
tests/test_order_profile_header_identity.py
|
||||
|
||||
用途:锁定 schema_canonical_header_atoms / schema_canonical_header_tokens 的表头
|
||||
别名语义归一行为,及其在表头原子硬互斥(_header_discriminator_atoms_conflict)
|
||||
与 signature_conflict 二次机会门禁中的防回归契约;含真实故障单 PO_6075316
|
||||
(日期换词 + 相邻列并格 + 空串 token)的形状回归。
|
||||
依赖:order_profile_matcher.schema_canonical_header_atoms /
|
||||
schema_canonical_header_tokens / _header_token_atoms /
|
||||
_header_discriminator_atoms_conflict。
|
||||
逻辑:pure_unit;别名命中产出 field::<field_code> 标记原子(atoms 为集合语义、
|
||||
tokens 为序列语义且同源——去重即 atoms),未命中词沿用既有词级原子过滤;
|
||||
None/空 dict 零行为变化;歧义短语整体弃用;PO_6075316 形状仅在含 Ship Date
|
||||
别名的契约下跨措辞对齐,异义词不归并。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.shipping_notice.document_layout.order_profile_matcher import (
|
||||
_header_discriminator_atoms_conflict,
|
||||
_header_token_atoms,
|
||||
schema_canonical_header_atoms,
|
||||
schema_canonical_header_tokens,
|
||||
)
|
||||
|
||||
pytestmark = pytest.mark.pure_unit
|
||||
|
||||
|
||||
def test_none_or_empty_mapping_degrades_to_word_atoms():
|
||||
"""未配置别名表时必须与既有词级原子化完全一致(零行为变化)。"""
|
||||
tokens = ['Requested Ship Date (ETD)', 'Qty', 'Unit Price']
|
||||
# 关键断言:None 与空 dict 均退化为 _header_token_atoms,结果与直接调用逐项相等
|
||||
assert schema_canonical_header_atoms(tokens, None) == _header_token_atoms(tokens)
|
||||
assert schema_canonical_header_atoms(tokens, {}) == _header_token_atoms(tokens)
|
||||
# 关键断言:退化路径下不得混入任何 field:: 标记原子
|
||||
assert not any(
|
||||
atom.startswith('field::')
|
||||
for atom in schema_canonical_header_atoms(tokens, None)
|
||||
)
|
||||
|
||||
|
||||
def test_exact_phrase_hit_emits_field_marker():
|
||||
"""别名精确命中时短语整体替换为 field::<field_code>,不残留短语内单词。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['Requested Ship Date'],
|
||||
{'requested ship date': 'requested_receipt_date'},
|
||||
)
|
||||
# 关键断言:命中段落被消费,仅剩语义标记原子,词级原子 requested/ship/date 不再出现
|
||||
assert atoms == frozenset({'field::requested_receipt_date'})
|
||||
|
||||
|
||||
def test_merged_cell_greedy_decomposition():
|
||||
"""合并格长文案按贪心最长短语分解为多个 field 标记原子。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['Requested Ship Date Unit Price'],
|
||||
{
|
||||
'requested ship date': 'requested_receipt_date',
|
||||
'unit price': 'unit_price',
|
||||
},
|
||||
)
|
||||
# 关键断言:两个别名短语各自命中并消费整段,互不残留单词原子
|
||||
assert atoms == frozenset({'field::requested_receipt_date', 'field::unit_price'})
|
||||
|
||||
|
||||
def test_greedy_prefers_longest_phrase():
|
||||
"""同一位置长短短语重叠时必须取最长短语(贪心最长匹配)。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['Requested Ship Date'],
|
||||
{
|
||||
'ship date': 'ship_date',
|
||||
'requested ship date': 'requested_receipt_date',
|
||||
},
|
||||
)
|
||||
# 关键断言:最长短语胜出且整段消费,短短语不产生任何残留 field/词级原子
|
||||
assert atoms == frozenset({'field::requested_receipt_date'})
|
||||
|
||||
|
||||
def test_case_insensitive_matching():
|
||||
"""表头与别名 key 大小写不同仍命中(casefold 同源词管线)。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['UNIT PRICE'],
|
||||
{'Unit Price': 'unit_price'},
|
||||
)
|
||||
# 关键断言:大小写差异不阻断短语命中,field_code 保留别名表原样
|
||||
assert atoms == frozenset({'field::unit_price'})
|
||||
|
||||
|
||||
def test_unmatched_words_kept_and_short_words_filtered():
|
||||
"""未命中别名的词沿用既有过滤:长度 >=3 且非虚词才保留为词级原子。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['Total Amount ok the ab'],
|
||||
{'unit price': 'unit_price'},
|
||||
)
|
||||
# 关键断言:total/amount 保留;'ok'/'ab' 过短被滤;'the' 为虚词被滤
|
||||
assert atoms == frozenset({'total', 'amount'})
|
||||
|
||||
mixed = schema_canonical_header_atoms(
|
||||
['Unit Price Remarks ok'],
|
||||
{'unit price': 'unit_price'},
|
||||
)
|
||||
# 关键断言:同一 token 内 field 标记原子与词级原子可共存
|
||||
assert mixed == frozenset({'field::unit_price', 'remarks'})
|
||||
|
||||
|
||||
def test_empty_tokens_skipped():
|
||||
"""空串/纯空白 token(MinerU 空格占位)直接跳过且不影响其余 token。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['', ' ', 'Unit Price'],
|
||||
{'unit price': 'unit_price'},
|
||||
)
|
||||
# 关键断言:空白 token 不产生原子也不中断匹配,后续 token 照常命中
|
||||
assert atoms == frozenset({'field::unit_price'})
|
||||
|
||||
|
||||
def test_chinese_alias_yields_no_field_atom():
|
||||
"""中文别名切词为空 → 自然跳过(有意行为:词级原子只保留 [a-z0-9])。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['数量', 'Qty'],
|
||||
{'数量': 'quantity'},
|
||||
)
|
||||
# 关键断言:中文别名不产生 field:: 原子;词级原子口径不变(qty 长度 >=3 保留)
|
||||
assert atoms == frozenset({'qty'})
|
||||
|
||||
|
||||
def test_casefold_collision_phrase_discarded():
|
||||
"""同一短语 casefold 后映射到多个 field_code → 整体弃用,回退词级原子。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['Ship Date'],
|
||||
{
|
||||
'Ship Date': 'ship_date',
|
||||
'ship date': 'requested_ship_date',
|
||||
},
|
||||
)
|
||||
# 关键断言:歧义短语不得产出任何 field:: 原子;未命中单词走既有过滤保留
|
||||
assert atoms == frozenset({'ship', 'date'})
|
||||
|
||||
|
||||
def test_casefold_equal_duplicate_alias_kept():
|
||||
"""同短语重复别名但 field_code 仅大小写不同 → 不视为歧义,短语保留。"""
|
||||
atoms = schema_canonical_header_atoms(
|
||||
['Ship Date'],
|
||||
{'Ship Date': 'ship_date', 'SHIP DATE': 'SHIP_DATE'},
|
||||
)
|
||||
# 关键断言:casefold 视角同码不构成身份歧义,短语照常产出标记原子
|
||||
assert atoms == frozenset({'field::ship_date'})
|
||||
|
||||
|
||||
# --- PO_6075316 真实故障形状回归:别名契约 vs 表头原子硬互斥 ---
|
||||
|
||||
_SIGNATURE_TRAINING_TOKENS = [
|
||||
'LN', 'Quantity', 'Part Number Vendor Item#', 'Description',
|
||||
'Requested Arrival Date', 'Unit Price', 'Extension',
|
||||
]
|
||||
_PO6075316_OBSERVED_TOKENS = [
|
||||
'LN', 'Quantity', 'Part Number Vendor Item#', 'Description',
|
||||
'Requested Ship Date Unit Price', '', 'Extension',
|
||||
]
|
||||
_SCHEMA_V4_HEADER_TO_FIELD = {
|
||||
'Requested Receipt Date': 'requested_receipt_date',
|
||||
'Requested Arrival Date': 'requested_receipt_date',
|
||||
'Requested Ship Date': 'requested_receipt_date',
|
||||
'Unit Price': 'unit_price',
|
||||
'Extension': 'line_amount_with_tax',
|
||||
'Part Number': 'customer_part_number',
|
||||
'Vendor Item': 'part_number',
|
||||
'Quantity': 'qty',
|
||||
'LN': 'customer_po_line_no',
|
||||
}
|
||||
|
||||
|
||||
def _po6075316_signature() -> dict:
|
||||
"""训练签名(命中模板 HYVE)的明细表 header_tokens 形状。"""
|
||||
return {'table_patterns': [{'header_tokens': list(_SIGNATURE_TRAINING_TOKENS)}]}
|
||||
|
||||
|
||||
def test_po6075316_fault_shape_passes_with_ship_date_alias_contract():
|
||||
"""PO_6075316 形状(日期换词+并格+空串)在含 Ship Date 别名契约下不再互斥。"""
|
||||
observed = {'header_tokens': list(_PO6075316_OBSERVED_TOKENS)}
|
||||
# 关键断言:两侧经 Schema 别名归一后字段语义原子全等,硬互斥判定为不冲突
|
||||
assert _header_discriminator_atoms_conflict(
|
||||
signature=_po6075316_signature(),
|
||||
observed=observed,
|
||||
header_to_field=_SCHEMA_V4_HEADER_TO_FIELD,
|
||||
) is False
|
||||
# 佐证:'Requested Ship Date' 与 'Requested Arrival Date' 归一为同一标记原子;
|
||||
# 并格长文案贪心分解出日期+单价两个标记原子;空串 token(MinerU 占位)零原子。
|
||||
assert schema_canonical_header_atoms(
|
||||
observed['header_tokens'], _SCHEMA_V4_HEADER_TO_FIELD,
|
||||
) == schema_canonical_header_atoms(
|
||||
_SIGNATURE_TRAINING_TOKENS, _SCHEMA_V4_HEADER_TO_FIELD,
|
||||
)
|
||||
|
||||
|
||||
def test_po6075316_fault_shape_still_conflicts_without_alias_contract():
|
||||
"""同形状不传契约(或契约缺 Ship Date 别名)时互斥仍在——豁免效果来自别名。"""
|
||||
observed = {'header_tokens': list(_PO6075316_OBSERVED_TOKENS)}
|
||||
# 关键断言:不传 header_to_field 时两侧退化词级原子,arrival≠ship,既有互斥零变化
|
||||
assert _header_discriminator_atoms_conflict(
|
||||
signature=_po6075316_signature(), observed=observed,
|
||||
) is True
|
||||
contract_without_ship_alias = {
|
||||
key: value
|
||||
for key, value in _SCHEMA_V4_HEADER_TO_FIELD.items()
|
||||
if key != 'Requested Ship Date'
|
||||
}
|
||||
# 关键断言:契约缺 Ship Date 别名时观测侧 ship 退回词级原子,互斥依旧成立
|
||||
assert _header_discriminator_atoms_conflict(
|
||||
signature=_po6075316_signature(),
|
||||
observed=observed,
|
||||
header_to_field=contract_without_ship_alias,
|
||||
) is True
|
||||
|
||||
|
||||
def test_po6075316_foreign_date_word_not_merged_by_alias():
|
||||
"""日期列换成未配别名的真正异义词(Customer PO Date)时不得归并,互斥仍触发。"""
|
||||
observed = {'header_tokens': [
|
||||
'LN', 'Quantity', 'Part Number Vendor Item#', 'Description',
|
||||
'Customer PO Date Unit Price', '', 'Extension',
|
||||
]}
|
||||
# 关键断言:别名契约只归并已治理措辞,不同语义字段(客户 PO 日期)保持互斥
|
||||
assert _header_discriminator_atoms_conflict(
|
||||
signature=_po6075316_signature(),
|
||||
observed=observed,
|
||||
header_to_field=_SCHEMA_V4_HEADER_TO_FIELD,
|
||||
) is True
|
||||
|
||||
|
||||
# --- schema_canonical_header_tokens:序列语义 canonical 归一(二次机会门禁供料) ---
|
||||
|
||||
def test_tokens_none_or_empty_mapping_returns_input_list_unchanged():
|
||||
"""None/空 dict 时原样返回输入列表(零归一,与 atoms 的退化口径一致)。"""
|
||||
tokens = ['Requested Ship Date (ETD)', 'Qty', '']
|
||||
# 关键断言:None 与空 dict 均不做任何归一,列表内容原样返回
|
||||
assert schema_canonical_header_tokens(tokens, None) == tokens
|
||||
assert schema_canonical_header_tokens(tokens, {}) == tokens
|
||||
# 关键断言:退化路径下不得混入任何 field:: 标记项
|
||||
assert not any(item.startswith('field::') for item in schema_canonical_header_tokens(tokens, None))
|
||||
|
||||
|
||||
def test_tokens_hit_phrase_collapses_to_single_item_and_keeps_order():
|
||||
"""命中片段坍缩为单个 field 标记列表项,且保持在原 token 的序列位置。"""
|
||||
canonical = schema_canonical_header_tokens(
|
||||
['Requested Ship Date', 'Remarks', 'Unit Price'],
|
||||
{
|
||||
'requested ship date': 'requested_receipt_date',
|
||||
'unit price': 'unit_price',
|
||||
},
|
||||
)
|
||||
# 关键断言:命中短语各坍缩为单列表项并按原顺序交错排列,短语内单词不残留
|
||||
assert canonical == [
|
||||
'field::requested_receipt_date', 'remarks', 'field::unit_price',
|
||||
]
|
||||
|
||||
|
||||
def test_tokens_sequence_semantics_keeps_duplicates_and_unmatched_words():
|
||||
"""序列语义:允许重复、未命中词原样保留——与 atoms 的集合语义形成对照。"""
|
||||
canonical = schema_canonical_header_tokens(
|
||||
['Unit Price', 'Total Amount ok the ab', 'Unit Price'],
|
||||
{'unit price': 'unit_price'},
|
||||
)
|
||||
# 关键断言:重复 token 各自产出标记项(不去重);total/amount 原词保序保留;
|
||||
# 'ok'/'ab' 过短、'the' 为虚词被滤(与 atoms 同一过滤口径)
|
||||
assert canonical == [
|
||||
'field::unit_price', 'total', 'amount', 'field::unit_price',
|
||||
]
|
||||
|
||||
|
||||
def test_tokens_dedup_equals_atoms_same_source_semantics():
|
||||
"""同源语义:同一输入下 tokens 版去重即 atoms 版结果(同管线同短语匹配)。"""
|
||||
tokens = ['', ' ', 'Requested Ship Date Unit Price', 'Vendor Item#', 'ok the ab']
|
||||
mapping = {
|
||||
'requested ship date': 'requested_receipt_date',
|
||||
'unit price': 'unit_price',
|
||||
'vendor item': 'part_number',
|
||||
}
|
||||
canonical = schema_canonical_header_tokens(tokens, mapping)
|
||||
atoms = schema_canonical_header_atoms(tokens, mapping)
|
||||
# 关键断言:序列版去重后与集合版逐项相等——两条路径完全同源,不得漂移
|
||||
assert set(canonical) == set(atoms)
|
||||
# 关键断言:空白 token 不产出列表项(与 atoms 跳过口径一致)
|
||||
assert len(canonical) == len([item for item in canonical if item])
|
||||
|
||||
|
||||
def test_po6075316_tokens_canonical_sequences_identical_with_ship_date_alias():
|
||||
"""PO_6075316 形状在含 Ship Date 别名下两侧 canonical 序列逐项相等(保序)。"""
|
||||
canonical_expected = schema_canonical_header_tokens(
|
||||
_SIGNATURE_TRAINING_TOKENS, _SCHEMA_V4_HEADER_TO_FIELD,
|
||||
)
|
||||
canonical_observed = schema_canonical_header_tokens(
|
||||
_PO6075316_OBSERVED_TOKENS, _SCHEMA_V4_HEADER_TO_FIELD,
|
||||
)
|
||||
# 关键断言:并格长文案贪心分解出的标记原子序列与训练侧完全一致(含顺序),
|
||||
# 供二次机会门禁按序列比较得出满配额软分
|
||||
assert canonical_expected == canonical_observed
|
||||
# 关键断言:LN 别名命中产出标记项(词级过滤会丢掉 2 字母 ln,别名先行兜住)
|
||||
assert canonical_expected[0] == 'field::customer_po_line_no'
|
||||
@@ -0,0 +1,34 @@
|
||||
"""
|
||||
tests/test_ot_inline_edit.py
|
||||
|
||||
用途:验证通知准备阶段(Notice 未建、仅 OT)的就地编辑全链路。
|
||||
依赖:pytest、task_workflow.update_notice_line、effective_order_view、有效视图夹具。
|
||||
逻辑:复现"FORMAL_NOTICE_REQUIRED"报错场景——OT task_no 直接走 update-notice-line 通道,
|
||||
编辑后有效值立即可见(库存匹配/Excel/通知行的统一读取口径)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.shipping_notice.effective_order_view import effective_order_field_values
|
||||
from app.services.shipping_notice.task_workflow import update_notice_line
|
||||
from tests.test_effective_order_view import _seed_frozen_order
|
||||
|
||||
|
||||
def test_update_notice_line_accepts_order_task_before_notice(app):
|
||||
"""通知准备阶段(无 Notice)编辑 OT 行字段必须成功且进入有效视图。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
response = update_notice_line({
|
||||
'task_id': fixture.order.task_no,
|
||||
'line_index': 0,
|
||||
'patch': {'part_number': 'D4-A08AR12000002'},
|
||||
'event_source': 'workspace_api',
|
||||
'reviewed_by_id': fixture.user.id,
|
||||
'expected_order_data_version': int(fixture.order.order_data_version or 1),
|
||||
})
|
||||
# 断言:服务层对 OT 放行(修复前 API 层 _require_formal_notice 报 FORMAL_NOTICE_REQUIRED)。
|
||||
assert response['status'] == 'ok'
|
||||
_header, lines = effective_order_field_values(fixture.order)
|
||||
# 断言:编辑后的料号进入有效视图(重新匹配库存的读取口径),旧值不再出现。
|
||||
assert lines[0]['f-part'] == 'D4-A08AR12000002'
|
||||
assert lines[1]['f-part'] == 'D4-B07BR07000001'
|
||||
@@ -0,0 +1,159 @@
|
||||
"""
|
||||
tests/test_reservation_effective_view.py
|
||||
|
||||
用途:验证预约注册与核验比对消费「冻结快照 + 已接受人工修正」的有效订单值视图
|
||||
(修复编辑料号/数量后核验必抛 SHIPPING.RESERVATION_MISMATCH 的阻断缺陷)。
|
||||
依赖:pytest、reservation_service、task_order_field_editor、test_effective_order_view 夹具。
|
||||
逻辑:先按冻结值注册预约 → 就地编辑料号/数量 → 再次 ensure 应走同 OT 确认修订
|
||||
(transfer,自动接替未履约预约)而非抛错;核验比对按归一化料号匹配有效值。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import ConflictError, ValidationError
|
||||
from app.models import (
|
||||
ShippingOrderFieldDecision,
|
||||
ShippingOrderFieldValue,
|
||||
ShippingOrderLine,
|
||||
ShippingReservation,
|
||||
)
|
||||
from app.services.shipping_notice.reservation_service import (
|
||||
ensure_task_reservations,
|
||||
record_inventory_verification,
|
||||
)
|
||||
from app.services.shipping_notice.task_order_field_editor import replace_current_line_field_value
|
||||
from tests.test_effective_order_view import _seed_frozen_order
|
||||
|
||||
|
||||
# 预约层契约只接受 5/10 位纯数字预约号(validated_reservation_id);夹具的 'RSV-*'
|
||||
# 为占位值,须补成契约内值才能驱动预约注册,同时补 PO 以支撑二次注册的归属校验。
|
||||
_NUMERIC_RESERVATION_IDS = ('1234567890', '2234567890')
|
||||
|
||||
|
||||
def _seed_frozen_order_for_reservations():
|
||||
"""复用有效视图夹具并补齐预约层契约值:纯数字预约号 + 单头 PO。"""
|
||||
fixture = _seed_frozen_order()
|
||||
for snap_line, reservation_id in zip(fixture.snap_lines, _NUMERIC_RESERVATION_IDS):
|
||||
snap_line.reservation_id = reservation_id
|
||||
fixture.snapshot.customer_po_number = 'PO-0001'
|
||||
order_lines = ShippingOrderLine.query.filter_by(
|
||||
extraction_id=fixture.extraction.id,
|
||||
).order_by(ShippingOrderLine.position).all()
|
||||
for line, reservation_id in zip(order_lines, _NUMERIC_RESERVATION_IDS):
|
||||
for item in ShippingOrderFieldValue.query.filter_by(
|
||||
extraction_id=fixture.extraction.id, line_id=line.id, field_id='f-rsv',
|
||||
).all():
|
||||
item.value_text = reservation_id
|
||||
item.value_json = reservation_id
|
||||
for item in ShippingOrderFieldDecision.query.filter_by(
|
||||
extraction_id=fixture.extraction.id, line_id=line.id, field_id='f-rsv',
|
||||
).all():
|
||||
item.resolved_value_json = reservation_id
|
||||
db.session.flush()
|
||||
return fixture
|
||||
|
||||
|
||||
def _registered_reservation(fixture, index: int = 0) -> ShippingReservation:
|
||||
"""按夹具第 index 行的预约号取全局预约注册行。"""
|
||||
return ShippingReservation.query.filter_by(
|
||||
task_id=fixture.order.id, reservation_id=_NUMERIC_RESERVATION_IDS[index],
|
||||
).one()
|
||||
|
||||
|
||||
def test_ensure_task_reservations_follows_effective_values(app):
|
||||
"""预约注册必须消费有效值:编辑料号后再次 ensure 应自动修订(transfer)而非校验失败。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order_for_reservations()
|
||||
# 第一次注册:按冻结值(带尾巴的旧料号)建预约。
|
||||
ensure_task_reservations(fixture.order)
|
||||
reservation = _registered_reservation(fixture)
|
||||
# 断言:初始注册值为冻结快照列原值。
|
||||
assert reservation.part_number == 'D4-A08AR12000002-'
|
||||
# 就地编辑第 0 行料号为正确值。
|
||||
replace_current_line_field_value(
|
||||
task=fixture.order, position=0, field_code='part_number', value='D4-A08AR12000002',
|
||||
)
|
||||
# 第二次 ensure(重匹配核验前的真实调用时序):必须成功且预约更新为有效值。
|
||||
ensure_task_reservations(fixture.order)
|
||||
db.session.refresh(reservation)
|
||||
# 断言:预约料号已随有效值修订,状态回 pending(可重新核验)。
|
||||
assert reservation.part_number == 'D4-A08AR12000002'
|
||||
assert reservation.status == 'pending'
|
||||
# 断言:修订走同 OT 确认修订路径,落 reservation_revision_confirmed 审计事件。
|
||||
assert any(
|
||||
event.event_type == 'reservation_revision_confirmed'
|
||||
for event in fixture.order.events
|
||||
)
|
||||
|
||||
|
||||
def test_ensure_task_reservations_revises_required_qty_from_effective_value(app):
|
||||
"""编辑数量后再次 ensure 必须按有效数量修订预约,而非保持冻结数量。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order_for_reservations()
|
||||
ensure_task_reservations(fixture.order)
|
||||
reservation = _registered_reservation(fixture)
|
||||
# 断言:初始注册数量为冻结值 10。
|
||||
assert reservation.required_qty == Decimal('10')
|
||||
replace_current_line_field_value(
|
||||
task=fixture.order, position=0, field_code='qty', value='15',
|
||||
)
|
||||
ensure_task_reservations(fixture.order)
|
||||
db.session.refresh(reservation)
|
||||
# 断言:需求数量已随有效值修订为 15,且版本在原 OT 上递增(不新建任务)。
|
||||
# order_data_version 经历两次 bump:编辑器写修正 +1,确认修订接替 +1。
|
||||
assert reservation.required_qty == Decimal('15')
|
||||
assert reservation.status == 'pending'
|
||||
assert fixture.order.order_data_version == 3
|
||||
assert fixture.order.progress_version == 2
|
||||
|
||||
|
||||
def test_record_inventory_verification_maps_effective_part_number(app):
|
||||
"""编辑料号后的库存核验必须能按有效料号(归一化后)映射预约,不再抛 RESERVATION_MISMATCH。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order_for_reservations()
|
||||
ensure_task_reservations(fixture.order)
|
||||
replace_current_line_field_value(
|
||||
task=fixture.order, position=0, field_code='part_number', value='D4-A08AR12000002',
|
||||
)
|
||||
# 模拟重匹配写入的有效值事实:第 0 行料号带大小写/空白差异(归一化后应相等)。
|
||||
verification = record_inventory_verification(
|
||||
fixture.order, inventory_snapshot_id=None, source_config_version='v1',
|
||||
line_results=[
|
||||
{
|
||||
'reservation_id': '1234567890', 'part_number': ' d4-a08ar12000002 ',
|
||||
'required_qty': Decimal('10'), 'available_qty': Decimal('10'), 'line_status': 'ok',
|
||||
},
|
||||
{
|
||||
'reservation_id': '2234567890', 'part_number': 'D4-B07BR07000001',
|
||||
'required_qty': Decimal('10'), 'available_qty': Decimal('10'), 'line_status': 'ok',
|
||||
},
|
||||
],
|
||||
)
|
||||
# 断言:核验轮次成功创建,修订后的预约按有效值完整满足并转 available。
|
||||
assert verification.lines[0].status == 'available'
|
||||
assert verification.result_json['available_count'] == 2
|
||||
|
||||
|
||||
def test_locked_reservation_still_rejects_effective_revision(app):
|
||||
"""已占用/已上传的预约不受有效值自动修订影响:保留 RESERVATION_REVISION_LOCKED 拒绝。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order_for_reservations()
|
||||
ensure_task_reservations(fixture.order)
|
||||
reservation = _registered_reservation(fixture)
|
||||
reservation.status = 'artifact_reserved'
|
||||
db.session.flush()
|
||||
replace_current_line_field_value(
|
||||
task=fixture.order, position=0, field_code='part_number', value='D4-A08AR12000002',
|
||||
)
|
||||
# 断言:带 Artifact 锁的预约不得自动修订,必须走人工复核。
|
||||
with pytest.raises(ConflictError) as locked:
|
||||
ensure_task_reservations(fixture.order)
|
||||
assert locked.value.code == 'SHIPPING.RESERVATION_REVISION_LOCKED'
|
||||
db.session.refresh(reservation)
|
||||
# 断言:预约料号保持注册原值,未被静默改写。
|
||||
assert reservation.part_number == 'D4-A08AR12000002-'
|
||||
@@ -0,0 +1,46 @@
|
||||
"""
|
||||
tests/test_review_line_fulfillment_shortage_projection.py
|
||||
|
||||
用途:锁定行级履约投影的匹配事实关联(修复草稿行ID vs 快照行ID 键错位)。
|
||||
依赖:pytest、order_review_fulfillment_decision_service、有效视图夹具。
|
||||
逻辑:确认 Case + 短缺匹配事实下,投影必须报 has_shortage=True 且行级 is_shortage=True。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app import db
|
||||
from app.models import ShippingNoticeLineInventoryMatch, ShippingOrderReviewCase, ShippingOrderReviewDraft
|
||||
from app.services.shipping_notice.order_review_fulfillment_decision_service import (
|
||||
project_review_case_line_decisions,
|
||||
)
|
||||
from tests.test_effective_order_view import _seed_frozen_order
|
||||
|
||||
|
||||
def test_line_fulfillment_has_shortage_with_match_facts(app):
|
||||
"""修复键错位:草稿行经 _line_index 关联匹配事实,has_shortage 必须为真。"""
|
||||
with app.app_context():
|
||||
fixture = _seed_frozen_order()
|
||||
# 短缺事实:第 0 行 not_found、缺 10。
|
||||
db.session.add(ShippingNoticeLineInventoryMatch(
|
||||
task_id=fixture.order.id, snapshot_line_id=fixture.snap_lines[0].id,
|
||||
line_no=1, line_index=0, match_result='not_found', inventory_status='ready',
|
||||
required_qty='10', available_qty='0', shortage_qty='10',
|
||||
reservation_id='RSV-1', part_number='D4-A08AR12000002-', is_current=True,
|
||||
))
|
||||
case = ShippingOrderReviewCase(
|
||||
case_no='SNRC-SHORTAGE-PROJ', run_id=911, unit_id=912, document_id=913,
|
||||
owner_user_id=fixture.user.id, status='confirmed', confirmed_task_id=fixture.order.id,
|
||||
)
|
||||
db.session.add(case)
|
||||
db.session.flush()
|
||||
db.session.add(ShippingOrderReviewDraft(
|
||||
case_id=case.id, draft_version=1, schema_version_id=fixture.snapshot.schema_version_id,
|
||||
header_values_json={}, lines_json=[{'draft_line_id': 'line-1', 'part_number': 'D4-A08AR12000002-'}],
|
||||
))
|
||||
db.session.flush()
|
||||
case.current_draft_id = case.drafts[0].id if case.drafts else None
|
||||
db.session.flush()
|
||||
result = project_review_case_line_decisions(case)
|
||||
# 断言:修复前 has_shortage 恒 False(键错位);修复后为 True。
|
||||
assert result['has_shortage'] is True
|
||||
assert result['lines'][0]['is_shortage'] is True
|
||||
@@ -0,0 +1,79 @@
|
||||
"""trigger_consumer 公共模块测试。
|
||||
|
||||
用途:锁定 trigger 文件四态目录契约(根目录待领取 → processing 处理中 →
|
||||
processed/failed 终态)的领取与归档行为。
|
||||
依赖:标准库 tempfile/pathlib、scripts.rpa.common.trigger_consumer。
|
||||
逻辑:claim 原子性(二次领取返回 None)、归档落位、非法入参拒绝。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "common"))
|
||||
|
||||
from trigger_consumer import archive_trigger, claim_trigger # noqa: E402
|
||||
|
||||
|
||||
def _write_trigger(root: Path, name: str = "batch_1.json") -> Path:
|
||||
path = root / name
|
||||
path.write_text('{"schema_version": "x"}', encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
def test_claim_moves_file_into_processing(tmp_path):
|
||||
"""首次领取应把 trigger 原子移入 processing/ 并返回新路径。"""
|
||||
path = _write_trigger(tmp_path)
|
||||
claimed = claim_trigger(path)
|
||||
assert claimed == tmp_path / "processing" / path.name
|
||||
assert claimed.read_text(encoding="utf-8") == '{"schema_version": "x"}'
|
||||
assert not path.exists()
|
||||
|
||||
|
||||
def test_claim_twice_returns_none(tmp_path):
|
||||
"""同一 trigger 二次领取必须返回 None(防双消费/重复导出)。"""
|
||||
path = _write_trigger(tmp_path)
|
||||
assert claim_trigger(path) is not None
|
||||
assert claim_trigger(path) is None
|
||||
|
||||
|
||||
def test_archive_processed_and_failed(tmp_path):
|
||||
"""processing/ 中的文件按 outcome 归档到同名终态目录。"""
|
||||
path = _write_trigger(tmp_path)
|
||||
claimed = claim_trigger(path)
|
||||
done = archive_trigger(claimed, "processed")
|
||||
assert done == tmp_path / "processed" / path.name and done.exists()
|
||||
path2 = _write_trigger(tmp_path, "batch_2.json")
|
||||
claimed2 = claim_trigger(path2)
|
||||
failed = archive_trigger(claimed2, "failed")
|
||||
assert failed == tmp_path / "failed" / path2.name and failed.exists()
|
||||
|
||||
|
||||
def test_archive_rejects_bad_outcome_and_unclaimed_path(tmp_path):
|
||||
"""非法 outcome 与未经领取的路径都必须拒绝,防止归档错位。"""
|
||||
path = _write_trigger(tmp_path)
|
||||
with pytest.raises(ValueError):
|
||||
archive_trigger(path, "processed") # 未领取,不在 processing/ 下
|
||||
claimed = claim_trigger(_write_trigger(tmp_path, "batch_3.json"))
|
||||
with pytest.raises(ValueError):
|
||||
archive_trigger(claimed, "done") # outcome 白名单外
|
||||
|
||||
|
||||
def test_inventory_worker_scans_with_claim(tmp_path):
|
||||
"""库存 Worker 扫描必须先领取(processing/),不得原地消费根目录文件。"""
|
||||
root = Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "inventory"
|
||||
text = (root / "inventory_rpa_worker.py").read_text(encoding="utf-8")
|
||||
assert "claim_trigger" in text
|
||||
# 三处 handler 的 failed 目录推导必须基于 processed_dir(根目录),不得再用 trigger_path.parent
|
||||
assert text.count('trigger_path.parent / "failed"') == 0
|
||||
|
||||
|
||||
def test_receipt_worker_runs_periodic_disk_cleanup():
|
||||
"""收料 Worker 必须周期执行保留清理(对齐库存),孤儿 receipt_* Profile 必须纳入清理。"""
|
||||
receipt = (Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "receipt" / "receipt_rpa_worker.py").read_text(encoding="utf-8")
|
||||
assert "run_worker_disk_cleanup" in receipt and "cleanup_interval_seconds" in receipt
|
||||
cleanup = (Path(__file__).resolve().parents[2] / "scripts" / "freight_rpa" / "common" / "worker_disk_cleanup.py").read_text(encoding="utf-8")
|
||||
assert '"receipt_"' in cleanup or "'receipt_'" in cleanup
|
||||
@@ -67,12 +67,12 @@ def _enable_prod_like_checks(app, tmp_path, *, scope_id: str = "hxops-rpa-test-d
|
||||
trigger_dir.mkdir()
|
||||
_write_shared_sentinel(trigger_dir, scope_id=scope_id)
|
||||
app.config["ENV_NAME"] = "test"
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"] = scope_id
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_MOCK"] = "false"
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = scope_id
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_MOCK"] = "false"
|
||||
return trigger_dir
|
||||
|
||||
|
||||
@@ -132,11 +132,11 @@ def test_missing_shared_sentinel_blocks_readiness_in_test_env(app, tmp_path):
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
app.config["ENV_NAME"] = "test"
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data"
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_MOCK"] = "false"
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data"
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_MOCK"] = "false"
|
||||
|
||||
with app.app_context():
|
||||
record_rpa_worker_heartbeat(
|
||||
@@ -154,9 +154,9 @@ def test_record_heartbeat_requires_redis_when_configured(app, tmp_path, monkeypa
|
||||
"""生产策略要求 Redis 时,写入失败应抛存储不可用。"""
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
|
||||
monkeypatch.setattr(
|
||||
"app.services.shipping_notice.rpa_worker_heartbeat._redis_store_worker",
|
||||
lambda _worker: False,
|
||||
@@ -169,23 +169,35 @@ def test_record_heartbeat_requires_redis_when_configured(app, tmp_path, monkeypa
|
||||
assert exc_info.value.message == RPA_HEARTBEAT_STORAGE_UNAVAILABLE_MESSAGE
|
||||
|
||||
|
||||
def test_assert_inventory_rpa_worker_ready_includes_reason_details(app, tmp_path):
|
||||
def test_assert_inventory_rpa_worker_ready_includes_reason_details(app, tmp_path, monkeypatch):
|
||||
"""fail-fast 应附带 reasons 详情供排程日志与运维定位。"""
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import (
|
||||
reset_rpa_worker_heartbeat_state_for_tests,
|
||||
)
|
||||
|
||||
# 隔离:强制无 Redis 分支(_redis_client 为模块级单例,config 置空不可靠,须 monkeypatch);
|
||||
# 并清空心跳存储,确保走 no_worker_heartbeat + 进程内存储原因码。
|
||||
from app.services.shipping_notice import rpa_worker_heartbeat as heartbeat_module
|
||||
monkeypatch.setattr(heartbeat_module, "_redis_client", lambda: None)
|
||||
reset_rpa_worker_heartbeat_state_for_tests()
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
_write_shared_sentinel(trigger_dir, scope_id="hxops-rpa-test-data")
|
||||
app.config["ENV_NAME"] = "test"
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data"
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_MOCK"] = "false"
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = "hxops-rpa-test-data"
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_MOCK"] = "false"
|
||||
|
||||
with app.app_context():
|
||||
with pytest.raises(ServiceUnavailableError) as exc_info:
|
||||
assert_inventory_rpa_worker_ready()
|
||||
assert exc_info.value.message == RPA_WORKER_OFFLINE_MESSAGE
|
||||
assert "no_worker_heartbeat" in (exc_info.value.details or {}).get("reasons", [])
|
||||
reasons = (exc_info.value.details or {}).get("reasons", [])
|
||||
assert "no_worker_heartbeat" in reasons
|
||||
# [断言意图] 无 Redis 时心跳存储为本进程内存,必须给出原因码与本地测试指引
|
||||
assert "heartbeat_store_process_local" in reasons
|
||||
assert (exc_info.value.details or {}).get("detail_message")
|
||||
|
||||
|
||||
@@ -194,7 +206,7 @@ def test_check_inventory_rpa_worker_ready_rejects_stale_heartbeat(app, tmp_path,
|
||||
import time as time_module
|
||||
|
||||
trigger_dir = _enable_prod_like_checks(app, tmp_path)
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_TTL_SECONDS"] = 90
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_TTL_SECONDS"] = 90
|
||||
base_now = time_module.time()
|
||||
|
||||
with app.app_context():
|
||||
@@ -218,7 +230,7 @@ def test_rpa_heartbeat_api_records_worker(client, app, tmp_path):
|
||||
trigger_dir = tmp_path / "triggers"
|
||||
trigger_dir.mkdir()
|
||||
app.config["SHIPPING_NOTICE_TOOL_API_KEY"] = "test-tool-key"
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
payload = _heartbeat_payload(trigger_dir=str(trigger_dir.resolve()))
|
||||
|
||||
res = client.post(
|
||||
@@ -258,11 +270,19 @@ def test_rpa_heartbeat_api_rejects_invalid_auth(client, app, tmp_path):
|
||||
assert res.status_code == 401
|
||||
|
||||
|
||||
def test_shipping_inventory_rpa_schedule_fails_fast_when_worker_offline(app, tmp_path):
|
||||
def test_shipping_inventory_rpa_schedule_fails_fast_when_worker_offline(app, tmp_path, monkeypatch):
|
||||
"""排程触发时 worker 离线应立即 failed,不进入 awaiting_rpa_callback。"""
|
||||
from app import db
|
||||
from app.models import ScheduleRun, ScheduleTask, User
|
||||
from app.services.schedule.shipping_inventory_rpa_job import run_shipping_inventory_rpa_schedule
|
||||
from app.services.shipping_notice import rpa_worker_heartbeat as heartbeat_module
|
||||
from app.services.shipping_notice.rpa_worker_heartbeat import (
|
||||
reset_rpa_worker_heartbeat_state_for_tests,
|
||||
)
|
||||
|
||||
# 隔离:强制无 Redis 分支(防真实心跳/单例缓存混入测试窗口)并清空存储,锁定离线 fail-fast 分支。
|
||||
monkeypatch.setattr(heartbeat_module, "_redis_client", lambda: None)
|
||||
reset_rpa_worker_heartbeat_state_for_tests()
|
||||
|
||||
trigger_dir = _enable_prod_like_checks(app, tmp_path)
|
||||
|
||||
@@ -304,8 +324,8 @@ def test_shipping_inventory_rpa_schedule_fails_fast_when_worker_offline(app, tmp
|
||||
def test_redis_read_failure_reports_storage_unavailable_not_offline(app, tmp_path, monkeypatch):
|
||||
"""Redis 读取异常应报 heartbeat_storage_unavailable,而非 no_worker_heartbeat。"""
|
||||
trigger_dir = _enable_prod_like_checks(app, tmp_path)
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
|
||||
|
||||
class BrokenRedis:
|
||||
def smembers(self, _key):
|
||||
@@ -327,8 +347,8 @@ def test_redis_read_failure_reports_storage_unavailable_not_offline(app, tmp_pat
|
||||
def test_redis_store_and_list_ready_with_prod_policy(app, tmp_path, monkeypatch):
|
||||
"""test/prod Redis 策略:写入+读取成功时应 ready。"""
|
||||
trigger_dir = _enable_prod_like_checks(app, tmp_path)
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = False
|
||||
bucket: dict[str, Any] = {"index": set()}
|
||||
|
||||
class FakeRedis:
|
||||
@@ -370,8 +390,8 @@ def test_shared_scope_id_derived_from_mount_path_when_env_missing(app, tmp_path)
|
||||
trigger_dir = tmp_path / "mnt" / "hxops-rpa-test-data" / "inventory_triggers"
|
||||
trigger_dir.mkdir(parents=True)
|
||||
_write_shared_sentinel(trigger_dir, scope_id="hxops-rpa-test-data")
|
||||
app.config.pop("SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID", None)
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
app.config.pop("FREIGHT_RPA_SHARED_SCOPE_ID", None)
|
||||
app.config["FREIGHT_RPA_SHARED_INVENTORY_TRIGGER_DIR"] = str(trigger_dir)
|
||||
|
||||
with app.app_context():
|
||||
assert shared_scope_id() == "hxops-rpa-test-data"
|
||||
@@ -385,15 +405,15 @@ def _enable_freight_upload_checks(app, tmp_path, *, scope_id: str = "hxops-rpa-t
|
||||
upload_queue.mkdir()
|
||||
_write_shared_sentinel(upload_trigger, scope_id=scope_id)
|
||||
app.config["ENV_NAME"] = "test"
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_TRIGGER_DIR"] = str(upload_trigger)
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(upload_queue)
|
||||
app.config["SHIPPING_NOTICE_RPA_SHARED_SCOPE_ID"] = scope_id
|
||||
app.config["SHIPPING_NOTICE_RPA_CREDENTIAL_KEY"] = "dGVzdC1rZXktMzItYnl0ZXMtZm9yLWZlcm5ldCE="
|
||||
app.config["FREIGHT_RPA_SHARED_UPLOAD_TRIGGER_DIR"] = str(upload_trigger)
|
||||
app.config["FREIGHT_RPA_SHARED_UPLOAD_QUEUE_DIR"] = str(upload_queue)
|
||||
app.config["FREIGHT_RPA_SHARED_SCOPE_ID"] = scope_id
|
||||
app.config["FREIGHT_RPA_CREDENTIAL_KEY"] = "dGVzdC1rZXktMzItYnl0ZXMtZm9yLWZlcm5ldCE="
|
||||
app.config["INTERNAL_API_BASE_URL"] = "http://127.0.0.1:5052"
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
app.config["SHIPPING_NOTICE_RPA_WORKER_MOCK"] = "false"
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRED"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_REQUIRE_REDIS"] = False
|
||||
app.config["FREIGHT_RPA_WORKER_HEARTBEAT_ALLOW_MEMORY_FALLBACK"] = True
|
||||
app.config["FREIGHT_RPA_WORKER_MOCK"] = "false"
|
||||
return upload_trigger
|
||||
|
||||
|
||||
@@ -437,7 +457,7 @@ def test_assert_freight_upload_rpa_ready_includes_reasons(app, tmp_path):
|
||||
|
||||
_enable_freight_upload_checks(app, tmp_path)
|
||||
# 去掉凭据主密钥:即使 Redis 残留心跳,静态配置缺失也必须阻断。
|
||||
app.config.pop("SHIPPING_NOTICE_RPA_CREDENTIAL_KEY", None)
|
||||
app.config.pop("FREIGHT_RPA_CREDENTIAL_KEY", None)
|
||||
reset_rpa_worker_heartbeat_state_for_tests()
|
||||
with app.app_context():
|
||||
with pytest.raises(ServiceUnavailableError) as exc_info:
|
||||
|
||||
Loaded 100 of 691 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user