feat(integration-connector): 绑定参数映射与凭据 DB 加密落库模式
- 绑定新增 param_mapping_json:域参数→接口参数声明式映射(map_response 规范),空对象同名直通 - 凭据引用新增 db 维护模式:secret_ciphertext Fernet 加密落库,主密钥 INTEGRATION_CREDENTIAL_KEY 仅环境注入,与 env 引用模式并存 - 新增 credential_types 凭据形态注册表:代码注册各类型字段清单,UI 动态渲染与 API 组装校验的唯一事实来源 - 移除绑定 context_source_code 独立列,路由条件统一 context_selector_json - 管理端表单 Modal 重构为 Drawer,新增 JSON 编辑字段组件与页面级测试 - 迁移 rd1/re1 重挂当前唯一 head dd22ee33ff44,维持单 head 链 - settings 移除 IN_TRANSIT_TRANSFER_ERP_* 配置,外部端点/凭据移交连接器客户端实例管理
This commit is contained in:
1 parent
5df204fdea
commit
31591e663e
35 files changed
+4345
-750
No files matched your search
@@ -146,6 +146,69 @@ def test_client_instance_test_connection(app, client, admin_headers, fake_gatewa
|
||||
assert response.get_json()["data"]["ok"] is True
|
||||
|
||||
|
||||
class ProbeSpyTransport:
|
||||
"""记录 probe 收到的 client 配置,验证独立列(endpoint/timeout)已拼回 config_json。"""
|
||||
|
||||
connector_type = "soap"
|
||||
|
||||
def __init__(self):
|
||||
self.seen = None
|
||||
|
||||
def probe(self, *, client):
|
||||
self.seen = client
|
||||
return {"ok": True, "code": "HTTP_200", "message": "wsdl root <definitions>"}
|
||||
|
||||
def call(self, *, client, interface, request): # pragma: no cover — 走到即失败
|
||||
self.seen = {"unexpected_call": True}
|
||||
|
||||
|
||||
def test_client_instance_test_connection_merges_endpoint_column(app, client, admin_headers, fake_gateway):
|
||||
"""连接测试回归:endpoint 存独立列(config_json 为空)时必须拼回配置再探测。
|
||||
|
||||
曾因测试端点只透传 config_json,SOAP 客户端误报
|
||||
'SOAP contract not frozen (missing wsdl/endpoint)'。
|
||||
"""
|
||||
created = client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-SOAP", "name": "soap client", "connector_type": "soap", "environment": "prod",
|
||||
"endpoint": "https://erp.invalid/wsdl", "timeout_seconds": 45,
|
||||
"config_json": {},
|
||||
})
|
||||
assert created.status_code == 201
|
||||
|
||||
spy = ProbeSpyTransport()
|
||||
fake_gateway.transports["soap"] = spy
|
||||
response = client.post(f"{API_PREFIX}/client-instances/CLI-SOAP/test", headers=admin_headers)
|
||||
|
||||
assert response.status_code == 200
|
||||
data = response.get_json()["data"]
|
||||
assert data["ok"] is True
|
||||
# 独立列值必须出现在传给 transport 的 config_json 里(关键断言)。
|
||||
assert spy.seen["config_json"]["endpoint"] == "https://erp.invalid/wsdl"
|
||||
assert spy.seen["config_json"]["timeout_seconds"] == 45
|
||||
|
||||
|
||||
def test_client_instance_test_connection_reports_unreachable(app, client, admin_headers, fake_gateway):
|
||||
"""probe 探测不通 → 仍 200 但 ok=False(探测结果是业务结果,不是请求错误)。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-DOWN", "name": "down", "connector_type": "rest", "environment": "prod",
|
||||
"endpoint": "https://down.invalid",
|
||||
})
|
||||
|
||||
class DownTransport:
|
||||
connector_type = "rest"
|
||||
|
||||
def probe(self, *, client):
|
||||
return {"ok": False, "code": "CONNECTION_FAILED", "message": "connection refused"}
|
||||
|
||||
fake_gateway.transports["rest"] = DownTransport()
|
||||
response = client.post(f"{API_PREFIX}/client-instances/CLI-DOWN/test", headers=admin_headers)
|
||||
assert response.status_code == 200
|
||||
data = response.get_json()["data"]
|
||||
assert data["ok"] is False
|
||||
assert data["status"] == "failed"
|
||||
assert data["result"]["code"] == "CONNECTION_FAILED"
|
||||
|
||||
|
||||
def test_update_client_instance(app, client, admin_headers):
|
||||
"""PUT /client-instances/<code> → 200,更新 name/config/enabled。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
@@ -162,13 +225,13 @@ def test_update_client_instance(app, client, admin_headers):
|
||||
|
||||
|
||||
def test_update_interface_definition(app, client, admin_headers):
|
||||
"""PUT /interface-definitions/<code> → 200,更新模板/回传映射/状态。"""
|
||||
"""PUT /interface-definitions/<code> → 200,更新模板/回传映射;body 里的 status 被忽略。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-I", "name": "cli", "connector_type": "rest", "environment": "prod",
|
||||
"config_json": {},
|
||||
})
|
||||
client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
|
||||
"code": "IF-U", "name": "iface", "client_instance_code": "CLI-I", "connector_type": "rest",
|
||||
"code": "IF-U", "name": "iface", "client_instance_code": "CLI-I",
|
||||
"request_spec_json": {"path": "/v1/old"}, "status": "draft",
|
||||
})
|
||||
response = client.put(f"{API_PREFIX}/interface-definitions/IF-U", headers=admin_headers, json={
|
||||
@@ -177,12 +240,86 @@ def test_update_interface_definition(app, client, admin_headers):
|
||||
})
|
||||
assert response.status_code == 200
|
||||
data = response.get_json()["data"]
|
||||
assert data["status"] == "published"
|
||||
# 状态只能经生命周期动作端点流转:PUT 携带 status 不生效,仍为创建时的 draft
|
||||
assert data["status"] == "draft"
|
||||
assert data["request_spec_json"] == {"path": "/v1/new"}
|
||||
assert data["response_mapping_json"] == {"qty": "data.quantity"}
|
||||
|
||||
|
||||
def test_interface_connector_type_derived_from_client(app, client, admin_headers):
|
||||
"""连接器类型由所属客户端实例服务端推导:创建/换绑客户端均以客户端为准,body 传值被忽略。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-D1", "name": "soap cli", "connector_type": "soap", "environment": "prod",
|
||||
"config_json": {},
|
||||
})
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-D2", "name": "rest cli", "connector_type": "rest", "environment": "prod",
|
||||
"config_json": {},
|
||||
})
|
||||
# 创建:body 误传 rest(与客户端 soap 不一致)→ 落库以客户端为准
|
||||
created = client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
|
||||
"code": "IF-DERIVE", "name": "iface", "client_instance_code": "CLI-D1",
|
||||
"connector_type": "rest",
|
||||
})
|
||||
assert created.status_code == 201
|
||||
assert created.get_json()["data"]["connector_type"] == "soap"
|
||||
# 换绑客户端 → 类型跟随新客户端
|
||||
updated = client.put(f"{API_PREFIX}/interface-definitions/IF-DERIVE", headers=admin_headers, json={
|
||||
"client_instance_code": "CLI-D2",
|
||||
})
|
||||
assert updated.status_code == 200
|
||||
assert updated.get_json()["data"]["connector_type"] == "rest"
|
||||
# 客户端不存在 → 400(而非依赖外键报 500)
|
||||
missing = client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
|
||||
"code": "IF-NOCLI", "name": "iface", "client_instance_code": "CLI-NOT-EXIST",
|
||||
})
|
||||
assert missing.status_code == 400
|
||||
|
||||
|
||||
def test_interface_create_freezes_enabled(app, client, admin_headers):
|
||||
"""接口定义 enabled 冻结:请求体传值被忽略,可用性只由 status 生命周期表达。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-FE", "name": "cli", "connector_type": "rest", "environment": "prod",
|
||||
})
|
||||
created = client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
|
||||
"code": "IF-FE", "name": "iface", "client_instance_code": "CLI-FE", "enabled": False,
|
||||
})
|
||||
assert created.status_code == 201
|
||||
assert created.get_json()["data"]["enabled"] is True
|
||||
|
||||
|
||||
def test_interface_lifecycle_transitions(app, client, admin_headers):
|
||||
"""发布/撤回/退役/恢复按转移表流转;非法转移与未知动作被拒绝。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-LC", "name": "cli", "connector_type": "rest", "environment": "prod",
|
||||
"config_json": {},
|
||||
})
|
||||
client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
|
||||
"code": "IF-LC", "name": "iface", "client_instance_code": "CLI-LC",
|
||||
})
|
||||
|
||||
def lifecycle(action, code="IF-LC"):
|
||||
return client.post(f"{API_PREFIX}/interface-definitions/{code}/{action}", headers=admin_headers)
|
||||
|
||||
# draft 上直接撤回/退役 → 400(源状态不符)
|
||||
assert lifecycle("unpublish").status_code == 400
|
||||
assert lifecycle("retire").status_code == 400
|
||||
# draft → published → draft(撤回)→ published → retired(退役)→ draft(恢复)
|
||||
assert lifecycle("publish").get_json()["data"]["status"] == "published"
|
||||
assert lifecycle("unpublish").get_json()["data"]["status"] == "draft"
|
||||
assert lifecycle("publish").get_json()["data"]["status"] == "published"
|
||||
assert lifecycle("retire").get_json()["data"]["status"] == "retired"
|
||||
# retired 不能直接发布,须经恢复为草稿
|
||||
illegal = lifecycle("publish")
|
||||
assert illegal.status_code == 400
|
||||
assert illegal.get_json()["error"]["code"] == "INTEGRATION.ILLEGAL_STATUS_TRANSITION"
|
||||
assert lifecycle("reopen").get_json()["data"]["status"] == "draft"
|
||||
# 接口不存在 → 404
|
||||
assert lifecycle("publish", code="IF-NOPE").status_code == 404
|
||||
|
||||
|
||||
def test_update_binding(app, client, admin_headers):
|
||||
"""PUT /bindings/<id> → 200,更新映射版本/优先级/状态。"""
|
||||
"""PUT /bindings/<id> → 200,更新映射版本/优先级;状态不经 PUT 改写(走生命周期端点)。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-B", "name": "cli", "connector_type": "rest", "environment": "prod",
|
||||
"config_json": {},
|
||||
@@ -192,7 +329,7 @@ def test_update_binding(app, client, admin_headers):
|
||||
})
|
||||
created = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={
|
||||
"capability": "in_transit_transfer.query_inventory", "client_instance_code": "CLI-B",
|
||||
"interface_definition_code": "IF-B", "status": "draft",
|
||||
"interface_definition_code": "IF-B",
|
||||
})
|
||||
binding_id = created.get_json()["data"]["id"]
|
||||
response = client.put(f"{API_PREFIX}/bindings/{binding_id}", headers=admin_headers, json={
|
||||
@@ -202,24 +339,153 @@ def test_update_binding(app, client, admin_headers):
|
||||
data = response.get_json()["data"]
|
||||
assert data["priority"] == 5
|
||||
assert data["mapping_version"] == 2
|
||||
assert data["status"] == "published"
|
||||
# 请求体携带 status 被忽略:状态只能经 /publish 动作端点流转
|
||||
assert data["status"] == "draft"
|
||||
|
||||
# 发布绑定有就绪门禁:接口定义须先发布
|
||||
client.post(f"{API_PREFIX}/interface-definitions/IF-B/publish", headers=admin_headers)
|
||||
published = client.post(f"{API_PREFIX}/bindings/{binding_id}/publish", headers=admin_headers)
|
||||
assert published.get_json()["data"]["status"] == "published"
|
||||
|
||||
|
||||
def test_binding_create_forces_draft_and_pair_validation(app, client, admin_headers):
|
||||
"""新建绑定固定落 draft;客户端与接口成对校验(错配/缺失均 400)。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-BC", "name": "cli", "connector_type": "rest", "environment": "prod",
|
||||
"endpoint": "https://erp.invalid",
|
||||
})
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-OTHER", "name": "other", "connector_type": "rest", "environment": "prod",
|
||||
})
|
||||
client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
|
||||
"code": "IF-BC", "name": "iface", "client_instance_code": "CLI-BC", "connector_type": "rest",
|
||||
})
|
||||
# 请求体携带 status / context_source_code 均被忽略:状态走生命周期端点,
|
||||
# 来源路由条件统一由 context_selector_json 表达(无独立快捷列)
|
||||
created = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={
|
||||
"capability": "in_transit_transfer.query_inventory",
|
||||
"client_instance_code": "CLI-BC", "interface_definition_code": "IF-BC",
|
||||
"status": "published", "context_source_code": "DBS-AWSBI",
|
||||
})
|
||||
assert created.status_code == 201
|
||||
data = created.get_json()["data"]
|
||||
assert data["status"] == "draft"
|
||||
assert "context_source_code" not in data
|
||||
|
||||
# 接口定义不属于所选客户端 → 400(fail-fast,不留给调用期)
|
||||
mismatch = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={
|
||||
"capability": "in_transit_transfer.query_inventory",
|
||||
"client_instance_code": "CLI-OTHER", "interface_definition_code": "IF-BC",
|
||||
})
|
||||
assert mismatch.status_code == 400
|
||||
assert mismatch.get_json()["error"]["code"] == "INTEGRATION.BINDING_PAIR_MISMATCH"
|
||||
# 客户端/接口不存在 → 400(而非依赖外键报 500)
|
||||
assert client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={
|
||||
"capability": "in_transit_transfer.query_inventory",
|
||||
"client_instance_code": "CLI-NOT-EXIST", "interface_definition_code": "IF-BC",
|
||||
}).status_code == 400
|
||||
assert client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={
|
||||
"capability": "in_transit_transfer.query_inventory",
|
||||
"client_instance_code": "CLI-BC", "interface_definition_code": "IF-NOT-EXIST",
|
||||
}).status_code == 400
|
||||
|
||||
# 更新换绑接口时同样成对校验:以变更后的最终组合为准
|
||||
binding_id = data["id"]
|
||||
updated = client.put(f"{API_PREFIX}/bindings/{binding_id}", headers=admin_headers, json={
|
||||
"client_instance_code": "CLI-OTHER",
|
||||
})
|
||||
assert updated.status_code == 400
|
||||
assert updated.get_json()["error"]["code"] == "INTEGRATION.BINDING_PAIR_MISMATCH"
|
||||
|
||||
|
||||
def test_binding_lifecycle_transitions(app, client, admin_headers):
|
||||
"""发布/撤回/退役/恢复按转移表流转;发布有就绪门禁(接口须已发布且客户端启用)。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-BLC", "name": "cli", "connector_type": "rest", "environment": "prod",
|
||||
"config_json": {},
|
||||
})
|
||||
client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
|
||||
"code": "IF-BLC", "name": "iface", "client_instance_code": "CLI-BLC",
|
||||
})
|
||||
created = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={
|
||||
"capability": "in_transit_transfer.query_inventory",
|
||||
"client_instance_code": "CLI-BLC", "interface_definition_code": "IF-BLC",
|
||||
})
|
||||
binding_id = created.get_json()["data"]["id"]
|
||||
|
||||
def lifecycle(action):
|
||||
return client.post(f"{API_PREFIX}/bindings/{binding_id}/{action}", headers=admin_headers)
|
||||
|
||||
# 接口定义还是草稿 → 发布绑定被就绪门禁拦截(避免发布永不生效的死绑定)
|
||||
not_ready = lifecycle("publish")
|
||||
assert not_ready.status_code == 400
|
||||
assert not_ready.get_json()["error"]["code"] == "INTEGRATION.BINDING_TARGET_NOT_READY"
|
||||
|
||||
# 接口发布后:draft → published → draft(撤回)→ published → retired(退役)→ draft(恢复)
|
||||
client.post(f"{API_PREFIX}/interface-definitions/IF-BLC/publish", headers=admin_headers)
|
||||
assert lifecycle("publish").get_json()["data"]["status"] == "published"
|
||||
assert lifecycle("unpublish").get_json()["data"]["status"] == "draft"
|
||||
assert lifecycle("publish").get_json()["data"]["status"] == "published"
|
||||
assert lifecycle("retire").get_json()["data"]["status"] == "retired"
|
||||
# retired 不能直接发布,须经恢复为草稿
|
||||
illegal = lifecycle("publish")
|
||||
assert illegal.status_code == 400
|
||||
assert illegal.get_json()["error"]["code"] == "INTEGRATION.ILLEGAL_STATUS_TRANSITION"
|
||||
assert lifecycle("reopen").get_json()["data"]["status"] == "draft"
|
||||
# 绑定不存在 → 404
|
||||
assert client.post(f"{API_PREFIX}/bindings/999999/publish", headers=admin_headers).status_code == 404
|
||||
|
||||
|
||||
def test_update_credential_reference(app, client, admin_headers):
|
||||
"""PUT /credential-references/<code> → 200,更新 secret_ref/status,且不回显明文。"""
|
||||
"""PUT /credential-references/<code> → 200,更新 secret_ref,且不回显明文。"""
|
||||
client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={
|
||||
"code": "CRED-U", "secret_ref": "IN_TRANSIT_ERP_PASSWORD",
|
||||
})
|
||||
response = client.put(f"{API_PREFIX}/credential-references/CRED-U", headers=admin_headers, json={
|
||||
"secret_ref": "IN_TRANSIT_ERP_PASSWORD_ROTATED", "status": "rotating",
|
||||
"secret_ref": "IN_TRANSIT_ERP_PASSWORD_ROTATED",
|
||||
})
|
||||
assert response.status_code == 200
|
||||
data = response.get_json()["data"]
|
||||
assert data["secret_ref"] == "IN_TRANSIT_ERP_PASSWORD_ROTATED"
|
||||
assert data["status"] == "rotating"
|
||||
assert "secret" not in str(data).lower() or data.get("secret") is None
|
||||
|
||||
|
||||
def test_credential_status_two_state_toggle(app, client, admin_headers):
|
||||
"""凭据状态两态开关:active/retired 可经 PUT 互切;rotating 不可进入;存量 rotating 可恢复。"""
|
||||
client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={
|
||||
"code": "CRED-TS", "secret_ref": "IN_TRANSIT_ERP_PASSWORD",
|
||||
})
|
||||
# active → retired(停用;解析层只认 active,停用即断流)
|
||||
retired = client.put(f"{API_PREFIX}/credential-references/CRED-TS", headers=admin_headers, json={
|
||||
"status": "retired",
|
||||
})
|
||||
assert retired.status_code == 200
|
||||
assert retired.get_json()["data"]["status"] == "retired"
|
||||
# rotating 不可进入(其现语义等于断供,真实版本化轮换属 P2)
|
||||
rotating = client.put(f"{API_PREFIX}/credential-references/CRED-TS", headers=admin_headers, json={
|
||||
"status": "rotating",
|
||||
})
|
||||
assert rotating.status_code == 400
|
||||
# retired → active(恢复启用)
|
||||
reactivated = client.put(f"{API_PREFIX}/credential-references/CRED-TS", headers=admin_headers, json={
|
||||
"status": "active",
|
||||
})
|
||||
assert reactivated.get_json()["data"]["status"] == "active"
|
||||
# 存量 rotating 数据(经 create 兼容通道落库)可经 PUT 置回 active 恢复
|
||||
client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={
|
||||
"code": "CRED-LEGACY", "secret_ref": "LEGACY_KEY", "status": "rotating",
|
||||
})
|
||||
recovered = client.put(f"{API_PREFIX}/credential-references/CRED-LEGACY", headers=admin_headers, json={
|
||||
"status": "active",
|
||||
})
|
||||
assert recovered.status_code == 200
|
||||
assert recovered.get_json()["data"]["status"] == "active"
|
||||
# 非法状态值 → 400
|
||||
assert client.put(f"{API_PREFIX}/credential-references/CRED-TS", headers=admin_headers, json={
|
||||
"status": "bogus",
|
||||
}).status_code == 400
|
||||
|
||||
|
||||
def test_client_instance_split_columns(app, client, admin_headers):
|
||||
"""POST /client-instances 写 endpoint/timeout_seconds 独立列,config_json 仅存扩展。"""
|
||||
created = client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
@@ -265,26 +531,101 @@ def test_interface_definition_split_columns(app, client, admin_headers):
|
||||
assert updated.get_json()["data"]["request_path"] == "/inventory/{invoice_no}"
|
||||
|
||||
|
||||
def test_binding_split_columns(app, client, admin_headers):
|
||||
"""POST/PUT /bindings 写 context_source_code 独立列并回显。"""
|
||||
# ---- 绑定参数映射 / 凭据 db 模式 ----
|
||||
|
||||
def test_binding_param_mapping_round_trip(app, client, admin_headers):
|
||||
"""POST/PUT /bindings 透传 param_mapping_json,序列化原样返回。"""
|
||||
client.post(f"{API_PREFIX}/client-instances", headers=admin_headers, json={
|
||||
"code": "CLI-BC", "name": "cli", "connector_type": "rest", "environment": "prod",
|
||||
"code": "CLI-PM", "name": "cli", "connector_type": "rest", "environment": "prod",
|
||||
"endpoint": "https://erp.invalid",
|
||||
})
|
||||
client.post(f"{API_PREFIX}/interface-definitions", headers=admin_headers, json={
|
||||
"code": "IF-BC", "name": "iface", "client_instance_code": "CLI-BC", "connector_type": "rest",
|
||||
"code": "IFACE-PM", "name": "iface", "client_instance_code": "CLI-PM", "connector_type": "rest",
|
||||
})
|
||||
created = client.post(f"{API_PREFIX}/bindings", headers=admin_headers, json={
|
||||
"capability": "in_transit_transfer.query_inventory",
|
||||
"client_instance_code": "CLI-BC", "interface_definition_code": "IF-BC",
|
||||
"context_source_code": "DBS-AWSBI", "status": "published",
|
||||
"client_instance_code": "CLI-PM", "interface_definition_code": "IFACE-PM",
|
||||
"param_mapping_json": {"organization": {"expr": "external_org"},
|
||||
"condition": {"template": "img04 = '{invoice_no}'"}},
|
||||
})
|
||||
assert created.status_code == 201
|
||||
data = created.get_json()["data"]
|
||||
assert data["context_source_code"] == "DBS-AWSBI"
|
||||
assert data["param_mapping_json"]["organization"] == {"expr": "external_org"}
|
||||
|
||||
updated = client.put(f"{API_PREFIX}/bindings/{data['id']}", headers=admin_headers, json={
|
||||
"context_source_code": "CRANE-SZ",
|
||||
})
|
||||
updated = client.put(f"{API_PREFIX}/bindings/{data['id']}", headers=admin_headers,
|
||||
json={"param_mapping_json": {"condition": {"template": "img02 = '{warehouse}'"}}})
|
||||
assert updated.status_code == 200
|
||||
assert updated.get_json()["data"]["context_source_code"] == "CRANE-SZ"
|
||||
assert updated.get_json()["data"]["param_mapping_json"] == {
|
||||
"condition": {"template": "img02 = '{warehouse}'"},
|
||||
}
|
||||
|
||||
|
||||
def test_credential_db_mode_round_trip(app, client, admin_headers):
|
||||
"""db 模式:按凭据类型加密字段落库;回显非密字段、绝不回显密文;只改密码保留用户名。"""
|
||||
from cryptography.fernet import Fernet
|
||||
|
||||
app.config["INTEGRATION_CREDENTIAL_KEY"] = Fernet.generate_key().decode("ascii")
|
||||
created = client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={
|
||||
"code": "CRED-DB", "secret_provider": "db",
|
||||
"username": "erp_user", "password": "erp_pass",
|
||||
})
|
||||
assert created.status_code == 201
|
||||
data = created.get_json()["data"]
|
||||
assert data["secret_fields"] == {"username": "erp_user"}
|
||||
assert data["has_secret"] is True
|
||||
assert "erp_pass" not in created.get_data(as_text=True)
|
||||
assert "secret_ciphertext" not in data
|
||||
|
||||
updated = client.put(f"{API_PREFIX}/credential-references/CRED-DB", headers=admin_headers,
|
||||
json={"password": "new_pass"})
|
||||
assert updated.status_code == 200
|
||||
data = updated.get_json()["data"]
|
||||
assert data["secret_fields"] == {"username": "erp_user"} # 只改密码时用户名保留
|
||||
assert "new_pass" not in updated.get_data(as_text=True)
|
||||
|
||||
|
||||
def test_credential_db_mode_token_type_and_types_endpoint(app, client, admin_headers):
|
||||
"""token 类型按其字段清单组装;类型清单端点返回注册表。"""
|
||||
from cryptography.fernet import Fernet
|
||||
|
||||
app.config["INTEGRATION_CREDENTIAL_KEY"] = Fernet.generate_key().decode("ascii")
|
||||
types = client.get(f"{API_PREFIX}/credential-references/types", headers=admin_headers)
|
||||
assert types.status_code == 200
|
||||
type_names = {item["type"] for item in types.get_json()["data"]}
|
||||
assert type_names == {"password", "token", "api_key"}
|
||||
|
||||
created = client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={
|
||||
"code": "CRED-TOKEN", "secret_provider": "db", "credential_type": "token",
|
||||
"token": "tk-123",
|
||||
})
|
||||
assert created.status_code == 201
|
||||
data = created.get_json()["data"]
|
||||
assert data["credential_type"] == "token"
|
||||
assert data["secret_fields"] == {} # token 是密文字段,不回显
|
||||
assert "tk-123" not in created.get_data(as_text=True)
|
||||
|
||||
# token 必填缺失 → 400
|
||||
missing = client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={
|
||||
"code": "CRED-TOKEN2", "secret_provider": "db", "credential_type": "token",
|
||||
})
|
||||
assert missing.status_code == 400
|
||||
|
||||
|
||||
def test_credential_db_mode_unknown_type_rejected(app, client, admin_headers):
|
||||
"""未知凭据类型 → 400(fail-closed)。"""
|
||||
from cryptography.fernet import Fernet
|
||||
|
||||
app.config["INTEGRATION_CREDENTIAL_KEY"] = Fernet.generate_key().decode("ascii")
|
||||
response = client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={
|
||||
"code": "CRED-BAD", "secret_provider": "db", "credential_type": "nope",
|
||||
"username": "u", "password": "p",
|
||||
})
|
||||
assert response.status_code == 400
|
||||
|
||||
|
||||
def test_credential_db_mode_requires_username_and_password(app, client, admin_headers):
|
||||
"""db 模式创建缺用户名或密码 → 400。"""
|
||||
response = client.post(f"{API_PREFIX}/credential-references", headers=admin_headers, json={
|
||||
"code": "CRED-DB2", "secret_provider": "db", "username": "only-user",
|
||||
})
|
||||
assert response.status_code == 400
|
||||
@@ -3,6 +3,7 @@
|
||||
用途:验证 Binding 解析与版本冻结——默认/上下文覆盖/优先级/生效区间/状态门禁/fail-closed。
|
||||
依赖:IntegrationBinding 等模型、binding.py、errors.py。
|
||||
逻辑:只匹配 published + environment + 生效区间 + context_selector 子集;
|
||||
接口定义须 published、客户端须 enabled,否则同样 fail-closed;
|
||||
无命中抛 BindingNotFoundError;快照冻结 interface 版本与配置(调用期冻结,非活表)。
|
||||
"""
|
||||
|
||||
@@ -120,3 +121,43 @@ def test_freeze_versions_in_snapshot(app):
|
||||
assert snap.credential_ref_code is None
|
||||
assert snap.request_spec.get("path") == "/stock"
|
||||
assert snap.config.get("endpoint") == "https://erp.invalid"
|
||||
|
||||
|
||||
def test_snapshot_carries_param_mapping_and_input_schema(app):
|
||||
"""快照冻结绑定参数映射与接口入参 Schema(引擎翻译契约)。"""
|
||||
db.session.add_all([
|
||||
_client(),
|
||||
_interface(input_schema_json={"type": "object", "required": ["condition"]}),
|
||||
_binding(param_mapping_json={"condition": {"template": "img04 = '{invoice_no}'"}}),
|
||||
])
|
||||
db.session.commit()
|
||||
snap = resolve_binding("in_transit_transfer.query_inventory", {}, "prod")
|
||||
assert snap.param_mapping == {"condition": {"template": "img04 = '{invoice_no}'"}}
|
||||
assert snap.input_schema == {"type": "object", "required": ["condition"]}
|
||||
|
||||
|
||||
def test_draft_interface_not_matched(app):
|
||||
"""接口定义为 draft 时不命中(fail-closed):绑定已发布但接口未发布视同无可用绑定。"""
|
||||
db.session.add_all([_client(), _interface(status="draft"), _binding()])
|
||||
db.session.commit()
|
||||
with pytest.raises(AppError) as exc:
|
||||
resolve_binding("in_transit_transfer.query_inventory", {}, "prod")
|
||||
assert exc.value.code == "INTEGRATION.BINDING_NOT_FOUND"
|
||||
|
||||
|
||||
def test_retired_interface_not_matched(app):
|
||||
"""接口定义为 retired 时不命中:退役是引用它的所有绑定的总开关。"""
|
||||
db.session.add_all([_client(), _interface(status="retired"), _binding()])
|
||||
db.session.commit()
|
||||
with pytest.raises(AppError) as exc:
|
||||
resolve_binding("in_transit_transfer.query_inventory", {}, "prod")
|
||||
assert exc.value.code == "INTEGRATION.BINDING_NOT_FOUND"
|
||||
|
||||
|
||||
def test_disabled_client_not_matched(app):
|
||||
"""客户端实例停用(enabled=False)时不命中:列表行内启停开关具备调用期语义。"""
|
||||
db.session.add_all([_client(enabled=False), _interface(), _binding()])
|
||||
db.session.commit()
|
||||
with pytest.raises(AppError) as exc:
|
||||
resolve_binding("in_transit_transfer.query_inventory", {}, "prod")
|
||||
assert exc.value.code == "INTEGRATION.BINDING_NOT_FOUND"
|
||||
@@ -11,9 +11,7 @@ import pytest
|
||||
|
||||
from app.services.integration_connector.capability import (
|
||||
CapabilitySpec,
|
||||
ensure_capabilities_loaded,
|
||||
get_capability,
|
||||
list_capabilities,
|
||||
register_capability,
|
||||
reset_capability_registry_for_tests,
|
||||
)
|
||||
@@ -47,13 +45,3 @@ def test_get_unregistered_raises_not_found():
|
||||
get_capability("in_transit_transfer.none")
|
||||
assert exc.value.code == "INTEGRATION.CAPABILITY_NOT_FOUND"
|
||||
assert exc.value.http_status == 404
|
||||
|
||||
|
||||
def test_ensure_loaded_registers_three_transfer_capabilities():
|
||||
"""ensure_capabilities_loaded 后注册 3 个在途调拨能力,write 标志正确。"""
|
||||
ensure_capabilities_loaded()
|
||||
names = {spec.name for spec in list_capabilities()}
|
||||
assert {"in_transit_transfer.query_inventory", "in_transit_transfer.create_transfer", "in_transit_transfer.verify_duplicate"}.issubset(names)
|
||||
assert get_capability("in_transit_transfer.create_transfer").write is True
|
||||
assert get_capability("in_transit_transfer.query_inventory").write is False
|
||||
assert get_capability("in_transit_transfer.verify_duplicate").write is False
|
||||
@@ -0,0 +1,51 @@
|
||||
"""tests/services/integration_connector/test_credential_types.py
|
||||
|
||||
用途:验证凭据类型注册表——字段组装/必填校验/非密回显/未知类型 fail-closed。
|
||||
依赖:credential_types(纯函数)。
|
||||
逻辑:build_secret_dict 只保留类型定义内字段且必填齐全;visible_fields 只回显非密字段。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import AppError
|
||||
from app.services.integration_connector.credential_types import (
|
||||
build_secret_dict,
|
||||
get_credential_type,
|
||||
list_credential_types,
|
||||
visible_fields,
|
||||
)
|
||||
|
||||
|
||||
def test_registry_contains_builtin_types():
|
||||
"""内置 password/token/api_key 三种类型,字段定义齐全。"""
|
||||
types = {item["type"] for item in list_credential_types()}
|
||||
assert types == {"password", "token", "api_key"}
|
||||
password_fields = {f["key"]: f for f in get_credential_type("password")["fields"]}
|
||||
assert set(password_fields) == {"username", "password"}
|
||||
assert password_fields["password"]["secret"] is True
|
||||
assert password_fields["username"]["secret"] is False
|
||||
|
||||
|
||||
def test_build_secret_dict_keeps_defined_keys_only():
|
||||
"""只保留类型定义内的键(未知键丢弃),必填齐全。"""
|
||||
values = {"username": "u", "password": "p", "evil": "x"}
|
||||
assert build_secret_dict("password", values) == {"username": "u", "password": "p"}
|
||||
|
||||
|
||||
def test_build_secret_dict_missing_required_fail_closed():
|
||||
"""必填字段缺失 → ValidationError。"""
|
||||
with pytest.raises(AppError):
|
||||
build_secret_dict("password", {"username": "u"})
|
||||
|
||||
|
||||
def test_build_secret_dict_unknown_type_fail_closed():
|
||||
with pytest.raises(AppError):
|
||||
build_secret_dict("nope", {})
|
||||
|
||||
|
||||
def test_visible_fields_returns_non_secret_only():
|
||||
assert visible_fields("password", {"username": "u", "password": "p"}) == {"username": "u"}
|
||||
assert visible_fields("token", {"token": "t"}) == {}
|
||||
assert visible_fields("nope", {"x": "y"}) == {}
|
||||
@@ -16,10 +16,20 @@ import pytest
|
||||
from app import db
|
||||
from app.core.errors import AppError
|
||||
from app.models import IntegrationBinding, IntegrationCall, IntegrationClientInstance, IntegrationInterfaceDefinition
|
||||
from app.services.integration_connector.capability import ensure_capabilities_loaded
|
||||
from app.services.in_transit_transfer.capabilities import register_transfer_capabilities
|
||||
from app.services.integration_connector.capability import reset_capability_registry_for_tests
|
||||
from app.services.integration_connector.engine import CapabilityGateway
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _transfer_capabilities():
|
||||
"""每用例前重建在途调拨能力注册:能力声明已移至领域包,注册表可能被其他用例 reset。"""
|
||||
reset_capability_registry_for_tests()
|
||||
register_transfer_capabilities()
|
||||
yield
|
||||
reset_capability_registry_for_tests()
|
||||
|
||||
|
||||
class FakeTransport:
|
||||
"""可注入响应或异常的传输替身。"""
|
||||
|
||||
@@ -60,14 +70,16 @@ def _seed(capability, *, connector_type="rest", response_mapping=None, output_sc
|
||||
|
||||
|
||||
def _params(**overrides):
|
||||
values = {"invoice_no": "INV-001", "from_warehouse": "W1", "to_warehouse": "W2", "quantity": 100}
|
||||
values = {
|
||||
"external_org": "HX-CN01",
|
||||
"targets": [{"material_no": "M-1", "from_warehouse": "W1", "lot_no": "L-1"}],
|
||||
}
|
||||
values.update(overrides)
|
||||
return values
|
||||
|
||||
|
||||
def test_call_success_records_integration_call(app):
|
||||
"""读能力成功:status=success、data 含映射结果、落 IntegrationCall。"""
|
||||
ensure_capabilities_loaded()
|
||||
_seed("in_transit_transfer.query_inventory")
|
||||
fake = FakeTransport({"found": True, "quantity": "100"})
|
||||
result = CapabilityGateway(transports={"rest": fake}).call(
|
||||
@@ -83,7 +95,6 @@ def test_call_success_records_integration_call(app):
|
||||
|
||||
def test_call_input_invalid_raises(app):
|
||||
"""入参不合输入 Schema → INTEGRATION.INPUT_INVALID。"""
|
||||
ensure_capabilities_loaded()
|
||||
_seed("in_transit_transfer.query_inventory")
|
||||
with pytest.raises(AppError) as exc:
|
||||
CapabilityGateway(transports={"rest": FakeTransport({"found": True})}).call(
|
||||
@@ -95,7 +106,6 @@ def test_call_input_invalid_raises(app):
|
||||
|
||||
def test_call_no_binding_raises(app):
|
||||
"""无可用绑定 → INTEGRATION.BINDING_NOT_FOUND(fail-closed)。"""
|
||||
ensure_capabilities_loaded()
|
||||
with pytest.raises(AppError) as exc:
|
||||
CapabilityGateway(transports={"rest": FakeTransport({"found": True})}).call(
|
||||
capability="in_transit_transfer.query_inventory", context={},
|
||||
@@ -106,7 +116,6 @@ def test_call_no_binding_raises(app):
|
||||
|
||||
def test_call_write_business_failed(app):
|
||||
"""写能力按原始 status 分类 → business_failed。"""
|
||||
ensure_capabilities_loaded()
|
||||
_seed("in_transit_transfer.create_transfer")
|
||||
fake = FakeTransport({"status": "business_failed", "code": "E1", "message": "reject"})
|
||||
result = CapabilityGateway(transports={"rest": fake}).call(
|
||||
@@ -119,7 +128,6 @@ def test_call_write_business_failed(app):
|
||||
|
||||
def test_call_transport_timeout_returns_timeout(app):
|
||||
"""传输超时 → status=timeout。"""
|
||||
ensure_capabilities_loaded()
|
||||
_seed("in_transit_transfer.query_inventory")
|
||||
result = CapabilityGateway(transports={"rest": FakeTransport(TimeoutError())}).call(
|
||||
capability="in_transit_transfer.query_inventory", context={},
|
||||
@@ -130,7 +138,6 @@ def test_call_transport_timeout_returns_timeout(app):
|
||||
|
||||
def test_call_mapping_invalid_raises(app):
|
||||
"""输出不合输出 Schema → INTEGRATION.MAPPING_INVALID(fail-closed)。"""
|
||||
ensure_capabilities_loaded()
|
||||
_seed("in_transit_transfer.query_inventory",
|
||||
output_schema={"type": "object", "required": ["found", "quantity"],
|
||||
"properties": {"found": {"type": "boolean"}, "quantity": {"type": "number"}}})
|
||||
@@ -145,7 +152,6 @@ def test_call_mapping_invalid_raises(app):
|
||||
|
||||
def test_call_result_unknown_no_auto_retry(app):
|
||||
"""result_unknown 不自动重试:transport 仅被调用一次。"""
|
||||
ensure_capabilities_loaded()
|
||||
_seed("in_transit_transfer.create_transfer")
|
||||
calls = []
|
||||
|
||||
@@ -160,3 +166,109 @@ def test_call_result_unknown_no_auto_retry(app):
|
||||
)
|
||||
assert result.status == "result_unknown"
|
||||
assert len(calls) == 1
|
||||
|
||||
|
||||
# ---- 参数映射与凭据注入(P1 绑定翻译契约)----
|
||||
|
||||
def _seed_full_params(*, param_mapping=None, input_schema=None, credential_ref=None):
|
||||
client = IntegrationClientInstance(
|
||||
code="CLI-P", name="client", connector_type="rest", environment="prod",
|
||||
config_json={"endpoint": "https://erp.invalid"}, credential_ref_code=credential_ref,
|
||||
)
|
||||
iface = IntegrationInterfaceDefinition(
|
||||
code="IFACE-P", name="iface", client_instance_code="CLI-P", connector_type="rest",
|
||||
request_spec_json={"method": "GET", "path": "/stock"},
|
||||
input_schema_json=input_schema or {},
|
||||
response_mapping_json={"found": {"expr": "found"}, "quantity": {"expr": "quantity", "transform": "decimal"}},
|
||||
output_schema_json={"type": "object", "properties": {"found": {"type": "boolean"}, "quantity": {"type": "number"}}},
|
||||
version=1, status="published",
|
||||
)
|
||||
db.session.add_all([client, iface])
|
||||
db.session.flush()
|
||||
binding = IntegrationBinding(
|
||||
capability="in_transit_transfer.query_inventory", context_selector_json={},
|
||||
param_mapping_json=param_mapping or {},
|
||||
client_instance_code="CLI-P", interface_definition_code="IFACE-P",
|
||||
mapping_version=1, priority=0, environment="prod", status="published",
|
||||
)
|
||||
db.session.add(binding)
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def test_call_applies_binding_param_mapping(app):
|
||||
"""绑定配置 param_mapping 时域参数先翻译为接口参数再下传传输层。"""
|
||||
_seed_full_params(
|
||||
param_mapping={"organization": {"expr": "external_org"},
|
||||
"condition": {"template": "{targets}",
|
||||
"args": {"list_item_template": "img04 = '{lot_no}'", "separator": " OR "}}},
|
||||
input_schema={"type": "object", "required": ["organization", "condition"],
|
||||
"properties": {"organization": {"type": "string"}, "condition": {"type": "string"}}},
|
||||
)
|
||||
captured = {}
|
||||
|
||||
class _Capture(FakeTransport):
|
||||
def call(self, *, client, interface, request):
|
||||
captured.update(params=request["params"], interface=interface)
|
||||
return {"found": True, "quantity": "5"}
|
||||
|
||||
result = CapabilityGateway(transports={"rest": _Capture(None)}).call(
|
||||
capability="in_transit_transfer.query_inventory", context={},
|
||||
params=_params(external_org="TGHX", targets=[{"material_no": "M-9", "from_warehouse": "W1", "lot_no": "L-9"}]),
|
||||
operation_id="OP-PM", environment="prod",
|
||||
)
|
||||
assert captured["params"] == {"organization": "TGHX", "condition": "img04 = 'L-9'"}
|
||||
assert result.status == "success"
|
||||
|
||||
|
||||
def test_call_mapped_params_fail_interface_schema(app):
|
||||
"""映射结果不合接口入参 Schema → INTEGRATION.MAPPING_INVALID(fail-closed)。"""
|
||||
_seed_full_params(
|
||||
param_mapping={"organization": {"expr": "external_org"}},
|
||||
input_schema={"type": "object", "required": ["organization", "condition"],
|
||||
"properties": {"organization": {"type": "string"}, "condition": {"type": "string"}}},
|
||||
)
|
||||
with pytest.raises(AppError) as exc:
|
||||
CapabilityGateway(transports={"rest": FakeTransport({"found": True})}).call(
|
||||
capability="in_transit_transfer.query_inventory", context={},
|
||||
params=_params(external_org="TGHX"),
|
||||
operation_id="OP-PM2", environment="prod",
|
||||
)
|
||||
assert exc.value.code == "INTEGRATION.MAPPING_INVALID"
|
||||
|
||||
|
||||
def test_call_injects_resolved_credential(app):
|
||||
"""客户端实例引用凭据时,引擎解析凭据并经 client['credential'] 注入传输层。"""
|
||||
_seed_full_params(credential_ref="CRED-1")
|
||||
app.config["CRED1_CFG"] = {"username": "u", "password": "p"}
|
||||
from app import db as _db
|
||||
from app.models import IntegrationCredentialReference
|
||||
_db.session.add(IntegrationCredentialReference(
|
||||
code="CRED-1", secret_ref="CRED1_CFG", secret_provider="env",
|
||||
credential_type="password", version=1, status="active",
|
||||
))
|
||||
_db.session.commit()
|
||||
captured = {}
|
||||
|
||||
class _Capture(FakeTransport):
|
||||
def call(self, *, client, interface, request):
|
||||
captured.update(credential=client["credential"])
|
||||
return {"found": True, "quantity": "5"}
|
||||
|
||||
CapabilityGateway(transports={"rest": _Capture(None)}).call(
|
||||
capability="in_transit_transfer.query_inventory", context={},
|
||||
params=_params(), operation_id="OP-CRED", environment="prod",
|
||||
)
|
||||
assert captured["credential"] == {"username": "u", "password": "p"}
|
||||
|
||||
|
||||
def test_call_read_capability_failure_passthrough(app):
|
||||
"""读能力返回带失败 status 的原始 dict 时原样分类,不做输出映射。"""
|
||||
_seed_full_params()
|
||||
result = CapabilityGateway(transports={"rest": FakeTransport(
|
||||
{"status": "business_failed", "code": "HTTP_500", "message": "boom"}
|
||||
)}).call(
|
||||
capability="in_transit_transfer.query_inventory", context={},
|
||||
params=_params(), operation_id="OP-RF", environment="prod",
|
||||
)
|
||||
assert result.status == "business_failed"
|
||||
assert result.error_code == "HTTP_500"
|
||||
@@ -8,6 +8,7 @@
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
@@ -94,3 +95,246 @@ def test_map_response_enum_violation_raises():
|
||||
},
|
||||
)
|
||||
assert exc.value.code == "INTEGRATION.MAPPING_INVALID"
|
||||
|
||||
|
||||
# ---- pick:键值对记录列表取值(XML Field[@name,@value] 归一化的通用消费方式)----
|
||||
|
||||
def _field_rows():
|
||||
return [
|
||||
{"@name": "img04", "@value": "HOW25071402"},
|
||||
{"@name": "img11", "@value": "30.000"},
|
||||
]
|
||||
|
||||
|
||||
def test_pick_returns_value_with_decimal_cast():
|
||||
mapped = map_response(
|
||||
{"quantity": {"expr": "rows", "transform": "pick",
|
||||
"args": {"key_field": "@name", "key_value": "img11", "value_field": "@value", "cast": "decimal"}}},
|
||||
{"rows": _field_rows()},
|
||||
{"type": "object", "properties": {"quantity": {"type": "number"}}},
|
||||
)
|
||||
assert mapped["quantity"] == Decimal("30.000")
|
||||
|
||||
|
||||
def test_pick_exists_boolean():
|
||||
mapped = map_response(
|
||||
{"found": {"expr": "rows", "transform": "pick",
|
||||
"args": {"key_field": "@name", "key_value": "img04", "exists": True}}},
|
||||
{"rows": _field_rows()},
|
||||
{"type": "object", "properties": {"found": {"type": "boolean"}}},
|
||||
)
|
||||
assert mapped["found"] is True
|
||||
mapped_absent = map_response(
|
||||
{"found": {"expr": "rows", "transform": "pick",
|
||||
"args": {"key_field": "@name", "key_value": "nope", "exists": True}}},
|
||||
{"rows": _field_rows()},
|
||||
{"type": "object", "properties": {"found": {"type": "boolean"}}},
|
||||
)
|
||||
assert mapped_absent["found"] is False
|
||||
|
||||
|
||||
def test_pick_requires_list_and_key_args():
|
||||
with pytest.raises(AppError):
|
||||
map_response({"q": {"expr": "rows", "transform": "pick", "args": {"key_field": "@name", "key_value": "x"}}},
|
||||
{"rows": {"not": "a list"}}, {})
|
||||
with pytest.raises(AppError):
|
||||
map_response({"q": {"expr": "rows", "transform": "pick", "args": {"key_field": "@name"}}},
|
||||
{"rows": _field_rows()}, {})
|
||||
|
||||
|
||||
def test_pick_miss_returns_missing_so_field_absent():
|
||||
mapped = map_response(
|
||||
{"quantity": {"expr": "rows", "transform": "pick",
|
||||
"args": {"key_field": "@name", "key_value": "nope", "value_field": "@value"}}},
|
||||
{"rows": _field_rows()},
|
||||
{"type": "object", "properties": {"quantity": {"type": "number"}}},
|
||||
)
|
||||
assert "quantity" not in mapped
|
||||
|
||||
|
||||
# ---- template:参数模板填充(域参数→接口参数翻译的列表渲染)----
|
||||
|
||||
def test_template_renders_list_into_in_clause():
|
||||
mapped = map_response(
|
||||
{"condition": {"template": "img02 = '{warehouse}' AND img04 IN ({lots})",
|
||||
"args": {"list_item_template": "'{item}'", "separator": ",", "escape": "quote"}}},
|
||||
{"warehouse": "HTP-D43", "lots": ["HOW25071402", "HOW25081302"]},
|
||||
{"type": "object", "properties": {"condition": {"type": "string"}}},
|
||||
)
|
||||
assert mapped["condition"] == "img02 = 'HTP-D43' AND img04 IN ('HOW25071402','HOW25081302')"
|
||||
|
||||
|
||||
def test_template_escapes_single_quotes_in_values():
|
||||
mapped = map_response(
|
||||
{"condition": {"template": "img02 = '{warehouse}'", "args": {"escape": "quote"}}},
|
||||
{"warehouse": "HT'D43"},
|
||||
{"type": "object", "properties": {"condition": {"type": "string"}}},
|
||||
)
|
||||
assert mapped["condition"] == "img02 = 'HT''D43'"
|
||||
|
||||
|
||||
def test_template_missing_param_fail_closed():
|
||||
with pytest.raises(AppError) as exc:
|
||||
map_response(
|
||||
{"condition": {"template": "img04 = '{invoice_no}'"}},
|
||||
{},
|
||||
{"type": "object", "properties": {"condition": {"type": "string"}}},
|
||||
)
|
||||
assert exc.value.code == "INTEGRATION.MAPPING_INVALID"
|
||||
|
||||
|
||||
# ---- dict 项列表模板:域元组列表 → OR 拼接条件(料号+库位+批号批量查询)----
|
||||
|
||||
def test_template_renders_dict_items_with_field_refs():
|
||||
mapped = map_response(
|
||||
{"condition": {"template": "{targets}",
|
||||
"args": {"list_item_template": "(img01 = '{material_no}' AND img02 = '{from_warehouse}' AND img04 = '{lot_no}')",
|
||||
"separator": " OR ", "escape": "quote"}}},
|
||||
{"targets": [
|
||||
{"material_no": "M-1", "from_warehouse": "HTP-D43", "lot_no": "LOT-1"},
|
||||
{"material_no": "M'2", "from_warehouse": "HTP-D49", "lot_no": "LOT-2"},
|
||||
]},
|
||||
{"type": "object", "properties": {"condition": {"type": "string"}}},
|
||||
)
|
||||
assert mapped["condition"] == (
|
||||
"(img01 = 'M-1' AND img02 = 'HTP-D43' AND img04 = 'LOT-1') OR "
|
||||
"(img01 = 'M''2' AND img02 = 'HTP-D49' AND img04 = 'LOT-2')"
|
||||
)
|
||||
|
||||
|
||||
def test_template_dict_item_missing_field_fail_closed():
|
||||
with pytest.raises(AppError) as exc:
|
||||
map_response(
|
||||
{"condition": {"template": "{targets}",
|
||||
"args": {"list_item_template": "(img01 = '{material_no}' AND img04 = '{lot_no}')",
|
||||
"separator": " OR "}}},
|
||||
{"targets": [{"material_no": "M-1"}]},
|
||||
{"type": "object", "properties": {"condition": {"type": "string"}}},
|
||||
)
|
||||
assert exc.value.code == "INTEGRATION.MAPPING_INVALID"
|
||||
|
||||
|
||||
# ---- each:列表逐元素子映射(多条外部记录 → 多行结果)----
|
||||
|
||||
def test_each_maps_record_list_via_pick_and_cast():
|
||||
raw = {"Master": [
|
||||
{"Record": {"Field": [
|
||||
{"name": "img01", "value": "M-1"}, {"name": "img02", "value": "W1"},
|
||||
{"name": "img04", "value": "L-1"}, {"name": "img11", "value": "36"}]}},
|
||||
{"Record": {"Field": [
|
||||
{"name": "img01", "value": "M-2"}, {"name": "img02", "value": "W2"},
|
||||
{"name": "img04", "value": "L-2"}, {"name": "img11", "value": "0"}]}},
|
||||
]}
|
||||
mapped = map_response(
|
||||
{"rows": {"expr": "Master", "transform": "each", "args": {"fields": {
|
||||
"material_no": {"expr": "Record.Field", "transform": "pick",
|
||||
"args": {"key_field": "name", "key_value": "img01", "value_field": "value"}},
|
||||
"lot_no": {"expr": "Record.Field", "transform": "pick",
|
||||
"args": {"key_field": "name", "key_value": "img04", "value_field": "value"}},
|
||||
"quantity": {"expr": "Record.Field", "transform": "pick",
|
||||
"args": {"key_field": "name", "key_value": "img11", "value_field": "value", "cast": "decimal"}},
|
||||
}}}},
|
||||
raw,
|
||||
{"type": "object", "required": ["rows"], "properties": {"rows": {"type": "array"}}},
|
||||
)
|
||||
assert mapped["rows"] == [
|
||||
{"material_no": "M-1", "lot_no": "L-1", "quantity": Decimal("36")},
|
||||
{"material_no": "M-2", "lot_no": "L-2", "quantity": Decimal("0")},
|
||||
]
|
||||
|
||||
|
||||
def test_each_single_record_dict_wrapped_to_one_row():
|
||||
"""XML 归一化单条记录为 dict → 自动包装为单元素列表,不 fail-closed。"""
|
||||
mapped = map_response(
|
||||
{"rows": {"expr": "Master", "transform": "each", "args": {"fields": {
|
||||
"lot_no": {"expr": "Record.Field", "transform": "pick",
|
||||
"args": {"key_field": "@name", "key_value": "img04", "value_field": "@value"}}}}}},
|
||||
{"Master": {"Record": {"Field": [{"@name": "img04", "@value": "L-1"}]}}},
|
||||
{"type": "object", "properties": {"rows": {"type": "array"}}},
|
||||
)
|
||||
assert mapped["rows"] == [{"lot_no": "L-1"}]
|
||||
|
||||
|
||||
def test_each_missing_target_yields_empty_rows():
|
||||
"""目标记录集整体缺失(外部系统对"查无记录"返回空 XML)→ 空列表而非 fail-closed。
|
||||
|
||||
空结果是合法答案:交领域层归类为"未找到",不因输出 Schema 校验抛映射错误。
|
||||
"""
|
||||
mapped = map_response(
|
||||
{"rows": {"expr": "GetItemStockListResponse.response.Response.ResponseContent.Document.RecordSet.Master",
|
||||
"transform": "each", "args": {"fields": {
|
||||
"lot_no": {"expr": "Record.Field", "transform": "pick",
|
||||
"args": {"key_field": "@name", "key_value": "img04", "value_field": "@value"}}}}}},
|
||||
{"GetItemStockListResponse": {"response": {"Response": {"ResponseContent": {"Document": {}}}}}},
|
||||
{"type": "object", "required": ["rows"], "properties": {"rows": {"type": "array"}}},
|
||||
)
|
||||
assert mapped["rows"] == []
|
||||
|
||||
|
||||
def test_each_skips_items_with_all_fields_missing():
|
||||
"""Master 存在但无 Record 子节点 → 逐字段全缺失的空行被跳过,不产出违反行 Schema 的 {}。"""
|
||||
mapped = map_response(
|
||||
{"rows": {"expr": "Master", "transform": "each", "args": {"fields": {
|
||||
"lot_no": {"expr": "Record.Field", "transform": "pick",
|
||||
"args": {"key_field": "@name", "key_value": "img04", "value_field": "@value"}}}}}},
|
||||
{"Master": {"@name": "img_file"}},
|
||||
{"type": "object", "required": ["rows"], "properties": {"rows": {"type": "array"}}},
|
||||
)
|
||||
assert mapped["rows"] == []
|
||||
|
||||
|
||||
def test_each_flattens_repeated_recordset_from_multi_target_query():
|
||||
"""多条件批量查询返回多个 RecordSet(重复节点列表)→ 路径扇出收集,行全部拉平。
|
||||
|
||||
[回归防线 2026-09-22] TIPTOP 对 OR 多目标查询按条件拆多个 RecordSet 返回:
|
||||
路径遇列表做逐元素收集后 each 正常产出全部行,不得误判为"查无记录"。
|
||||
"""
|
||||
raw = json.loads(r"""
|
||||
{"GetItemStockListResponse": {"response": {"Response": {"ResponseContent": {"Document": {"RecordSet": [
|
||||
{"@id": "1", "Master": {"@name": "img_file", "Record": {"Field": [
|
||||
{"@name": "img01", "@value": "M-1"}, {"@name": "img04", "@value": "L-1"},
|
||||
{"@name": "img10", "@value": "0.000"}]}}},
|
||||
{"@id": "2", "Master": {"@name": "img_file", "Record": {"Field": [
|
||||
{"@name": "img01", "@value": "M-2"}, {"@name": "img04", "@value": "L-2"},
|
||||
{"@name": "img10", "@value": "5.000"}]}}}
|
||||
]}}}}}
|
||||
}""")
|
||||
mapped = map_response(
|
||||
{"rows": {"expr": "GetItemStockListResponse.response.Response.ResponseContent.Document.RecordSet.Master",
|
||||
"transform": "each", "args": {"fields": {
|
||||
"material_no": {"expr": "Record.Field", "transform": "pick",
|
||||
"args": {"key_field": "@name", "key_value": "img01", "value_field": "@value"}},
|
||||
"lot_no": {"expr": "Record.Field", "transform": "pick",
|
||||
"args": {"key_field": "@name", "key_value": "img04", "value_field": "@value"}},
|
||||
"quantity": {"expr": "Record.Field", "transform": "pick",
|
||||
"args": {"key_field": "@name", "key_value": "img10", "value_field": "@value",
|
||||
"cast": "decimal"}}}}}},
|
||||
raw,
|
||||
{"type": "object", "required": ["rows"], "properties": {"rows": {"type": "array"}}},
|
||||
)
|
||||
# [断言意图] 两个条件的记录都进入 rows,数量不足/未找到的判定输入完整。
|
||||
assert mapped["rows"] == [
|
||||
{"material_no": "M-1", "lot_no": "L-1", "quantity": Decimal("0.000")},
|
||||
{"material_no": "M-2", "lot_no": "L-2", "quantity": Decimal("5.000")},
|
||||
]
|
||||
|
||||
|
||||
def test_each_target_not_list_fail_closed():
|
||||
with pytest.raises(AppError) as exc:
|
||||
map_response(
|
||||
{"rows": {"expr": "Master", "transform": "each", "args": {"fields": {}}}},
|
||||
{"Master": "not a dict or list"},
|
||||
{"type": "object", "properties": {"rows": {"type": "array"}}},
|
||||
)
|
||||
assert exc.value.code == "INTEGRATION.MAPPING_INVALID"
|
||||
|
||||
|
||||
def test_each_unknown_nested_transform_fail_closed():
|
||||
with pytest.raises(AppError) as exc:
|
||||
map_response(
|
||||
{"rows": {"expr": "Master", "transform": "each", "args": {"fields": {
|
||||
"x": {"expr": "a", "transform": "no_such_fn"}}}}},
|
||||
{"Master": [{"a": 1}]},
|
||||
{"type": "object", "properties": {"rows": {"type": "array"}}},
|
||||
)
|
||||
assert exc.value.code == "INTEGRATION.MAPPING_INVALID"
|
||||
@@ -84,3 +84,31 @@ def test_split_migration_chains_after_create():
|
||||
split = _load_migration('integration_connector_columns_migration', 'ix1a2b3c4d5e_split_integration_connector_columns.py')
|
||||
assert split.revision == 'ix1a2b3c4d5e'
|
||||
assert split.down_revision == 'iy1a2b3c4d5e'
|
||||
|
||||
|
||||
def test_drop_context_source_code_migration_round_trip():
|
||||
"""删列迁移承接 head rd1e2f3a4b5c:升级后 context_source_code 消失,回滚后恢复。"""
|
||||
engine = sa.create_engine('sqlite:///:memory:')
|
||||
base = _load_migration('integration_connector_migration', 'ic1a2b3c4d5f_add_integration_connector.py')
|
||||
split = _load_migration('integration_connector_columns_migration', 'ix1a2b3c4d5e_split_integration_connector_columns.py')
|
||||
drop = _load_migration(
|
||||
'integration_binding_drop_source_code_migration',
|
||||
're1f3a4b5c6d_drop_integration_binding_context_source_code.py',
|
||||
)
|
||||
assert drop.revision == 're1f3a4b5c6d'
|
||||
assert drop.down_revision == 'rd1e2f3a4b5c'
|
||||
with engine.begin() as connection:
|
||||
context = MigrationContext.configure(connection)
|
||||
operations = Operations(context)
|
||||
for module in (base, split, drop):
|
||||
module.op = operations
|
||||
|
||||
base.upgrade()
|
||||
split.upgrade()
|
||||
drop.upgrade()
|
||||
cols = {item['name'] for item in sa.inspect(connection).get_columns('integration_bindings')}
|
||||
assert 'context_source_code' not in cols
|
||||
|
||||
drop.downgrade()
|
||||
cols = {item['name'] for item in sa.inspect(connection).get_columns('integration_bindings')}
|
||||
assert 'context_source_code' in cols
|
||||
@@ -71,3 +71,59 @@ def test_credential_summary_has_no_plaintext(app):
|
||||
assert "s3cretLY" not in json.dumps(summary)
|
||||
assert "svc_user_erp" not in json.dumps(summary)
|
||||
assert summary["version"] == 1
|
||||
|
||||
|
||||
# ---- db 模式:密文落库 + 主密钥解密 ----
|
||||
|
||||
def _add_db_credential(code="DB-CRED", ciphertext=None):
|
||||
cred = IntegrationCredentialReference(
|
||||
code=code, secret_ref=f"db:{code}", secret_provider="db",
|
||||
credential_type="password", version=1, status="active",
|
||||
secret_ciphertext=ciphertext,
|
||||
)
|
||||
db.session.add(cred)
|
||||
db.session.commit()
|
||||
return cred
|
||||
|
||||
|
||||
def _crypto_codes():
|
||||
from app.core.credential_crypto import CredentialCryptoErrorCodes
|
||||
return CredentialCryptoErrorCodes(
|
||||
key_missing="K1", key_invalid="K2", secret_empty="S0", secret_missing="S1", secret_invalid="S2",
|
||||
)
|
||||
|
||||
|
||||
def test_resolve_credential_db_mode_decrypts(app):
|
||||
"""db 模式:用 INTEGRATION_CREDENTIAL_KEY 解密密文还原凭据字典。"""
|
||||
from cryptography.fernet import Fernet
|
||||
|
||||
from app.core.credential_crypto import encrypt_secret
|
||||
app.config["INTEGRATION_CREDENTIAL_KEY"] = Fernet.generate_key().decode("ascii")
|
||||
ciphertext = encrypt_secret(
|
||||
json.dumps({"username": "u", "password": "p"}),
|
||||
key_config_name="INTEGRATION_CREDENTIAL_KEY", codes=_crypto_codes(),
|
||||
)
|
||||
_add_db_credential(ciphertext=ciphertext)
|
||||
assert resolve_credential("DB-CRED") == {"username": "u", "password": "p"}
|
||||
|
||||
|
||||
def test_resolve_credential_db_mode_missing_ciphertext_fail_closed(app):
|
||||
"""db 模式缺密文 → CredentialUnresolvedError。"""
|
||||
_add_db_credential(ciphertext=None)
|
||||
with pytest.raises(AppError) as exc:
|
||||
resolve_credential("DB-CRED")
|
||||
assert exc.value.code == "INTEGRATION.CREDENTIAL_UNRESOLVED"
|
||||
|
||||
|
||||
def test_resolve_credential_db_mode_missing_master_key_fail_closed(app):
|
||||
"""主密钥无效 → 统一折算为 CredentialUnresolvedError(fail-closed)。"""
|
||||
from cryptography.fernet import Fernet
|
||||
|
||||
from app.core.credential_crypto import encrypt_secret
|
||||
app.config["INTEGRATION_CREDENTIAL_KEY"] = Fernet.generate_key().decode("ascii")
|
||||
ciphertext = encrypt_secret("x", key_config_name="INTEGRATION_CREDENTIAL_KEY", codes=_crypto_codes())
|
||||
_add_db_credential(ciphertext=ciphertext)
|
||||
app.config["INTEGRATION_CREDENTIAL_KEY"] = "not-a-valid-key"
|
||||
with pytest.raises(AppError) as exc:
|
||||
resolve_credential("DB-CRED")
|
||||
assert exc.value.code == "INTEGRATION.CREDENTIAL_UNRESOLVED"
|
||||
@@ -1,9 +1,10 @@
|
||||
"""tests/services/integration_connector/test_transports.py
|
||||
|
||||
用途:验证 REST/SOAP Transport 的请求构造、业务错误映射与 fail-closed;
|
||||
以及结果分类(classify_transport_response)的六态语义。
|
||||
连接测试探针(probe)的可达判定;以及结果分类(classify_transport_response)的六态语义。
|
||||
依赖:transports/base.py、transports/rest.py、transports/soap.py、errors.py。
|
||||
逻辑:Transport.call 返回原始 dict;分类器把 dict 归一为 IntegrationCallResult。
|
||||
probe 只做网络可达性探测(REST 任意响应即通;SOAP 校验 WSDL/Envelope 根元素)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
@@ -102,3 +103,289 @@ def test_classify_transport_response_states():
|
||||
assert dup.status == "duplicate_success"
|
||||
unknown = classify_transport_response({})
|
||||
assert unknown.status == "technical_failed"
|
||||
|
||||
|
||||
# ---- SOAP Transport 实装 ----
|
||||
|
||||
_SOAP_TEMPLATE = (
|
||||
'<?xml version="1.0" encoding="utf-8"?>'
|
||||
'<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">'
|
||||
'<soap:Body><fjs:GetItemStockListRequest xmlns:fjs="http://www.dsc.com.tw/tiptop/TIPTOPServiceGateWay">'
|
||||
'<fjs:request><![CDATA[<Request><Organization name="{organization}"/>'
|
||||
'<Field name="condition" value="{condition}"/>'
|
||||
'<Authentication user="{credential_username}" password="{credential_password}"/>'
|
||||
'</Request>]]></fjs:request></fjs:GetItemStockListRequest></soap:Body></soap:Envelope>'
|
||||
)
|
||||
|
||||
# 带命名空间前缀 + 转义内嵌 XML 的典型网关响应。
|
||||
_SOAP_RESPONSE = (
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="no"?>'
|
||||
'<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">'
|
||||
'<SOAP-ENV:Body>'
|
||||
'<fjs1:GetItemStockListResponse xmlns:fjs1="http://www.dsc.com.tw/tiptop/TIPTOPServiceGateWay">'
|
||||
'<fjs1:response><Response>'
|
||||
'<Execution><Status code="0" sqlcode="0" description=""/></Execution>'
|
||||
'<ResponseContent><Parameter/>'
|
||||
'<Document><RecordSet id="1"><Master name="img_file"><Record>'
|
||||
'<Field name="img04" value="HOW25071402"/>'
|
||||
'<Field name="img11" value="30.000"/>'
|
||||
'</Record></Master></RecordSet></Document>'
|
||||
'</ResponseContent></Response></fjs1:response>'
|
||||
'</fjs1:GetItemStockListResponse>'
|
||||
'</SOAP-ENV:Body></SOAP-ENV:Envelope>'
|
||||
)
|
||||
|
||||
|
||||
def _soap_client(**overrides):
|
||||
cfg = {"endpoint": "https://erp.invalid/ws", "timeout_seconds": 30}
|
||||
cfg.update(overrides)
|
||||
return {"config_json": cfg, "credential": {"username": "u1", "password": "p1"}}
|
||||
|
||||
|
||||
def test_soap_fills_template_with_params_and_credential():
|
||||
"""模板占位符从请求参数与凭据(credential_* 前缀)填充,按 text/xml POST。"""
|
||||
captured = {}
|
||||
|
||||
def fake_http(method, url, **kw):
|
||||
captured.update(method=method, url=url, data=kw.get("data"), headers=kw.get("headers"))
|
||||
return _resp(200, text=_SOAP_RESPONSE)
|
||||
|
||||
result = SoapTransport(http_request=fake_http).call(
|
||||
client=_soap_client(),
|
||||
interface={"request_spec_json": {"method": "POST", "soap": {"action": "", "body_template": _SOAP_TEMPLATE}}},
|
||||
request={"params": {"organization": "TGHX", "condition": "img04 IN ('HOW25071402')"}},
|
||||
)
|
||||
body = captured["data"].decode("utf-8")
|
||||
assert captured["method"] == "POST"
|
||||
assert captured["url"] == "https://erp.invalid/ws"
|
||||
assert captured["headers"]["Content-Type"].startswith("text/xml")
|
||||
assert captured["headers"]["SOAPAction"] == '""' # SOAPAction 头恒存在(空契约即带引号空串)
|
||||
assert 'name="TGHX"' in body
|
||||
assert "img04 IN ('HOW25071402')" in body
|
||||
assert 'user="u1"' in body and 'password="p1"' in body
|
||||
# 内嵌转义 XML 被递归展开,且按 localname 归一化(前缀 fjs1 不出现)。
|
||||
assert result["GetItemStockListResponse"]["response"]["Response"]["Execution"]["Status"]["@code"] == "0"
|
||||
fields = result["GetItemStockListResponse"]["response"]["Response"]["ResponseContent"]["Document"]["RecordSet"]["Master"]["Record"]["Field"]
|
||||
by_name = {f["@name"]: f["@value"] for f in fields}
|
||||
assert by_name["img11"] == "30.000"
|
||||
|
||||
|
||||
def test_soap_missing_template_param_fail_closed():
|
||||
"""占位符缺值 → INTEGRATION.INPUT_INVALID(fail-closed,不静默出空串)。"""
|
||||
from app.core.errors import AppError
|
||||
transport = SoapTransport(http_request=lambda *a, **k: None)
|
||||
with pytest.raises(AppError) as exc:
|
||||
transport.call(
|
||||
client=_soap_client(),
|
||||
interface={"request_spec_json": {"soap": {"body_template": _SOAP_TEMPLATE}}},
|
||||
request={"params": {"condition": "x"}}, # 缺 organization
|
||||
)
|
||||
assert exc.value.code == "INTEGRATION.INPUT_INVALID"
|
||||
|
||||
|
||||
def test_soap_cdata_terminator_rejected():
|
||||
"""参数值含 CDATA 终止符 ]]> 时拒绝,防报文被截断。"""
|
||||
from app.core.errors import AppError
|
||||
transport = SoapTransport(http_request=lambda *a, **k: None)
|
||||
with pytest.raises(AppError) as exc:
|
||||
transport.call(
|
||||
client=_soap_client(),
|
||||
interface={"request_spec_json": {"soap": {"body_template": _SOAP_TEMPLATE}}},
|
||||
request={"params": {"organization": "TGHX", "condition": "a]]>b"}},
|
||||
)
|
||||
assert exc.value.details.get("reason") == "soap_cdata_terminator_in_params"
|
||||
|
||||
|
||||
def test_soap_fail_closed_without_body_template():
|
||||
"""endpoint 存在但缺 soap.body_template → 仍 fail-closed。"""
|
||||
transport = SoapTransport(http_request=lambda *a, **k: None)
|
||||
with pytest.raises(TransportNotFrozenError):
|
||||
transport.call(
|
||||
client=_soap_client(),
|
||||
interface={"request_spec_json": {"soap": {}}},
|
||||
request={"params": {}},
|
||||
)
|
||||
|
||||
|
||||
def test_soap_fault_maps_to_business_failed():
|
||||
"""标准 SOAP Fault → business_failed dict(faultcode/faultstring 透传)。"""
|
||||
fault = (
|
||||
'<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">'
|
||||
'<SOAP-ENV:Body><SOAP-ENV:Fault><faultcode>soap:Client</faultcode>'
|
||||
'<faultstring>bad request</faultstring></SOAP-ENV:Fault></SOAP-ENV:Body></SOAP-ENV:Envelope>'
|
||||
)
|
||||
transport = SoapTransport(http_request=lambda *a, **k: _resp(200, text=fault))
|
||||
result = transport.call(
|
||||
client=_soap_client(),
|
||||
interface={"request_spec_json": {"soap": {"body_template": _SOAP_TEMPLATE}}},
|
||||
request={"params": {"organization": "TGHX", "condition": "c"}},
|
||||
)
|
||||
assert result["status"] == "business_failed"
|
||||
assert result["message"] == "bad request"
|
||||
|
||||
|
||||
def test_soap_http_error_and_non_xml():
|
||||
"""HTTP 5xx → business_failed;200 非 XML → technical_failed(与 REST 同语义)。"""
|
||||
transport = SoapTransport(http_request=lambda *a, **k: _resp(500, text="boom"))
|
||||
result = transport.call(
|
||||
client=_soap_client(),
|
||||
interface={"request_spec_json": {"soap": {"body_template": _SOAP_TEMPLATE}}},
|
||||
request={"params": {"organization": "T", "condition": "c"}},
|
||||
)
|
||||
assert result["status"] == "business_failed" and result["code"] == "HTTP_500"
|
||||
|
||||
transport = SoapTransport(http_request=lambda *a, **k: _resp(200, text="<html>not soap"))
|
||||
result = transport.call(
|
||||
client=_soap_client(),
|
||||
interface={"request_spec_json": {"soap": {"body_template": _SOAP_TEMPLATE}}},
|
||||
request={"params": {"organization": "T", "condition": "c"}},
|
||||
)
|
||||
assert result["status"] == "technical_failed" and result["code"] == "NON_XML"
|
||||
|
||||
|
||||
def test_soap_error_message_masks_credentials():
|
||||
"""错误回显(可能含请求体)中的凭据值必须替换为 ***,不得进审计/响应。"""
|
||||
transport = SoapTransport(http_request=lambda *a, **k: _resp(500, text='echo: password="p1" failed'))
|
||||
result = transport.call(
|
||||
client=_soap_client(),
|
||||
interface={"request_spec_json": {"soap": {"body_template": _SOAP_TEMPLATE}}},
|
||||
request={"params": {"organization": "T", "condition": "c"}},
|
||||
)
|
||||
assert result["message"] == 'echo: password="***" failed'
|
||||
assert "p1" not in result["message"]
|
||||
|
||||
|
||||
def test_soap_params_cannot_shadow_credentials():
|
||||
"""请求参数不得冒充 credential_* 占位符值(凭据注入永远后写覆盖)。"""
|
||||
captured = {}
|
||||
|
||||
def fake_http(method, url, **kw):
|
||||
captured.update(data=kw.get("data"))
|
||||
return _resp(200, text=_SOAP_RESPONSE)
|
||||
|
||||
SoapTransport(http_request=fake_http).call(
|
||||
client=_soap_client(),
|
||||
interface={"request_spec_json": {"soap": {"body_template": _SOAP_TEMPLATE}}},
|
||||
request={"params": {"organization": "T", "condition": "c", "credential_password": "evil"}},
|
||||
)
|
||||
assert 'password="p1"' in captured["data"].decode("utf-8")
|
||||
assert "evil" not in captured["data"].decode("utf-8")
|
||||
|
||||
|
||||
def test_soap_action_header_sent_when_configured():
|
||||
"""soap.action 非空时写入 SOAPAction 头。"""
|
||||
captured = {}
|
||||
|
||||
def fake_http(method, url, **kw):
|
||||
captured.update(headers=kw.get("headers"))
|
||||
return _resp(200, text=_SOAP_RESPONSE)
|
||||
|
||||
SoapTransport(http_request=fake_http).call(
|
||||
client=_soap_client(),
|
||||
interface={"request_spec_json": {"soap": {"action": "urn:GetItemStockList", "body_template": _SOAP_TEMPLATE}}},
|
||||
request={"params": {"organization": "T", "condition": "c"}},
|
||||
)
|
||||
assert captured["headers"]["SOAPAction"] == '"urn:GetItemStockList"' # 按规范带引号
|
||||
|
||||
|
||||
# ---- 连接测试探针(probe):只证明网络/服务可达,不做业务调用 ----
|
||||
|
||||
_WSDL = (
|
||||
'<?xml version="1.0" encoding="utf-8"?>'
|
||||
'<wsdl:definitions xmlns:wsdl="http://schemas.xmlsoap.org/wsdl/" targetNamespace="urn:t">'
|
||||
'</wsdl:definitions>'
|
||||
)
|
||||
|
||||
|
||||
def test_rest_probe_reachable_on_any_http_response():
|
||||
"""REST probe:任意 HTTP 响应(含 404)都证明 endpoint 网络可达。"""
|
||||
captured = {}
|
||||
|
||||
def fake_http(method, url, **kw):
|
||||
captured.update(method=method, url=url)
|
||||
return _resp(404, text="not found")
|
||||
|
||||
result = RestTransport(http_request=fake_http).probe(client=_client())
|
||||
assert captured["method"] == "GET"
|
||||
assert captured["url"] == "https://erp.invalid"
|
||||
assert result["ok"] is True
|
||||
assert result["code"] == "HTTP_404"
|
||||
|
||||
|
||||
def test_rest_probe_connection_failure_not_ok_and_masked():
|
||||
"""REST probe:连接异常 → ok=False,异常回显中凭据值脱敏。"""
|
||||
|
||||
def fake_http(method, url, **kw):
|
||||
raise ConnectionError('connect failed with password="p1"')
|
||||
|
||||
probe_client = _client()
|
||||
probe_client["credential"] = {"password": "p1"}
|
||||
result = RestTransport(http_request=fake_http).probe(client=probe_client)
|
||||
assert result["ok"] is False
|
||||
assert result["code"] == "CONNECTION_FAILED"
|
||||
assert "p1" not in result["message"]
|
||||
|
||||
|
||||
def test_rest_probe_fail_closed_without_endpoint():
|
||||
"""REST probe:endpoint 未冻结时同样 fail-closed。"""
|
||||
transport = RestTransport(http_request=lambda *a, **k: None)
|
||||
with pytest.raises(TransportNotFrozenError):
|
||||
transport.probe(client={"config_json": {}})
|
||||
|
||||
|
||||
def test_soap_probe_wsdl_and_envelope_reachable():
|
||||
"""SOAP probe:WSDL(definitions)与直连服务端点(Envelope)根元素均算可达。"""
|
||||
captured = {}
|
||||
|
||||
def fake_http(method, url, **kw):
|
||||
captured.update(method=method, url=url)
|
||||
return _resp(200, text=_WSDL)
|
||||
|
||||
result = SoapTransport(http_request=fake_http).probe(client=_soap_client())
|
||||
assert captured["method"] == "GET"
|
||||
# 裸服务端点自动补 ?wsdl:SOAP 端点对裸 GET 常返回 404/405/501
|
||||
assert captured["url"] == "https://erp.invalid/ws?wsdl"
|
||||
assert result["ok"] is True
|
||||
|
||||
envelope = (
|
||||
'<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">'
|
||||
'<SOAP-ENV:Body/></SOAP-ENV:Envelope>'
|
||||
)
|
||||
ok_envelope = SoapTransport(http_request=lambda *a, **k: _resp(200, text=envelope))
|
||||
assert ok_envelope.probe(client=_soap_client())["ok"] is True
|
||||
|
||||
|
||||
def test_soap_probe_keeps_existing_query():
|
||||
"""SOAP probe:endpoint 已带 query(如 ?wsdl)时按原地址探测,不重复追加。"""
|
||||
captured = {}
|
||||
|
||||
def fake_http(method, url, **kw):
|
||||
captured.update(url=url)
|
||||
return _resp(200, text=_WSDL)
|
||||
|
||||
result = SoapTransport(http_request=fake_http).probe(
|
||||
client=_soap_client(endpoint="https://erp.invalid/web/ws/r/aws_ttsrv2?wsdl"),
|
||||
)
|
||||
assert captured["url"] == "https://erp.invalid/web/ws/r/aws_ttsrv2?wsdl"
|
||||
assert result["ok"] is True
|
||||
|
||||
|
||||
def test_soap_probe_failure_paths():
|
||||
"""SOAP probe:HTTP 错误/非 XML/根元素不符/连接异常 → ok=False;缺 wsdl fail-closed。"""
|
||||
http_error = SoapTransport(http_request=lambda *a, **k: _resp(500, text="boom"))
|
||||
result = http_error.probe(client=_soap_client())
|
||||
assert result["ok"] is False and result["code"] == "HTTP_500"
|
||||
|
||||
not_xml = SoapTransport(http_request=lambda *a, **k: _resp(200, text="<html>broken"))
|
||||
assert not_xml.probe(client=_soap_client())["code"] == "NON_XML"
|
||||
|
||||
wrong_root = SoapTransport(http_request=lambda *a, **k: _resp(200, text="<html></html>"))
|
||||
assert wrong_root.probe(client=_soap_client())["code"] == "NOT_WSDL"
|
||||
|
||||
def unreachable(method, url, **kw):
|
||||
raise ConnectionError("connection refused")
|
||||
|
||||
assert SoapTransport(http_request=unreachable).probe(client=_soap_client())["ok"] is False
|
||||
|
||||
with pytest.raises(TransportNotFrozenError):
|
||||
SoapTransport().probe(client={"config_json": {}})
|
||||
Reference in new issue
Block a user