Merge branch 'dev' into runny827
feat(training): 新增精益培训视频与周任务管理 # Conflicts: # backend/app/models/__init__.py
This commit is contained in:
1 parent
85d27e9ffa
commit
91b7233872
812 files changed
+73763
-18908
No files matched your search
@@ -0,0 +1,448 @@
|
||||
"""在途调拨预检 API 契约测试(L2,Flask test client)。
|
||||
|
||||
用途:验证 POST /prechecks 创建(含 envelope/权限/参数校验)与
|
||||
GET /prechecks/{id} 进度恢复;无权限 403、未认证 401。
|
||||
依赖:app fixture、client、issue_local_access_token、fakes/repo_fakes。
|
||||
逻辑:API 依赖经 deps._override 注入 Fake 替身;权限按 admin 放行或
|
||||
in_transit_transfer Agent 授权校验。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.models import Agent, User
|
||||
from tests.services.in_transit_transfer.repo_fakes import make_transfer_deps
|
||||
|
||||
API_PREFIX = "/api/in-transit-transfer"
|
||||
|
||||
|
||||
def _jwt_headers(user: User) -> dict:
|
||||
"""为指定用户签发 Bearer JWT 请求头。"""
|
||||
token = issue_local_access_token(user)
|
||||
return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def transfer_deps(monkeypatch, dbs_ready_file):
|
||||
"""注入 Fake 预检依赖,并预置可执行库存。"""
|
||||
deps, erp, _ = make_transfer_deps(dbs_ready_file)
|
||||
erp.seed_inventory("INV-001", "1200")
|
||||
erp.seed_inventory("INV-002", "1200")
|
||||
monkeypatch.setattr("app.services.in_transit_transfer.deps._override", deps)
|
||||
return deps
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admin_headers(app):
|
||||
"""创建 admin 用户并返回 JWT 请求头(token 在 app context 内签发)。"""
|
||||
with app.app_context():
|
||||
user = db.session.query(User).filter_by(username="admin").first()
|
||||
if not user:
|
||||
user = User(username="admin", email="admin@example.com", role="admin", status="active")
|
||||
user.set_password("admin")
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
token = issue_local_access_token(user)
|
||||
return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def warehouse_headers(app):
|
||||
"""创建持有 in_transit_transfer Agent 权限的仓库管理员并返回 JWT 请求头。"""
|
||||
with app.app_context():
|
||||
agent = Agent.query.filter_by(agent_code="in_transit_transfer").first()
|
||||
if not agent:
|
||||
agent = Agent(name="在途仓调拨", agent_code="in_transit_transfer",
|
||||
type="api", is_active=True)
|
||||
db.session.add(agent)
|
||||
db.session.flush()
|
||||
user = db.session.query(User).filter_by(username="warehouse").first()
|
||||
if not user:
|
||||
user = User(username="warehouse", email="warehouse@example.com",
|
||||
role="user", status="active")
|
||||
user.set_password("x")
|
||||
db.session.add(user)
|
||||
db.session.flush()
|
||||
if agent not in user.agents:
|
||||
user.agents.append(agent)
|
||||
db.session.commit()
|
||||
token = issue_local_access_token(user)
|
||||
return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def unauthorized_headers(app):
|
||||
"""无 Agent 权限的普通用户 JWT 请求头。"""
|
||||
with app.app_context():
|
||||
user = db.session.query(User).filter_by(username="no_perm").first()
|
||||
if not user:
|
||||
user = User(username="no_perm", email="no_perm@example.com", role="user", status="active")
|
||||
user.set_password("x")
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
token = issue_local_access_token(user)
|
||||
return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
|
||||
|
||||
|
||||
def test_create_precheck_returns_envelope_with_precheck_id(app, client, admin_headers, transfer_deps):
|
||||
"""POST /prechecks → 201 envelope,data 含 precheck_id/hash/计数。"""
|
||||
response = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
})
|
||||
assert response.status_code == 201
|
||||
body = response.get_json()
|
||||
assert body["success"] is True
|
||||
data = body["data"]
|
||||
assert data["precheck_id"].startswith("TPC-")
|
||||
assert data["precheck_hash"].startswith("sha256:")
|
||||
assert data["estimated_erp_write_count"] == 2
|
||||
assert body.get("request_id")
|
||||
|
||||
|
||||
def test_create_precheck_requires_authentication(client):
|
||||
"""未认证 → 401(envelope error)。"""
|
||||
response = client.post(f"{API_PREFIX}/prechecks", json={"source_codes": ["DBS-AWSBI"]})
|
||||
assert response.status_code == 401
|
||||
assert response.get_json()["success"] is False
|
||||
|
||||
|
||||
def test_create_precheck_forbidden_without_agent_permission(client, unauthorized_headers):
|
||||
"""无 in_transit_transfer Agent 权限 → 403。"""
|
||||
response = client.post(f"{API_PREFIX}/prechecks", headers=unauthorized_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
})
|
||||
assert response.status_code == 403
|
||||
assert response.get_json()["error"]["code"] == "AUTH.FORBIDDEN"
|
||||
|
||||
|
||||
def test_create_precheck_warehouse_manager_allowed(app, client, warehouse_headers, transfer_deps):
|
||||
"""持有 Agent 权限的仓库管理员可创建预检。"""
|
||||
response = client.post(f"{API_PREFIX}/prechecks", headers=warehouse_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
})
|
||||
assert response.status_code == 201
|
||||
assert response.get_json()["data"]["precheck_id"]
|
||||
|
||||
|
||||
def test_create_precheck_validates_source_codes(app, client, admin_headers, transfer_deps):
|
||||
"""缺少 source_codes → 400 参数错误。"""
|
||||
response = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={"business_date": "2026-08-06"})
|
||||
assert response.status_code == 400
|
||||
assert response.get_json()["success"] is False
|
||||
|
||||
|
||||
def test_restore_precheck_progress(app, client, admin_headers, transfer_deps):
|
||||
"""GET /prechecks/{id} 恢复预检进度(Hash/明细一致)。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
restored = client.get(f"{API_PREFIX}/prechecks/{created['precheck_id']}", headers=admin_headers)
|
||||
assert restored.status_code == 200
|
||||
body = restored.get_json()["data"]
|
||||
assert body["summary"]["precheck_hash"] == created["precheck_hash"]
|
||||
assert {item["invoice_no"] for item in body["items"]} == {"INV-001", "INV-002"}
|
||||
|
||||
|
||||
def test_restore_unknown_precheck_404(app, client, admin_headers, transfer_deps):
|
||||
"""未知 precheck → 404。"""
|
||||
response = client.get(f"{API_PREFIX}/prechecks/TPC-NOT-EXIST", headers=admin_headers)
|
||||
assert response.status_code == 404
|
||||
|
||||
|
||||
def test_execute_precheck_creates_run_and_projects_documents(app, client, admin_headers, transfer_deps):
|
||||
"""执行预检 → 201 run_no;GET run 返回 ERP 单号聚合结果。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
executed = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={"invoice_nos": ["INV-001", "INV-002"]},
|
||||
)
|
||||
assert executed.status_code == 201
|
||||
run_no = executed.get_json()["data"]["run_no"]
|
||||
assert run_no.startswith("RUN-")
|
||||
|
||||
run = client.get(f"{API_PREFIX}/runs/{run_no}", headers=admin_headers)
|
||||
assert run.status_code == 200
|
||||
result = run.get_json()["data"]["result"]
|
||||
assert len(result["erp_documents"]) == 2
|
||||
assert result["exceptions"] == []
|
||||
|
||||
|
||||
def test_execute_unconfirmed_precheck_rejected(app, client, admin_headers, transfer_deps):
|
||||
"""预检未就绪时执行 → 400 领域错误,不产生 Run。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
with app.app_context():
|
||||
from app.models import TransferPrecheck
|
||||
|
||||
precheck = TransferPrecheck.query.filter_by(precheck_no=created["precheck_id"]).first()
|
||||
precheck.status = "prechecking"
|
||||
db.session.commit()
|
||||
response = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={"invoice_nos": ["INV-001"]},
|
||||
)
|
||||
assert response.status_code == 400
|
||||
assert response.get_json()["error"]["code"] == "TRANSFER_CONFIRMATION_REQUIRED"
|
||||
|
||||
|
||||
def test_cancel_run_requires_reason(app, client, admin_headers, transfer_deps):
|
||||
"""取消缺少原因 → 400。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
executed = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={},
|
||||
)
|
||||
run_no = executed.get_json()["data"]["run_no"]
|
||||
response = client.post(f"{API_PREFIX}/runs/{run_no}/cancel", headers=admin_headers, json={"reason": ""})
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_cancel_run_marks_remaining_cancelled(app, client, admin_headers, transfer_deps):
|
||||
"""取消未开始项并保留成功单据。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
executed = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={"invoice_nos": ["INV-001", "INV-002"]},
|
||||
)
|
||||
run_no = executed.get_json()["data"]["run_no"]
|
||||
# 模拟执行中状态:Run 回退 executing,INV-002 尚未开始
|
||||
with app.app_context():
|
||||
from app.models import TransferInvoiceItem, TransferRun
|
||||
|
||||
run = TransferRun.query.filter_by(run_no=run_no).first()
|
||||
run.status = "executing"
|
||||
item = TransferInvoiceItem.query.filter_by(run_id=run.id, invoice_no="INV-002").first()
|
||||
item.status = "ready_to_execute"
|
||||
item.erp_document_no = None
|
||||
db.session.commit()
|
||||
response = client.post(f"{API_PREFIX}/runs/{run_no}/cancel", headers=admin_headers, json={
|
||||
"reason": "货源调整,停止剩余",
|
||||
})
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["data"]["cancelled_count"] == 1
|
||||
|
||||
|
||||
def test_manual_close_item_requires_reason(app, client, admin_headers, transfer_deps):
|
||||
"""人工关闭缺少原因 → 400。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
with app.app_context():
|
||||
from app.models import TransferInvoiceItem
|
||||
|
||||
item = TransferInvoiceItem.query.filter_by(invoice_no="INV-001").first()
|
||||
item.status = "blocked_recoverable"
|
||||
item.result_code = "blocked_quantity_mismatch"
|
||||
db.session.commit()
|
||||
item_id = item.id
|
||||
response = client.post(f"{API_PREFIX}/items/{item_id}/manual-close", headers=admin_headers, json={"reason": ""})
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_manual_close_item_success(app, client, admin_headers, transfer_deps):
|
||||
"""人工关闭成功 → 状态 manually_closed。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
with app.app_context():
|
||||
from app.models import TransferInvoiceItem
|
||||
|
||||
item = TransferInvoiceItem.query.filter_by(invoice_no="INV-001").first()
|
||||
item.status = "blocked_recoverable"
|
||||
item.result_code = "blocked_quantity_mismatch"
|
||||
db.session.commit()
|
||||
item_id = item.id
|
||||
response = client.post(f"{API_PREFIX}/items/{item_id}/manual-close", headers=admin_headers, json={
|
||||
"reason": "线下已处理",
|
||||
})
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["data"]["status"] == "manually_closed"
|
||||
|
||||
|
||||
def test_exceptions_excel_download(app, transfer_db, client, admin_headers, transfer_deps):
|
||||
"""下载异常 Excel → 200 xlsx,且记录访问审计。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
executed = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={"invoice_nos": ["INV-001", "INV-002"]},
|
||||
)
|
||||
run_no = executed.get_json()["data"]["run_no"]
|
||||
response = client.get(f"{API_PREFIX}/runs/{run_no}/exceptions.xlsx", headers=admin_headers)
|
||||
assert response.status_code == 200
|
||||
assert response.content_type.startswith("application/vnd.openxmlformats")
|
||||
with app.app_context():
|
||||
from app.models import TransferAuditEvent
|
||||
|
||||
audit = TransferAuditEvent.query.filter_by(event_type="TRANSFER_EXCEL_DOWNLOADED").first()
|
||||
assert audit is not None
|
||||
assert audit.run_no == run_no
|
||||
|
||||
|
||||
def test_receipt_files_download_records_access_audit(app, transfer_db, client, admin_headers, transfer_deps):
|
||||
"""下载收料来源文件 → 200(zip),记录访问审计。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
executed = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={"invoice_nos": ["INV-001", "INV-002"]},
|
||||
)
|
||||
run_no = executed.get_json()["data"]["run_no"]
|
||||
response = client.get(f"{API_PREFIX}/runs/{run_no}/receipt-files", headers=admin_headers)
|
||||
assert response.status_code == 200
|
||||
assert response.content_type.startswith("application/zip")
|
||||
with app.app_context():
|
||||
from app.models import TransferAuditEvent
|
||||
|
||||
audit = TransferAuditEvent.query.filter_by(event_type="TRANSFER_RECEIPT_FILES_DOWNLOADED").first()
|
||||
assert audit is not None
|
||||
|
||||
|
||||
def test_erp_inventory_download_records_access_audit(app, transfer_db, client, admin_headers, transfer_deps):
|
||||
"""下载预检冻结的 ERP 库存表 → 200(csv),记录访问审计。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
executed = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={"invoice_nos": ["INV-001", "INV-002"]},
|
||||
)
|
||||
run_no = executed.get_json()["data"]["run_no"]
|
||||
response = client.get(f"{API_PREFIX}/runs/{run_no}/erp-inventory", headers=admin_headers)
|
||||
assert response.status_code == 200
|
||||
assert "csv" in response.content_type
|
||||
assert b"INV-001" in response.data
|
||||
with app.app_context():
|
||||
from app.models import TransferAuditEvent
|
||||
|
||||
audit = TransferAuditEvent.query.filter_by(event_type="TRANSFER_ERP_INVENTORY_DOWNLOADED").first()
|
||||
assert audit is not None
|
||||
|
||||
|
||||
def test_downloads_forbidden_without_permission(app, transfer_db, client, admin_headers, unauthorized_headers, transfer_deps):
|
||||
"""无权限下载 → 403(越权检查)。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
executed = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={},
|
||||
)
|
||||
run_no = executed.get_json()["data"]["run_no"]
|
||||
for path in (f"{API_PREFIX}/runs/{run_no}/receipt-files",
|
||||
f"{API_PREFIX}/runs/{run_no}/erp-inventory",
|
||||
f"{API_PREFIX}/runs/{run_no}/exceptions.xlsx"):
|
||||
response = client.get(path, headers=unauthorized_headers)
|
||||
assert response.status_code == 403, path
|
||||
|
||||
|
||||
def test_execute_ignores_forged_warehouse_and_quantity(app, transfer_db, client, admin_headers, transfer_deps):
|
||||
"""前端伪造来源仓/目标仓/数量 → 服务端忽略,使用冻结快照值(防篡改)。"""
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
executed = client.post(
|
||||
f"{API_PREFIX}/prechecks/{created['precheck_id']}/execute",
|
||||
headers=admin_headers, json={
|
||||
"invoice_nos": ["INV-001"],
|
||||
"from_warehouse": "FAKE-TRANSIT",
|
||||
"to_warehouse": "FAKE-HUB",
|
||||
"quantity": "1",
|
||||
},
|
||||
)
|
||||
assert executed.status_code == 201
|
||||
run_no = executed.get_json()["data"]["run_no"]
|
||||
run = client.get(f"{API_PREFIX}/runs/{run_no}", headers=admin_headers).get_json()["data"]
|
||||
documents = run["result"]["erp_documents"]
|
||||
assert documents[0]["from_warehouse"] == "DBS-TRANSIT" # 冻结值,非伪造值
|
||||
assert documents[0]["to_warehouse"] == "HUB-CN01"
|
||||
assert documents[0]["total_quantity"] == "1200"
|
||||
|
||||
|
||||
def test_backlog_list_and_summary(app, transfer_db, client, admin_headers, transfer_deps):
|
||||
"""待处理异常列表/汇总 API:收纳 blocked 项、排除 success、含老化等级。"""
|
||||
# 预检含 1 个数量不一致(blocked)项
|
||||
created = client.post(f"{API_PREFIX}/prechecks", headers=admin_headers, json={
|
||||
"source_codes": ["DBS-AWSBI"],
|
||||
"business_date": "2026-08-06",
|
||||
}).get_json()["data"]
|
||||
with app.app_context():
|
||||
from app.models import TransferInvoiceItem
|
||||
|
||||
item = TransferInvoiceItem.query.filter_by(invoice_no="INV-001").first()
|
||||
item.status = "blocked_recoverable"
|
||||
item.result_code = "blocked_quantity_mismatch"
|
||||
item.result_message = "收料 1200 / ERP 1000"
|
||||
db.session.commit()
|
||||
|
||||
listed = client.get(f"{API_PREFIX}/backlog", headers=admin_headers)
|
||||
assert listed.status_code == 200
|
||||
invoice_set = {entry["invoice_no"] for entry in listed.get_json()["data"]}
|
||||
assert "INV-001" in invoice_set
|
||||
assert "INV-002" not in invoice_set # 可执行项不在待处理池
|
||||
assert listed.get_json()["data"][0]["aging_level"] in {"normal", "warn_3d", "escalate_5d", "critical_7d"}
|
||||
|
||||
summary = client.get(f"{API_PREFIX}/backlog/summary", headers=admin_headers)
|
||||
assert summary.status_code == 200
|
||||
assert summary.get_json()["data"]["recoverable"] >= 1
|
||||
|
||||
|
||||
def test_backlog_forbidden_without_permission(app, transfer_db, client, unauthorized_headers, transfer_deps):
|
||||
"""无权限访问待处理池 → 403(越权检查)。"""
|
||||
response = client.get(f"{API_PREFIX}/backlog", headers=unauthorized_headers)
|
||||
assert response.status_code == 403
|
||||
|
||||
|
||||
def test_list_transfer_sources(app, client, admin_headers):
|
||||
"""来源实例列表:返回启用来源(平台=connector_type,来源实例为执行边界)。"""
|
||||
response = client.get(f"{API_PREFIX}/sources", headers=admin_headers)
|
||||
assert response.status_code == 200
|
||||
sources = response.get_json()["data"]
|
||||
assert isinstance(sources, list)
|
||||
# 测试种子来源 DSV360_AWSDU(dbs)应在列表中
|
||||
assert any(item["source_code"] == "DSV360_AWSDU" for item in sources)
|
||||
for item in sources:
|
||||
assert item["source_code"]
|
||||
assert item["platform"] in {"dbs", "crane"}
|
||||
assert item["enabled"] is True
|
||||
|
||||
|
||||
def test_list_transfer_sources_forbidden(app, client, unauthorized_headers):
|
||||
"""无权限查看来源实例 → 403。"""
|
||||
response = client.get(f"{API_PREFIX}/sources", headers=unauthorized_headers)
|
||||
assert response.status_code == 403
|
||||
|
||||
|
||||
def test_metrics_endpoint(app, transfer_db, client, admin_headers, transfer_deps):
|
||||
"""运营指标端点:返回 Run/明细/待处理/通知失败结构。"""
|
||||
response = client.get(f"{API_PREFIX}/metrics", headers=admin_headers)
|
||||
assert response.status_code == 200
|
||||
data = response.get_json()["data"]
|
||||
assert "runs" in data and "items" in data and "backlog" in data
|
||||
assert "notification_failed_runs" in data["runs"]
|
||||
@@ -0,0 +1,290 @@
|
||||
"""tests/api/test_integration_connector_api.py
|
||||
|
||||
用途:Integration Connector Admin API 契约测试——能力清单、客户端 CRUD、能力调用、
|
||||
interface_id 拒绝、连接测试、鉴权(401/403)。依赖 Fake 网关注入。
|
||||
依赖:app fixture、client、issue_local_access_token、gateway 覆盖注入。
|
||||
逻辑:Admin API 全部 require_admin;能力调用只暴露 Capability,拒绝传 interface_id。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.models import User
|
||||
from app.services.integration_connector.transports.base import IntegrationCallResult
|
||||
from app.services.integration_connector.gateway import set_capability_gateway
|
||||
|
||||
API_PREFIX = "/api/integration-connector"
|
||||
|
||||
|
||||
class FakeTransport:
|
||||
connector_type = "rest"
|
||||
|
||||
def call(self, *, client, interface, request):
|
||||
return {"found": True, "quantity": "100"}
|
||||
|
||||
|
||||
class _FakeGateway:
|
||||
"""纯替代网关:call 直接返回,不解析绑定;transports 供连接测试。"""
|
||||
|
||||
def __init__(self):
|
||||
self.transports = {"rest": FakeTransport()}
|
||||
|
||||
def call(self, **kwargs):
|
||||
return IntegrationCallResult(status="success", data={"found": True, "quantity": None})
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admin_headers(app):
|
||||
with app.app_context():
|
||||
user = db.session.query(User).filter_by(username="admin").first()
|
||||
if not user:
|
||||
user = User(username="admin", email="admin@example.com", role="admin", status="active")
|
||||
user.set_password("admin")
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
token = issue_local_access_token(user)
|
||||
return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def plain_headers(app):
|
||||
with app.app_context():
|
||||
user = db.session.query(User).filter_by(username="plain").first()
|
||||
if not user:
|
||||
user = User(username="plain", email="plain@example.com", role="user", status="active")
|
||||
user.set_password("x")
|
||||
db.session.add(user)
|
||||
db.session.commit()
|
||||
token = issue_local_access_token(user)
|
||||
return {"Authorization": f"Bearer {token}", "Content-Type": "application/json"}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fake_gateway():
|
||||
gw = _FakeGateway()
|
||||
set_capability_gateway(gw)
|
||||
yield gw
|
||||
set_capability_gateway(None)
|
||||
|
||||
|
||||
def _params():
|
||||
return {"invoice_no": "INV-001", "from_warehouse": "W1", "to_warehouse": "W2", "quantity": 100}
|
||||
|
||||
|
||||
def test_list_capabilities(app, client, admin_headers):
|
||||
"""GET /capabilities → 200,含 3 个在途调拨能力。"""
|
||||
response = client.get(f"{API_PREFIX}/capabilities", headers=admin_headers)
|
||||
assert response.status_code == 200
|
||||
names = {item["name"] for item in response.get_json()["data"]}
|
||||
assert {"in_transit_transfer.query_inventory", "in_transit_transfer.create_transfer", "in_transit_transfer.verify_duplicate"}.issubset(names)
|
||||
|
||||
|
||||
def test_create_and_list_client_instance(app, client, admin_headers):
|
||||
"""POST /client-instances → 201;GET 列表可查。"""
|
||||
created = client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "ERP-T100", "name": "T100 ERP", "connector_type": "soap", "environment": "prod",
|
||||
"config_json": {"endpoint": "https://t100.invalid/ws"},
|
||||
})
|
||||
assert created.status_code == 201
|
||||
assert created.get_json()["data"]["code"] == "ERP-T100"
|
||||
|
||||
listed = client.get(f"{API_PREFIX}/client-instances", headers=admin_headers)
|
||||
assert listed.status_code == 200
|
||||
assert any(item["code"] == "ERP-T100" for item in listed.get_json()["data"])
|
||||
|
||||
|
||||
def test_client_instance_invalid_connector_type(app, client, admin_headers):
|
||||
"""非法 connector_type → 400。"""
|
||||
response = client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "X", "name": "x", "connector_type": "ftp",
|
||||
})
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_call_capability_success(app, client, admin_headers, fake_gateway):
|
||||
"""POST /capabilities/<name> → 200 success。"""
|
||||
response = client.post(f"{API_PREFIX}/capabilities/in_transit_transfer.query_inventory",
|
||||
headers=admin_headers, json={"params": _params(), "context": {}})
|
||||
assert response.status_code == 200
|
||||
data = response.get_json()["data"]
|
||||
assert data["status"] == "success"
|
||||
assert data["data"]["found"] is True
|
||||
|
||||
|
||||
def test_call_capability_rejects_interface_id(app, client, admin_headers, fake_gateway):
|
||||
"""body 携带 interface_id → 400(禁止覆盖 Binding)。"""
|
||||
response = client.post(f"{API_PREFIX}/capabilities/in_transit_transfer.query_inventory",
|
||||
headers=admin_headers, json={"params": _params(), "context": {}, "interface_id": "X"})
|
||||
assert response.status_code == 400
|
||||
assert response.get_json()["error"]["code"] == "INTEGRATION.INTERFACE_ID_NOT_ALLOWED"
|
||||
|
||||
|
||||
def test_call_requires_authentication(client):
|
||||
"""未认证 → 401。"""
|
||||
response = client.post(f"{API_PREFIX}/capabilities/in_transit_transfer.query_inventory",
|
||||
json={"params": _params()})
|
||||
assert response.status_code == 401
|
||||
|
||||
|
||||
def test_admin_only_forbidden(app, client, plain_headers):
|
||||
"""普通用户访问 Admin API → 403。"""
|
||||
response = client.get(f"{API_PREFIX}/client-instances", headers=plain_headers)
|
||||
assert response.status_code == 403
|
||||
|
||||
|
||||
def test_client_instance_test_connection(app, client, admin_headers, fake_gateway):
|
||||
"""POST /client-instances/<code>/test → 200(用注入的 Fake transport)。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-A", "name": "client", "connector_type": "rest", "environment": "prod",
|
||||
"config_json": {"endpoint": "https://erp.invalid"},
|
||||
})
|
||||
response = client.post(f"{API_PREFIX}/client-instances/CLI-A/test", headers=admin_headers)
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["data"]["ok"] is True
|
||||
|
||||
|
||||
def test_update_client_instance(app, client, admin_headers):
|
||||
"""PUT /client-instances/<code> → 200,更新 name/config/enabled。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-U", "name": "old", "connector_type": "rest", "environment": "prod",
|
||||
"config_json": {"endpoint": "https://old.invalid"},
|
||||
})
|
||||
response = client.put(f"{API_PREFIX}/client-instances/CLI-U", headers=admin_headers, json={
|
||||
"name": "new", "config_json": {"endpoint": "https://new.invalid"}, "enabled": False,
|
||||
})
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["data"]["name"] == "new"
|
||||
assert response.get_json()["data"]["enabled"] is False
|
||||
assert response.get_json()["data"]["config_json"] == {"endpoint": "https://new.invalid"}
|
||||
|
||||
|
||||
def test_update_interface_definition(app, client, admin_headers):
|
||||
"""PUT /interface-definitions/<code> → 200,更新模板/回传映射/状态。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-I", "name": "cli", "connector_type": "rest", "environment": "prod",
|
||||
"config_json": {},
|
||||
})
|
||||
client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
|
||||
"code": "IF-U", "name": "iface", "client_instance_code": "CLI-I", "connector_type": "rest",
|
||||
"request_spec_json": {"path": "/v1/old"}, "status": "draft",
|
||||
})
|
||||
response = client.put(f"{API_PREFIX}/interface-definitions/IF-U", headers=admin_headers, json={
|
||||
"request_spec_json": {"path": "/v1/new"}, "response_mapping_json": {"qty": "data.quantity"},
|
||||
"status": "published",
|
||||
})
|
||||
assert response.status_code == 200
|
||||
data = response.get_json()["data"]
|
||||
assert data["status"] == "published"
|
||||
assert data["request_spec_json"] == {"path": "/v1/new"}
|
||||
|
||||
|
||||
def test_update_binding(app, client, admin_headers):
|
||||
"""PUT /bindings/<id> → 200,更新映射版本/优先级/状态。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-B", "name": "cli", "connector_type": "rest", "environment": "prod",
|
||||
"config_json": {},
|
||||
})
|
||||
client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
|
||||
"code": "IF-B", "name": "iface", "client_instance_code": "CLI-B", "connector_type": "rest",
|
||||
})
|
||||
created = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={
|
||||
"capability": "in_transit_transfer.query_inventory", "client_instance_code": "CLI-B",
|
||||
"interface_definition_code": "IF-B", "status": "draft",
|
||||
})
|
||||
binding_id = created.get_json()["data"]["id"]
|
||||
response = client.put(f"{API_PREFIX}/bindings/{binding_id}", headers=admin_headers, json={
|
||||
"priority": 5, "mapping_version": 2, "status": "published",
|
||||
})
|
||||
assert response.status_code == 200
|
||||
data = response.get_json()["data"]
|
||||
assert data["priority"] == 5
|
||||
assert data["mapping_version"] == 2
|
||||
assert data["status"] == "published"
|
||||
|
||||
|
||||
def test_update_credential_reference(app, client, admin_headers):
|
||||
"""PUT /credential-references/<code> → 200,更新 secret_ref/status,且不回显明文。"""
|
||||
client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={
|
||||
"code": "CRED-U", "secret_ref": "IN_TRANSIT_ERP_PASSWORD",
|
||||
})
|
||||
response = client.put(f"{API_PREFIX}/credential-references/CRED-U", headers=admin_headers, json={
|
||||
"secret_ref": "IN_TRANSIT_ERP_PASSWORD_ROTATED", "status": "rotating",
|
||||
})
|
||||
assert response.status_code == 200
|
||||
data = response.get_json()["data"]
|
||||
assert data["secret_ref"] == "IN_TRANSIT_ERP_PASSWORD_ROTATED"
|
||||
assert data["status"] == "rotating"
|
||||
assert "secret" not in str(data).lower() or data.get("secret") is None
|
||||
|
||||
|
||||
def test_client_instance_split_columns(app, client, admin_headers):
|
||||
"""POST /client-instances 写 endpoint/timeout_seconds 独立列,config_json 仅存扩展。"""
|
||||
created = client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-COL", "name": "col client", "connector_type": "soap", "environment": "prod",
|
||||
"endpoint": "https://erp.invalid/wsdl", "timeout_seconds": 90,
|
||||
"config_json": {"headers": {"X-Tenant": "A"}},
|
||||
})
|
||||
assert created.status_code == 201
|
||||
data = created.get_json()["data"]
|
||||
assert data["endpoint"] == "https://erp.invalid/wsdl"
|
||||
assert data["timeout_seconds"] == 90
|
||||
assert data["config_json"] == {"headers": {"X-Tenant": "A"}}
|
||||
|
||||
updated = client.put(f"{API_PREFIX}/client-instances/CLI-COL", headers=admin_headers, json={
|
||||
"endpoint": "https://erp2.invalid/wsdl", "timeout_seconds": 120,
|
||||
})
|
||||
assert updated.status_code == 200
|
||||
assert updated.get_json()["data"]["endpoint"] == "https://erp2.invalid/wsdl"
|
||||
assert updated.get_json()["data"]["timeout_seconds"] == 120
|
||||
|
||||
|
||||
def test_interface_definition_split_columns(app, client, admin_headers):
|
||||
"""POST/PUT /interface-definitions 写 http_method/request_path 独立列。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-IF", "name": "cli", "connector_type": "rest", "environment": "prod",
|
||||
"endpoint": "https://erp.invalid",
|
||||
})
|
||||
created = client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
|
||||
"code": "IF-COL", "name": "iface", "client_instance_code": "CLI-IF", "connector_type": "rest",
|
||||
"http_method": "post", "request_path": "/transfer/{invoice_no}",
|
||||
"request_spec_json": {"template": {"qty": "{quantity}"}},
|
||||
})
|
||||
assert created.status_code == 201
|
||||
data = created.get_json()["data"]
|
||||
assert data["http_method"] == "POST"
|
||||
assert data["request_path"] == "/transfer/{invoice_no}"
|
||||
|
||||
updated = client.put(f"{API_PREFIX}/interface-definitions/IF-COL", headers=admin_headers, json={
|
||||
"http_method": "get", "request_path": "/inventory/{invoice_no}",
|
||||
})
|
||||
assert updated.status_code == 200
|
||||
assert updated.get_json()["data"]["http_method"] == "GET"
|
||||
assert updated.get_json()["data"]["request_path"] == "/inventory/{invoice_no}"
|
||||
|
||||
|
||||
def test_binding_split_columns(app, client, admin_headers):
|
||||
"""POST/PUT /bindings 写 context_source_code 独立列并回显。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-BC", "name": "cli", "connector_type": "rest", "environment": "prod",
|
||||
"endpoint": "https://erp.invalid",
|
||||
})
|
||||
client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
|
||||
"code": "IF-BC", "name": "iface", "client_instance_code": "CLI-BC", "connector_type": "rest",
|
||||
})
|
||||
created = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={
|
||||
"capability": "in_transit_transfer.query_inventory",
|
||||
"client_instance_code": "CLI-BC", "interface_definition_code": "IF-BC",
|
||||
"context_source_code": "DBS-AWSBI", "status": "published",
|
||||
})
|
||||
assert created.status_code == 201
|
||||
data = created.get_json()["data"]
|
||||
assert data["context_source_code"] == "DBS-AWSBI"
|
||||
|
||||
updated = client.put(f"{API_PREFIX}/bindings/{data['id']}", headers=admin_headers, json={
|
||||
"context_source_code": "CRANE-SZ",
|
||||
})
|
||||
assert updated.status_code == 200
|
||||
assert updated.get_json()["data"]["context_source_code"] == "CRANE-SZ"
|
||||
Reference in new issue
Block a user