Merge branch 'hugo-shipping-notice' into dev

# Conflicts:
#	backend/app/services/shipping_notice/receipt_report_notification.py
This commit is contained in:
hugo committed 2026-09-23 01:09:28 +08:00
commit 876a7ade7d
212 files changed
+12056 -2889

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
+5 -5
View File
@@ -701,13 +701,13 @@ def dbs_ready_file() -> dict:
"checksum": "d" * 64,
"status": "ready",
"rows": [
{"sheet": "Receipt", "row_no": 10, "doc_no": "INV-001", "material_code": "MAT-001",
{"sheet": "Receipt", "row_no": 10, "doc_no": "HOM-001", "lot_no": "LOT-10", "material_code": "MAT-001",
"material_name": "连接器组件", "specification": "A 型 / 24PIN",
"movement_date": "2026-08-05", "quantity": "500", "source_code": "DBS-AWSBI"},
{"sheet": "Receipt", "row_no": 11, "doc_no": "INV-001", "material_code": "MAT-001",
{"sheet": "Receipt", "row_no": 11, "doc_no": "HOM-001", "lot_no": "LOT-10", "material_code": "MAT-001",
"material_name": "连接器组件", "specification": "A 型 / 24PIN",
"movement_date": "2026-08-05", "quantity": "700", "source_code": "DBS-AWSBI"},
{"sheet": "Receipt", "row_no": 20, "doc_no": "INV-002", "material_code": "MAT-002",
{"sheet": "Receipt", "row_no": 20, "doc_no": "HOX-002", "lot_no": "LOT-20", "material_code": "MAT-002",
"material_name": "控制器组件", "specification": "标准型 / 48V",
"movement_date": "2026-08-05", "quantity": "1200", "source_code": "DBS-AWSBI"},
],
@@ -729,7 +729,7 @@ def crane_ready_file() -> dict:
"checksum": "c" * 64,
"status": "ready",
"rows": [
{"sheet": "Inbound", "row_no": 5, "doc_no": "INV-008", "material_code": "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",
"movement_date": "2026-08-05", "quantity": "600", "source_code": "CRANE-SZ"},
],
@@ -751,7 +751,7 @@ def same_day_receipt_file() -> dict:
"checksum": "s" * 64,
"status": "ready",
"rows": [
{"sheet": "Receipt", "row_no": 3, "doc_no": "INV-041", "material_code": "MAT-041",
{"sheet": "Receipt", "row_no": 3, "doc_no": "HOM-3", "lot_no": "INV-041", "material_code": "MAT-041",
"material_name": "连接器组件", "specification": "C 型",
"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
@@ -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')
@@ -534,22 +534,54 @@ 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['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['FREIGHT_RPA_CREDENTIAL_KEY'] = Fernet.generate_key().decode('ascii')
with app.app_context():
profile = shipping_inventory_service.save_profile(_profile_data(), actor_id=None)
@@ -557,7 +589,7 @@ def test_external_mapping_normalizes_freight_warehouse_identity(app):
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'
@@ -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"
@@ -71,6 +71,44 @@ def test_extract_movement_rows_maps_columns_to_domain_fields():
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():
@@ -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,7 +11,7 @@ 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,
@@ -20,20 +20,23 @@ from app.services.in_transit_transfer.precheck_service import (
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,
@@ -44,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,
@@ -106,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,
)
@@ -114,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
@@ -130,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,
@@ -141,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,
@@ -176,13 +301,125 @@ def test_run_precheck_consumes_movement_field_rows(app):
"file_no": "F1", "file_version": "v1", "checksum": "sha:x",
"rows": [{
"sheet": "Movement", "row_no": 1,
"doc_no": "INV-1", "material_code": "M1", "material_name": "物料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(erp_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
routes={"DSV360_AWSDU": RouteMapping(external_org="1000", from_warehouse="WH1", to_warehouse="WH2")},
)
erp_fake.seed_inventory("INV-1", 5) # FakeERP 按 invoice_no 键维护账面库存
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 == "INV-1")
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)
@@ -95,15 +95,42 @@ def test_trigger_receipt_rpa_creates_unit_run_before_writing_trigger(app, receip
assert outcome["ok"] is True
unit = ShippingReceiptRpaUnitRun.query.filter_by(callback_id=outcome["callback_id"]).one()
assert unit.status == "awaiting_rpa"
assert unit.schedule_run_id == 0 # 调拨触发无排程 run,沿用 0 占位约定
# [断言意图] 按需触发无排程 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",
@@ -113,6 +140,20 @@ def test_default_rpa_trigger_writes_real_trigger_file(app, receipt_source, tmp_p
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
@@ -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>&lt;Response&gt;'
'&lt;Execution&gt;&lt;Status code="0" sqlcode="0" description=""/&gt;&lt;/Execution&gt;'
'&lt;ResponseContent&gt;&lt;Parameter/&gt;'
'&lt;Document&gt;&lt;RecordSet id="1"&gt;&lt;Master name="img_file"&gt;&lt;Record&gt;'
'&lt;Field name="img04" value="HOW25071402"/&gt;'
'&lt;Field name="img11" value="30.000"/&gt;'
'&lt;/Record&gt;&lt;/Master&gt;&lt;/RecordSet&gt;&lt;/Document&gt;'
'&lt;/ResponseContent&gt;&lt;/Response&gt;</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,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
@@ -166,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
@@ -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'
@@ -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'] == []
@@ -166,6 +166,43 @@ def test_attachment_selection_snapshot_stops_at_total_byte_budget():
assert by_name['second.pdf']['skip_reason_codes'] == ['budget_total_bytes']
def test_attachment_selection_snapshot_selects_all_eligible_attachments():
"""合格业务附件全量入选批次 1:数量类预算字段不得截断,有多少单解析多少单。"""
attachments = [
{
'attachment_key': f'po-{no:02d}.pdf',
'filename': f'PO_45188381{no:02d}.pdf',
'mime_type': 'application/pdf',
'size': 48000,
'content_hash': f'{no:02d}' * 32,
'ready_for_extraction': True,
'catalog_reason': 'ready_for_extraction',
}
for no in range(1, 13)
]
snapshot = build_attachment_selection_snapshot(
intakes=[_preview_intake('SNI-ALL', attachments)],
max_total_attachments=6,
expansion_batch_size=2,
)
assert snapshot['selection_version'] == 'shipping_notice_attachment_selection.v1'
# 关键断言:即使数量预算字段为 6,12 份同分 PDF 也必须全部入选批次 1,
# 不产生 planned_selection_batch 或任何跳过原因码(本用例复现历史丢件形态)。
assert snapshot['eligible_attachment_count'] == 12
assert snapshot['selected_attachment_count'] == 12
assert snapshot['planned_attachment_count'] == 12
assert snapshot['pending_expansion_attachment_count'] == 0
assert snapshot['pending_expansion_batches'] == {}
assert [item['filename'] for item in snapshot['items'] if item['selected']] == [
f'PO_45188381{no:02d}.pdf' for no in range(1, 13)
]
for item in snapshot['items']:
assert item['selection_batch'] == 1
assert item['planned_selection_batch'] is None
assert item['skip_reason_codes'] == []
def test_attachment_selection_snapshot_excludes_inline_resources_from_counts():
"""邮件签名图不属于用户业务附件,不能占用识别计划的附件数量或预算。"""
snapshot = build_attachment_selection_snapshot(intakes=[
@@ -234,6 +271,7 @@ def test_serialize_order_extraction_run_includes_selection_plan_summary(monkeypa
run_no='SNER-SELECTION',
owner_agent_id=1,
conversation_id='conv-selection',
client_submission_id=None,
status='queued',
phase='queued',
schema_version_id=1,
@@ -688,6 +688,8 @@ def test_build_schedule_run_wecom_description_includes_skipped_count():
skipped_count=1,
failed_count=0,
response_summary_json=None,
# 收料文件附加行读取 run.task 识别收料排程;非收料场景显式置 None。
task=None,
)
text = _build_schedule_run_wecom_description(run)
assert "跳过: 1" in text
@@ -1461,6 +1461,10 @@ def test_expansion_batch_syncs_materialized_document_into_frozen_run_before_crea
assert run.input_snapshot_hash != old_hash
assert plan.input_snapshot_hash == run.input_snapshot_hash
assert [unit.document_id for unit in created] == [second_document.id]
# 关键断言:批次激活后扩批事实必须按明细重算归零,否则投影层会误报「预算停扩」。
selection_after = run.input_snapshot_json['attachment_selection']
assert selection_after['pending_expansion_attachment_count'] == 0
assert selection_after['pending_expansion_batches'] == {}
def test_run_submission_rejects_changed_frozen_mail_context(app):
@@ -231,7 +231,14 @@ def test_worker_processes_ready_unit_then_defers_while_sibling_layout_pending(mo
handler, 'merge_unit_orders',
lambda *, orders, schema_definition, keep_primary_documents_separate: orders,
)
monkeypatch.setattr(handler, 'progress_ready_extraction_unit', lambda **_kwargs: events.append('progressed') or {})
progress_calls: list[dict] = []
def _record_progress(**kwargs):
progress_calls.append(kwargs)
events.append('progressed')
return {}
monkeypatch.setattr(handler, 'progress_ready_extraction_unit', _record_progress)
monkeypatch.setattr(handler, 'submit_order_extraction_run_result', lambda **_kwargs: events.append('terminalized') or {})
monkeypatch.setattr(handler, 'mark_order_extraction_persistence_started', lambda _run: events.append('persist_started'))
@@ -249,6 +256,8 @@ def test_worker_processes_ready_unit_then_defers_while_sibling_layout_pending(mo
assert 'processed' in events
assert 'progressed' in events
# [交接不变量] 开工快照有 pending 版面(必交接):推送照发,但 STP 入队必须推迟。
assert progress_calls and progress_calls[0]['defer_stp_enqueue'] is True
assert 'terminalized' not in events
assert 'persist_started' not in events
assert run.phase == 'waiting_layout'
@@ -474,7 +483,14 @@ def test_worker_layout_ready_continue_when_stale_snapshot_skipped_pending_unit(m
handler, 'merge_unit_orders',
lambda *, orders, schema_definition, keep_primary_documents_separate: orders,
)
monkeypatch.setattr(handler, 'progress_ready_extraction_unit', lambda **_kwargs: events.append('progressed') or {})
progress_calls_layout_continue: list[dict] = []
def _record_progress_layout_continue(**kwargs):
progress_calls_layout_continue.append(kwargs)
events.append('progressed')
return {}
monkeypatch.setattr(handler, 'progress_ready_extraction_unit', _record_progress_layout_continue)
monkeypatch.setattr(handler, 'submit_order_extraction_run_result', lambda **_kwargs: events.append('terminalized') or {})
monkeypatch.setattr(handler, 'mark_order_extraction_persistence_started', lambda _run: events.append('persist_started'))
@@ -500,6 +516,8 @@ def test_worker_layout_ready_continue_when_stale_snapshot_skipped_pending_unit(m
assert 'processed' in events
assert 'progressed' in events
# [交接不变量] 开工快照含 pending 版面(后续 layout 已 mock 就绪、仍走交接):STP 入队推迟。
assert progress_calls_layout_continue[0]['defer_stp_enqueue'] is True
assert 'terminalized' not in events
assert 'persist_started' not in events
assert enqueue_calls == [{
@@ -1147,3 +1165,288 @@ def test_pending_snapshot_batches_ignore_already_activated_units():
assert _pending_snapshot_batches(run, plan) == [3]
assert [unit.selection_batch for unit in _units_for_batch(plan, selection_batch=1)] == [1]
def test_worker_replay_pushes_without_defer_when_all_layouts_ready(monkeypatch):
"""全量版面就绪(必为最后一个抽取 Job):重放推送 defer_stp_enqueue=False,STP 正常入队。"""
import app.jobs.handlers.shipping_order_extraction as handler
events: list[str] = []
progress_calls: list[dict] = []
finished: dict = {}
run = SimpleNamespace(
id=61, user_id=9, run_no='SNER-WORKER-FINAL', status='processing', phase='queued',
current_job_id=None, attempt_count=0, cancellation_requested_at=None,
input_snapshot_json={'attachment_selection': {}, 'intakes': [], 'schema': {}},
execution_result_json=None, extraction_completed_at=None,
)
job = SimpleNamespace(id=61, attempts=1, business_ref=run.run_no, max_attempts=3)
replay_unit = SimpleNamespace(
id=61, document_id=201, intake_id=1, status='candidate_ready',
result_json={'orders': [{'po_number': 'PO-REPLAY', '_hxops_intake_id': 1}]},
position=1, cancellation_requested_at=None,
)
process_unit = SimpleNamespace(
id=62, document_id=202, intake_id=1, status='review_required', result_json=None,
position=2, cancellation_requested_at=None,
)
plan = SimpleNamespace(id=61, unit_count=2, units=[replay_unit, process_unit])
monkeypatch.setattr(handler.db.session, 'get', lambda model, _id: job if model is handler.Job else replay_unit)
monkeypatch.setattr(
handler, 'ShippingOrderProcessingRun',
SimpleNamespace(query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(
with_for_update=lambda: SimpleNamespace(first=lambda: run),
))),
)
monkeypatch.setattr(handler, 'ShippingOrderProcessingUnit', SimpleNamespace(
position=SimpleNamespace(asc=lambda: None),
status=SimpleNamespace(in_=lambda *_a, **_k: True),
query=SimpleNamespace(
filter_by=lambda **_kwargs: SimpleNamespace(
order_by=lambda *_args: SimpleNamespace(all=lambda: [replay_unit, process_unit]),
),
join=lambda *_a, **_k: SimpleNamespace(
filter=lambda *_a, **_k: SimpleNamespace(first=lambda: None),
),
),
))
monkeypatch.setattr(handler, 'ShippingOrderProcessingPlan', SimpleNamespace(run_id=SimpleNamespace()))
monkeypatch.setattr(handler, 'begin_input_freeze', lambda _run: None)
monkeypatch.setattr(handler, 'complete_input_freeze', lambda _run: None)
monkeypatch.setattr(
handler, 'materialize_order_extraction_run_inputs',
lambda _run, *, finalize_plan=True: plan if finalize_plan else None,
)
monkeypatch.setattr(handler, 'ensure_workflow_items_for_run', lambda *_a, **_k: [])
monkeypatch.setattr(handler, 'schedule_order_extraction_layouts', lambda *_a, **_k: False)
monkeypatch.setattr(handler, 'order_extraction_layout_prerequisite_issues', lambda _run: {})
monkeypatch.setattr(handler, 'order_extraction_ready_document_ids', lambda _run: set())
monkeypatch.setattr(handler, 'order_extraction_layouts_pending', lambda _run: False)
monkeypatch.setattr(handler, 'order_extraction_has_extractable_ready_work', lambda _run: False)
monkeypatch.setattr(
handler, 'transition_order_extraction_run',
lambda target, **kwargs: setattr(target, 'status', kwargs.get('target_status', target.status)),
)
monkeypatch.setattr(handler, 'record_run_progress', lambda **_kwargs: None)
monkeypatch.setattr(handler, 'record_unit_progress', lambda **_kwargs: None)
monkeypatch.setattr(
handler, '_units_for_batch',
lambda _plan, *, selection_batch: [replay_unit, process_unit],
)
monkeypatch.setattr(handler, '_next_existing_batch', lambda *_a, **_k: None)
monkeypatch.setattr(handler, '_pending_snapshot_batches', lambda *_a, **_k: [])
monkeypatch.setattr(handler, '_selection_progress_summary', lambda _run: {'budget_limited_attachment_count': 0})
monkeypatch.setattr(handler, '_wave_orders_for_expansion', lambda _run, *, orders: orders)
monkeypatch.setattr(handler, '_expansion_trigger_reason_codes', lambda **_kwargs: [])
fail_calls: dict = {}
def _record_progress(**kwargs):
progress_calls.append(kwargs)
events.append('progressed')
return {'created_count': 1, 'pending_count': 0}
monkeypatch.setattr(handler, 'progress_ready_extraction_unit', _record_progress)
monkeypatch.setattr(
handler, 'submit_order_extraction_run_result',
lambda **_kwargs: events.append('terminalized') or {},
)
monkeypatch.setattr(handler, 'mark_order_extraction_persistence_started', lambda _run: events.append('persist_started'))
monkeypatch.setattr(handler, 'finish_job', lambda *_a, **kwargs: finished.update(kwargs) or True)
monkeypatch.setattr(
handler, 'fail_job',
lambda job_id, *, error, retryable, owned_attempt: fail_calls.update(
{'job_id': job_id, 'error': error, 'retryable': retryable},
),
)
monkeypatch.setattr(handler.db.session, 'commit', lambda: None)
monkeypatch.setattr(handler.db.session, 'refresh', lambda *_a, **_k: None)
monkeypatch.setattr(handler.db.session, 'expire_all', lambda: None)
monkeypatch.setattr(handler, '_intake_source_types', lambda _ids: {1: 'direct_pdf'})
handler.run_shipping_order_extraction(SimpleNamespace(), {'job_id': 61})
# 断言:收口 Job(无 pending 版面)的重放推送不推迟,STP 由本 Job 正常入队;
# review_required 单元本就不推送。
assert len(progress_calls) == 1
assert progress_calls[0]['defer_stp_enqueue'] is False
assert progress_calls[0]['unit'].id == replay_unit.id
assert 'terminalized' in events
def test_worker_replay_push_failure_fails_job_non_retryable(monkeypatch):
"""重放推送失败必须冒泡收口(禁止吞错静默丢单);非瞬时错误终态失败。"""
import app.jobs.handlers.shipping_order_extraction as handler
run = SimpleNamespace(
id=62, user_id=9, run_no='SNER-WORKER-PROP', status='processing', phase='queued',
current_job_id=None, attempt_count=0, cancellation_requested_at=None,
input_snapshot_json={'attachment_selection': {}, 'intakes': []},
execution_result_json=None, extraction_completed_at=None,
)
job = SimpleNamespace(id=62, attempts=1, business_ref=run.run_no, max_attempts=3)
replay_unit = SimpleNamespace(
id=62, document_id=202, intake_id=1, status='candidate_ready',
result_json={'orders': [{'po_number': 'PO-PROP', '_hxops_intake_id': 1}]},
position=1, cancellation_requested_at=None,
)
plan = SimpleNamespace(id=62, unit_count=1, units=[replay_unit])
fail_calls: dict = {}
transitions: list = []
monkeypatch.setattr(handler.db.session, 'get', lambda model, _id: job if model is handler.Job else replay_unit)
monkeypatch.setattr(
handler, 'ShippingOrderProcessingRun',
SimpleNamespace(query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(
with_for_update=lambda: SimpleNamespace(first=lambda: run),
))),
)
monkeypatch.setattr(handler, 'ShippingOrderProcessingUnit', SimpleNamespace(
position=SimpleNamespace(asc=lambda: None),
status=SimpleNamespace(in_=lambda *_a, **_k: True),
query=SimpleNamespace(
filter_by=lambda **_kwargs: SimpleNamespace(
order_by=lambda *_args: SimpleNamespace(all=lambda: [replay_unit]),
),
join=lambda *_a, **_k: SimpleNamespace(
filter=lambda *_a, **_k: SimpleNamespace(first=lambda: None),
),
),
))
monkeypatch.setattr(handler, 'ShippingOrderProcessingPlan', SimpleNamespace(run_id=SimpleNamespace()))
monkeypatch.setattr(handler, 'begin_input_freeze', lambda _run: None)
monkeypatch.setattr(handler, 'complete_input_freeze', lambda _run: None)
monkeypatch.setattr(
handler, 'materialize_order_extraction_run_inputs',
lambda _run, *, finalize_plan=True: plan if finalize_plan else None,
)
monkeypatch.setattr(handler, 'ensure_workflow_items_for_run', lambda *_a, **_k: [])
monkeypatch.setattr(handler, 'schedule_order_extraction_layouts', lambda *_a, **_k: False)
monkeypatch.setattr(handler, 'order_extraction_layout_prerequisite_issues', lambda _run: {})
monkeypatch.setattr(handler, 'order_extraction_ready_document_ids', lambda _run: set())
monkeypatch.setattr(handler, 'order_extraction_layouts_pending', lambda _run: False)
monkeypatch.setattr(handler, 'order_extraction_has_extractable_ready_work', lambda _run: False)
monkeypatch.setattr(
handler, 'transition_order_extraction_run',
lambda target, **kwargs: (
transitions.append(kwargs.get('target_status', '')),
setattr(target, 'status', kwargs.get('target_status', target.status)),
),
)
monkeypatch.setattr(handler, 'record_run_progress', lambda **_kwargs: None)
monkeypatch.setattr(handler, 'record_unit_progress', lambda **_kwargs: None)
monkeypatch.setattr(handler, '_units_for_batch', lambda _plan, *, selection_batch: [replay_unit])
monkeypatch.setattr(handler, '_next_existing_batch', lambda *_a, **_k: None)
monkeypatch.setattr(handler, '_pending_snapshot_batches', lambda *_a, **_k: [])
monkeypatch.setattr(handler, '_selection_progress_summary', lambda _run: {})
def _raise_progress(**_kwargs):
raise RuntimeError('replay push exploded')
monkeypatch.setattr(handler, 'progress_ready_extraction_unit', _raise_progress)
monkeypatch.setattr(handler, 'submit_order_extraction_run_result', lambda **_kwargs: None)
monkeypatch.setattr(handler, 'mark_order_extraction_persistence_started', lambda _run: None)
monkeypatch.setattr(
handler, 'fail_job',
lambda job_id, *, error, retryable, owned_attempt: fail_calls.update(
{'job_id': job_id, 'error': error, 'retryable': retryable},
),
)
monkeypatch.setattr(handler.db.session, 'commit', lambda: None)
monkeypatch.setattr(handler.db.session, 'rollback', lambda: None)
monkeypatch.setattr(handler.db.session, 'refresh', lambda *_a, **_k: None)
monkeypatch.setattr(handler.db.session, 'expire_all', lambda: None)
monkeypatch.setattr(handler, '_intake_source_types', lambda _ids: {1: 'direct_pdf'})
handler.run_shipping_order_extraction(SimpleNamespace(), {'job_id': 62})
# 断言:推送异常冒泡到失败收口,非瞬时错误终态失败(retryable=False)。
assert fail_calls['retryable'] is False
assert 'replay push exploded' in fail_calls['error']
assert 'failed' in transitions
def test_worker_transient_lock_error_requeues_without_failing_run(monkeypatch):
"""死锁 40P01 / 锁超时 55P03 为瞬时错误:retryable 重排,且不得把 run 收口为 failed。"""
import app.jobs.handlers.shipping_order_extraction as handler
class _FakeDBAPIError(Exception):
pass
for pgcode in ('40P01', '55P03'):
events: list = []
run = SimpleNamespace(
id=63, user_id=9, run_no='SNER-WORKER-TX', status='queued', phase='queued',
current_job_id=None, attempt_count=0, cancellation_requested_at=None,
input_snapshot_json={'attachment_selection': {}, 'intakes': []},
execution_result_json=None, extraction_completed_at=None,
)
job = SimpleNamespace(id=63, attempts=1, business_ref=run.run_no, max_attempts=3)
fail_calls: dict = {}
exc = _FakeDBAPIError('deadlock detected by postgres')
exc.orig = SimpleNamespace(pgcode=pgcode)
def _raise_freeze(_run, _exc=exc):
raise _exc
monkeypatch.setattr(handler.db.session, 'get', lambda model, _id: job if model is handler.Job else None)
monkeypatch.setattr(
handler, 'ShippingOrderProcessingRun',
SimpleNamespace(query=SimpleNamespace(filter_by=lambda **_kwargs: SimpleNamespace(
with_for_update=lambda: SimpleNamespace(first=lambda: run),
))),
)
monkeypatch.setattr(handler, 'begin_input_freeze', _raise_freeze)
monkeypatch.setattr(handler.db.session, 'rollback', lambda: None)
monkeypatch.setattr(handler.db.session, 'commit', lambda: None)
monkeypatch.setattr(
handler, 'fail_job',
lambda job_id, *, error, retryable, owned_attempt: fail_calls.update(
{'job_id': job_id, 'error': error, 'retryable': retryable},
),
)
monkeypatch.setattr(
handler, 'transition_order_extraction_run',
lambda target, **kwargs: events.append(f"transition:{kwargs.get('target_status')}"),
)
monkeypatch.setattr(handler, 'record_run_progress', lambda **_kwargs: events.append('progress'))
handler.run_shipping_order_extraction(SimpleNamespace(), {'job_id': 63})
# 断言:瞬时锁错可重试;run/unit 不做失败收口(重试 Job 才不会被状态门弹掉)。
assert fail_calls['retryable'] is True, f'pgcode={pgcode}'
assert 'deadlock detected' in fail_calls['error']
assert events == [], f'pgcode={pgcode} 不应收口 run: {events}'
def test_sync_extraction_run_failure_sync_ignores_requeued_job():
"""requeue(status=queued)不触发 run 失败收口;只有终态 failed 才同步。"""
from app.services.shipping_notice.order_extraction_run_service import (
sync_order_extraction_run_after_job_failure,
)
requeued = SimpleNamespace(
job_type='shipping_order_extraction', status='queued', business_ref='SNER-RQ',
)
# 断言:requeue 的 Job 直接跳过(不查询、不触碰 Run),自动重试不会被状态门弹掉。
assert sync_order_extraction_run_after_job_failure(requeued) is None
def test_progress_ready_extraction_unit_threads_defer_flag(monkeypatch):
"""推送入口必须把 defer_stp_enqueue 原样传递给 unit 级 submit。"""
from app.services.shipping_notice import order_extraction_run_service as svc
captured: dict = {}
monkeypatch.setattr(svc, 'mark_order_extraction_persistence_started', lambda _run: None)
monkeypatch.setattr(
'app.services.shipping_notice.order_extraction.submit_order_extraction_unit_result',
lambda **kwargs: captured.update(kwargs) or {'created_count': 0},
)
run = SimpleNamespace(id=1)
unit = SimpleNamespace(id=2)
svc.progress_ready_extraction_unit(run=run, unit=unit, orders=[], defer_stp_enqueue=True)
assert captured['defer_stp_enqueue'] is True
svc.progress_ready_extraction_unit(run=run, unit=unit, orders=[])
assert captured['defer_stp_enqueue'] is False
@@ -0,0 +1,115 @@
"""
tests/test_shipping_review_draft_validate_idempotency.py
用途:锁定显式校验(draft_validated)在 STP 自动建单持有草稿时的幂等短路契约。
依赖:pytest、order_review_draft_service、unittest.mock。
逻辑:不依赖 DB;内容未变且自动化持锁时不得递增版本/写事件(不触发 _record_change),
内容变化或自动化未持锁时保持原行为;另覆盖内容摘要的稳定性与旧草稿兼容。
背景:2026-09-22 生产事故——用户 11 秒连点 8 次“保存并校验”,每次递增 draft_version
并入队新 STP Job,同文档多 Job 并发在建单 advisory 锁上死锁且 max_attempts=1 不重试。
"""
from __future__ import annotations
from types import SimpleNamespace
def test_validate_draft_short_circuits_when_automation_holds_and_content_unchanged(monkeypatch):
"""自动化持锁 + 内容未变:重复校验必须幂等短路,不得递增版本或写事件。"""
from app.services.shipping_notice import order_review_draft_service as svc
case = object()
monkeypatch.setattr(svc, '_locked_case', lambda **kwargs: case)
monkeypatch.setattr(svc, '_assert_version', lambda *args, **kwargs: None)
monkeypatch.setattr(svc, '_stp_automation_holds_draft', lambda c: True)
monkeypatch.setattr(svc, '_draft_content_unchanged', lambda c: True)
monkeypatch.setattr(svc, 'serialize_review_case', lambda c: {'serialized': True})
def _unexpected_record_change(*args, **kwargs):
raise AssertionError('_record_change 必须被短路跳过')
monkeypatch.setattr(svc, '_record_change', _unexpected_record_change)
result = svc.validate_draft(user_id=1, case_no='SORC-IDEM-1', expected_draft_version=5)
assert result == {'serialized': True}
def test_validate_draft_runs_validation_when_content_changed(monkeypatch):
"""内容变化(含人工改脏):不允许短路,必须走真实校验路径。"""
from app.services.shipping_notice import order_review_draft_service as svc
case = object()
monkeypatch.setattr(svc, '_locked_case', lambda **kwargs: case)
monkeypatch.setattr(svc, '_assert_version', lambda *args, **kwargs: None)
monkeypatch.setattr(svc, '_stp_automation_holds_draft', lambda c: True)
monkeypatch.setattr(svc, '_draft_content_unchanged', lambda c: False)
monkeypatch.setattr(svc, 'serialize_review_case', lambda c: {'serialized': True})
recorded: dict = {}
monkeypatch.setattr(
svc, '_record_change',
lambda *args, **kwargs: recorded.update(kwargs) or {'recorded': True},
)
result = svc.validate_draft(user_id=1, case_no='SORC-IDEM-2', expected_draft_version=6)
assert result == {'recorded': True}
assert recorded['event_type'] == 'draft_validated'
assert recorded['validate'] is True
def test_validate_draft_runs_validation_when_automation_not_holding(monkeypatch):
"""自动化未持锁(如失败超 120s 逃生门后):保持原行为,允许重新校验触发重试。"""
from app.services.shipping_notice import order_review_draft_service as svc
case = object()
monkeypatch.setattr(svc, '_locked_case', lambda **kwargs: case)
monkeypatch.setattr(svc, '_assert_version', lambda *args, **kwargs: None)
monkeypatch.setattr(svc, '_stp_automation_holds_draft', lambda c: False)
monkeypatch.setattr(svc, '_draft_content_unchanged', lambda c: True)
monkeypatch.setattr(svc, 'serialize_review_case', lambda c: {'serialized': True})
monkeypatch.setattr(svc, '_record_change', lambda *args, **kwargs: {'recorded': True})
result = svc.validate_draft(user_id=1, case_no='SORC-IDEM-3', expected_draft_version=7)
assert result == {'recorded': True}
def test_draft_content_checksum_is_stable_and_content_sensitive():
"""内容摘要:相同内容稳定一致,任一字段变化即不同;与版本/时间无关。"""
from app.services.shipping_notice import order_review_draft_service as svc
draft_a = SimpleNamespace(header_values_json={'po': 'P1'}, lines_json=[{'line': 1}])
draft_a_same = SimpleNamespace(header_values_json={'po': 'P1'}, lines_json=[{'line': 1}])
draft_changed = SimpleNamespace(header_values_json={'po': 'P1'}, lines_json=[{'line': 2}])
draft_none = SimpleNamespace(header_values_json=None, lines_json=None)
assert svc._draft_content_checksum(draft_a) == svc._draft_content_checksum(draft_a_same)
assert svc._draft_content_checksum(draft_a) != svc._draft_content_checksum(draft_changed)
# None 视为空内容,不抛异常
assert svc._draft_content_checksum(draft_none)
def test_draft_content_unchanged_false_for_legacy_draft_without_checksum():
"""旧草稿(升级前校验)没有 content_checksum:不短路,保持原行为。"""
from app.services.shipping_notice import order_review_draft_service as svc
legacy_case = SimpleNamespace(current_draft=SimpleNamespace(
header_values_json={'po': 'P1'},
lines_json=[],
validation_result_json={'can_build': True, 'status': 'ready'},
))
assert svc._draft_content_unchanged(legacy_case) is False
unchanged_case = SimpleNamespace(current_draft=SimpleNamespace(
header_values_json={'po': 'P1'},
lines_json=[],
validation_result_json={'content_checksum': svc._draft_content_checksum(
SimpleNamespace(header_values_json={'po': 'P1'}, lines_json=[]),
)},
))
assert svc._draft_content_unchanged(unchanged_case) is True
changed_case = SimpleNamespace(current_draft=SimpleNamespace(
header_values_json={'po': 'P2'},
lines_json=[],
validation_result_json=unchanged_case.current_draft.validation_result_json,
))
assert svc._draft_content_unchanged(changed_case) is False
@@ -324,3 +324,101 @@ def test_stp_handler_flattens_business_error_details(app):
persisted = fail_mock.call_args.kwargs['result']['blocking_reason_details']
assert persisted['fields'] == ['unexpected_field']
assert persisted['schema_version_id'] == 31
def test_ensure_stp_supersedes_stale_queued_jobs_and_enqueues_with_retries(app):
"""入队前必须作废同文档旧版本 queued Job;max_attempts>1 允许瞬时失败自动重试。
背景(2026-09-22 生产事故):同文档 v8/v9 两个 STP Job 并发执行在建单 advisory 锁上
死锁,且 max_attempts=1 一次判死、无补偿,case 永久停在 ready。
"""
from app.services.shipping_notice import order_stp_auto_create_service as svc
case = SimpleNamespace(
id=31,
case_no='SORC-STP-31',
status='ready',
confirmed_task_id=None,
document_id=10,
candidate_id=None,
disposition=None,
run_id=1,
run=SimpleNamespace(run_no='SNER-TEST-31', id=1),
owner_user_id=1,
current_draft=SimpleNamespace(
draft_version=9,
validation_result_json={'can_build': True, 'can_auto_create': True, 'status': 'ready'},
issue_summary_json=[],
),
)
captured: dict = {}
superseded_kwargs: dict = {}
def _enqueue(*args, **kwargs):
captured['max_attempts'] = kwargs.get('max_attempts')
captured['business_ref'] = kwargs.get('business_ref')
return 901
def _supersede(**kwargs):
superseded_kwargs.update(kwargs)
return 1
with patch.object(svc, '_persist_case_candidate_qualification', return_value=None), patch.object(
svc, '_draft_has_manual_edits', return_value=False
), patch.object(svc, '_supersede_stale_queued_stp_jobs', side_effect=_supersede), patch.object(
svc, 'find_active_stp_job', return_value=None
), patch.object(svc, 'find_latest_stp_job', return_value=None), patch.object(
svc, 'enqueue', side_effect=_enqueue
), patch.object(svc, 'record_fulfillment_audit'), patch.object(svc, 'db'):
result = svc.ensure_stp_auto_create_for_case(case=case, commit=False)
# 断言:入队前先作废旧版本 queued Job,且按当前草稿版本调用
assert superseded_kwargs == {
'run_no': 'SNER-TEST-31',
'document_id': 10,
'current_draft_version': 9,
}
# 断言:瞬时失败可重试(死锁类不再一次判死)
assert captured['max_attempts'] == 3
assert captured['business_ref'] == 'stp-auto:SNER-TEST-31:doc-10:v9'
assert result['status'] == 'queued'
def test_supersede_stale_queued_stp_jobs_only_touches_lower_version_queued(app):
"""只作废同 run+doc 低版本 queued Job;running 留给执行期检查,跨 run 不动。"""
from app import db
from app.models import Job
from app.services.shipping_notice import order_stp_auto_create_service as svc
def _mk(ref: str, status: str) -> Job:
job = Job(
domain='shipping_notice',
job_type='shipping_stp_auto_create',
status=status,
business_ref=ref,
)
db.session.add(job)
return job
queued_v1 = _mk('stp-auto:SNER-T:doc-9:v1', 'queued')
running_v2 = _mk('stp-auto:SNER-T:doc-9:v2', 'running')
success_v3 = _mk('stp-auto:SNER-T:doc-9:v3', 'success')
queued_v8 = _mk('stp-auto:SNER-T:doc-9:v8', 'queued')
other_run_v1 = _mk('stp-auto:SNER-OTHER:doc-9:v1', 'queued')
db.session.commit()
count = svc._supersede_stale_queued_stp_jobs(
run_no='SNER-T', document_id=9, current_draft_version=9,
)
# 断言:恰好作废同 run 的 v1/v8 两条 queued;其余状态与跨 run Job 不受影响
assert count == 2
superseded_v1 = db.session.get(Job, queued_v1.id)
assert superseded_v1.status == 'success'
assert '已被新版草稿替代' in str(superseded_v1.message or '')
assert superseded_v1.result_json.get('superseded_at_enqueue') is True
assert superseded_v1.result_json.get('superseded_by_draft_version') == 9
assert db.session.get(Job, running_v2.id).status == 'running'
assert db.session.get(Job, success_v3.id).status == 'success'
assert db.session.get(Job, queued_v8.id).status == 'success'
assert db.session.get(Job, other_run_v1.id).status == 'queued'