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
@@ -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