feat(integration-connector): database 传输类型、两步绑定编排与调用日志捕获查询
- 新增 database 传输:直连 MySQL/Oracle/SQLServer/PostgreSQL 执行绑定 SQL(新增 pymysql/pymssql 驱动依赖) - 绑定支持 steps_json 多步编排:每步独立传输调用与审计,无 steps 的既有绑定走单步兼容路径 - 客户端实例校验 connector_type ∈ rest/soap/database,database 强制 db_kind 白名单,非 database 置空 - 三个传输层捕获线级事实(最终 SQL/渲染后 XML/原始响应)随调用记录落库,引擎可选透传 business_ref 业务锚点 - 新增调用日志查询 API(列表/详情/同 operation 步骤时间线,仅管理员)与管理端「调用日志」tab:筛选、双栏对照、外部工具复现命令 - 迁移 tt7a/tta9/tt5b:连接器类型枚举、绑定 steps_json、放开 calls 操作唯一约束 - 说明:wire_json 列迁移挂链尾(依赖域表迁移),随后续批次单独落地
This commit is contained in:
1 parent
8a814e7152
commit
e750fa8602
47 files changed
+7441
-353
No files matched your search
@@ -1,7 +1,8 @@
|
||||
"""tests/api/test_integration_connector_api.py
|
||||
|
||||
用途:Integration Connector Admin API 契约测试——能力清单、客户端 CRUD、能力调用、
|
||||
interface_id 拒绝、连接测试、鉴权(401/403)。依赖 Fake 网关注入。
|
||||
interface_id 拒绝、连接测试、集成调用日志查询(列表筛选/keyword/详情时间线)、
|
||||
鉴权(401/403)。依赖 Fake 网关注入。
|
||||
依赖:app fixture、client、issue_local_access_token、gateway 覆盖注入。
|
||||
逻辑:Admin API 全部 require_admin;能力调用只暴露 Capability,拒绝传 interface_id。
|
||||
"""
|
||||
@@ -12,7 +13,7 @@ import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.models import User
|
||||
from app.models import IntegrationCall, User
|
||||
from app.services.integration_connector.transports.base import IntegrationCallResult
|
||||
from app.services.integration_connector.gateway import set_capability_gateway
|
||||
|
||||
@@ -75,11 +76,11 @@ def _params():
|
||||
|
||||
|
||||
def test_list_capabilities(app, client, admin_headers):
|
||||
"""GET /capabilities → 200,含 3 个在途调拨能力。"""
|
||||
"""GET /capabilities → 200,含 2 个在途调拨能力(D13 收缩:读+写)。"""
|
||||
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)
|
||||
assert {"in_transit_transfer.query_inventory", "in_transit_transfer.create_transfer"}.issubset(names)
|
||||
|
||||
|
||||
def test_create_and_list_client_instance(app, client, admin_headers):
|
||||
@@ -187,6 +188,44 @@ def test_client_instance_test_connection_merges_endpoint_column(app, client, adm
|
||||
assert spy.seen["config_json"]["timeout_seconds"] == 45
|
||||
|
||||
|
||||
def test_client_instance_test_connection_resolves_credential_ref(app, client, admin_headers, fake_gateway):
|
||||
"""连接测试回归:有凭据引用时必须解析真实凭据传给 transport(与 engine 调用链同源)。
|
||||
|
||||
曾因测试端点恒传空 credential,数据库直连探针必然认证失败——
|
||||
连接测试按设计须证明「网络与认证」可用,无凭据无法建连。
|
||||
"""
|
||||
# env 模式凭据:secret_ref 指向 app config 键,避免解密依赖(db 模式解密另有专门测试)。
|
||||
client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={
|
||||
"code": "CRED-ENV", "secret_provider": "env", "secret_ref": "PROBE_TEST_CREDENTIAL",
|
||||
})
|
||||
created = client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-DB", "name": "db client", "connector_type": "database", "environment": "prod",
|
||||
"endpoint": "192.168.8.24:1521/topprod", "db_kind": "oracle",
|
||||
"credential_ref_code": "CRED-ENV",
|
||||
})
|
||||
assert created.status_code == 201
|
||||
|
||||
seen = {}
|
||||
|
||||
class DbSpyTransport:
|
||||
connector_type = "database"
|
||||
|
||||
def probe(self, *, client):
|
||||
seen.update(client)
|
||||
return {"ok": True, "code": "DB_PROBE_OK", "message": "ok"}
|
||||
|
||||
fake_gateway.transports["database"] = DbSpyTransport()
|
||||
with app.app_context():
|
||||
app.config["PROBE_TEST_CREDENTIAL"] = {"username": "erp_u", "password": "erp_p"}
|
||||
response = client.post(f"{API_PREFIX}/client-instances/CLI-DB/test", headers=admin_headers)
|
||||
|
||||
assert response.status_code == 200
|
||||
assert response.get_json()["data"]["ok"] is True
|
||||
# 凭据引用必须解析成真实凭据注入 transport(关键断言);db_kind 专列拼回 config_json。
|
||||
assert seen["credential"] == {"username": "erp_u", "password": "erp_p"}
|
||||
assert seen["config_json"]["db_kind"] == "oracle"
|
||||
|
||||
|
||||
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={
|
||||
@@ -534,7 +573,7 @@ def test_interface_definition_split_columns(app, client, admin_headers):
|
||||
# ---- 绑定参数映射 / 凭据 db 模式 ----
|
||||
|
||||
def test_binding_param_mapping_round_trip(app, client, admin_headers):
|
||||
"""POST/PUT /bindings 透传 param_mapping_json,序列化原样返回。"""
|
||||
"""POST/PUT /bindings:steps_json 携带 param_mapping;旧字段镜像首步。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-PM", "name": "cli", "connector_type": "rest", "environment": "prod",
|
||||
"endpoint": "https://erp.invalid",
|
||||
@@ -544,20 +583,238 @@ def test_binding_param_mapping_round_trip(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-PM", "interface_definition_code": "IFACE-PM",
|
||||
"param_mapping_json": {"organization": {"expr": "external_org"},
|
||||
"condition": {"template": "img04 = '{invoice_no}'"}},
|
||||
"steps_json": [{
|
||||
"interface_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["steps_json"][0]["param_mapping_json"]["organization"] == {"expr": "external_org"}
|
||||
assert data["param_mapping_json"]["organization"] == {"expr": "external_org"}
|
||||
assert data["interface_definition_code"] == "IFACE-PM"
|
||||
assert data["client_instance_code"] == "CLI-PM"
|
||||
|
||||
updated = client.put(f"{API_PREFIX}/bindings/{data['id']}", headers=admin_headers,
|
||||
json={"param_mapping_json": {"condition": {"template": "img02 = '{warehouse}'"}}})
|
||||
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"]["param_mapping_json"] == {
|
||||
body = updated.get_json()["data"]
|
||||
assert body["param_mapping_json"] == {
|
||||
"condition": {"template": "img02 = '{warehouse}'"},
|
||||
}
|
||||
assert body["steps_json"][0]["param_mapping_json"] == {
|
||||
"condition": {"template": "img02 = '{warehouse}'"},
|
||||
}
|
||||
|
||||
|
||||
def test_binding_steps_json_multi_step_and_validation(app, client, admin_headers):
|
||||
"""POST steps_json 多步落库;空数组/非法映射/缺失接口 → 400。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-S1", "name": "db", "connector_type": "database", "environment": "prod",
|
||||
"endpoint": "127.0.0.1:1521/ORCL", "db_kind": "oracle",
|
||||
})
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-S2", "name": "ws", "connector_type": "soap", "environment": "prod",
|
||||
"endpoint": "https://ws.invalid",
|
||||
})
|
||||
client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
|
||||
"code": "IF-S1", "name": "stage", "client_instance_code": "CLI-S1",
|
||||
})
|
||||
client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
|
||||
"code": "IF-S2", "name": "submit", "client_instance_code": "CLI-S2",
|
||||
})
|
||||
|
||||
created = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={
|
||||
"capability": "in_transit_transfer.create_transfer",
|
||||
"steps_json": [
|
||||
{"interface_code": "IF-S1", "param_mapping_json": {"maker": {"expr": "external_org"}}},
|
||||
{"interface_code": "IF-S2", "param_mapping_json": {}},
|
||||
],
|
||||
})
|
||||
assert created.status_code == 201
|
||||
data = created.get_json()["data"]
|
||||
assert len(data["steps_json"]) == 2
|
||||
assert data["steps_json"][0]["interface_code"] == "IF-S1"
|
||||
assert data["steps_json"][1]["interface_code"] == "IF-S2"
|
||||
# 旧列镜像首步(跨客户端绑定:首步 database)
|
||||
assert data["client_instance_code"] == "CLI-S1"
|
||||
assert data["interface_definition_code"] == "IF-S1"
|
||||
|
||||
empty = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={
|
||||
"capability": "in_transit_transfer.create_transfer",
|
||||
"steps_json": [],
|
||||
})
|
||||
assert empty.status_code == 400
|
||||
assert empty.get_json()["error"]["code"] == "INTEGRATION.BINDING_STEPS_INVALID"
|
||||
|
||||
bad_mapping = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={
|
||||
"capability": "in_transit_transfer.create_transfer",
|
||||
"steps_json": [{"interface_code": "IF-S1", "param_mapping_json": ["not", "dict"]}],
|
||||
})
|
||||
assert bad_mapping.status_code == 400
|
||||
assert bad_mapping.get_json()["error"]["code"] == "INTEGRATION.BINDING_STEPS_INVALID"
|
||||
|
||||
missing = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={
|
||||
"capability": "in_transit_transfer.create_transfer",
|
||||
"steps_json": [{"interface_code": "IF-NOPE", "param_mapping_json": {}}],
|
||||
})
|
||||
assert missing.status_code == 400
|
||||
assert missing.get_json()["error"]["code"] == "INTEGRATION.INTERFACE_NOT_FOUND"
|
||||
|
||||
# 发布门禁:两步接口均须 published
|
||||
binding_id = data["id"]
|
||||
not_ready = client.post(f"{API_PREFIX}/bindings/{binding_id}/publish", headers=admin_headers)
|
||||
assert not_ready.status_code == 400
|
||||
assert not_ready.get_json()["error"]["code"] == "INTEGRATION.BINDING_TARGET_NOT_READY"
|
||||
client.post(f"{API_PREFIX}/interface-definitions/IF-S1/publish", headers=admin_headers)
|
||||
still = client.post(f"{API_PREFIX}/bindings/{binding_id}/publish", headers=admin_headers)
|
||||
assert still.status_code == 400
|
||||
client.post(f"{API_PREFIX}/interface-definitions/IF-S2/publish", headers=admin_headers)
|
||||
ok_pub = client.post(f"{API_PREFIX}/bindings/{binding_id}/publish", headers=admin_headers)
|
||||
assert ok_pub.status_code == 200
|
||||
assert ok_pub.get_json()["data"]["status"] == "published"
|
||||
|
||||
|
||||
def test_binding_legacy_single_step_fields_still_accepted(app, client, admin_headers):
|
||||
"""兼容窗:无 steps_json 时旧 client+interface+param_mapping 合成单元素 steps。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-LEG", "name": "cli", "connector_type": "rest", "environment": "prod",
|
||||
"endpoint": "https://erp.invalid",
|
||||
})
|
||||
client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
|
||||
"code": "IF-LEG", "name": "iface", "client_instance_code": "CLI-LEG",
|
||||
})
|
||||
created = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={
|
||||
"capability": "in_transit_transfer.query_inventory",
|
||||
"client_instance_code": "CLI-LEG",
|
||||
"interface_definition_code": "IF-LEG",
|
||||
"param_mapping_json": {"org": {"expr": "external_org"}},
|
||||
})
|
||||
assert created.status_code == 201
|
||||
data = created.get_json()["data"]
|
||||
assert data["steps_json"] == [{
|
||||
"interface_code": "IF-LEG",
|
||||
"param_mapping_json": {"org": {"expr": "external_org"}},
|
||||
}]
|
||||
|
||||
|
||||
def _seed_two_step_binding(client, admin_headers):
|
||||
"""公共夹具:两客户端两接口 + 一个两步绑定(database 中间表 → soap 触发 WS)。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-P1", "name": "db", "connector_type": "database", "environment": "prod",
|
||||
"endpoint": "127.0.0.1:1521/ORCL", "db_kind": "oracle",
|
||||
})
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-P2", "name": "ws", "connector_type": "soap", "environment": "prod",
|
||||
"endpoint": "https://ws.invalid",
|
||||
})
|
||||
client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
|
||||
"code": "IF-P1", "name": "stage", "client_instance_code": "CLI-P1",
|
||||
})
|
||||
client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
|
||||
"code": "IF-P2", "name": "submit", "client_instance_code": "CLI-P2",
|
||||
})
|
||||
created = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={
|
||||
"capability": "in_transit_transfer.create_transfer",
|
||||
"steps_json": [
|
||||
{"interface_code": "IF-P1", "param_mapping_json": {"maker": {"expr": "external_org"}}},
|
||||
{"interface_code": "IF-P2", "param_mapping_json": {}},
|
||||
],
|
||||
})
|
||||
assert created.status_code == 201
|
||||
return created.get_json()["data"]["id"]
|
||||
|
||||
|
||||
def test_binding_legacy_put_rejected_on_multi_step(app, client, admin_headers):
|
||||
"""多步绑定 PUT 携带旧单步字段 → 400 BINDING_LEGACY_PUT_REJECTED(防截断多步配方)。"""
|
||||
binding_id = _seed_two_step_binding(client, admin_headers)
|
||||
|
||||
# 三把旧钥匙(interface_definition_code / param_mapping_json / client_instance_code)
|
||||
# 任一出现在多步绑定 PUT 均拒绝:都会经兼容窗合成单元素 steps 回写、静默销毁第 2..n 步
|
||||
for legacy_body in (
|
||||
{"interface_definition_code": "IF-P1"},
|
||||
{"param_mapping_json": {"org": {"expr": "external_org"}}},
|
||||
{"client_instance_code": "CLI-P2"},
|
||||
):
|
||||
rejected = client.put(f"{API_PREFIX}/bindings/{binding_id}", headers=admin_headers, json=legacy_body)
|
||||
assert rejected.status_code == 400
|
||||
assert rejected.get_json()["error"]["code"] == "INTEGRATION.BINDING_LEGACY_PUT_REJECTED"
|
||||
|
||||
# 多步配方未被截断
|
||||
listed = client.get(f"{API_PREFIX}/bindings", headers=admin_headers)
|
||||
row = next(item for item in listed.get_json()["data"] if item["id"] == binding_id)
|
||||
assert len(row["steps_json"]) == 2
|
||||
|
||||
# 纯 steps_json PUT 不受影响:整表替换且可重排
|
||||
reordered = client.put(f"{API_PREFIX}/bindings/{binding_id}", headers=admin_headers, json={
|
||||
"steps_json": [
|
||||
{"interface_code": "IF-P2", "param_mapping_json": {}},
|
||||
{"interface_code": "IF-P1", "param_mapping_json": {"maker": {"expr": "external_org"}}},
|
||||
],
|
||||
})
|
||||
assert reordered.status_code == 200
|
||||
assert [s["interface_code"] for s in reordered.get_json()["data"]["steps_json"]] == ["IF-P2", "IF-P1"]
|
||||
|
||||
|
||||
def test_binding_steps_json_with_legacy_keys_rejected(app, client, admin_headers):
|
||||
"""矛盾载荷:steps_json 与旧单步字段同 PUT → 400(防旧键被静默忽略、部分生效无提示)。"""
|
||||
binding_id = _seed_two_step_binding(client, admin_headers)
|
||||
|
||||
for conflicting_key in ("param_mapping_json", "interface_definition_code"):
|
||||
contradictory = client.put(f"{API_PREFIX}/bindings/{binding_id}", headers=admin_headers, json={
|
||||
"steps_json": [{"interface_code": "IF-P1", "param_mapping_json": {}}],
|
||||
conflicting_key: "IF-P1" if conflicting_key == "interface_definition_code" else {"x": {"expr": "y"}},
|
||||
})
|
||||
assert contradictory.status_code == 400
|
||||
assert contradictory.get_json()["error"]["code"] == "INTEGRATION.BINDING_LEGACY_PUT_REJECTED"
|
||||
|
||||
# 矛盾载荷未被部分应用:配方保持原两步(IF-P1 → IF-P2)
|
||||
listed = client.get(f"{API_PREFIX}/bindings", headers=admin_headers)
|
||||
row = next(item for item in listed.get_json()["data"] if item["id"] == binding_id)
|
||||
assert [s["interface_code"] for s in row["steps_json"]] == ["IF-P1", "IF-P2"]
|
||||
|
||||
# 对照:去掉旧键后同一 steps_json PUT 正常生效
|
||||
ok_put = client.put(f"{API_PREFIX}/bindings/{binding_id}", headers=admin_headers, json={
|
||||
"steps_json": [{"interface_code": "IF-P1", "param_mapping_json": {}}],
|
||||
})
|
||||
assert ok_put.status_code == 200
|
||||
|
||||
|
||||
def test_binding_legacy_put_compat_single_step(app, client, admin_headers):
|
||||
"""兼容窗:单步绑定旧字段 PUT 仍通(换绑接口 / 更新首步映射)。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-C1", "name": "cli", "connector_type": "rest", "environment": "prod",
|
||||
"endpoint": "https://erp.invalid",
|
||||
})
|
||||
for code in ("IF-C1", "IF-C2"):
|
||||
client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
|
||||
"code": code, "name": "iface", "client_instance_code": "CLI-C1",
|
||||
})
|
||||
created = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={
|
||||
"capability": "in_transit_transfer.query_inventory",
|
||||
"steps_json": [{"interface_code": "IF-C1", "param_mapping_json": {}}],
|
||||
})
|
||||
binding_id = created.get_json()["data"]["id"]
|
||||
|
||||
# 单步绑定换绑接口仍走兼容窗
|
||||
rebinding = client.put(f"{API_PREFIX}/bindings/{binding_id}", headers=admin_headers, json={
|
||||
"interface_definition_code": "IF-C2",
|
||||
})
|
||||
assert rebinding.status_code == 200
|
||||
assert rebinding.get_json()["data"]["interface_definition_code"] == "IF-C2"
|
||||
assert rebinding.get_json()["data"]["steps_json"][0]["interface_code"] == "IF-C2"
|
||||
|
||||
# 单步绑定仅更新映射仍走兼容窗(只更新首步映射)
|
||||
mapping = client.put(f"{API_PREFIX}/bindings/{binding_id}", headers=admin_headers, json={
|
||||
"param_mapping_json": {"a": {"expr": "x"}},
|
||||
})
|
||||
assert mapping.status_code == 200
|
||||
assert mapping.get_json()["data"]["steps_json"][0]["param_mapping_json"] == {"a": {"expr": "x"}}
|
||||
|
||||
|
||||
|
||||
def test_credential_db_mode_round_trip(app, client, admin_headers):
|
||||
@@ -629,3 +886,100 @@ def test_credential_db_mode_requires_username_and_password(app, client, admin_he
|
||||
"code": "CRED-DB2", "secret_provider": "db", "username": "only-user",
|
||||
})
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
# ---- 集成调用日志查询(Task 5)----
|
||||
|
||||
def _seed_integration_calls():
|
||||
"""集成调用日志查询造数:1 条无关能力 + 同一 operation_id 的两步(stage 成功 + ws 失败)。
|
||||
|
||||
与 engine._record_call 落库口径同构:binding_snapshot_json 含 client_code/
|
||||
interface_code/connector_type/step_index/step_count/steps;单号
|
||||
TGHX1-OR-26092600002 写入 request_summary_json 供 keyword 模糊命中。
|
||||
插入顺序:无关行最先、ws 步最后 → 详情用例取 id 最大行即 ws 步,
|
||||
timeline 覆盖同 operation 两步、wire_json 命中 dict 分支。
|
||||
|
||||
Returns:
|
||||
落库后的 [无关行, stage 步, ws 步] 三条 IntegrationCall。
|
||||
"""
|
||||
def _snap(interface_code, connector_type, step_index, step_count):
|
||||
return {
|
||||
'client_code': 'CLI-ERP',
|
||||
'interface_code': interface_code,
|
||||
'connector_type': connector_type,
|
||||
'step_index': step_index,
|
||||
'step_count': step_count,
|
||||
'steps': [
|
||||
{'interface_code': 'erp-db-stage-transfer',
|
||||
'client_code': 'CLI-ERP', 'connector_type': 'database'},
|
||||
{'interface_code': 'erp-ws-submit-transfer',
|
||||
'client_code': 'CLI-ERP', 'connector_type': 'soap'},
|
||||
][:step_count],
|
||||
}
|
||||
|
||||
rows = [
|
||||
# 无关能力行:不应被 interface_code=erp-ws-submit-transfer / operation 筛选命中
|
||||
IntegrationCall(
|
||||
operation_id='OP-OTHER', capability='in_transit_transfer.query_inventory',
|
||||
binding_snapshot_json=_snap('erp-db-query-stock', 'database', 0, 1),
|
||||
request_summary_json={'invoice_no': 'INV-OTHER-001'},
|
||||
response_summary_json={'found': True},
|
||||
status='success', elapsed_ms=12, trace_id='TRC-OTHER',
|
||||
),
|
||||
# 同一 operation_id 的第 1 步(database 中间表,成功)
|
||||
IntegrationCall(
|
||||
operation_id='OP-TGHX-26092600002', capability='in_transit_transfer.create_transfer',
|
||||
binding_snapshot_json=_snap('erp-db-stage-transfer', 'database', 0, 2),
|
||||
request_summary_json={'document_no': 'TGHX1-OR-26092600002', 'maker': 'HW'},
|
||||
response_summary_json={'inserted': 1},
|
||||
status='success', elapsed_ms=88, trace_id='TRC-STAGE',
|
||||
),
|
||||
# 同一 operation_id 的第 2 步(soap 触发 WS,失败;带线级事实 wire_json)
|
||||
IntegrationCall(
|
||||
operation_id='OP-TGHX-26092600002', capability='in_transit_transfer.create_transfer',
|
||||
binding_snapshot_json=_snap('erp-ws-submit-transfer', 'soap', 1, 2),
|
||||
request_summary_json={'document_no': 'TGHX1-OR-26092600002'},
|
||||
response_summary_json={'code': '504', 'message': 'ws timeout'},
|
||||
wire_json={'endpoint': 'https://ws.invalid/Service',
|
||||
'request_xml': '<soap/>', 'http_status': 504},
|
||||
status='technical_failed', elapsed_ms=5021, trace_id='TRC-WS',
|
||||
business_ref='TGHX1-OR-26092600002',
|
||||
),
|
||||
]
|
||||
db.session.add_all(rows)
|
||||
db.session.commit()
|
||||
return rows
|
||||
|
||||
|
||||
def test_list_calls_filters_by_interface_and_keyword(client, admin_headers):
|
||||
"""GET /calls?interface_code=… → 只命中快照含该接口的那一条(能力无关通用口径)。"""
|
||||
_seed_integration_calls()
|
||||
resp = client.get('/api/integration-connector/calls?interface_code=erp-ws-submit-transfer',
|
||||
headers=admin_headers)
|
||||
body = resp.get_json()['data']
|
||||
# 关键断言:interface_code 精确筛选走 binding_snapshot_json JSON 路径,
|
||||
# 三行里只有 ws 步快照带该接口 → total 恰为 1
|
||||
assert body['total'] == 1
|
||||
assert body['items'][0]['interface_code'] == 'erp-ws-submit-transfer'
|
||||
|
||||
|
||||
def test_list_calls_keyword_searches_request_summary(client, admin_headers):
|
||||
"""GET /calls?keyword=… → keyword 对 request_summary_json 文本化后模糊匹配。"""
|
||||
_seed_integration_calls()
|
||||
resp = client.get('/api/integration-connector/calls?keyword=TGHX1-OR-26092600002',
|
||||
headers=admin_headers)
|
||||
# 关键断言:单号只出现在两步的 request_summary_json 里 → 至少命中 1 条
|
||||
assert resp.get_json()['data']['total'] >= 1
|
||||
|
||||
|
||||
def test_call_detail_returns_wire_and_timeline(client, admin_headers):
|
||||
"""GET /calls/<id> → 单条全量(wire_json 透传)+ 同 operation_id 各步时间线。"""
|
||||
_seed_integration_calls()
|
||||
call = IntegrationCall.query.order_by(IntegrationCall.id.desc()).first()
|
||||
resp = client.get(f'/api/integration-connector/calls/{call.id}', headers=admin_headers)
|
||||
data = resp.get_json()['data']
|
||||
# 关键断言:详情返回所取行本身;wire_json 为 NULL 或 dict(JSON 列可空透传);
|
||||
# timeline 按 operation_id 串联——种子最大 id 是两步 operation 的末步 → 至少 1 步
|
||||
assert data['call']['id'] == call.id
|
||||
assert data['call']['wire_json'] is None or isinstance(data['call']['wire_json'], dict)
|
||||
assert len(data['timeline']) >= 1
|
||||
@@ -3,8 +3,8 @@
|
||||
用途:验证 Binding 解析与版本冻结——默认/上下文覆盖/优先级/生效区间/状态门禁/fail-closed。
|
||||
依赖:IntegrationBinding 等模型、binding.py、errors.py。
|
||||
逻辑:只匹配 published + environment + 生效区间 + context_selector 子集;
|
||||
接口定义须 published、客户端须 enabled,否则同样 fail-closed;
|
||||
无命中抛 BindingNotFoundError;快照冻结 interface 版本与配置(调用期冻结,非活表)。
|
||||
每步接口须 published、客户端须 enabled,否则同样 fail-closed;
|
||||
无命中抛 BindingNotFoundError;快照冻结 steps 与配置(调用期冻结,非活表)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -16,7 +16,7 @@ import pytest
|
||||
from app import db
|
||||
from app.core.errors import AppError
|
||||
from app.models import IntegrationBinding, IntegrationClientInstance, IntegrationInterfaceDefinition
|
||||
from app.services.integration_connector.binding import BindingSnapshot, resolve_binding
|
||||
from app.services.integration_connector.binding import resolve_binding
|
||||
|
||||
|
||||
def _client(code="CLI-A", **overrides):
|
||||
@@ -37,9 +37,26 @@ def _interface(code="IFACE-Q", **overrides):
|
||||
|
||||
|
||||
def _binding(capability="in_transit_transfer.query_inventory", **overrides):
|
||||
values = {"capability": capability, "context_selector_json": {},
|
||||
"client_instance_code": "CLI-A", "interface_definition_code": "IFACE-Q",
|
||||
"mapping_version": 2, "priority": 0, "environment": "prod", "status": "published"}
|
||||
"""构造单步绑定(steps_json 一元素);旧列镜像首步。"""
|
||||
iface_code = overrides.pop("interface_definition_code", "IFACE-Q")
|
||||
client_code = overrides.pop("client_instance_code", "CLI-A")
|
||||
param_mapping = overrides.pop("param_mapping_json", {})
|
||||
steps = overrides.pop(
|
||||
"steps_json",
|
||||
[{"interface_code": iface_code, "param_mapping_json": param_mapping}],
|
||||
)
|
||||
values = {
|
||||
"capability": capability,
|
||||
"context_selector_json": {},
|
||||
"steps_json": steps,
|
||||
"client_instance_code": client_code,
|
||||
"interface_definition_code": iface_code,
|
||||
"param_mapping_json": param_mapping,
|
||||
"mapping_version": 2,
|
||||
"priority": 0,
|
||||
"environment": "prod",
|
||||
"status": "published",
|
||||
}
|
||||
values.update(overrides)
|
||||
return IntegrationBinding(**values)
|
||||
|
||||
@@ -53,8 +70,9 @@ def test_default_binding_matches_any_context(app):
|
||||
"""空 context_selector 的默认绑定命中(context 含额外键也可命中)。"""
|
||||
_seed_default(app)
|
||||
snap = resolve_binding("in_transit_transfer.query_inventory", {"source_code": "DBS-AWSBI"}, "prod")
|
||||
assert snap.client_code == "CLI-A"
|
||||
assert snap.interface_code == "IFACE-Q"
|
||||
assert len(snap.steps) == 1
|
||||
assert snap.steps[0].client_code == "CLI-A"
|
||||
assert snap.steps[0].interface_code == "IFACE-Q"
|
||||
assert snap.mapping_version == 2
|
||||
|
||||
|
||||
@@ -117,10 +135,11 @@ def test_freeze_versions_in_snapshot(app):
|
||||
"""快照冻结 interface 版本与调用期配置(非活表)。"""
|
||||
_seed_default(app)
|
||||
snap = resolve_binding("in_transit_transfer.query_inventory", {}, "prod")
|
||||
assert snap.interface_version == 3
|
||||
assert snap.credential_ref_code is None
|
||||
assert snap.request_spec.get("path") == "/stock"
|
||||
assert snap.config.get("endpoint") == "https://erp.invalid"
|
||||
step = snap.steps[0]
|
||||
assert step.interface_version == 3
|
||||
assert step.credential_ref_code is None
|
||||
assert step.request_spec.get("path") == "/stock"
|
||||
assert step.config.get("endpoint") == "https://erp.invalid"
|
||||
|
||||
|
||||
def test_snapshot_carries_param_mapping_and_input_schema(app):
|
||||
@@ -132,8 +151,8 @@ def test_snapshot_carries_param_mapping_and_input_schema(app):
|
||||
])
|
||||
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"]}
|
||||
assert snap.steps[0].param_mapping == {"condition": {"template": "img04 = '{invoice_no}'"}}
|
||||
assert snap.steps[0].input_schema == {"type": "object", "required": ["condition"]}
|
||||
|
||||
|
||||
def test_draft_interface_not_matched(app):
|
||||
|
||||
@@ -0,0 +1,324 @@
|
||||
"""tests/services/integration_connector/test_binding_steps.py
|
||||
|
||||
用途:验证绑定一对多有序步骤(steps_json)——多步快照解析、逐项发布门禁、
|
||||
存量单步迁移形态、读能力单步兼容、空/非法步骤 fail-closed。
|
||||
依赖:IntegrationBinding 等模型、binding.BindingStep/BindingSnapshot/resolve_binding。
|
||||
逻辑:steps_json 为有序数组;每步自带 interface_code + param_mapping;
|
||||
客户端由接口归属推导;任一步接口未发布或客户端停用 → BindingNotFoundError。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError
|
||||
from app.models import IntegrationBinding, IntegrationClientInstance, IntegrationInterfaceDefinition
|
||||
from app.services.integration_connector.binding import BindingStep, resolve_binding
|
||||
|
||||
|
||||
def _client(code="CLI-A", **overrides):
|
||||
values = {
|
||||
"name": f"client {code}",
|
||||
"connector_type": "soap",
|
||||
"environment": "prod",
|
||||
"config_json": {"endpoint": "https://erp.invalid"},
|
||||
"enabled": True,
|
||||
}
|
||||
values.update(overrides)
|
||||
return IntegrationClientInstance(code=code, **values)
|
||||
|
||||
|
||||
def _interface(code="IFACE-Q", client_code="CLI-A", **overrides):
|
||||
values = {
|
||||
"name": f"iface {code}",
|
||||
"client_instance_code": client_code,
|
||||
"connector_type": "soap",
|
||||
"request_spec_json": {"method": "GET", "path": f"/{code}"},
|
||||
"input_schema_json": {},
|
||||
"response_mapping_json": {},
|
||||
"output_schema_json": {},
|
||||
"version": 1,
|
||||
"status": "published",
|
||||
}
|
||||
values.update(overrides)
|
||||
return IntegrationInterfaceDefinition(code=code, **values)
|
||||
|
||||
|
||||
def _binding(capability="in_transit_transfer.create_transfer", **overrides):
|
||||
"""构造绑定:默认两步 steps_json;旧列仍填首步以满足 NOT NULL(P2 删列前)。"""
|
||||
steps = overrides.pop(
|
||||
"steps_json",
|
||||
[
|
||||
{"interface_code": "IFACE-STAGE", "param_mapping_json": {"maker": {"expr": "external_org"}}},
|
||||
{"interface_code": "IFACE-SUBMIT", "param_mapping_json": {"source_ip": {"template": "0.0.0.0"}}},
|
||||
],
|
||||
)
|
||||
first = steps[0] if steps else {}
|
||||
first_iface = first.get("interface_code") or "IFACE-STAGE"
|
||||
first_mapping = first.get("param_mapping_json") or first.get("param_mapping") or {}
|
||||
if not isinstance(first_mapping, dict):
|
||||
first_mapping = {}
|
||||
values = {
|
||||
"capability": capability,
|
||||
"context_selector_json": {},
|
||||
"steps_json": steps,
|
||||
"client_instance_code": "CLI-DB",
|
||||
"interface_definition_code": first_iface,
|
||||
"param_mapping_json": first_mapping,
|
||||
"mapping_version": 1,
|
||||
"priority": 0,
|
||||
"environment": "prod",
|
||||
"status": "published",
|
||||
}
|
||||
values.update(overrides)
|
||||
values["steps_json"] = steps
|
||||
return IntegrationBinding(**values)
|
||||
|
||||
|
||||
def _seed_two_step(app):
|
||||
"""造两客户端 + 两接口 + 有序两步绑定(create_transfer 形态)。"""
|
||||
db.session.add_all([
|
||||
_client("CLI-DB", connector_type="database", endpoint="127.0.0.1:1521/ORCL",
|
||||
config_json={}, db_kind="oracle"),
|
||||
_client("CLI-WS", connector_type="soap", config_json={"endpoint": "https://ws.invalid"}),
|
||||
_interface("IFACE-STAGE", "CLI-DB", connector_type="database",
|
||||
request_spec_json={"sql": {"mode": "execute", "pre": [], "bulk": None, "post": []}}),
|
||||
_interface("IFACE-SUBMIT", "CLI-WS", connector_type="soap",
|
||||
request_spec_json={"method": "POST", "path": "/submit"}, version=5),
|
||||
_binding(),
|
||||
])
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def test_multi_step_snapshot_preserves_order_and_per_step_fields(app):
|
||||
"""多步绑定解析为 BindingStep 有序元组;每步独立 client/config/mapping。"""
|
||||
_seed_two_step(app)
|
||||
snap = resolve_binding("in_transit_transfer.create_transfer", {}, "prod")
|
||||
assert len(snap.steps) == 2
|
||||
assert all(isinstance(step, BindingStep) for step in snap.steps)
|
||||
# 顺序锁定:写中间表 → 触发 WS
|
||||
assert [s.interface_code for s in snap.steps] == ["IFACE-STAGE", "IFACE-SUBMIT"]
|
||||
assert snap.steps[0].connector_type == "database"
|
||||
assert snap.steps[0].client_code == "CLI-DB"
|
||||
assert snap.steps[0].param_mapping == {"maker": {"expr": "external_org"}}
|
||||
assert snap.steps[1].connector_type == "soap"
|
||||
assert snap.steps[1].client_code == "CLI-WS"
|
||||
assert snap.steps[1].param_mapping == {"source_ip": {"template": "0.0.0.0"}}
|
||||
assert snap.steps[1].request_spec.get("path") == "/submit"
|
||||
assert snap.mapping_version == 1
|
||||
|
||||
|
||||
def test_read_capability_single_step_shape(app):
|
||||
"""读能力单步绑定:steps 恰一元素,形状与多步统一(无扁平遗留字段依赖)。"""
|
||||
db.session.add_all([
|
||||
_client(),
|
||||
_interface(code="IFACE-Q", version=3,
|
||||
response_mapping_json={"qty": {"expr": "quantity"}},
|
||||
request_spec_json={"method": "GET", "path": "/stock"}),
|
||||
IntegrationBinding(
|
||||
capability="in_transit_transfer.query_inventory",
|
||||
context_selector_json={},
|
||||
steps_json=[{"interface_code": "IFACE-Q", "param_mapping_json": {"condition": {"expr": "invoice_no"}}}],
|
||||
client_instance_code="CLI-A",
|
||||
interface_definition_code="IFACE-Q",
|
||||
param_mapping_json={"condition": {"expr": "invoice_no"}},
|
||||
mapping_version=2,
|
||||
priority=0,
|
||||
environment="prod",
|
||||
status="published",
|
||||
),
|
||||
])
|
||||
db.session.commit()
|
||||
snap = resolve_binding("in_transit_transfer.query_inventory", {"source_code": "X"}, "prod")
|
||||
assert len(snap.steps) == 1
|
||||
step = snap.steps[0]
|
||||
assert step.interface_code == "IFACE-Q"
|
||||
assert step.client_code == "CLI-A"
|
||||
assert step.param_mapping == {"condition": {"expr": "invoice_no"}}
|
||||
assert step.request_spec.get("path") == "/stock"
|
||||
assert snap.capability == "in_transit_transfer.query_inventory"
|
||||
|
||||
|
||||
def test_legacy_columns_fallback_to_one_element_steps(app):
|
||||
"""存量单步:steps_json 空时由旧列合成单元素步骤(迁移兜底 / 兼容窗)。"""
|
||||
db.session.add_all([
|
||||
_client(),
|
||||
_interface(code="IFACE-LEGACY"),
|
||||
IntegrationBinding(
|
||||
capability="in_transit_transfer.query_inventory",
|
||||
context_selector_json={},
|
||||
steps_json=[], # 空:模拟迁移前或未回填
|
||||
client_instance_code="CLI-A",
|
||||
interface_definition_code="IFACE-LEGACY",
|
||||
param_mapping_json={"org": {"expr": "external_org"}},
|
||||
mapping_version=1,
|
||||
priority=0,
|
||||
environment="prod",
|
||||
status="published",
|
||||
),
|
||||
])
|
||||
db.session.commit()
|
||||
snap = resolve_binding("in_transit_transfer.query_inventory", {}, "prod")
|
||||
assert len(snap.steps) == 1
|
||||
assert snap.steps[0].interface_code == "IFACE-LEGACY"
|
||||
assert snap.steps[0].param_mapping == {"org": {"expr": "external_org"}}
|
||||
|
||||
|
||||
def test_gate_rejects_when_any_step_interface_not_published(app):
|
||||
"""门禁:第二步接口 draft → 整绑定 fail-closed(BindingNotFoundError)。"""
|
||||
db.session.add_all([
|
||||
_client("CLI-DB", connector_type="database", endpoint="127.0.0.1:1521/ORCL",
|
||||
config_json={}, db_kind="oracle"),
|
||||
_client("CLI-WS", connector_type="soap", config_json={"endpoint": "https://ws.invalid"}),
|
||||
_interface("IFACE-STAGE", "CLI-DB", connector_type="database"),
|
||||
_interface("IFACE-SUBMIT", "CLI-WS", status="draft"), # 末步未发布
|
||||
_binding(),
|
||||
])
|
||||
db.session.commit()
|
||||
with pytest.raises(AppError) as exc:
|
||||
resolve_binding("in_transit_transfer.create_transfer", {}, "prod")
|
||||
assert exc.value.code == "INTEGRATION.BINDING_NOT_FOUND"
|
||||
|
||||
|
||||
def test_gate_rejects_when_any_step_client_disabled(app):
|
||||
"""门禁:任一步客户端 enabled=False → BindingNotFoundError。"""
|
||||
db.session.add_all([
|
||||
_client("CLI-DB", connector_type="database", endpoint="127.0.0.1:1521/ORCL",
|
||||
config_json={}, db_kind="oracle"),
|
||||
_client("CLI-WS", connector_type="soap", config_json={"endpoint": "https://ws.invalid"},
|
||||
enabled=False),
|
||||
_interface("IFACE-STAGE", "CLI-DB", connector_type="database"),
|
||||
_interface("IFACE-SUBMIT", "CLI-WS"),
|
||||
_binding(),
|
||||
])
|
||||
db.session.commit()
|
||||
with pytest.raises(AppError) as exc:
|
||||
resolve_binding("in_transit_transfer.create_transfer", {}, "prod")
|
||||
assert exc.value.code == "INTEGRATION.BINDING_NOT_FOUND"
|
||||
|
||||
|
||||
def test_gate_rejects_missing_step_interface(app):
|
||||
"""门禁:步骤引用的接口不存在 → BindingNotFoundError。"""
|
||||
db.session.add_all([
|
||||
_client("CLI-DB", connector_type="database", endpoint="127.0.0.1:1521/ORCL",
|
||||
config_json={}, db_kind="oracle"),
|
||||
_interface("IFACE-STAGE", "CLI-DB", connector_type="database"),
|
||||
_binding(steps_json=[
|
||||
{"interface_code": "IFACE-STAGE", "param_mapping_json": {}},
|
||||
{"interface_code": "IFACE-MISSING", "param_mapping_json": {}},
|
||||
]),
|
||||
])
|
||||
db.session.commit()
|
||||
with pytest.raises(AppError) as exc:
|
||||
resolve_binding("in_transit_transfer.create_transfer", {}, "prod")
|
||||
assert exc.value.code == "INTEGRATION.BINDING_NOT_FOUND"
|
||||
|
||||
|
||||
def test_empty_steps_without_legacy_columns_raises(app):
|
||||
"""无步骤且旧列也无法兜底时 fail-closed(禁止静默空配方)。"""
|
||||
db.session.add_all([
|
||||
_client(),
|
||||
_interface(),
|
||||
IntegrationBinding(
|
||||
capability="in_transit_transfer.query_inventory",
|
||||
context_selector_json={},
|
||||
steps_json=[],
|
||||
client_instance_code="CLI-A",
|
||||
interface_definition_code="IFACE-Q",
|
||||
param_mapping_json={},
|
||||
mapping_version=1,
|
||||
priority=0,
|
||||
environment="prod",
|
||||
status="published",
|
||||
),
|
||||
])
|
||||
# 故意把旧列指向不存在的接口,阻断兜底
|
||||
row = IntegrationBinding.query.filter_by(capability="in_transit_transfer.query_inventory").first()
|
||||
row.interface_definition_code = "IFACE-GONE"
|
||||
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"
|
||||
|
||||
|
||||
# ---- 迁移契约(tta9b0c1d2e3):加列 + 存量行回填单步数组 ----
|
||||
|
||||
VERSIONS_DIR = Path(__file__).parents[3] / 'migrations' / 'versions'
|
||||
STEPS_MIGRATION_FILE = 'tta9b0c1d2e3_add_binding_steps_json.py'
|
||||
|
||||
|
||||
def _load_steps_migration():
|
||||
"""加载 binding steps_json 迁移模块(数据迁移须可脱离 Alembic 运行环境独立验证)。"""
|
||||
path = VERSIONS_DIR / STEPS_MIGRATION_FILE
|
||||
spec = importlib.util.spec_from_file_location('tta9b0c1d2e3_migration', path)
|
||||
assert spec is not None and spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def test_steps_migration_chain_contract():
|
||||
"""迁移链契约:revision=tta9b0c1d2e3,down_revision=tt7a8b9c0d1e(Task 1 之后单线)。"""
|
||||
migration = _load_steps_migration()
|
||||
assert migration.revision == 'tta9b0c1d2e3'
|
||||
assert migration.down_revision == 'tt7a8b9c0d1e'
|
||||
assert callable(migration.upgrade) and callable(migration.downgrade)
|
||||
|
||||
|
||||
def test_steps_migration_backfills_legacy_rows_as_single_step_array():
|
||||
"""存量行回填契约:旧列 → [{"interface_code", "param_mapping_json"}],mapping 须为 dict。
|
||||
|
||||
在内存 SQLite 真实执行 upgrade/downgrade(非仅源码断言):原生 SELECT 绕过 ORM
|
||||
类型层,JSON 列读回是文本,若不还原为 dict 直接回填,解析层会按
|
||||
param_mapping_not_dict fail-closed(存量绑定全部失效);NULL mapping 回填 {};
|
||||
downgrade 仅删 steps_json,旧单步列保留。
|
||||
"""
|
||||
migration = _load_steps_migration()
|
||||
engine = sa.create_engine('sqlite://')
|
||||
with engine.connect() as conn:
|
||||
conn.execute(sa.text(
|
||||
"CREATE TABLE integration_bindings ("
|
||||
" id INTEGER PRIMARY KEY, capability VARCHAR(128) NOT NULL,"
|
||||
" client_instance_code VARCHAR(64) NOT NULL,"
|
||||
" interface_definition_code VARCHAR(64) NOT NULL,"
|
||||
" param_mapping_json TEXT)"
|
||||
))
|
||||
# 行 1 模拟 ORM(JSON 列) 已写入的存量映射;行 2 模拟 NULL 映射
|
||||
conn.execute(sa.text(
|
||||
"INSERT INTO integration_bindings (id, capability, client_instance_code,"
|
||||
" interface_definition_code, param_mapping_json) VALUES"
|
||||
" (1,'cap.a','CLI-A','IFACE-Q','{\"org\": \"HX-CN01\"}'),"
|
||||
" (2,'cap.b','CLI-B','IFACE-R',NULL)"
|
||||
))
|
||||
conn.commit()
|
||||
mc = MigrationContext.configure(conn)
|
||||
with Operations.context(mc) as op:
|
||||
migration.upgrade()
|
||||
conn.commit()
|
||||
rows = conn.execute(
|
||||
sa.text('SELECT id, steps_json FROM integration_bindings ORDER BY id')
|
||||
).fetchall()
|
||||
# 断言 1:存量行回填为单元素数组,形状 {interface_code, param_mapping_json} 且映射为 dict
|
||||
assert json.loads(rows[0][1]) == [
|
||||
{"interface_code": "IFACE-Q", "param_mapping_json": {"org": "HX-CN01"}},
|
||||
]
|
||||
# 断言 2:NULL 映射回填为空对象(同样必须是 dict 而非 JSON 文本)
|
||||
assert json.loads(rows[1][1]) == [
|
||||
{"interface_code": "IFACE-R", "param_mapping_json": {}},
|
||||
]
|
||||
with Operations.context(mc) as op:
|
||||
migration.downgrade()
|
||||
conn.commit()
|
||||
# 断言 3:downgrade 删 steps_json,旧单步列仍在(P2 前保持可服务)
|
||||
cols = [r[1] for r in conn.execute(
|
||||
sa.text('PRAGMA table_info(integration_bindings)')).fetchall()]
|
||||
assert 'steps_json' not in cols
|
||||
assert 'interface_definition_code' in cols and 'param_mapping_json' in cols
|
||||
@@ -0,0 +1,211 @@
|
||||
"""tests/services/integration_connector/test_database_connector_type.py
|
||||
|
||||
用途:Task 1——database 连接器类型注册回归:模型常量、db_kind 专列、API 必填/枚举、
|
||||
迁移链与 CHECK 重建。
|
||||
依赖:app fixture、IntegrationClientInstance、API Blueprint 常量、Alembic 迁移模块。
|
||||
逻辑:先断言 CONNECTOR_TYPES / VALID_CONNECTOR_TYPES 含 database 且同源;再断言
|
||||
db_kind 列可落库;API create/update 对 database 必填且四库枚举 fail-closed,
|
||||
非 database 强制置 NULL;迁移挂接当前 head 并加列+重建两表 CHECK。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
from app import db
|
||||
from app.api.integration_connector import VALID_CONNECTOR_TYPES, VALID_DB_KINDS
|
||||
from app.core.auth.jwt import issue_local_access_token
|
||||
from app.models import IntegrationClientInstance, User
|
||||
from app.models.integration_connector import CONNECTOR_TYPES, DB_KINDS
|
||||
|
||||
API_PREFIX = '/api/integration-connector'
|
||||
VERSIONS_DIR = Path(__file__).parents[3] / 'migrations' / 'versions'
|
||||
MIGRATION_FILE = 'tt7a8b9c0d1e_add_database_connector_type.py'
|
||||
|
||||
|
||||
def _load_migration():
|
||||
"""加载 database 连接器类型迁移模块。"""
|
||||
path = VERSIONS_DIR / MIGRATION_FILE
|
||||
spec = importlib.util.spec_from_file_location('tt7a8b9c0d1e_migration', path)
|
||||
assert spec is not None and spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def admin_headers(app):
|
||||
"""发放 admin Bearer,供客户端实例 API 用例复用。"""
|
||||
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'}
|
||||
|
||||
|
||||
def test_connector_types_include_database():
|
||||
"""模型 CONNECTOR_TYPES 必须含 database,且与 API 白名单同源。"""
|
||||
assert 'database' in CONNECTOR_TYPES
|
||||
assert CONNECTOR_TYPES == ('rest', 'soap', 'database')
|
||||
assert VALID_CONNECTOR_TYPES == CONNECTOR_TYPES
|
||||
|
||||
|
||||
def test_db_kinds_enum_four_values():
|
||||
"""db_kind 四库枚举为 mysql/oracle/sqlserver/postgresql(非 mssql),模型与 API 同源。"""
|
||||
assert DB_KINDS == ('mysql', 'oracle', 'sqlserver', 'postgresql')
|
||||
assert VALID_DB_KINDS == DB_KINDS
|
||||
assert 'mssql' not in DB_KINDS
|
||||
|
||||
|
||||
def test_client_instance_accepts_database_type_with_db_kind(app):
|
||||
"""connector_type=database + 合法 db_kind 可落库;响应可回读。"""
|
||||
client = IntegrationClientInstance(
|
||||
code='ERP-ORA-01',
|
||||
name='Oracle ERP',
|
||||
connector_type='database',
|
||||
environment='prod',
|
||||
endpoint='erp.invalid:1521/ORCL',
|
||||
db_kind='oracle',
|
||||
config_json={},
|
||||
)
|
||||
db.session.add(client)
|
||||
db.session.commit()
|
||||
loaded = IntegrationClientInstance.query.filter_by(code='ERP-ORA-01').one()
|
||||
assert loaded.connector_type == 'database'
|
||||
assert loaded.db_kind == 'oracle'
|
||||
|
||||
|
||||
def test_api_create_database_requires_db_kind(app, client, admin_headers):
|
||||
"""POST database 缺 db_kind → 400 ValidationError。"""
|
||||
response = client.post(f'{API_PREFIX}/client-instances', headers=admin_headers, json={
|
||||
'code': 'DB-NO-KIND', 'name': 'no kind', 'connector_type': 'database',
|
||||
'endpoint': 'host:3306/db',
|
||||
})
|
||||
assert response.status_code == 400
|
||||
body = response.get_json()
|
||||
assert body['success'] is False
|
||||
|
||||
|
||||
def test_api_create_database_rejects_unknown_db_kind(app, client, admin_headers):
|
||||
"""POST database + 未知 db_kind(含历史别名 mssql)→ 400 fail-closed。"""
|
||||
for bad in ('mssql', 'sqlite', 'mongo', ''):
|
||||
response = client.post(f'{API_PREFIX}/client-instances', headers=admin_headers, json={
|
||||
'code': f'DB-BAD-{bad or "empty"}', 'name': 'bad', 'connector_type': 'database',
|
||||
'endpoint': 'host:1433/db', 'db_kind': bad,
|
||||
})
|
||||
assert response.status_code == 400, bad
|
||||
|
||||
|
||||
@pytest.mark.parametrize('db_kind', list(DB_KINDS))
|
||||
def test_api_create_database_accepts_four_kinds(app, client, admin_headers, db_kind):
|
||||
"""POST database + 四库之一 → 201,序列化含 db_kind。"""
|
||||
response = client.post(f'{API_PREFIX}/client-instances', headers=admin_headers, json={
|
||||
'code': f'DB-OK-{db_kind}', 'name': f'{db_kind} client',
|
||||
'connector_type': 'database', 'environment': 'dev',
|
||||
'endpoint': 'host:5432/app', 'db_kind': db_kind,
|
||||
})
|
||||
assert response.status_code == 201
|
||||
data = response.get_json()['data']
|
||||
assert data['connector_type'] == 'database'
|
||||
assert data['db_kind'] == db_kind
|
||||
|
||||
|
||||
def test_api_non_database_forces_db_kind_null(app, client, admin_headers):
|
||||
"""rest/soap 创建时即使传 db_kind 也强制置 NULL(不进库、不回显有效值)。"""
|
||||
created = client.post(f'{API_PREFIX}/client-instances', headers=admin_headers, json={
|
||||
'code': 'REST-FORCE-NULL', 'name': 'rest', 'connector_type': 'rest',
|
||||
'endpoint': 'https://api.invalid', 'db_kind': 'oracle',
|
||||
})
|
||||
assert created.status_code == 201
|
||||
assert created.get_json()['data']['db_kind'] is None
|
||||
|
||||
row = IntegrationClientInstance.query.filter_by(code='REST-FORCE-NULL').one()
|
||||
assert row.db_kind is None
|
||||
|
||||
|
||||
def test_api_update_database_requires_valid_db_kind(app, client, admin_headers):
|
||||
"""PUT 切到 database 缺/非法 db_kind → 400;合法则落库。"""
|
||||
client.post(f'{API_PREFIX}/client-instances', headers=admin_headers, json={
|
||||
'code': 'CLI-UPD', 'name': 'upd', 'connector_type': 'rest',
|
||||
'endpoint': 'https://api.invalid',
|
||||
})
|
||||
missing = client.put(f'{API_PREFIX}/client-instances/CLI-UPD', headers=admin_headers, json={
|
||||
'connector_type': 'database', 'endpoint': 'host:1521/ORCL',
|
||||
})
|
||||
assert missing.status_code == 400
|
||||
|
||||
bad = client.put(f'{API_PREFIX}/client-instances/CLI-UPD', headers=admin_headers, json={
|
||||
'connector_type': 'database', 'endpoint': 'host:1521/ORCL', 'db_kind': 'mssql',
|
||||
})
|
||||
assert bad.status_code == 400
|
||||
|
||||
ok = client.put(f'{API_PREFIX}/client-instances/CLI-UPD', headers=admin_headers, json={
|
||||
'connector_type': 'database', 'endpoint': 'host:1521/ORCL', 'db_kind': 'oracle',
|
||||
})
|
||||
assert ok.status_code == 200
|
||||
assert ok.get_json()['data']['db_kind'] == 'oracle'
|
||||
|
||||
|
||||
def test_api_update_away_from_database_clears_db_kind(app, client, admin_headers):
|
||||
"""从 database 改回 rest 时强制清空 db_kind。"""
|
||||
client.post(f'{API_PREFIX}/client-instances', headers=admin_headers, json={
|
||||
'code': 'CLI-CLR', 'name': 'clr', 'connector_type': 'database',
|
||||
'endpoint': 'host:3306/db', 'db_kind': 'mysql',
|
||||
})
|
||||
updated = client.put(f'{API_PREFIX}/client-instances/CLI-CLR', headers=admin_headers, json={
|
||||
'connector_type': 'rest', 'endpoint': 'https://api.invalid',
|
||||
})
|
||||
assert updated.status_code == 200
|
||||
assert updated.get_json()['data']['db_kind'] is None
|
||||
|
||||
|
||||
def test_migration_chains_after_current_head():
|
||||
"""迁移 revision=tt7a8b9c0d1e,down_revision 指向 flask db heads 当前 head。"""
|
||||
migration = _load_migration()
|
||||
assert migration.revision == 'tt7a8b9c0d1e'
|
||||
assert migration.down_revision == 'rn1a2b3c4d5e6'
|
||||
|
||||
|
||||
def test_migration_rebuilds_checks_and_adds_db_kind_contract():
|
||||
"""迁移源码契约:两表 CHECK 含 database、加 db_kind;SQLite 验证列往返。
|
||||
|
||||
生产目标为 PostgreSQL(drop/create CHECK);SQLite 不支持 DROP CHECK,
|
||||
故不对整段 upgrade 做内存库执行,仅断言源码步骤 + 加列/删列往返。
|
||||
"""
|
||||
migration = _load_migration()
|
||||
source = (VERSIONS_DIR / MIGRATION_FILE).read_text(encoding='utf-8')
|
||||
assert "connector_type IN ('rest', 'soap', 'database')" in source
|
||||
assert "connector_type IN ('rest', 'soap')" in source
|
||||
assert 'ck_integration_client_instances_connector_type' in source
|
||||
assert 'ck_integration_interface_definitions_connector_type' in source
|
||||
assert 'op.add_column' in source and 'db_kind' in source
|
||||
assert 'op.drop_constraint' in source and 'op.create_check_constraint' in source
|
||||
assert callable(migration.upgrade) and callable(migration.downgrade)
|
||||
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
with engine.begin() as connection:
|
||||
connection.execute(sa.text(
|
||||
'CREATE TABLE integration_client_instances ('
|
||||
'id INTEGER PRIMARY KEY, code VARCHAR(64) NOT NULL)'
|
||||
))
|
||||
context = MigrationContext.configure(connection)
|
||||
operations = Operations(context)
|
||||
operations.add_column(
|
||||
'integration_client_instances',
|
||||
sa.Column('db_kind', sa.String(length=32), nullable=True),
|
||||
)
|
||||
cols = {c['name'] for c in sa.inspect(connection).get_columns('integration_client_instances')}
|
||||
assert 'db_kind' in cols
|
||||
operations.drop_column('integration_client_instances', 'db_kind')
|
||||
cols_after = {c['name'] for c in sa.inspect(connection).get_columns('integration_client_instances')}
|
||||
assert 'db_kind' not in cols_after
|
||||
@@ -0,0 +1,834 @@
|
||||
"""tests/services/integration_connector/test_database_transport.py
|
||||
|
||||
用途:Task 2——DatabaseTransport 四库驱动注册表、execute/query/probe、D17 标识符替换、
|
||||
D12 业务无关回归锁;并覆盖 merge_client_config 拼入 db_kind。
|
||||
依赖:transports.database、transports.base、errors、unittest.mock / monkeypatch。
|
||||
逻辑:连接工厂一律替身(monkeypatch `_DRIVERS` 或底层驱动 connect);断言执行顺序、
|
||||
事务 commit/不 commit、脱敏、endpoint 拆解、标识符 fail-closed 与源码无业务词;
|
||||
StrictFakeCursor 断言 bind 键 ⊆ SQL 占位符(标识符键须剔除)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import inspect
|
||||
import re
|
||||
from typing import Any
|
||||
from unittest.mock import MagicMock
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.integration_connector.errors import InputInvalidError, TransportNotFrozenError
|
||||
from app.services.integration_connector.transports import database as database_mod
|
||||
from app.services.integration_connector.transports.base import merge_client_config
|
||||
from app.services.integration_connector.transports.database import DatabaseTransport, _DRIVERS
|
||||
|
||||
# 与驱动 :name 风格一致,用于严格游标校验 bind 键 ⊆ SQL 占位符
|
||||
_BIND_PLACEHOLDER_RE = re.compile(r':([A-Za-z_][A-Za-z0-9_]*)')
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 连接/游标替身
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class FakeCursor:
|
||||
"""记录 execute/executemany,供断言 SQL 顺序与参数合并。"""
|
||||
|
||||
def __init__(self, rows: list[tuple] | None = None, description: list | None = None):
|
||||
self.calls: list[tuple[str, Any, Any]] = []
|
||||
self._rows = list(rows or [])
|
||||
self.description = description
|
||||
self.closed = False
|
||||
|
||||
def execute(self, sql, params=None):
|
||||
self.calls.append(('execute', sql, params))
|
||||
|
||||
def executemany(self, sql, seq_of_params):
|
||||
self.calls.append(('executemany', sql, list(seq_of_params)))
|
||||
|
||||
def fetchall(self):
|
||||
return list(self._rows)
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
|
||||
class StrictFakeCursor(FakeCursor):
|
||||
"""严格游标:断言每次 bind dict 的键 ⊆ SQL 中 `:name` 占位符(模拟 oracledb)。"""
|
||||
|
||||
@staticmethod
|
||||
def _assert_bind_keys_subset(sql: str, params: dict | None) -> None:
|
||||
"""校验 params 键均出现在 SQL `:bind` 中,禁止残留 `schema` 等标识符键。"""
|
||||
if params is None:
|
||||
return
|
||||
allowed = set(_BIND_PLACEHOLDER_RE.findall(sql))
|
||||
extras = set(params) - allowed
|
||||
assert not extras, (
|
||||
f'extra bind keys {sorted(extras)!r} not in SQL placeholders '
|
||||
f'{sorted(allowed)!r}; sql={sql!r}'
|
||||
)
|
||||
|
||||
def execute(self, sql, params=None):
|
||||
self._assert_bind_keys_subset(sql, params if isinstance(params, dict) else None)
|
||||
super().execute(sql, params)
|
||||
|
||||
def executemany(self, sql, seq_of_params):
|
||||
for row in list(seq_of_params or []):
|
||||
if isinstance(row, dict):
|
||||
self._assert_bind_keys_subset(sql, row)
|
||||
super().executemany(sql, seq_of_params)
|
||||
|
||||
|
||||
class FakeConn:
|
||||
"""单事务替身:记录 commit/rollback/close。"""
|
||||
|
||||
def __init__(self, cursor: FakeCursor | None = None):
|
||||
self._cursor = cursor or FakeCursor()
|
||||
self.committed = False
|
||||
self.rolled_back = False
|
||||
self.closed = False
|
||||
|
||||
def cursor(self):
|
||||
return self._cursor
|
||||
|
||||
def commit(self):
|
||||
self.committed = True
|
||||
|
||||
def rollback(self):
|
||||
self.rolled_back = True
|
||||
|
||||
def close(self):
|
||||
self.closed = True
|
||||
|
||||
|
||||
def _client(
|
||||
*,
|
||||
endpoint: str = 'db.invalid:3306/appdb',
|
||||
db_kind: str = 'mysql',
|
||||
username: str = 'u1',
|
||||
password: str = 'secret-pass',
|
||||
extra_config: dict | None = None,
|
||||
) -> dict:
|
||||
"""构造已拼回 config 的客户端 payload(模拟 merge_client_config 之后)。"""
|
||||
cfg = {'endpoint': endpoint, 'db_kind': db_kind, 'timeout_seconds': 30}
|
||||
if extra_config:
|
||||
cfg.update(extra_config)
|
||||
return {'config_json': cfg, 'credential': {'username': username, 'password': password}}
|
||||
|
||||
|
||||
def _iface_execute(**sql_overrides) -> dict:
|
||||
"""执行型 request_spec:pre → bulk → post。"""
|
||||
sql = {
|
||||
'mode': 'execute',
|
||||
'pre': ['DELETE FROM t WHERE batch=:batch'],
|
||||
'bulk': {'sql': 'INSERT INTO t (batch, sku) VALUES (:batch, :sku)', 'rows_param': 'lines'},
|
||||
'post': ['UPDATE t SET done=1 WHERE batch=:batch'],
|
||||
'identifiers': [],
|
||||
}
|
||||
sql.update(sql_overrides)
|
||||
return {'request_spec_json': {'sql': sql}}
|
||||
|
||||
|
||||
def _iface_query(sql: str = 'SELECT sku AS sku, qty AS qty FROM t', identifiers=None) -> dict:
|
||||
"""查询型 request_spec。"""
|
||||
node = {'mode': 'query', 'sql': sql}
|
||||
if identifiers is not None:
|
||||
node['identifiers'] = identifiers
|
||||
return {'request_spec_json': {'sql': node}}
|
||||
|
||||
|
||||
def _patch_driver(monkeypatch, db_kind: str, connect_fn, probe_sql: str | None = None):
|
||||
"""用替身 connect 覆盖指定库的 DriverSpec,保留/覆盖 probe_sql。"""
|
||||
original = _DRIVERS[db_kind]
|
||||
spec = database_mod.DriverSpec(
|
||||
connect=connect_fn,
|
||||
probe_sql=probe_sql if probe_sql is not None else original.probe_sql,
|
||||
)
|
||||
monkeypatch.setitem(database_mod._DRIVERS, db_kind, spec)
|
||||
return spec
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ① execute:pre→bulk→post + commit + bulk 行合并基础参数
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_execute_pre_bulk_post_commit_and_merge_base_params(monkeypatch):
|
||||
"""execute 按 pre→bulk→post 顺序执行,bulk 行与基础参数合并(行内覆盖),最终 commit。"""
|
||||
conn = FakeConn()
|
||||
|
||||
def fake_connect(**kwargs):
|
||||
return conn
|
||||
|
||||
_patch_driver(monkeypatch, 'mysql', fake_connect)
|
||||
transport = DatabaseTransport()
|
||||
result = transport.call(
|
||||
client=_client(db_kind='mysql'),
|
||||
interface=_iface_execute(),
|
||||
request={
|
||||
'params': {
|
||||
'batch': 'B1',
|
||||
'lines': [
|
||||
{'sku': 'S1'},
|
||||
{'sku': 'S2', 'batch': 'OVERRIDE'},
|
||||
],
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
assert result['status'] == 'success'
|
||||
assert conn.committed is True
|
||||
assert conn.rolled_back is False
|
||||
assert conn.closed is True
|
||||
|
||||
calls = conn._cursor.calls
|
||||
assert len(calls) == 3
|
||||
assert calls[0][0] == 'execute'
|
||||
assert 'DELETE FROM t' in calls[0][1]
|
||||
assert calls[0][2] == {'batch': 'B1'}
|
||||
|
||||
assert calls[1][0] == 'executemany'
|
||||
assert 'INSERT INTO t' in calls[1][1]
|
||||
# 行与基础参数合并;第二行 batch 被行内覆盖
|
||||
assert calls[1][2] == [
|
||||
{'batch': 'B1', 'sku': 'S1'},
|
||||
{'batch': 'OVERRIDE', 'sku': 'S2'},
|
||||
]
|
||||
|
||||
assert calls[2][0] == 'execute'
|
||||
assert 'UPDATE t SET done=1' in calls[2][1]
|
||||
assert calls[2][2] == {'batch': 'B1'}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ② query:返回行 dict 且不 commit
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_query_returns_row_dicts_without_commit(monkeypatch):
|
||||
"""query 将列别名映射为 dict 键,成功返回 rows,且不 commit。"""
|
||||
cursor = FakeCursor(
|
||||
rows=[('S1', 10), ('S2', 20)],
|
||||
description=[('sku',), ('qty',)],
|
||||
)
|
||||
conn = FakeConn(cursor)
|
||||
|
||||
_patch_driver(monkeypatch, 'postgresql', lambda **kw: conn)
|
||||
transport = DatabaseTransport()
|
||||
result = transport.call(
|
||||
client=_client(endpoint='pg.invalid:5432/inv', db_kind='postgresql'),
|
||||
interface=_iface_query('SELECT sku AS sku, qty AS qty FROM stock WHERE wh=:wh'),
|
||||
request={'params': {'wh': 'HUB'}},
|
||||
)
|
||||
|
||||
# `_wire` 为 Task 2 起新增的保留键(线级事实,供引擎剥离落库),
|
||||
# 全等断言排除该键,其余键保持全等。
|
||||
assert {k: v for k, v in result.items() if k != '_wire'} == {
|
||||
'status': 'success',
|
||||
'rows': [{'sku': 'S1', 'qty': 10}, {'sku': 'S2', 'qty': 20}],
|
||||
}
|
||||
assert conn.committed is False
|
||||
assert conn.closed is True
|
||||
assert cursor.calls[0][0] == 'execute'
|
||||
assert cursor.calls[0][2] == {'wh': 'HUB'}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ③ DB 异常 → technical_failed + 凭据脱敏
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_db_exception_maps_to_technical_failed_and_masks_secret(monkeypatch):
|
||||
"""驱动抛错时返回 technical_failed,message 中密码替换为 ***,并 rollback。"""
|
||||
|
||||
class BoomConn(FakeConn):
|
||||
def cursor(self):
|
||||
raise RuntimeError('login failed for secret-pass at host')
|
||||
|
||||
conn = BoomConn()
|
||||
_patch_driver(monkeypatch, 'mysql', lambda **kw: conn)
|
||||
transport = DatabaseTransport()
|
||||
result = transport.call(
|
||||
client=_client(password='secret-pass'),
|
||||
interface=_iface_execute(),
|
||||
request={'params': {'batch': 'B1', 'lines': []}},
|
||||
)
|
||||
|
||||
assert result['status'] == 'technical_failed'
|
||||
assert 'secret-pass' not in result['message']
|
||||
assert '***' in result['message']
|
||||
assert conn.rolled_back is True
|
||||
assert conn.closed is True
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ④ probe:oracle FROM DUAL / 其余 SELECT 1
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
@pytest.mark.parametrize(
|
||||
'db_kind,endpoint,expected_probe',
|
||||
[
|
||||
('oracle', 'ora.invalid:1521/ORCL', 'SELECT 1 FROM DUAL'),
|
||||
('mysql', 'my.invalid:3306/db', 'SELECT 1'),
|
||||
('postgresql', 'pg.invalid:5432/db', 'SELECT 1'),
|
||||
('sqlserver', 'ms.invalid:1433/db', 'SELECT 1'),
|
||||
],
|
||||
)
|
||||
def test_probe_uses_driver_sql(monkeypatch, db_kind, endpoint, expected_probe):
|
||||
"""probe 按库种执行注册表 probe_sql,成功返回 ok。"""
|
||||
cursor = FakeCursor()
|
||||
conn = FakeConn(cursor)
|
||||
# 用真实注册表的 probe_sql,只替换 connect
|
||||
_patch_driver(monkeypatch, db_kind, lambda **kw: conn)
|
||||
|
||||
transport = DatabaseTransport()
|
||||
result = transport.probe(client=_client(endpoint=endpoint, db_kind=db_kind))
|
||||
|
||||
assert result['ok'] is True
|
||||
assert cursor.calls[0][0] == 'execute'
|
||||
assert cursor.calls[0][1] == expected_probe
|
||||
assert conn.closed is True
|
||||
# probe 不做业务写入,不应依赖 commit
|
||||
assert _DRIVERS[db_kind].probe_sql == expected_probe
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ⑤ 缺 endpoint / 未知 db_kind → fail-closed
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_fail_closed_missing_endpoint():
|
||||
"""缺 endpoint 时 fail-closed 抛 TransportNotFrozenError。"""
|
||||
transport = DatabaseTransport()
|
||||
with pytest.raises(TransportNotFrozenError):
|
||||
transport.call(
|
||||
client={'config_json': {'db_kind': 'mysql'}, 'credential': {}},
|
||||
interface=_iface_query(),
|
||||
request={'params': {}},
|
||||
)
|
||||
|
||||
|
||||
def test_fail_closed_unknown_db_kind():
|
||||
"""未知 db_kind(含历史别名 mssql)fail-closed。"""
|
||||
transport = DatabaseTransport()
|
||||
with pytest.raises(TransportNotFrozenError):
|
||||
transport.call(
|
||||
client=_client(db_kind='mssql'),
|
||||
interface=_iface_query(),
|
||||
request={'params': {}},
|
||||
)
|
||||
with pytest.raises(TransportNotFrozenError):
|
||||
transport.call(
|
||||
client=_client(db_kind='sqlite'),
|
||||
interface=_iface_query(),
|
||||
request={'params': {}},
|
||||
)
|
||||
|
||||
|
||||
def test_fail_closed_missing_db_kind():
|
||||
"""缺 db_kind 时 fail-closed。"""
|
||||
transport = DatabaseTransport()
|
||||
with pytest.raises(TransportNotFrozenError):
|
||||
transport.call(
|
||||
client={'config_json': {'endpoint': 'h:1/db'}, 'credential': {}},
|
||||
interface=_iface_query(),
|
||||
request={'params': {}},
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ⑥ 四库 connect 工厂收到正确拆解的驱动参数
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_connect_factories_receive_parsed_endpoint_params(monkeypatch):
|
||||
"""四库真实 connect 工厂:endpoint 拆为 host/port/database,凭据传入对应驱动关键字。"""
|
||||
import sys
|
||||
|
||||
captured: dict[str, dict] = {}
|
||||
|
||||
def _install(mod_name: str, kind: str):
|
||||
fake = MagicMock()
|
||||
|
||||
def _connect(**kw):
|
||||
captured[kind] = kw
|
||||
return FakeConn()
|
||||
|
||||
fake.connect.side_effect = _connect
|
||||
monkeypatch.setitem(sys.modules, mod_name, fake)
|
||||
return fake
|
||||
|
||||
_install('oracledb', 'oracle')
|
||||
_install('pymysql', 'mysql')
|
||||
_install('psycopg2', 'postgresql')
|
||||
_install('pymssql', 'sqlserver')
|
||||
|
||||
cred = {'username': 'alice', 'password': 'pw'}
|
||||
_DRIVERS['oracle'].connect(config={'endpoint': 'ora.host:1521/ORCLPDB'}, credential=cred)
|
||||
assert captured['oracle']['user'] == 'alice'
|
||||
assert captured['oracle']['password'] == 'pw'
|
||||
assert captured['oracle']['dsn'] == 'ora.host:1521/ORCLPDB'
|
||||
|
||||
_DRIVERS['mysql'].connect(config={'endpoint': 'my.host:3306/appdb'}, credential=cred)
|
||||
assert captured['mysql']['host'] == 'my.host'
|
||||
assert captured['mysql']['port'] == 3306
|
||||
assert captured['mysql']['database'] == 'appdb'
|
||||
assert captured['mysql']['user'] == 'alice'
|
||||
assert captured['mysql']['password'] == 'pw'
|
||||
assert captured['mysql']['charset'] == 'utf8mb4'
|
||||
|
||||
_DRIVERS['postgresql'].connect(config={'endpoint': 'pg.host:5432/inv'}, credential=cred)
|
||||
assert captured['postgresql']['host'] == 'pg.host'
|
||||
assert captured['postgresql']['port'] == 5432
|
||||
assert captured['postgresql']['dbname'] == 'inv'
|
||||
assert captured['postgresql']['user'] == 'alice'
|
||||
|
||||
_DRIVERS['sqlserver'].connect(config={'endpoint': 'ms.host:1433/erp'}, credential=cred)
|
||||
assert captured['sqlserver']['server'] == 'ms.host'
|
||||
assert captured['sqlserver']['port'] == 1433
|
||||
assert captured['sqlserver']['database'] == 'erp'
|
||||
assert captured['sqlserver']['user'] == 'alice'
|
||||
|
||||
# 注册表键必须是 sqlserver(D16),不是 mssql
|
||||
assert 'sqlserver' in _DRIVERS
|
||||
assert 'mssql' not in _DRIVERS
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ⑦ schema 标识符替换进表名
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_identifier_schema_substituted_into_sql(monkeypatch):
|
||||
"""白名单 identifiers 将 {schema} 替换为安全标识符值后再执行。"""
|
||||
conn = FakeConn()
|
||||
_patch_driver(monkeypatch, 'oracle', lambda **kw: conn)
|
||||
transport = DatabaseTransport()
|
||||
transport.call(
|
||||
client=_client(endpoint='ora:1521/X', db_kind='oracle'),
|
||||
interface=_iface_execute(
|
||||
pre=['DELETE FROM {schema}.stage WHERE id=:id'],
|
||||
bulk={'sql': 'INSERT INTO {schema}.stage (id) VALUES (:id)', 'rows_param': 'lines'},
|
||||
post=[],
|
||||
identifiers=['schema'],
|
||||
),
|
||||
request={'params': {'schema': 'HTT01', 'id': 1, 'lines': [{'id': 1}]}},
|
||||
)
|
||||
|
||||
pre_sql = conn._cursor.calls[0][1]
|
||||
bulk_sql = conn._cursor.calls[1][1]
|
||||
assert '{schema}' not in pre_sql
|
||||
assert 'HTT01.stage' in pre_sql
|
||||
assert 'HTT01.stage' in bulk_sql
|
||||
|
||||
|
||||
def test_identifier_keys_stripped_from_bind_params(monkeypatch):
|
||||
"""标识符替换后 bind dict 不得残留 schema 等键(StrictFakeCursor 模拟 oracledb)。
|
||||
|
||||
断言:每次 execute/executemany 的 bind 键 ⊆ SQL `:name` 占位符;无 leftover `schema`。
|
||||
"""
|
||||
cursor = StrictFakeCursor()
|
||||
conn = FakeConn(cursor)
|
||||
_patch_driver(monkeypatch, 'oracle', lambda **kw: conn)
|
||||
transport = DatabaseTransport()
|
||||
result = transport.call(
|
||||
client=_client(endpoint='ora:1521/X', db_kind='oracle'),
|
||||
interface=_iface_execute(
|
||||
pre=['DELETE FROM {schema}.stage WHERE id=:id'],
|
||||
bulk={
|
||||
'sql': 'INSERT INTO {schema}.stage (id, sku) VALUES (:id, :sku)',
|
||||
'rows_param': 'lines',
|
||||
},
|
||||
post=['UPDATE {schema}.stage SET done=1 WHERE id=:id'],
|
||||
identifiers=['schema'],
|
||||
),
|
||||
request={
|
||||
'params': {
|
||||
'schema': 'HTT01',
|
||||
'id': 1,
|
||||
'lines': [{'sku': 'S1'}, {'sku': 'S2', 'schema': 'SHOULD_STRIP'}],
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
assert result['status'] == 'success'
|
||||
# StrictFakeCursor 已在调用时断言 keys ⊆ placeholders;再显式确认无 schema 残留
|
||||
pre_params = cursor.calls[0][2]
|
||||
bulk_rows = cursor.calls[1][2]
|
||||
post_params = cursor.calls[2][2]
|
||||
assert 'schema' not in pre_params
|
||||
assert pre_params == {'id': 1}
|
||||
assert all('schema' not in row for row in bulk_rows)
|
||||
assert bulk_rows == [{'id': 1, 'sku': 'S1'}, {'id': 1, 'sku': 'S2'}]
|
||||
assert 'schema' not in post_params
|
||||
assert post_params == {'id': 1}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ⑧ 非法标识符 / 未声明 {xxx} → fail-closed
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_illegal_identifier_value_fail_closed(monkeypatch):
|
||||
"""标识符含引号/空格等非法字符 → InputInvalidError。"""
|
||||
conn = FakeConn()
|
||||
_patch_driver(monkeypatch, 'mysql', lambda **kw: conn)
|
||||
transport = DatabaseTransport()
|
||||
with pytest.raises(InputInvalidError):
|
||||
transport.call(
|
||||
client=_client(),
|
||||
interface=_iface_query(
|
||||
'SELECT 1 FROM {schema}.t',
|
||||
identifiers=['schema'],
|
||||
),
|
||||
request={'params': {'schema': 'bad schema'}},
|
||||
)
|
||||
with pytest.raises(InputInvalidError):
|
||||
transport.call(
|
||||
client=_client(),
|
||||
interface=_iface_query(
|
||||
'SELECT 1 FROM {schema}.t',
|
||||
identifiers=['schema'],
|
||||
),
|
||||
request={'params': {'schema': 'x"; DROP'}},
|
||||
)
|
||||
|
||||
|
||||
def test_undeclared_placeholder_fail_closed(monkeypatch):
|
||||
"""语句出现未在 identifiers 白名单声明的 {xxx} → InputInvalidError。"""
|
||||
conn = FakeConn()
|
||||
_patch_driver(monkeypatch, 'mysql', lambda **kw: conn)
|
||||
transport = DatabaseTransport()
|
||||
with pytest.raises(InputInvalidError):
|
||||
transport.call(
|
||||
client=_client(),
|
||||
interface=_iface_query('SELECT 1 FROM {schema}.t', identifiers=[]),
|
||||
request={'params': {'schema': 'HTT'}},
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ⑨ D12 业务无关回归锁
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_database_transport_has_no_business_sql_literals():
|
||||
"""inspect.getsource 断言 database.py 无 gls_cm / 调拨 / C0089(D12 代码级锁)。"""
|
||||
source = inspect.getsource(database_mod)
|
||||
for forbidden in ('gls_cm', '调拨', 'C0089'):
|
||||
assert forbidden not in source, f'D12 violation: found {forbidden!r} in database.py'
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# merge_client_config 拼入 db_kind(Task 1 延期项)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_merge_client_config_includes_db_kind():
|
||||
"""merge_client_config 将专列 db_kind 拼入 config,与 endpoint/timeout 同模式。"""
|
||||
merged = merge_client_config({
|
||||
'config_json': {'headers': {'X': '1'}},
|
||||
'endpoint': 'h:1521/ORCL',
|
||||
'timeout_seconds': 45,
|
||||
'db_kind': 'oracle',
|
||||
})
|
||||
assert merged['endpoint'] == 'h:1521/ORCL'
|
||||
assert merged['timeout_seconds'] == 45
|
||||
assert merged['db_kind'] == 'oracle'
|
||||
assert merged['headers'] == {'X': '1'}
|
||||
|
||||
|
||||
def test_gateway_registers_database_transport():
|
||||
"""CapabilityGateway 默认装配含 database → DatabaseTransport。"""
|
||||
from app.services.integration_connector.gateway import get_capability_gateway
|
||||
from app.services.integration_connector.gateway import set_capability_gateway
|
||||
|
||||
set_capability_gateway(None)
|
||||
gw = get_capability_gateway()
|
||||
assert 'database' in gw.transports
|
||||
assert isinstance(gw.transports['database'], DatabaseTransport)
|
||||
assert gw.transports['database'].connector_type == 'database'
|
||||
|
||||
|
||||
def test_drivers_registry_keys_match_d16():
|
||||
"""_DRIVERS 键 = D16 四库:mysql/oracle/sqlserver/postgresql。"""
|
||||
assert set(_DRIVERS.keys()) == {'mysql', 'oracle', 'sqlserver', 'postgresql'}
|
||||
assert _DRIVERS['oracle'].probe_sql == 'SELECT 1 FROM DUAL'
|
||||
for kind in ('mysql', 'postgresql', 'sqlserver'):
|
||||
assert _DRIVERS[kind].probe_sql == 'SELECT 1'
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# P2-1 四库 connect 工厂消费 timeout_seconds(T1-T3 评审遗留)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _capture_driver_connects(monkeypatch) -> dict[str, dict]:
|
||||
"""伪造四个驱动模块并捕获各库 connect 工厂收到的关键字参数。"""
|
||||
import sys
|
||||
|
||||
captured: dict[str, dict] = {}
|
||||
|
||||
def _install(mod_name: str, kind: str):
|
||||
fake = MagicMock()
|
||||
|
||||
def _connect(**kw):
|
||||
captured[kind] = kw
|
||||
return FakeConn()
|
||||
|
||||
fake.connect.side_effect = _connect
|
||||
monkeypatch.setitem(sys.modules, mod_name, fake)
|
||||
|
||||
_install('oracledb', 'oracle')
|
||||
_install('pymysql', 'mysql')
|
||||
_install('psycopg2', 'postgresql')
|
||||
_install('pymssql', 'sqlserver')
|
||||
return captured
|
||||
|
||||
|
||||
def test_connect_factories_receive_timeout_params(monkeypatch):
|
||||
"""timeout_seconds=30 → 四库工厂收到各自驱动的超时参数(单位秒)。
|
||||
|
||||
断言意图:pymysql=connect/read/write 三参、pymssql=login/timeout 两参、
|
||||
psycopg2=connect_timeout、oracledb=tcp_connect_timeout 且建连后设 call_timeout(毫秒)。
|
||||
"""
|
||||
captured = _capture_driver_connects(monkeypatch)
|
||||
cred = {'username': 'u', 'password': 'p'}
|
||||
cfg = {'timeout_seconds': 30}
|
||||
|
||||
conn_oracle = _DRIVERS['oracle'].connect(config={'endpoint': 'ora:1521/X', **cfg}, credential=cred)
|
||||
assert captured['oracle']['tcp_connect_timeout'] == 30
|
||||
# 断言意图:call_timeout(毫秒,单次 round-trip 超时)在建连后按连接属性设置
|
||||
assert conn_oracle.call_timeout == 30000
|
||||
|
||||
_DRIVERS['mysql'].connect(config={'endpoint': 'my:3306/db', **cfg}, credential=cred)
|
||||
assert captured['mysql']['connect_timeout'] == 30
|
||||
assert captured['mysql']['read_timeout'] == 30
|
||||
assert captured['mysql']['write_timeout'] == 30
|
||||
|
||||
_DRIVERS['postgresql'].connect(config={'endpoint': 'pg:5432/db', **cfg}, credential=cred)
|
||||
assert captured['postgresql']['connect_timeout'] == 30
|
||||
|
||||
_DRIVERS['sqlserver'].connect(config={'endpoint': 'ms:1433/db', **cfg}, credential=cred)
|
||||
assert captured['sqlserver']['login_timeout'] == 30
|
||||
assert captured['sqlserver']['timeout'] == 30
|
||||
|
||||
|
||||
def test_connect_factories_without_timeout_use_driver_defaults(monkeypatch):
|
||||
"""timeout_seconds 缺失/非法 → 工厂不传任何超时参数(用驱动默认,不报错)。"""
|
||||
captured = _capture_driver_connects(monkeypatch)
|
||||
cred = {'username': 'u', 'password': 'p'}
|
||||
|
||||
_DRIVERS['oracle'].connect(config={'endpoint': 'ora:1521/X'}, credential=cred)
|
||||
_DRIVERS['mysql'].connect(config={'endpoint': 'my:3306/db', 'timeout_seconds': 'abc'}, credential=cred)
|
||||
_DRIVERS['postgresql'].connect(config={'endpoint': 'pg:5432/db'}, credential=cred)
|
||||
_DRIVERS['sqlserver'].connect(config={'endpoint': 'ms:1433/db'}, credential=cred)
|
||||
|
||||
# 断言意图:无超时配置时键必须整体缺席(而非传 None 破坏驱动默认值)
|
||||
assert 'tcp_connect_timeout' not in captured['oracle']
|
||||
assert 'connect_timeout' not in captured['mysql']
|
||||
assert 'read_timeout' not in captured['mysql']
|
||||
assert 'connect_timeout' not in captured['postgresql']
|
||||
assert 'login_timeout' not in captured['sqlserver']
|
||||
assert 'timeout' not in captured['sqlserver']
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# P2-2 标识符替换后残留占位符 → fail-closed(T1-T3 评审遗留)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_malformed_placeholder_with_dot_fail_closed(monkeypatch):
|
||||
"""畸形占位符 {schema.}(不匹配白名单替换正则)替换后残留 → InputInvalidError,禁止静默直通。"""
|
||||
conn = FakeConn()
|
||||
_patch_driver(monkeypatch, 'mysql', lambda **kw: conn)
|
||||
transport = DatabaseTransport()
|
||||
with pytest.raises(InputInvalidError):
|
||||
transport.call(
|
||||
client=_client(),
|
||||
interface=_iface_query('SELECT 1 FROM {schema.}t', identifiers=['schema']),
|
||||
request={'params': {'schema': 'HTT'}},
|
||||
)
|
||||
|
||||
|
||||
def test_malformed_placeholder_starts_with_digit_fail_closed(monkeypatch):
|
||||
"""畸形占位符 {1abc}(数字开头不匹配白名单正则)替换后残留 → InputInvalidError。"""
|
||||
conn = FakeConn()
|
||||
_patch_driver(monkeypatch, 'mysql', lambda **kw: conn)
|
||||
transport = DatabaseTransport()
|
||||
with pytest.raises(InputInvalidError):
|
||||
transport.call(
|
||||
client=_client(),
|
||||
interface=_iface_query('SELECT 1 FROM {1abc}.t', identifiers=['schema']),
|
||||
request={'params': {'schema': 'HTT'}},
|
||||
)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ⑨ 逐语句绑定过滤:pre/bulk/post/query 只传各语句实际引用的 :bind
|
||||
# (回归:oracledb 不容多余 bind 键,生产 submit-stage-table 的 pre 仅引用
|
||||
# :submit_timestamp,全量 base 直传触发 ORA-01036 unrecognized bind doc_no)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_pre_statement_filters_unused_binds(monkeypatch):
|
||||
"""pre 语句只引用 :submit_timestamp 时,多余的 doc_no 等键不得传入驱动(StrictFakeCursor 模拟 oracledb)。"""
|
||||
cursor = StrictFakeCursor()
|
||||
conn = FakeConn(cursor)
|
||||
_patch_driver(monkeypatch, 'oracle', lambda **kw: conn)
|
||||
transport = DatabaseTransport()
|
||||
result = transport.call(
|
||||
client=_client(endpoint='ora:1521/X', db_kind='oracle'),
|
||||
interface=_iface_execute(
|
||||
pre=["DELETE FROM t WHERE ts=:submit_timestamp AND flag='10'"],
|
||||
bulk={
|
||||
'sql': 'INSERT INTO t (ts, doc) VALUES (:submit_timestamp, :doc_no)',
|
||||
'rows_param': 'lines',
|
||||
},
|
||||
post=[],
|
||||
identifiers=[],
|
||||
),
|
||||
request={
|
||||
'params': {
|
||||
'doc_no': 'D1',
|
||||
'doc_date': '2026-09-26',
|
||||
'external_org': 'TGHX1',
|
||||
'posting_date': '2026-09-26',
|
||||
'maker_account': 'admin',
|
||||
'submit_timestamp': 'TS1',
|
||||
'lines': [{'doc_no': 'D1'}],
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
# 关键断言:StrictFakeCursor 已断言键 ⊆ 占位符(旧实现此处即抛 ORA-01036 同款失败)
|
||||
assert result['status'] == 'success'
|
||||
pre_params = cursor.calls[0][2]
|
||||
assert pre_params == {'submit_timestamp': 'TS1'}
|
||||
bulk_rows = cursor.calls[1][2]
|
||||
assert bulk_rows == [{'submit_timestamp': 'TS1', 'doc_no': 'D1'}]
|
||||
|
||||
|
||||
def test_bulk_row_extra_keys_filtered(monkeypatch):
|
||||
"""行键含 bulk SQL 未引用的 invoice_no 时不得传入 executemany(生产已潜伏的第二个多余键)。"""
|
||||
cursor = StrictFakeCursor()
|
||||
conn = FakeConn(cursor)
|
||||
_patch_driver(monkeypatch, 'oracle', lambda **kw: conn)
|
||||
transport = DatabaseTransport()
|
||||
result = transport.call(
|
||||
client=_client(endpoint='ora:1521/X', db_kind='oracle'),
|
||||
interface=_iface_execute(
|
||||
pre=[],
|
||||
bulk={
|
||||
'sql': 'INSERT INTO t (doc, sku) VALUES (:doc_no, :sku)',
|
||||
'rows_param': 'lines',
|
||||
},
|
||||
post=[],
|
||||
identifiers=[],
|
||||
),
|
||||
request={
|
||||
'params': {
|
||||
'doc_no': 'D1',
|
||||
'lines': [{'sku': 'S1', 'invoice_no': 'INV1'}],
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
assert result['status'] == 'success'
|
||||
assert cursor.calls[0][2] == [{'doc_no': 'D1', 'sku': 'S1'}]
|
||||
|
||||
|
||||
def test_bind_extraction_ignores_colons_in_literals_and_comments(monkeypatch):
|
||||
"""字符串字面量与注释中的 ':name' 不算占位符:语句未真实引用的键必须被过滤。"""
|
||||
cursor = StrictFakeCursor()
|
||||
conn = FakeConn(cursor)
|
||||
_patch_driver(monkeypatch, 'oracle', lambda **kw: conn)
|
||||
transport = DatabaseTransport()
|
||||
result = transport.call(
|
||||
client=_client(endpoint='ora:1521/X', db_kind='oracle'),
|
||||
interface=_iface_execute(
|
||||
pre=[
|
||||
# 字面量含 :doc_no、行注释含 :doc_no,均非真实绑定
|
||||
"DELETE FROM t WHERE ts=:submit_timestamp -- :doc_no\nAND url='http://x/:doc_no'",
|
||||
],
|
||||
bulk={'sql': 'INSERT INTO t (ts) VALUES (:submit_timestamp)', 'rows_param': 'lines'},
|
||||
post=[],
|
||||
identifiers=[],
|
||||
),
|
||||
request={
|
||||
'params': {
|
||||
'doc_no': 'D1',
|
||||
'submit_timestamp': 'TS1',
|
||||
'lines': [],
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
assert result['status'] == 'success'
|
||||
assert cursor.calls[0][2] == {'submit_timestamp': 'TS1'}
|
||||
|
||||
|
||||
def test_query_filters_unused_binds(monkeypatch):
|
||||
"""query 同口径:SQL 未引用的参数键不得传入 execute。"""
|
||||
cursor = StrictFakeCursor()
|
||||
conn = FakeConn(cursor)
|
||||
_patch_driver(monkeypatch, 'postgresql', lambda **kw: conn)
|
||||
transport = DatabaseTransport()
|
||||
result = transport.call(
|
||||
client=_client(endpoint='pg.invalid:5432/inv', db_kind='postgresql'),
|
||||
interface=_iface_query('SELECT sku AS sku FROM t WHERE wh=:wh'),
|
||||
request={'params': {'wh': 'HUB', 'unused_key': 'X'}},
|
||||
)
|
||||
|
||||
assert result['status'] == 'success'
|
||||
assert cursor.calls[0][2] == {'wh': 'HUB'}
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Task 2 wire 捕获:execute/query 返回 dict 附带保留键 `_wire`(线级事实,
|
||||
# 供调用日志引擎(Task 4)剥离落库 IntegrationCall.wire_json)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_execute_attaches_wire_with_final_sql_and_binds(monkeypatch):
|
||||
"""execute 返回的 _wire 必须带标识符替换后的最终 SQL、逐语句绑定与行数。"""
|
||||
conn = FakeConn()
|
||||
_patch_driver(monkeypatch, 'mysql', lambda **kw: conn)
|
||||
transport = DatabaseTransport()
|
||||
result = transport.call(
|
||||
client=_client(),
|
||||
interface=_iface_execute(
|
||||
pre=['DELETE FROM t WHERE batch=:batch'],
|
||||
bulk={'sql': 'INSERT INTO t (batch, sku) VALUES (:batch, :sku)', 'rows_param': 'lines'},
|
||||
post=[],
|
||||
),
|
||||
request={'params': {'batch': 'B1', 'lines': [{'sku': 'S1'}]}},
|
||||
)
|
||||
wire = result['_wire']
|
||||
# 关键断言:kind 固定 database、语句相位按 pre→bulk 顺序、SQL 为标识符替换后
|
||||
# 的最终文本、binds 为逐语句过滤后的实际绑定、顶层 rowcount 为各语句之和
|
||||
assert wire['kind'] == 'database'
|
||||
assert [s['phase'] for s in wire['statements']] == ['pre', 'bulk']
|
||||
assert wire['statements'][0]['sql'] == 'DELETE FROM t WHERE batch=:batch'
|
||||
assert wire['statements'][0]['binds'] == {'batch': 'B1'}
|
||||
assert wire['statements'][1]['sql'] == 'INSERT INTO t (batch, sku) VALUES (:batch, :sku)'
|
||||
assert wire['statements'][1]['binds'] == {'batch': 'B1', 'sku': 'S1'}
|
||||
assert 'rowcount' in wire
|
||||
|
||||
|
||||
def test_query_attaches_wire_with_sql_and_rows(monkeypatch):
|
||||
"""query 返回的 _wire 记录最终 SQL、实际绑定与行快照(与返回 rows 同源)。"""
|
||||
cursor = FakeCursor(rows=[('S1', 10)], description=[('sku',), ('qty',)])
|
||||
conn = FakeConn(cursor)
|
||||
_patch_driver(monkeypatch, 'postgresql', lambda **kw: conn)
|
||||
transport = DatabaseTransport()
|
||||
result = transport.call(
|
||||
client=_client(endpoint='pg.invalid:5432/inv', db_kind='postgresql'),
|
||||
interface=_iface_query('SELECT sku AS sku, qty AS qty FROM t WHERE wh=:wh'),
|
||||
request={'params': {'wh': 'HUB'}},
|
||||
)
|
||||
# 关键断言:query 相位单语句、SQL 为替换后最终文本、rows 与返回值同源
|
||||
assert result['_wire']['kind'] == 'database'
|
||||
assert result['_wire']['statements'][0]['sql'] == 'SELECT sku AS sku, qty AS qty FROM t WHERE wh=:wh'
|
||||
assert result['_wire']['rows'] == [{'sku': 'S1', 'qty': 10}]
|
||||
@@ -63,6 +63,8 @@ def _seed(capability, *, connector_type="rest", response_mapping=None, output_sc
|
||||
capability=capability, context_selector_json={}, client_instance_code="CLI-A",
|
||||
interface_definition_code="IFACE-Q", mapping_version=2, priority=0, environment="prod",
|
||||
status="published",
|
||||
steps_json=[{"interface_code": "IFACE-Q", "param_mapping_json": {}}],
|
||||
param_mapping_json={},
|
||||
)
|
||||
db.session.add(binding)
|
||||
db.session.commit()
|
||||
@@ -72,7 +74,25 @@ def _seed(capability, *, connector_type="rest", response_mapping=None, output_sc
|
||||
def _params(**overrides):
|
||||
values = {
|
||||
"external_org": "HX-CN01",
|
||||
"targets": [{"material_no": "M-1", "from_warehouse": "W1", "lot_no": "L-1"}],
|
||||
"targets": [{"material_no": "M-1", "warehouse_code": "W1", "lot_no": "L-1"}],
|
||||
}
|
||||
values.update(overrides)
|
||||
return values
|
||||
|
||||
|
||||
def _order_params(**overrides):
|
||||
"""create_transfer 单据级入参(能力收缩后契约):七必填 = 六域参数 + 制单人。"""
|
||||
values = {
|
||||
"external_org": "HX-CN01",
|
||||
"doc_no": "HX-CN01-OR-26092400001",
|
||||
"submit_timestamp": "b4f9c2d1a7e307260924101010123",
|
||||
"doc_date": "2026-09-24",
|
||||
"posting_date": "2026-09-24",
|
||||
"maker_account": "15070211",
|
||||
"lines": [{
|
||||
"line_no": 1, "material_no": "M-1", "from_warehouse": "W1",
|
||||
"to_warehouse": "W2", "lot_no": "L-1", "quantity": 10, "unit": "EA",
|
||||
}],
|
||||
}
|
||||
values.update(overrides)
|
||||
return values
|
||||
@@ -115,12 +135,12 @@ def test_call_no_binding_raises(app):
|
||||
|
||||
|
||||
def test_call_write_business_failed(app):
|
||||
"""写能力按原始 status 分类 → business_failed。"""
|
||||
"""写能力按原始 status 分类 → business_failed(入参为单据级契约)。"""
|
||||
_seed("in_transit_transfer.create_transfer")
|
||||
fake = FakeTransport({"status": "business_failed", "code": "E1", "message": "reject"})
|
||||
result = CapabilityGateway(transports={"rest": fake}).call(
|
||||
capability="in_transit_transfer.create_transfer", context={},
|
||||
params=_params(), operation_id="OP-4", environment="prod",
|
||||
params=_order_params(), operation_id="OP-4", environment="prod",
|
||||
)
|
||||
assert result.status == "business_failed"
|
||||
assert result.error_code == "E1"
|
||||
@@ -162,7 +182,7 @@ def test_call_result_unknown_no_auto_retry(app):
|
||||
|
||||
result = CapabilityGateway(transports={"rest": _OneShot(None)}).call(
|
||||
capability="in_transit_transfer.create_transfer", context={},
|
||||
params=_params(), operation_id="OP-7", environment="prod",
|
||||
params=_order_params(), operation_id="OP-7", environment="prod",
|
||||
)
|
||||
assert result.status == "result_unknown"
|
||||
assert len(calls) == 1
|
||||
@@ -190,6 +210,10 @@ def _seed_full_params(*, param_mapping=None, input_schema=None, credential_ref=N
|
||||
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",
|
||||
steps_json=[{
|
||||
"interface_code": "IFACE-P",
|
||||
"param_mapping_json": param_mapping or {},
|
||||
}],
|
||||
)
|
||||
db.session.add(binding)
|
||||
db.session.commit()
|
||||
@@ -213,7 +237,7 @@ def test_call_applies_binding_param_mapping(app):
|
||||
|
||||
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"}]),
|
||||
params=_params(external_org="TGHX", targets=[{"material_no": "M-9", "warehouse_code": "W1", "lot_no": "L-9"}]),
|
||||
operation_id="OP-PM", environment="prod",
|
||||
)
|
||||
assert captured["params"] == {"organization": "TGHX", "condition": "img04 = 'L-9'"}
|
||||
@@ -272,3 +296,46 @@ def test_call_read_capability_failure_passthrough(app):
|
||||
)
|
||||
assert result.status == "business_failed"
|
||||
assert result.error_code == "HTTP_500"
|
||||
|
||||
|
||||
# ---- 引擎落库 wire_json / business_ref(Task 4:`_wire` 保留键剥离 + 业务锚点透传)----
|
||||
|
||||
def test_record_call_persists_wire_json(app):
|
||||
"""读能力执行落 IntegrationCall:传输层 `_wire` 剥离落 wire_json,不混入响应摘要。"""
|
||||
_seed("in_transit_transfer.query_inventory")
|
||||
fake = FakeTransport({"found": True, "quantity": "100", "_wire": {"kind": "database", "rowcount": 1}})
|
||||
result = CapabilityGateway(transports={"rest": fake}).call(
|
||||
capability="in_transit_transfer.query_inventory", context={},
|
||||
params=_params(), operation_id="OP-WIRE", environment="prod",
|
||||
)
|
||||
assert result.status == "success"
|
||||
call_row = IntegrationCall.query.filter_by(operation_id="OP-WIRE").first()
|
||||
assert call_row is not None
|
||||
# `_wire` 剥离后原样落 wire_json(线级事实独立成列)。
|
||||
assert call_row.wire_json == {"kind": "database", "rowcount": 1}
|
||||
# wire 不混入响应摘要。
|
||||
assert "_wire" not in (call_row.response_summary_json or {})
|
||||
|
||||
|
||||
def test_call_persists_business_ref(app):
|
||||
"""写能力 business_ref 透传落库(执行服务以 doc_no 为业务锚点);不传时为 NULL。"""
|
||||
_seed("in_transit_transfer.create_transfer")
|
||||
fake = FakeTransport({"status": "business_failed", "code": "E1", "message": "reject"})
|
||||
gateway = CapabilityGateway(transports={"rest": fake})
|
||||
gateway.call(
|
||||
capability="in_transit_transfer.create_transfer", context={},
|
||||
params=_order_params(), operation_id="OP-BR-1", environment="prod",
|
||||
business_ref="TGHX1-OR-26092600002",
|
||||
)
|
||||
call_row = IntegrationCall.query.filter_by(operation_id="OP-BR-1").first()
|
||||
assert call_row is not None
|
||||
# business_ref 透传落库(写能力多步路径经 _execute_step 逐步审计同样携带)。
|
||||
assert call_row.business_ref == "TGHX1-OR-26092600002"
|
||||
# 不传 business_ref:现有消费者零改动,落 NULL。
|
||||
gateway.call(
|
||||
capability="in_transit_transfer.create_transfer", context={},
|
||||
params=_order_params(), operation_id="OP-BR-2", environment="prod",
|
||||
)
|
||||
row_without = IntegrationCall.query.filter_by(operation_id="OP-BR-2").first()
|
||||
assert row_without is not None
|
||||
assert row_without.business_ref is None
|
||||
@@ -0,0 +1,539 @@
|
||||
"""tests/services/integration_connector/test_engine_steps.py
|
||||
|
||||
用途:Task 4(R8 修订:末步判定 = response_mapping 映射 + 六态分类,无二次解释层)——
|
||||
写能力多步顺序执行引擎:多步顺序、
|
||||
resume 跳过非末步、非末步失败/超时中止(超时中止对外=技术失败、审计保 timeout 真相)、
|
||||
末步映射→classify→data 恒带 mapped 全链、每步审计同 operation_id、读能力回归、
|
||||
on_nonfinal_success 步进回调(时序与异常中止)。
|
||||
依赖:capability/binding/mapping/transports、engine.CapabilityGateway、
|
||||
IntegrationCall 模型、errors。
|
||||
逻辑:假 transport(ScriptedTransport 记录调用并可脚本化响应/异常)注入
|
||||
CapabilityGateway(transports={...});绑定用 steps_json 两步形态
|
||||
(stage=database / submit=soap,TIPTOP C0089 响应形状);审计断言查 IntegrationCall 表。
|
||||
审计契约:每步一条、同裸 operation_id(一单一次执行 = N 条;模型唯一约束已由
|
||||
迁移 tt5b6c7d8e9f 解除并补普通索引),步骤定位靠 binding_snapshot_json.step_index。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.models import IntegrationBinding, IntegrationCall, IntegrationClientInstance, IntegrationInterfaceDefinition
|
||||
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
|
||||
|
||||
# TIPTOP C0089 WS 响应形状(与 Task 15 接口定义同源):status 由 @code enum-map 推导
|
||||
# (映射表仅 '0'→success,非 0 业务码原样穿透),code 缺失/为空时映射不产出 status、
|
||||
# classify 按原始响应兜底分类;document_no 经 pick 从键值 Field 列表提取。
|
||||
_TIPTOP_RESPONSE_MAPPING = {
|
||||
"status": {"expr": "Response.Execution.Status.@code", "transform": "enum-map",
|
||||
"args": {"mapping": {"0": "success"}}},
|
||||
"code": {"expr": "Response.Execution.Status.@code"},
|
||||
"message": {"expr": "Response.Execution.Status.@description"},
|
||||
"document_no": {"expr": "Response.ResponseContent.Parameter.Record.Field",
|
||||
"transform": "pick",
|
||||
"args": {"key_field": "@name", "key_value": "doc_no", "value_field": "@value"}},
|
||||
}
|
||||
_TIPTOP_OUTPUT_SCHEMA = {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"status": {"type": "string"}, "code": {"type": "string"},
|
||||
"message": {"type": "string"}, "document_no": {"type": "string"},
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def _tiptop_raw(*, code: str, description: str = "ok", doc_no: str | None = None) -> dict:
|
||||
"""构造归一化后的 SOAP 响应;doc_no=None 模拟 ERP 查不到 30 行的失败形态。"""
|
||||
content: dict = {"Response": {"Execution": {"Status": {"@code": code, "@description": description}}}}
|
||||
if doc_no is not None:
|
||||
content["Response"]["ResponseContent"] = {
|
||||
"Parameter": {"Record": {"Field": [{"@name": "doc_no", "@value": doc_no}]}},
|
||||
}
|
||||
return content
|
||||
|
||||
|
||||
class ScriptedTransport:
|
||||
"""可脚本化响应/异常并记录调用的传输替身(按 connector_type 注入网关)。"""
|
||||
|
||||
def __init__(self, connector_type: str, response=None):
|
||||
self.connector_type = connector_type
|
||||
self._response = response
|
||||
self.calls: list[dict] = []
|
||||
|
||||
def call(self, *, client, interface, request):
|
||||
self.calls.append(request)
|
||||
if isinstance(self._response, Exception):
|
||||
raise self._response
|
||||
return self._response
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _transfer_capabilities():
|
||||
"""每用例前重建在途调拨能力注册:reset 后依赖领域包注册函数重建(write 标志随能力走)。"""
|
||||
reset_capability_registry_for_tests()
|
||||
register_transfer_capabilities()
|
||||
yield
|
||||
reset_capability_registry_for_tests()
|
||||
|
||||
|
||||
def _seed_write_two_steps(
|
||||
*,
|
||||
stage_param_mapping=None,
|
||||
submit_param_mapping=None,
|
||||
):
|
||||
"""造两客户端 + 两接口 + 有序两步写绑定(create_transfer 形态)。"""
|
||||
stage_spec = {"sql": {"mode": "execute", "pre": [], "bulk": None, "post": []}}
|
||||
submit_spec = {"method": "POST", "path": "/submit"}
|
||||
db.session.add_all([
|
||||
IntegrationClientInstance(
|
||||
code="CLI-STAGE", name="stage", connector_type="database", environment="prod",
|
||||
config_json={}, endpoint="127.0.0.1:1521/ORCL", db_kind="oracle",
|
||||
),
|
||||
IntegrationClientInstance(
|
||||
code="CLI-WS", name="ws", connector_type="soap", environment="prod",
|
||||
config_json={"endpoint": "https://ws.invalid"},
|
||||
),
|
||||
IntegrationInterfaceDefinition(
|
||||
code="IFACE-STAGE", name="stage", client_instance_code="CLI-STAGE",
|
||||
connector_type="database", request_spec_json=stage_spec,
|
||||
input_schema_json={}, response_mapping_json={}, output_schema_json={},
|
||||
version=1, status="published",
|
||||
),
|
||||
IntegrationInterfaceDefinition(
|
||||
code="IFACE-SUBMIT", name="submit", client_instance_code="CLI-WS",
|
||||
connector_type="soap", request_spec_json=submit_spec,
|
||||
input_schema_json={}, response_mapping_json=_TIPTOP_RESPONSE_MAPPING,
|
||||
output_schema_json=_TIPTOP_OUTPUT_SCHEMA,
|
||||
version=2, status="published",
|
||||
),
|
||||
IntegrationBinding(
|
||||
capability="in_transit_transfer.create_transfer", context_selector_json={},
|
||||
steps_json=[
|
||||
{"interface_code": "IFACE-STAGE", "param_mapping_json": stage_param_mapping or {}},
|
||||
{"interface_code": "IFACE-SUBMIT", "param_mapping_json": submit_param_mapping or {}},
|
||||
],
|
||||
client_instance_code="CLI-STAGE", interface_definition_code="IFACE-STAGE",
|
||||
param_mapping_json=stage_param_mapping or {},
|
||||
mapping_version=1, priority=0, environment="prod", status="published",
|
||||
),
|
||||
])
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def _seed_read_single_step():
|
||||
"""读能力单步绑定(query_inventory 形态),供回归对照。"""
|
||||
db.session.add_all([
|
||||
IntegrationClientInstance(
|
||||
code="CLI-Q", name="client", connector_type="rest", environment="prod",
|
||||
config_json={"endpoint": "https://erp.invalid"},
|
||||
),
|
||||
IntegrationInterfaceDefinition(
|
||||
code="IFACE-Q", name="iface", client_instance_code="CLI-Q", connector_type="rest",
|
||||
request_spec_json={"method": "GET", "path": "/stock"},
|
||||
input_schema_json={},
|
||||
response_mapping_json={"found": {"expr": "found"},
|
||||
"quantity": {"expr": "quantity", "transform": "decimal"}},
|
||||
output_schema_json={"type": "object", "properties": {"found": {"type": "boolean"},
|
||||
"quantity": {"type": "number"}}},
|
||||
version=3, status="published",
|
||||
),
|
||||
IntegrationBinding(
|
||||
capability="in_transit_transfer.query_inventory", context_selector_json={},
|
||||
steps_json=[{"interface_code": "IFACE-Q", "param_mapping_json": {}}],
|
||||
client_instance_code="CLI-Q", interface_definition_code="IFACE-Q",
|
||||
param_mapping_json={}, mapping_version=2, priority=0,
|
||||
environment="prod", status="published",
|
||||
),
|
||||
])
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def _params(**overrides):
|
||||
"""读能力(query_inventory)入参:external_org + targets(_INVENTORY_QUERY_INPUT_SCHEMA)。"""
|
||||
values = {
|
||||
"external_org": "HX-CN01",
|
||||
"targets": [{"material_no": "M-1", "warehouse_code": "W1", "lot_no": "L-1"}],
|
||||
}
|
||||
values.update(overrides)
|
||||
return values
|
||||
|
||||
|
||||
def _order_params(**overrides):
|
||||
"""写能力(create_transfer)单据级入参:对齐 _TICKET_INPUT_SCHEMA 七必填(R9 加制单人)。"""
|
||||
values = {
|
||||
"external_org": "HX-CN01",
|
||||
"doc_no": "HX-CN01-OR-26092300001",
|
||||
"submit_timestamp": "0f1e2d3c4b5a69788796a5b4c3d2e1f0" + "20260923010101123",
|
||||
"doc_date": "2026-09-23",
|
||||
"posting_date": "2026-09-23",
|
||||
"maker_account": "15070211",
|
||||
"lines": [{"line_no": 1, "material_no": "M-1", "from_warehouse": "W1",
|
||||
"to_warehouse": "W2", "lot_no": "L-1", "quantity": 100, "unit": "KG"}],
|
||||
}
|
||||
values.update(overrides)
|
||||
return values
|
||||
|
||||
|
||||
def _gateway(stage, submit) -> CapabilityGateway:
|
||||
return CapabilityGateway(transports={"database": stage, "soap": submit})
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ① 多步顺序执行:步序 + 各步收到各自 param_mapping 翻译后的参数
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_write_multi_step_executes_in_order_with_per_step_param_mapping(app):
|
||||
"""两步按绑定顺序执行;每步 transport 收到该步 param_mapping 翻译后的接口参数(非域参数)。"""
|
||||
_seed_write_two_steps(
|
||||
stage_param_mapping={"schema": {"expr": "external_org"}},
|
||||
submit_param_mapping={"source_ip": {"template": "0.0.0.0"}},
|
||||
)
|
||||
stage = ScriptedTransport("database", {"status": "success"})
|
||||
submit = ScriptedTransport("soap", _tiptop_raw(code="0", doc_no="1401-2609230007"))
|
||||
|
||||
result = _gateway(stage, submit).call(
|
||||
capability="in_transit_transfer.create_transfer", context={},
|
||||
params=_order_params(), operation_id="OP-MS", environment="prod",
|
||||
)
|
||||
|
||||
# 断言意图:步序锁定 stage→submit,各恰好一次;跨步不串参(每步只见自己的翻译结果)
|
||||
assert len(stage.calls) == 1
|
||||
assert len(submit.calls) == 1
|
||||
assert stage.calls[0]["params"] == {"schema": "HX-CN01"}
|
||||
assert submit.calls[0]["params"] == {"source_ip": "0.0.0.0"}
|
||||
# 断言意图:末步全链产出 success,data 恒带映射结果
|
||||
assert result.status == "success"
|
||||
assert result.document_no == "1401-2609230007"
|
||||
assert result.data["code"] == "0"
|
||||
assert result.data["document_no"] == "1401-2609230007"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ② resume=True 跳过全部非末步(非末步 transport 零调用、不审计)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_resume_skips_all_non_final_steps(app):
|
||||
"""resume=True 只执行末步(断点续跑禁重插):stage 零调用、审计仅末步一条。"""
|
||||
_seed_write_two_steps()
|
||||
stage = ScriptedTransport("database", {"status": "success"})
|
||||
submit = ScriptedTransport("soap", _tiptop_raw(code="0", doc_no="1401-1"))
|
||||
|
||||
result = _gateway(stage, submit).call(
|
||||
capability="in_transit_transfer.create_transfer", context={},
|
||||
params=_order_params(), operation_id="OP-RS", environment="prod", resume=True,
|
||||
)
|
||||
|
||||
# 断言意图:非末步不建连不执行;末步照常产出结果
|
||||
assert stage.calls == []
|
||||
assert len(submit.calls) == 1
|
||||
assert result.status == "success"
|
||||
rows = IntegrationCall.query.filter_by(operation_id="OP-RS").order_by(IntegrationCall.id).all()
|
||||
assert len(rows) == 1
|
||||
assert rows[0].binding_snapshot_json["step_index"] == 1
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ③ 非末步失败 → 中止(后续步零调用),返回该步失败态
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_non_final_step_failure_aborts_remaining_steps(app):
|
||||
"""stage 判 technical_failed → 立即中止:submit 零调用,返回 technical_failed,仅 1 条审计。"""
|
||||
_seed_write_two_steps()
|
||||
stage = ScriptedTransport("database", {"status": "technical_failed", "code": "DB_ERROR", "message": "boom"})
|
||||
submit = ScriptedTransport("soap", _tiptop_raw(code="0", doc_no="1401-1"))
|
||||
|
||||
result = _gateway(stage, submit).call(
|
||||
capability="in_transit_transfer.create_transfer", context={},
|
||||
params=_order_params(), operation_id="OP-ABF", environment="prod",
|
||||
)
|
||||
|
||||
# 断言意图:非末步失败禁止继续触发 WS(防漏插先提交)
|
||||
assert result.status == "technical_failed"
|
||||
assert submit.calls == []
|
||||
rows = IntegrationCall.query.filter_by(operation_id="OP-ABF").order_by(IntegrationCall.id).all()
|
||||
assert len(rows) == 1
|
||||
assert rows[0].status == "technical_failed"
|
||||
assert rows[0].binding_snapshot_json["step_index"] == 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ④ 非末步超时 → 中止(后续步零调用),status=timeout 交上层按中止规则落位
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_non_final_step_timeout_aborts_remaining_steps(app):
|
||||
"""stage 抛 TimeoutError → 中止=技术失败:submit 零调用;审计行保 'timeout' 技术真相,
|
||||
引擎对外返回 technical_failed(error_code 与末步超时区分,防误入 result_unknown 红线态)。"""
|
||||
_seed_write_two_steps()
|
||||
stage = ScriptedTransport("database", TimeoutError())
|
||||
submit = ScriptedTransport("soap", _tiptop_raw(code="0", doc_no="1401-1"))
|
||||
|
||||
result = _gateway(stage, submit).call(
|
||||
capability="in_transit_transfer.create_transfer", context={},
|
||||
params=_order_params(), operation_id="OP-ABT", environment="prod",
|
||||
)
|
||||
|
||||
# 断言意图:非末步超时对外按技术失败落位(恢复路径=全量重跑,stage SQL 幂等),
|
||||
# error_code=EXTERNAL_TIMEOUT_ABORTED 与末步超时 EXTERNAL_TIMEOUT_UNKNOWN 可区分
|
||||
assert result.status == "technical_failed"
|
||||
assert result.error_code == "EXTERNAL_TIMEOUT_ABORTED"
|
||||
assert submit.calls == []
|
||||
rows = IntegrationCall.query.filter_by(operation_id="OP-ABT").all()
|
||||
assert len(rows) == 1
|
||||
# 断言意图:审计保留技术真相——该步 IntegrationCall.status 仍记 timeout(与对外口径分离)
|
||||
assert rows[0].status == "timeout"
|
||||
assert rows[0].binding_snapshot_json["step_index"] == 0
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ⑤ 末步映射 → classify 全链(success 带 mapped data)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_final_step_mapping_classify_chain_success(app):
|
||||
"""code='0':enum-map 映射出 status=success → classify success;data 恒带 mapped。"""
|
||||
_seed_write_two_steps()
|
||||
stage = ScriptedTransport("database", {"status": "success"})
|
||||
submit = ScriptedTransport("soap", _tiptop_raw(code="0", description="ok", doc_no="1401-2609230008"))
|
||||
|
||||
result = _gateway(stage, submit).call(
|
||||
capability="in_transit_transfer.create_transfer", context={},
|
||||
params=_order_params(), operation_id="OP-CHAIN", environment="prod",
|
||||
)
|
||||
|
||||
# 断言意图:末步 data 恒带 mapped(非原始响应);单号经 pick 提取
|
||||
assert result.status == "success"
|
||||
assert result.document_no == "1401-2609230008"
|
||||
assert result.data["status"] == "success"
|
||||
assert result.data["code"] == "0"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ⑥ 末步超时 → status=timeout(上层执行服务落 result_unknown,引擎不管)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_final_step_timeout_returns_timeout(app):
|
||||
"""末步(submit)抛 TimeoutError → status=timeout,且非末步已照常执行并审计。"""
|
||||
_seed_write_two_steps()
|
||||
stage = ScriptedTransport("database", {"status": "success"})
|
||||
submit = ScriptedTransport("soap", TimeoutError())
|
||||
|
||||
result = _gateway(stage, submit).call(
|
||||
capability="in_transit_transfer.create_transfer", context={},
|
||||
params=_order_params(), operation_id="OP-FT", environment="prod",
|
||||
)
|
||||
|
||||
assert result.status == "timeout"
|
||||
# 断言意图:超时发生在末步——stage 已成功执行,两步各落一条审计
|
||||
assert len(stage.calls) == 1
|
||||
rows = IntegrationCall.query.filter_by(operation_id="OP-FT").order_by(IntegrationCall.id).all()
|
||||
assert [row.binding_snapshot_json["step_index"] for row in rows] == [0, 1]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ⑦ code='0' → success;code 缺失(映射未覆盖 status)→ classify 兜底 technical_failed
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_final_step_classify_fallback_on_zero_or_missing_code(app):
|
||||
"""code='0' 经 enum-map 映射 success;code 缺失(空 Status)时映射不产出 status,
|
||||
classify 按原始响应兜底归 technical_failed(畸形/无码响应禁止误判成功)。"""
|
||||
_seed_write_two_steps()
|
||||
stage_ok = ScriptedTransport("database", {"status": "success"})
|
||||
submit_ok = ScriptedTransport("soap", _tiptop_raw(code="0", doc_no="1401-1"))
|
||||
result_ok = _gateway(stage_ok, submit_ok).call(
|
||||
capability="in_transit_transfer.create_transfer", context={},
|
||||
params=_order_params(), operation_id="OP-Z0", environment="prod",
|
||||
)
|
||||
assert result_ok.status == "success"
|
||||
|
||||
stage_miss = ScriptedTransport("database", {"status": "success"})
|
||||
submit_miss = ScriptedTransport("soap", {"Response": {"Execution": {"Status": {}}}})
|
||||
result_miss = _gateway(stage_miss, submit_miss).call(
|
||||
capability="in_transit_transfer.create_transfer", context={},
|
||||
params=_order_params(), operation_id="OP-ZM", environment="prod",
|
||||
)
|
||||
# 断言意图:缺失 code 的畸形响应按技术失败兜底(classify 未知 status 不猜测语义)
|
||||
assert result_miss.status == "technical_failed"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ⑧ ERP 业务拒单(code≠0)→ technical_failed,code/message 随 data 透传
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_erp_business_reject_maps_technical_failed_with_data_passthrough(app):
|
||||
"""R8 用户口径:ERP 返回非 0 业务码(查不到 30 行)= 失败+原因——classify 归
|
||||
technical_failed(enum-map 未命中原样穿透为未知 status),ERP 业务码与描述
|
||||
经 result.data 原样携带供上层消费;不再二次改判 business_failed。"""
|
||||
_seed_write_two_steps()
|
||||
stage = ScriptedTransport("database", {"status": "success"})
|
||||
submit = ScriptedTransport("soap", _tiptop_raw(code="B1234", description="料号无有效成本"))
|
||||
|
||||
result = _gateway(stage, submit).call(
|
||||
capability="in_transit_transfer.create_transfer", context={},
|
||||
params=_order_params(), operation_id="OP-REJ", environment="prod",
|
||||
)
|
||||
|
||||
# 断言意图:非 0 码即失败(technical_failed),不再区分业务/技术内部标签;
|
||||
# 描述透传走 data(code/message 原样保留),失败态下 data 恒带 mapped
|
||||
assert result.status == "technical_failed"
|
||||
assert result.data["code"] == "B1234"
|
||||
assert result.data["message"] == "料号无有效成本"
|
||||
assert result.document_no is None
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ⑨ 每步一条 IntegrationCall:同 operation_id + step_index 定位
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_each_step_records_integration_call_with_step_index(app):
|
||||
"""成功两步 → 两条审计同裸 operation_id;step_index 递增可排序、定位各步接口/客户端。"""
|
||||
_seed_write_two_steps()
|
||||
stage = ScriptedTransport("database", {"status": "success"})
|
||||
submit = ScriptedTransport("soap", _tiptop_raw(code="0", doc_no="1401-1"))
|
||||
|
||||
_gateway(stage, submit).call(
|
||||
capability="in_transit_transfer.create_transfer", context={},
|
||||
params=_order_params(), operation_id="OP-AUD", environment="prod",
|
||||
)
|
||||
|
||||
rows = IntegrationCall.query.filter_by(operation_id="OP-AUD").order_by(IntegrationCall.id).all()
|
||||
# 断言意图:一单一次执行 = N 条审计同 operation_id(串联键),step_index 递增可排序
|
||||
assert len(rows) == 2
|
||||
assert all(row.operation_id == "OP-AUD" for row in rows)
|
||||
assert [row.binding_snapshot_json["step_index"] for row in rows] == [0, 1]
|
||||
assert [row.binding_snapshot_json["step_count"] for row in rows] == [2, 2]
|
||||
assert [row.binding_snapshot_json["interface_code"] for row in rows] == ["IFACE-STAGE", "IFACE-SUBMIT"]
|
||||
assert [row.binding_snapshot_json["client_code"] for row in rows] == ["CLI-STAGE", "CLI-WS"]
|
||||
assert all(row.capability == "in_transit_transfer.create_transfer" for row in rows)
|
||||
assert rows[1].status == "success"
|
||||
|
||||
|
||||
def test_integration_call_operation_id_index_contract():
|
||||
"""模型元数据契约:operation_id 无唯一约束(多步审计 N 行同值)、有普通索引补位查询。
|
||||
|
||||
断言意图:锁定「删 uq_integration_calls_operation_id + 建 ix_integration_calls_operation_id」
|
||||
的迁移终态不被模型改动悄悄回退(唯一约束会让多步审计落库直接失败)。
|
||||
"""
|
||||
import sqlalchemy as sa
|
||||
|
||||
table = IntegrationCall.__table__
|
||||
unique_col_sets = {
|
||||
tuple(sorted(col.name for col in constraint.columns))
|
||||
for constraint in table.constraints
|
||||
if isinstance(constraint, sa.UniqueConstraint)
|
||||
}
|
||||
assert ('operation_id',) not in unique_col_sets
|
||||
index_col_sets = {
|
||||
tuple(sorted(col.name for col in index.columns))
|
||||
for index in table.indexes
|
||||
}
|
||||
assert ('operation_id',) in index_col_sets
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ⑩ 读能力行为不变(回归):单步 + 成功态映射 + 失败直通
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_read_capability_behavior_unchanged(app):
|
||||
"""读能力回归:success 映射出 data(decimal 转换保留);传输层失败态原样分类。"""
|
||||
_seed_read_single_step()
|
||||
fake = ScriptedTransport("rest", {"found": True, "quantity": "100"})
|
||||
result = CapabilityGateway(transports={"rest": fake}).call(
|
||||
capability="in_transit_transfer.query_inventory", context={},
|
||||
params=_params(), operation_id="OP-RD", environment="prod",
|
||||
)
|
||||
# 断言意图:读路径输出映射/分类语义与 Task 4 之前完全一致
|
||||
assert result.status == "success"
|
||||
assert result.data["quantity"] == Decimal("100")
|
||||
rows = IntegrationCall.query.filter_by(operation_id="OP-RD").all()
|
||||
assert len(rows) == 1
|
||||
assert rows[0].binding_snapshot_json["step_index"] == 0
|
||||
|
||||
fake_fail = ScriptedTransport("rest", {"status": "business_failed", "code": "HTTP_500", "message": "boom"})
|
||||
result_fail = CapabilityGateway(transports={"rest": fake_fail}).call(
|
||||
capability="in_transit_transfer.query_inventory", context={},
|
||||
params=_params(), operation_id="OP-RD2", environment="prod",
|
||||
)
|
||||
assert result_fail.status == "business_failed"
|
||||
assert result_fail.error_code == "HTTP_500"
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# ⑪⑫ on_nonfinal_success 步进回调(T10 断点标记机制)
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
class _EventTransport(ScriptedTransport):
|
||||
"""在 ScriptedTransport 之上向全局事件表记录传输调用时序。"""
|
||||
|
||||
def __init__(self, connector_type: str, response, events: list, label: str):
|
||||
super().__init__(connector_type, response)
|
||||
self._events = events
|
||||
self._label = label
|
||||
|
||||
def call(self, **kwargs):
|
||||
self._events.append(f"transport:{self._label}")
|
||||
return super().call(**kwargs)
|
||||
|
||||
|
||||
def test_nonfinal_success_callback_fires_between_steps(app):
|
||||
"""回调在非末步成功放行(审计落库)后、末步执行前同步触发一次,收到该步快照与步号。"""
|
||||
_seed_write_two_steps()
|
||||
events: list[str] = []
|
||||
seen: list[tuple[str, int]] = []
|
||||
stage = _EventTransport("database", {"status": "success"}, events, "stage")
|
||||
submit = _EventTransport("soap", _tiptop_raw(code="0", doc_no="1401-2609230007"), events, "submit")
|
||||
|
||||
def on_stage_confirmed(step, index):
|
||||
seen.append((step.interface_code, index))
|
||||
events.append(f"callback:{index}")
|
||||
|
||||
result = _gateway(stage, submit).call(
|
||||
capability="in_transit_transfer.create_transfer", context={},
|
||||
params=_order_params(), operation_id="OP-CB1", environment="prod",
|
||||
on_nonfinal_success=on_stage_confirmed,
|
||||
)
|
||||
|
||||
# 断言意图:回调恰好一次、收到步 0 的 BindingStep 定位信息
|
||||
assert seen == [("IFACE-STAGE", 0)]
|
||||
# 断言意图:时序锁定 stage 传输成功 → 回调(断点标记)→ submit 传输(先落库再触发)
|
||||
assert events == ["transport:stage", "callback:0", "transport:submit"]
|
||||
assert result.status == "success"
|
||||
|
||||
|
||||
def test_nonfinal_success_callback_exception_aborts_as_technical_failed(app):
|
||||
"""回调抛异常 → 按该步失败处理:中止 technical_failed、后续步零调用、异常结果追加落审计。"""
|
||||
_seed_write_two_steps()
|
||||
stage = ScriptedTransport("database", {"status": "success"})
|
||||
submit = ScriptedTransport("soap", _tiptop_raw(code="0", doc_no="1401-1"))
|
||||
|
||||
def boom(step, index):
|
||||
raise RuntimeError("stage_confirmed_at flush failed")
|
||||
|
||||
result = _gateway(stage, submit).call(
|
||||
capability="in_transit_transfer.create_transfer", context={},
|
||||
params=_order_params(), operation_id="OP-CB2", environment="prod",
|
||||
on_nonfinal_success=boom,
|
||||
)
|
||||
|
||||
# 断言意图:回调异常禁止继续触发末步(断点未落库不得触发),对外按技术失败
|
||||
assert result.status == "technical_failed"
|
||||
assert result.error_code == "STEP_CALLBACK_FAILED"
|
||||
assert submit.calls == []
|
||||
rows = IntegrationCall.query.filter_by(operation_id="OP-CB2").order_by(IntegrationCall.id).all()
|
||||
# 断言意图:append-only 审计——原传输成功行保留,追加一行回调异常(同 operation_id 同步号)
|
||||
assert [row.status for row in rows] == ["success", "technical_failed"]
|
||||
assert all(row.binding_snapshot_json["step_index"] == 0 for row in rows)
|
||||
@@ -133,10 +133,23 @@ def test_pick_exists_boolean():
|
||||
assert mapped_absent["found"] is False
|
||||
|
||||
|
||||
def test_pick_single_dict_normalized_as_one_element_list():
|
||||
"""单条 Field(dict)按单元素列表语义 pick(回归:ERP 返回单条 doc_no Field
|
||||
时 pick_target_not_list → 单号丢失,调拨单被误判 technical_failed)。"""
|
||||
mapped = map_response(
|
||||
{"doc_no": {"expr": "Parameter.Record.Field", "transform": "pick",
|
||||
"args": {"key_field": "@name", "key_value": "doc_no", "value_field": "@value"}}},
|
||||
{"Parameter": {"Record": {"Field": {"@name": "doc_no", "@value": "1406-2609260001"}}}},
|
||||
{},
|
||||
)
|
||||
assert mapped["doc_no"] == "1406-2609260001"
|
||||
|
||||
|
||||
def test_pick_requires_list_and_key_args():
|
||||
# 标量目标仍拒绝(既非 dict 也非 list,无键值对语义)
|
||||
with pytest.raises(AppError):
|
||||
map_response({"q": {"expr": "rows", "transform": "pick", "args": {"key_field": "@name", "key_value": "x"}}},
|
||||
{"rows": {"not": "a list"}}, {})
|
||||
{"rows": "not-a-structure"}, {})
|
||||
with pytest.raises(AppError):
|
||||
map_response({"q": {"expr": "rows", "transform": "pick", "args": {"key_field": "@name"}}},
|
||||
{"rows": _field_rows()}, {})
|
||||
@@ -183,16 +196,16 @@ def test_template_missing_param_fail_closed():
|
||||
assert exc.value.code == "INTEGRATION.MAPPING_INVALID"
|
||||
|
||||
|
||||
# ---- dict 项列表模板:域元组列表 → OR 拼接条件(料号+库位+批号批量查询)----
|
||||
# ---- 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}')",
|
||||
"args": {"list_item_template": "(img01 = '{material_no}' AND img02 = '{warehouse_code}' 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"},
|
||||
{"material_no": "M-1", "warehouse_code": "HTP-D43", "lot_no": "LOT-1"},
|
||||
{"material_no": "M'2", "warehouse_code": "HTP-D49", "lot_no": "LOT-2"},
|
||||
]},
|
||||
{"type": "object", "properties": {"condition": {"type": "string"}}},
|
||||
)
|
||||
|
||||
+36
-28
@@ -21,30 +21,33 @@ from app.services.integration_connector.mapping import extract_path, map_respons
|
||||
from app.services.integration_connector.transports.base import IntegrationCallResult
|
||||
from app.services.integration_connector.transports.soap import _parse_soap_payload
|
||||
|
||||
# 生产绑定同构的 rows 映射(expr/each/pick 与 2026-09-22 回归用例一致,
|
||||
# from_warehouse 按 img02、批号 img04、库存数 img10)。
|
||||
# 生产绑定同构的 rows 映射(expr/each/pick 与生产 response_mapping 一致:
|
||||
# material_no=img01 料件编号、warehouse_code=img02 仓库编号、lot_no=img04 批号、
|
||||
# stock_quantity=img10 库存数量、stock_unit=img09 库存单位)。
|
||||
_ROWS_MAPPING = {"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"}},
|
||||
"from_warehouse": {"expr": "Record.Field", "transform": "pick",
|
||||
"warehouse_code": {"expr": "Record.Field", "transform": "pick",
|
||||
"args": {"key_field": "@name", "key_value": "img02", "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"}}}}}}
|
||||
"stock_quantity": {"expr": "Record.Field", "transform": "pick",
|
||||
"args": {"key_field": "@name", "key_value": "img10", "value_field": "@value",
|
||||
"cast": "decimal"}},
|
||||
"stock_unit": {"expr": "Record.Field", "transform": "pick",
|
||||
"args": {"key_field": "@name", "key_value": "img09", "value_field": "@value"}}}}}}
|
||||
_ROWS_OUTPUT_SCHEMA = {"type": "object", "required": ["rows"], "properties": {"rows": {"type": "array", "items": {
|
||||
"type": "object", "required": ["material_no", "from_warehouse", "lot_no", "quantity"]}}}}
|
||||
"type": "object", "required": ["material_no", "warehouse_code", "lot_no", "stock_quantity"]}}}}
|
||||
|
||||
|
||||
def _field(name: str, value: str) -> dict:
|
||||
return {"@name": name, "@value": value}
|
||||
|
||||
|
||||
def _record(material: str, warehouse: str, lot: str, qty: str) -> dict:
|
||||
def _record(material: str, warehouse: str, lot: str, qty: str, unit: str = "PCS") -> dict:
|
||||
return {"Field": [_field("img01", material), _field("img02", warehouse),
|
||||
_field("img04", lot), _field("img10", qty)]}
|
||||
_field("img04", lot), _field("img09", unit), _field("img10", qty)]}
|
||||
|
||||
|
||||
def _stock_response(record_sets: list[dict]) -> dict:
|
||||
@@ -69,7 +72,8 @@ def test_single_target_single_record_maps_one_row():
|
||||
{"@id": "1", "Master": {"@name": "img_file", "Record": _record("M-1", "W-1", "L-1", "30")}},
|
||||
])
|
||||
rows = map_response(_ROWS_MAPPING, raw, _ROWS_OUTPUT_SCHEMA)["rows"]
|
||||
assert rows == [{"material_no": "M-1", "from_warehouse": "W-1", "lot_no": "L-1", "quantity": Decimal("30")}]
|
||||
assert rows == [{"material_no": "M-1", "warehouse_code": "W-1", "lot_no": "L-1",
|
||||
"stock_quantity": Decimal("30"), "stock_unit": "PCS"}]
|
||||
|
||||
|
||||
def test_multi_record_master_maps_every_record_row():
|
||||
@@ -89,9 +93,12 @@ def test_multi_record_master_maps_every_record_row():
|
||||
rows = map_response(_ROWS_MAPPING, raw, _ROWS_OUTPUT_SCHEMA)["rows"]
|
||||
# [断言意图] 同料号不同批号(L-1/L-2)与同批号不同料号(M-1/M-2)全部保留。
|
||||
assert rows == [
|
||||
{"material_no": "M-1", "from_warehouse": "W-1", "lot_no": "L-1", "quantity": Decimal("30")},
|
||||
{"material_no": "M-1", "from_warehouse": "W-1", "lot_no": "L-2", "quantity": Decimal("40")},
|
||||
{"material_no": "M-2", "from_warehouse": "W-1", "lot_no": "L-1", "quantity": Decimal("36")},
|
||||
{"material_no": "M-1", "warehouse_code": "W-1", "lot_no": "L-1",
|
||||
"stock_quantity": Decimal("30"), "stock_unit": "PCS"},
|
||||
{"material_no": "M-1", "warehouse_code": "W-1", "lot_no": "L-2",
|
||||
"stock_quantity": Decimal("40"), "stock_unit": "PCS"},
|
||||
{"material_no": "M-2", "warehouse_code": "W-1", "lot_no": "L-1",
|
||||
"stock_quantity": Decimal("36"), "stock_unit": "PCS"},
|
||||
]
|
||||
|
||||
|
||||
@@ -107,8 +114,9 @@ def test_multi_recordset_with_multi_record_master_keeps_all_rows():
|
||||
rows = map_response(_ROWS_MAPPING, raw, _ROWS_OUTPUT_SCHEMA)["rows"]
|
||||
# [断言意图] RecordSet 逐元素扇出 + 重复 Record 展开叠加时行数完整(2+1=3 行)。
|
||||
assert len(rows) == 3
|
||||
assert rows[0]["quantity"] == Decimal("30")
|
||||
assert rows[2] == {"material_no": "M-2", "from_warehouse": "W-2", "lot_no": "L-9", "quantity": Decimal("40")}
|
||||
assert rows[0]["stock_quantity"] == Decimal("30")
|
||||
assert rows[2] == {"material_no": "M-2", "warehouse_code": "W-2", "lot_no": "L-9",
|
||||
"stock_quantity": Decimal("40"), "stock_unit": "PCS"}
|
||||
|
||||
|
||||
def test_batch_vs_single_lookup_parity_on_multi_record_response():
|
||||
@@ -130,19 +138,19 @@ def test_batch_vs_single_lookup_parity_on_multi_record_response():
|
||||
batch_rows = map_response(_ROWS_MAPPING, raw_batch, _ROWS_OUTPUT_SCHEMA)["rows"]
|
||||
single_rows = map_response(_ROWS_MAPPING, raw_single, _ROWS_OUTPUT_SCHEMA)["rows"]
|
||||
|
||||
targets = [StockTarget(material_no="M-1", from_warehouse="W-1", lot_no="L-1"),
|
||||
StockTarget(material_no="M-1", from_warehouse="W-1", lot_no="L-2"),
|
||||
StockTarget(material_no="M-2", from_warehouse="W-1", lot_no="L-1")]
|
||||
targets = [StockTarget(material_no="M-1", warehouse_code="W-1", lot_no="L-1"),
|
||||
StockTarget(material_no="M-1", warehouse_code="W-1", lot_no="L-2"),
|
||||
StockTarget(material_no="M-2", warehouse_code="W-1", lot_no="L-1")]
|
||||
batch_result = _client_with_rows(batch_rows).query_stock(
|
||||
operation_id="op-batch", external_org="HX-CN01", targets=targets)
|
||||
single_result = _client_with_rows(single_rows).query_stock(
|
||||
operation_id="op-single", external_org="HX-CN01", targets=[targets[0]])
|
||||
|
||||
# [断言意图] 批量与单查逐 target 对账一致:批量不再整批 0(inventory_not_found)。
|
||||
assert single_result.lookup(material_no="M-1", from_warehouse="W-1", lot_no="L-1") == Decimal("30")
|
||||
assert batch_result.lookup(material_no="M-1", from_warehouse="W-1", lot_no="L-1") == Decimal("30")
|
||||
assert batch_result.lookup(material_no="M-1", from_warehouse="W-1", lot_no="L-2") == Decimal("40")
|
||||
assert batch_result.lookup(material_no="M-2", from_warehouse="W-1", lot_no="L-1") == Decimal("36")
|
||||
assert single_result.lookup(material_no="M-1", warehouse_code="W-1", lot_no="L-1") == Decimal("30")
|
||||
assert batch_result.lookup(material_no="M-1", warehouse_code="W-1", lot_no="L-1") == Decimal("30")
|
||||
assert batch_result.lookup(material_no="M-1", warehouse_code="W-1", lot_no="L-2") == Decimal("40")
|
||||
assert batch_result.lookup(material_no="M-2", warehouse_code="W-1", lot_no="L-1") == Decimal("36")
|
||||
|
||||
|
||||
def test_soap_multi_record_payload_end_to_end_mapping():
|
||||
@@ -163,7 +171,7 @@ def test_soap_multi_record_payload_end_to_end_mapping():
|
||||
raw = _parse_soap_payload(xml)
|
||||
rows = map_response(_ROWS_MAPPING, raw, _ROWS_OUTPUT_SCHEMA)["rows"]
|
||||
# [断言意图] 转义内嵌报文同样走归一化+映射:两条 Record(不同批号)都成行。
|
||||
assert [(r["lot_no"], str(r["quantity"])) for r in rows] == [("L-1", "30"), ("L-2", "40")]
|
||||
assert [(r["lot_no"], str(r["stock_quantity"])) for r in rows] == [("L-1", "30"), ("L-2", "40")]
|
||||
|
||||
|
||||
def test_extract_path_fanout_nested_list_flattened():
|
||||
@@ -193,11 +201,11 @@ def test_case_and_space_variants_pass_through_exact_match():
|
||||
])
|
||||
rows = map_response(_ROWS_MAPPING, raw, _ROWS_OUTPUT_SCHEMA)["rows"]
|
||||
# [断言意图] 行值原样保留(未改写大小写、未截断空格)。
|
||||
assert rows == [{"material_no": "m-1 ", "from_warehouse": "W-1", "lot_no": "l-1",
|
||||
"quantity": Decimal("30")}]
|
||||
assert rows == [{"material_no": "m-1 ", "warehouse_code": "W-1", "lot_no": "l-1",
|
||||
"stock_quantity": Decimal("30"), "stock_unit": "PCS"}]
|
||||
result = _client_with_rows(rows).query_stock(
|
||||
operation_id="op-case", external_org="HX-CN01",
|
||||
targets=[StockTarget(material_no="M-1", from_warehouse="W-1", lot_no="L-1")])
|
||||
targets=[StockTarget(material_no="M-1", warehouse_code="W-1", lot_no="L-1")])
|
||||
# [断言意图] 精确匹配下大小写/空格不同的键不命中(两侧路径同语义)。
|
||||
assert result.lookup(material_no="M-1", from_warehouse="W-1", lot_no="L-1") is None
|
||||
assert result.lookup(material_no="m-1 ", from_warehouse="W-1", lot_no="l-1") == Decimal("30")
|
||||
assert result.lookup(material_no="M-1", warehouse_code="W-1", lot_no="L-1") is None
|
||||
assert result.lookup(material_no="m-1 ", warehouse_code="W-1", lot_no="l-1") == Decimal("30")
|
||||
@@ -0,0 +1,49 @@
|
||||
"""tests/services/integration_connector/test_rest_transport.py
|
||||
|
||||
用途:Task 3——RestTransport call 返回 dict 附带保留键 `_wire`(线级事实),
|
||||
供调用日志引擎(Task 4)剥离落库 IntegrationCall.wire_json。
|
||||
依赖:transports.rest(http_request 注入替身,不触网)。
|
||||
逻辑:FakeResponse 提供 text/status_code/raise_for_status 三件套;断言 _wire 含
|
||||
kind/method/url/请求头(脱敏)/请求体/状态码/响应体(脱敏、截断)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.integration_connector.transports.rest import RestTransport
|
||||
|
||||
|
||||
class FakeResponse:
|
||||
"""HTTP 响应替身:text/status_code/raise_for_status 三件套(与 requests.Response 同形)。"""
|
||||
|
||||
def __init__(self, text: str = '', status_code: int = 200):
|
||||
self.text = text
|
||||
self.status_code = status_code
|
||||
|
||||
def raise_for_status(self) -> None:
|
||||
"""模拟 requests 语义:≥400 抛 HTTPError(当前传输层不调用,仅为形状完整)。"""
|
||||
if self.status_code >= 400:
|
||||
import requests
|
||||
raise requests.HTTPError(f'HTTP {self.status_code}')
|
||||
|
||||
|
||||
def test_call_attaches_wire_with_method_url_headers_body(monkeypatch):
|
||||
"""call 后 _wire 记录 method/url/脱敏请求头/请求体/状态码/响应体(线级事实)。"""
|
||||
captured = {}
|
||||
|
||||
def fake_http(method, url, **kwargs):
|
||||
captured.update(method=method, url=url, kwargs=kwargs)
|
||||
return FakeResponse(text='{"ok": true}', status_code=200)
|
||||
|
||||
transport = RestTransport(http_request=fake_http)
|
||||
result = transport.call(
|
||||
client={'config_json': {'endpoint': 'http://api', 'headers': {'X-App': 'hxops'}}},
|
||||
interface={'request_spec_json': {'method': 'POST', 'path': 'v1/things'}},
|
||||
request={'body': {'a': 1}},
|
||||
)
|
||||
wire = result['_wire']
|
||||
# 关键断言:url 为 endpoint+path 拼接、请求体为 JSON 序列化的最终报文
|
||||
assert wire['kind'] == 'rest'
|
||||
assert wire['method'] == 'POST'
|
||||
assert wire['url'] == 'http://api/v1/things'
|
||||
assert wire['http_status'] == 200
|
||||
assert '"a": 1' in wire['request_body'] or wire['request_body'] == '{"a":1}'
|
||||
@@ -0,0 +1,75 @@
|
||||
"""tests/services/integration_connector/test_soap_transport.py
|
||||
|
||||
用途:Task 3——SoapTransport call 返回 dict 附带保留键 `_wire`(线级事实),
|
||||
供调用日志引擎(Task 4)剥离落库 IntegrationCall.wire_json。
|
||||
依赖:transports.soap(http_request 注入替身,不触网)。
|
||||
逻辑:FakeResponse 提供 text/status_code/raise_for_status 三件套;断言 _wire 含
|
||||
method/url/soap_action/request_body/http_status/response_body,且
|
||||
request_body 中的凭据值已脱敏;既有 NON_XML / HTTP≥400 分类行为不变。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from app.services.integration_connector.transports.soap import SoapTransport
|
||||
|
||||
|
||||
class FakeResponse:
|
||||
"""HTTP 响应替身:text/status_code/raise_for_status 三件套(与 requests.Response 同形)。"""
|
||||
|
||||
def __init__(self, text: str = '', status_code: int = 200):
|
||||
self.text = text
|
||||
self.status_code = status_code
|
||||
|
||||
def raise_for_status(self) -> None:
|
||||
"""模拟 requests 语义:≥400 抛 HTTPError(当前传输层不调用,仅为形状完整)。"""
|
||||
if self.status_code >= 400:
|
||||
import requests
|
||||
raise requests.HTTPError(f'HTTP {self.status_code}')
|
||||
|
||||
|
||||
def test_call_attaches_wire_with_url_body_and_response():
|
||||
"""call 成功后 _wire 记录 method/url/soap_action/请求体/状态码/响应体(线级事实)。"""
|
||||
captured = {}
|
||||
|
||||
def fake_http(method, url, **kwargs):
|
||||
captured['method'], captured['url'], captured['kwargs'] = method, url, kwargs
|
||||
return FakeResponse(text='<Envelope><Body><ok>1</ok></Body></Envelope>', status_code=200)
|
||||
|
||||
transport = SoapTransport(http_request=fake_http)
|
||||
result = transport.call(
|
||||
# 凭据值避免单字母(如 'u'):mask_secrets 按值做子串替换,单字母会把
|
||||
# Envelope 等普通文本一并打码,无法区分"脱敏生效"与"误伤"。
|
||||
client={'config_json': {'endpoint': 'http://erp/WS?wsdl', 'timeout_seconds': 30},
|
||||
'credential': {'username': 'u1', 'password': 'p1'}},
|
||||
interface={'request_spec_json': {'method': 'POST', 'soap': {
|
||||
'action': 'do.it',
|
||||
'body_template': '<Env><a>{credential_username}</a><b>{v}</b></Env>'}}},
|
||||
request={'params': {'v': '1'}},
|
||||
)
|
||||
wire = result['_wire']
|
||||
# 关键断言:soap_action 按规范带引号、request_body 为凭据脱敏后的最终报文
|
||||
# (mask_secrets 按凭据值替换:username 'u' 注入报文后同被替换为 ***,
|
||||
# 与任务书接口规格 request_body(masked) 一致)、response_body 无凭据时保持原文。
|
||||
assert wire['kind'] == 'soap'
|
||||
assert wire['method'] == 'POST'
|
||||
assert wire['url'] == 'http://erp/WS?wsdl'
|
||||
assert wire['soap_action'] == '"do.it"'
|
||||
assert wire['request_body'] == '<Env><a>***</a><b>1</b></Env>'
|
||||
assert wire['http_status'] == 200
|
||||
assert 'Envelope' in wire['response_body']
|
||||
|
||||
|
||||
def test_call_wire_masks_credential_in_body():
|
||||
"""_wire.request_body 中的凭据值必须替换为 ***,防凭据进审计列。"""
|
||||
|
||||
def fake_http(method, url, **kwargs):
|
||||
return FakeResponse(text='<Envelope/>', status_code=200)
|
||||
|
||||
transport = SoapTransport(http_request=fake_http)
|
||||
result = transport.call(
|
||||
client={'config_json': {'endpoint': 'http://erp/WS'}, 'credential': {'password': 'sup3r'}},
|
||||
interface={'request_spec_json': {'soap': {'action': '', 'body_template': '<p>{credential_password}</p>'}}},
|
||||
request={'params': {}},
|
||||
)
|
||||
# 关键断言:凭据明文不得出现在落库线级事实中
|
||||
assert 'sup3r' not in result['_wire']['request_body']
|
||||
@@ -53,7 +53,8 @@ def test_rest_builds_url_and_sends_request():
|
||||
assert captured["url"] == "https://erp.invalid/stock"
|
||||
assert captured["method"] == "GET"
|
||||
assert captured["params"] == {"invoice_no": "INV-001"}
|
||||
assert result == {"found": True, "quantity": "100"}
|
||||
# `_wire` 为调用日志新增的保留键(线级事实,由引擎剥离落库),全等断言排除该键。
|
||||
assert {k: v for k, v in result.items() if k != "_wire"} == {"found": True, "quantity": "100"}
|
||||
|
||||
|
||||
def test_rest_business_error_maps_to_dict():
|
||||
@@ -389,3 +390,66 @@ def test_soap_probe_failure_paths():
|
||||
|
||||
with pytest.raises(TransportNotFrozenError):
|
||||
SoapTransport().probe(client={"config_json": {}})
|
||||
|
||||
|
||||
# ---- Oracle thick 模式 lib_dir 取值优先级(11g 等老服务端必须 thick) ----
|
||||
|
||||
def test_oracle_connect_lib_dir_client_config_overrides_env(monkeypatch):
|
||||
"""oracle thick 目录:按客户端 config_json.oracle_lib_dir 优先于全局环境变量。"""
|
||||
import sys
|
||||
import types
|
||||
|
||||
from app.services.integration_connector.transports.database import _connect_oracle
|
||||
|
||||
captured = {}
|
||||
fake_oracledb = types.SimpleNamespace(
|
||||
init_oracle_client=lambda lib_dir=None: captured.setdefault('lib_dir', lib_dir),
|
||||
connect=lambda **kw: types.SimpleNamespace(),
|
||||
)
|
||||
monkeypatch.setitem(sys.modules, 'oracledb', fake_oracledb)
|
||||
monkeypatch.setenv('ORACLE_CLIENT_LIB_DIR', r'C:\global\instantclient')
|
||||
|
||||
_connect_oracle(
|
||||
config={'endpoint': 'h:1521/svc', 'oracle_lib_dir': r'C:\client\dir'},
|
||||
credential={'username': 'u', 'password': 'p'},
|
||||
)
|
||||
# 按客户端配置优先(关键断言)
|
||||
assert captured['lib_dir'] == r'C:\client\dir'
|
||||
|
||||
|
||||
def test_oracle_connect_lib_dir_falls_back_to_env(monkeypatch):
|
||||
"""oracle thick 目录:未配置 oracle_lib_dir 时回退 ORACLE_CLIENT_LIB_DIR 环境变量。"""
|
||||
import sys
|
||||
import types
|
||||
|
||||
from app.services.integration_connector.transports.database import _connect_oracle
|
||||
|
||||
captured = {}
|
||||
fake_oracledb = types.SimpleNamespace(
|
||||
init_oracle_client=lambda lib_dir=None: captured.setdefault('lib_dir', lib_dir),
|
||||
connect=lambda **kw: types.SimpleNamespace(),
|
||||
)
|
||||
monkeypatch.setitem(sys.modules, 'oracledb', fake_oracledb)
|
||||
monkeypatch.setenv('ORACLE_CLIENT_LIB_DIR', r'C:\global\instantclient')
|
||||
|
||||
_connect_oracle(config={'endpoint': 'h:1521/svc'}, credential={'username': 'u', 'password': 'p'})
|
||||
assert captured['lib_dir'] == r'C:\global\instantclient'
|
||||
|
||||
|
||||
def test_oracle_connect_without_lib_dir_skips_thick_init(monkeypatch):
|
||||
"""oracle thick 目录:两侧均未配置时不调 init_oracle_client(保持 thin 模式)。"""
|
||||
import sys
|
||||
import types
|
||||
|
||||
from app.services.integration_connector.transports.database import _connect_oracle
|
||||
|
||||
monkeypatch.delenv('ORACLE_CLIENT_LIB_DIR', raising=False)
|
||||
called = {'init': 0}
|
||||
fake_oracledb = types.SimpleNamespace(
|
||||
init_oracle_client=lambda lib_dir=None: called.__setitem__('init', called['init'] + 1),
|
||||
connect=lambda **kw: types.SimpleNamespace(),
|
||||
)
|
||||
monkeypatch.setitem(sys.modules, 'oracledb', fake_oracledb)
|
||||
|
||||
_connect_oracle(config={'endpoint': 'h:1521/svc'}, credential={'username': 'u', 'password': 'p'})
|
||||
assert called['init'] == 0
|
||||
@@ -0,0 +1,114 @@
|
||||
"""
|
||||
backend/tests/test_integration_calls_operation_id_migration.py
|
||||
|
||||
用途:验证 integration_calls.operation_id 唯一约束删除迁移(tt5b6c7d8e9f)可完整
|
||||
upgrade/downgrade 往返(多步顺序引擎审计契约的库级防线)。
|
||||
依赖:Alembic Operations、SQLite 内存数据库、tt5b6c7d8e9f 迁移。
|
||||
逻辑:前置建含 uq_integration_calls_operation_id 唯一约束的 integration_calls 表
|
||||
(ic1a2b3c4d5f 原状),upgrade 后唯一约束删除、同名普通索引补回且同
|
||||
operation_id 两行可共存(一票一次执行 = N 步审计);清理多步行后 downgrade
|
||||
重建唯一约束,重复插入被 IntegrityError 拒绝。带重复行直接 downgrade 按迁移
|
||||
文档预期报错(旧唯一约束与多步审计不兼容),不属本往返用例覆盖范围。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib
|
||||
|
||||
import pytest
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
_MIGRATION_MODULE = (
|
||||
'migrations.versions.tt5b6c7d8e9f_drop_integration_calls_operation_unique'
|
||||
)
|
||||
_UQ_NAME = 'uq_integration_calls_operation_id'
|
||||
_IX_NAME = 'ix_integration_calls_operation_id'
|
||||
|
||||
|
||||
def _pre_migration_schema(engine: sa.Engine) -> None:
|
||||
"""迁移前形态:integration_calls 带 operation_id 唯一约束(单步审计时代原状)。"""
|
||||
metadata = sa.MetaData()
|
||||
sa.Table(
|
||||
'integration_calls',
|
||||
metadata,
|
||||
sa.Column('id', sa.Integer(), primary_key=True),
|
||||
sa.Column('operation_id', sa.String(128), nullable=False),
|
||||
sa.Column('capability', sa.String(128)),
|
||||
sa.Column('status', sa.String(32)),
|
||||
sa.UniqueConstraint('operation_id', name=_UQ_NAME),
|
||||
)
|
||||
metadata.create_all(engine)
|
||||
|
||||
|
||||
def _insert_call(connection: sa.Connection, operation_id: str) -> None:
|
||||
"""插入一条最小审计行(仅唯一约束相关列有业务含义,其余可空)。"""
|
||||
connection.execute(
|
||||
sa.text(
|
||||
'INSERT INTO integration_calls (operation_id, capability, status) '
|
||||
'VALUES (:operation_id, :capability, :status)'
|
||||
),
|
||||
{
|
||||
'operation_id': operation_id,
|
||||
'capability': 'in_transit_transfer.create_transfer',
|
||||
'status': 'success',
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
def test_integration_calls_operation_unique_drop_round_trip(monkeypatch):
|
||||
"""关键断言:upgrade 后同 operation_id 两行可共存且普通索引补回;
|
||||
downgrade 重建唯一约束、重复插入被拒。"""
|
||||
migration = importlib.import_module(_MIGRATION_MODULE)
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
_pre_migration_schema(engine)
|
||||
|
||||
with engine.begin() as connection:
|
||||
operations = Operations(MigrationContext.configure(connection))
|
||||
monkeypatch.setattr(migration, 'op', operations)
|
||||
|
||||
migration.upgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
# [断言意图] 唯一约束已删除,同名普通索引补回(查询性能不回退)。
|
||||
unique_names = {
|
||||
constraint['name']
|
||||
for constraint in inspector.get_unique_constraints('integration_calls')
|
||||
}
|
||||
assert _UQ_NAME not in unique_names
|
||||
indexes = {
|
||||
index['name']: index
|
||||
for index in inspector.get_indexes('integration_calls')
|
||||
}
|
||||
assert indexes[_IX_NAME]['column_names'] == ['operation_id']
|
||||
# SQLite 方言 unique 返回 0/1,用真值断言而非 `is False`。
|
||||
assert not indexes[_IX_NAME]['unique']
|
||||
|
||||
# [断言意图] 核心契约:同 operation_id 两行共存——多步顺序引擎一次能力
|
||||
# 调用按步骤落 N 条审计、共享同一 operation_id 串联。
|
||||
_insert_call(connection, 'OP-1')
|
||||
_insert_call(connection, 'OP-1')
|
||||
same_op_count = connection.execute(
|
||||
sa.text("SELECT count(*) FROM integration_calls WHERE operation_id = 'OP-1'")
|
||||
).scalar_one()
|
||||
assert same_op_count == 2
|
||||
|
||||
# 清理多步行再回滚:带重复行 downgrade 按迁移文档预期报错(多步审计本身
|
||||
# 不兼容旧唯一约束),该预期错误行为不在本往返用例覆盖。
|
||||
connection.execute(sa.text('DELETE FROM integration_calls'))
|
||||
|
||||
migration.downgrade()
|
||||
inspector = sa.inspect(connection)
|
||||
restored_unique = {
|
||||
constraint['name']
|
||||
for constraint in inspector.get_unique_constraints('integration_calls')
|
||||
}
|
||||
assert _UQ_NAME in restored_unique
|
||||
assert _IX_NAME not in {
|
||||
index['name'] for index in inspector.get_indexes('integration_calls')
|
||||
}
|
||||
|
||||
# [断言意图] 旧唯一约束恢复后,重复 operation_id 插入被 IntegrityError 拒绝。
|
||||
_insert_call(connection, 'OP-2')
|
||||
with pytest.raises(sa.exc.IntegrityError):
|
||||
_insert_call(connection, 'OP-2')
|
||||
Reference in new issue
Block a user