Merge branch 'dev' into runny827
feat(training): 新增精益培训视频与周任务管理 # Conflicts: # backend/app/models/__init__.py
This commit is contained in:
1 parent
85d27e9ffa
commit
91b7233872
812 files changed
+73763
-18908
No files matched your search
@@ -0,0 +1,122 @@
|
||||
"""tests/services/integration_connector/test_binding.py
|
||||
|
||||
用途:验证 Binding 解析与版本冻结——默认/上下文覆盖/优先级/生效区间/状态门禁/fail-closed。
|
||||
依赖:IntegrationBinding 等模型、binding.py、errors.py。
|
||||
逻辑:只匹配 published + environment + 生效区间 + context_selector 子集;
|
||||
无命中抛 BindingNotFoundError;快照冻结 interface 版本与配置(调用期冻结,非活表)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError
|
||||
from app.models import IntegrationBinding, IntegrationClientInstance, IntegrationInterfaceDefinition
|
||||
from app.services.integration_connector.binding import BindingSnapshot, resolve_binding
|
||||
|
||||
|
||||
def _client(code="CLI-A", **overrides):
|
||||
values = {"name": f"client {code}", "connector_type": "soap", "environment": "prod",
|
||||
"config_json": {"endpoint": "https://erp.invalid"}}
|
||||
values.update(overrides)
|
||||
return IntegrationClientInstance(code=code, **values)
|
||||
|
||||
|
||||
def _interface(code="IFACE-Q", **overrides):
|
||||
values = {"name": "查询库存", "client_instance_code": "CLI-A", "connector_type": "soap",
|
||||
"request_spec_json": {"method": "GET", "path": "/stock"},
|
||||
"input_schema_json": {}, "response_mapping_json": {"qty": {"expr": "quantity", "transform": "decimal"}},
|
||||
"output_schema_json": {"type": "object", "properties": {"qty": {"type": "number"}}},
|
||||
"version": 3, "status": "published"}
|
||||
values.update(overrides)
|
||||
return IntegrationInterfaceDefinition(code=code, **values)
|
||||
|
||||
|
||||
def _binding(capability="in_transit_transfer.query_inventory", **overrides):
|
||||
values = {"capability": capability, "context_selector_json": {},
|
||||
"client_instance_code": "CLI-A", "interface_definition_code": "IFACE-Q",
|
||||
"mapping_version": 2, "priority": 0, "environment": "prod", "status": "published"}
|
||||
values.update(overrides)
|
||||
return IntegrationBinding(**values)
|
||||
|
||||
|
||||
def _seed_default(app):
|
||||
db.session.add_all([_client(), _interface(), _binding()])
|
||||
db.session.commit()
|
||||
|
||||
|
||||
def test_default_binding_matches_any_context(app):
|
||||
"""空 context_selector 的默认绑定命中(context 含额外键也可命中)。"""
|
||||
_seed_default(app)
|
||||
snap = resolve_binding("in_transit_transfer.query_inventory", {"source_code": "DBS-AWSBI"}, "prod")
|
||||
assert snap.client_code == "CLI-A"
|
||||
assert snap.interface_code == "IFACE-Q"
|
||||
assert snap.mapping_version == 2
|
||||
|
||||
|
||||
def test_context_specific_overrides_default(app):
|
||||
"""context_selector 匹配的来源专属绑定(更高优先级)覆盖默认绑定。"""
|
||||
db.session.add_all([_client(), _interface()])
|
||||
db.session.add_all([
|
||||
_binding(),
|
||||
_binding(context_selector_json={"source_code": "CRANE-SZ"}, priority=10),
|
||||
])
|
||||
db.session.commit()
|
||||
snap = resolve_binding("in_transit_transfer.query_inventory", {"source_code": "CRANE-SZ"}, "prod")
|
||||
assert snap.context_selector == {"source_code": "CRANE-SZ"}
|
||||
|
||||
|
||||
def test_higher_priority_wins_among_matching(app):
|
||||
"""同一 context 下、不同 context_selector 均命中时,priority 高者优先。"""
|
||||
db.session.add_all([_client(), _interface()])
|
||||
db.session.add_all([
|
||||
_binding(context_selector_json={"source_code": "X", "region": "cn"}, priority=1),
|
||||
_binding(context_selector_json={"source_code": "X"}, priority=5),
|
||||
])
|
||||
db.session.commit()
|
||||
snap = resolve_binding("in_transit_transfer.query_inventory", {"source_code": "X", "region": "cn"}, "prod")
|
||||
assert snap.context_selector == {"source_code": "X"} # priority 5 绑定胜出
|
||||
|
||||
|
||||
def test_expired_effective_window_not_matched(app):
|
||||
"""effective_to 已过期的绑定不命中,回落到默认。"""
|
||||
past = datetime.now(timezone.utc) - timedelta(days=1)
|
||||
db.session.add_all([_client(), _interface()])
|
||||
db.session.add_all([
|
||||
_binding(context_selector_json={"source_code": "X"}, effective_from=past, effective_to=past),
|
||||
_binding(),
|
||||
])
|
||||
db.session.commit()
|
||||
snap = resolve_binding("in_transit_transfer.query_inventory", {"source_code": "X"}, "prod")
|
||||
assert snap.context_selector == {}
|
||||
|
||||
|
||||
def test_draft_status_not_matched(app):
|
||||
"""status=draft 的绑定不命中;无默认时抛 BindingNotFoundError。"""
|
||||
db.session.add_all([_client(), _interface(), _binding(status="draft")])
|
||||
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_no_match_raises(app):
|
||||
"""无任何可命中绑定抛 BindingNotFoundError(fail-closed)。"""
|
||||
db.session.add_all([_client(), _interface(), _binding(capability="other.cap")])
|
||||
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_freeze_versions_in_snapshot(app):
|
||||
"""快照冻结 interface 版本与调用期配置(非活表)。"""
|
||||
_seed_default(app)
|
||||
snap = resolve_binding("in_transit_transfer.query_inventory", {}, "prod")
|
||||
assert snap.interface_version == 3
|
||||
assert snap.credential_ref_code is None
|
||||
assert snap.request_spec.get("path") == "/stock"
|
||||
assert snap.config.get("endpoint") == "https://erp.invalid"
|
||||
@@ -0,0 +1,59 @@
|
||||
"""tests/services/integration_connector/test_capability.py
|
||||
|
||||
用途:验证 Capability 强类型契约注册表:注册/查询/清单/重复/未注册。
|
||||
依赖:服务层 capability.py(纯代码,不依赖 DB);errors.py。
|
||||
逻辑:领域只能调用已注册的强类型能力;未注册 fail-closed 抛 INTEGRATION.CAPABILITY_NOT_FOUND。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.integration_connector.capability import (
|
||||
CapabilitySpec,
|
||||
ensure_capabilities_loaded,
|
||||
get_capability,
|
||||
list_capabilities,
|
||||
register_capability,
|
||||
reset_capability_registry_for_tests,
|
||||
)
|
||||
from app.core.errors import AppError, ValidationError
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def _fresh_registry():
|
||||
reset_capability_registry_for_tests()
|
||||
yield
|
||||
reset_capability_registry_for_tests()
|
||||
|
||||
|
||||
def test_register_then_get_returns_same_spec():
|
||||
"""注册后按名查询返回同一对象。"""
|
||||
spec = CapabilitySpec(name="demo.echo", input_schema={}, output_schema={}, idempotency="none", write=False)
|
||||
register_capability(spec)
|
||||
assert get_capability("demo.echo") is spec
|
||||
|
||||
|
||||
def test_duplicate_register_raises_validation():
|
||||
"""同名能力重复注册抛 ValidationError。"""
|
||||
register_capability(CapabilitySpec(name="demo.echo", input_schema={}, output_schema={}, idempotency="none", write=False))
|
||||
with pytest.raises(ValidationError):
|
||||
register_capability(CapabilitySpec(name="demo.echo", input_schema={}, output_schema={}, idempotency="none", write=False))
|
||||
|
||||
|
||||
def test_get_unregistered_raises_not_found():
|
||||
"""未注册能力抛 INTEGRATION.CAPABILITY_NOT_FOUND(fail-closed)。"""
|
||||
with pytest.raises(AppError) as exc:
|
||||
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,162 @@
|
||||
"""tests/services/integration_connector/test_engine.py
|
||||
|
||||
用途:验证 CapabilityGateway 调用引擎管线——resolve→validate→call→map→classify→落 IntegrationCall。
|
||||
依赖:capability/binding/mapping/security/transports、IntegrationCall 模型、errors.py。
|
||||
逻辑:读能力走 success(映射校验通过);写能力按原始 status 分类;超时→timeout;
|
||||
入参非法/无绑定/映射失败/result_unknown 均 fail-closed,且 result_unknown 不自动重试。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime
|
||||
from decimal import Decimal
|
||||
|
||||
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.integration_connector.engine import CapabilityGateway
|
||||
|
||||
|
||||
class FakeTransport:
|
||||
"""可注入响应或异常的传输替身。"""
|
||||
|
||||
connector_type = "rest"
|
||||
|
||||
def __init__(self, response):
|
||||
self._response = response
|
||||
|
||||
def call(self, *, client, interface, request):
|
||||
if isinstance(self._response, Exception):
|
||||
raise self._response
|
||||
return self._response
|
||||
|
||||
|
||||
def _seed(capability, *, connector_type="rest", response_mapping=None, output_schema=None):
|
||||
resp_map = response_mapping or {"found": {"expr": "found"}, "quantity": {"expr": "quantity", "transform": "decimal"}}
|
||||
out_schema = output_schema or {"type": "object", "properties": {"found": {"type": "boolean"}, "quantity": {"type": "number"}}}
|
||||
client = IntegrationClientInstance(
|
||||
code="CLI-A", name="client", connector_type=connector_type, environment="prod",
|
||||
config_json={"endpoint": "https://erp.invalid"},
|
||||
)
|
||||
iface = IntegrationInterfaceDefinition(
|
||||
code="IFACE-Q", name="iface", client_instance_code="CLI-A", connector_type=connector_type,
|
||||
request_spec_json={"method": "GET", "path": "/stock/{invoice_no}"},
|
||||
input_schema_json={}, response_mapping_json=resp_map, output_schema_json=out_schema,
|
||||
version=3, status="published",
|
||||
)
|
||||
db.session.add_all([client, iface])
|
||||
db.session.flush()
|
||||
binding = IntegrationBinding(
|
||||
capability=capability, context_selector_json={}, client_instance_code="CLI-A",
|
||||
interface_definition_code="IFACE-Q", mapping_version=2, priority=0, environment="prod",
|
||||
status="published",
|
||||
)
|
||||
db.session.add(binding)
|
||||
db.session.commit()
|
||||
return connector_type
|
||||
|
||||
|
||||
def _params(**overrides):
|
||||
values = {"invoice_no": "INV-001", "from_warehouse": "W1", "to_warehouse": "W2", "quantity": 100}
|
||||
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(
|
||||
capability="in_transit_transfer.query_inventory", context={},
|
||||
params=_params(), operation_id="OP-1", environment="prod",
|
||||
)
|
||||
assert result.status == "success"
|
||||
assert result.data["quantity"] == Decimal("100")
|
||||
call_row = IntegrationCall.query.filter_by(operation_id="OP-1").first()
|
||||
assert call_row is not None
|
||||
assert call_row.status == "success"
|
||||
|
||||
|
||||
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(
|
||||
capability="in_transit_transfer.query_inventory", context={},
|
||||
params={}, operation_id="OP-2", environment="prod",
|
||||
)
|
||||
assert exc.value.code == "INTEGRATION.INPUT_INVALID"
|
||||
|
||||
|
||||
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={},
|
||||
params=_params(), operation_id="OP-3", environment="prod",
|
||||
)
|
||||
assert exc.value.code == "INTEGRATION.BINDING_NOT_FOUND"
|
||||
|
||||
|
||||
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(
|
||||
capability="in_transit_transfer.create_transfer", context={},
|
||||
params=_params(), operation_id="OP-4", environment="prod",
|
||||
)
|
||||
assert result.status == "business_failed"
|
||||
assert result.error_code == "E1"
|
||||
|
||||
|
||||
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={},
|
||||
params=_params(), operation_id="OP-5", environment="prod",
|
||||
)
|
||||
assert result.status == "timeout"
|
||||
|
||||
|
||||
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"}}})
|
||||
fake = FakeTransport({"found": True}) # 缺 quantity
|
||||
with pytest.raises(AppError) as exc:
|
||||
CapabilityGateway(transports={"rest": fake}).call(
|
||||
capability="in_transit_transfer.query_inventory", context={},
|
||||
params=_params(), operation_id="OP-6", environment="prod",
|
||||
)
|
||||
assert exc.value.code == "INTEGRATION.MAPPING_INVALID"
|
||||
|
||||
|
||||
def test_call_result_unknown_no_auto_retry(app):
|
||||
"""result_unknown 不自动重试:transport 仅被调用一次。"""
|
||||
ensure_capabilities_loaded()
|
||||
_seed("in_transit_transfer.create_transfer")
|
||||
calls = []
|
||||
|
||||
class _OneShot(FakeTransport):
|
||||
def call(self, **kw):
|
||||
calls.append(1)
|
||||
return {"status": "result_unknown"}
|
||||
|
||||
result = CapabilityGateway(transports={"rest": _OneShot(None)}).call(
|
||||
capability="in_transit_transfer.create_transfer", context={},
|
||||
params=_params(), operation_id="OP-7", environment="prod",
|
||||
)
|
||||
assert result.status == "result_unknown"
|
||||
assert len(calls) == 1
|
||||
@@ -0,0 +1,96 @@
|
||||
"""tests/services/integration_connector/test_mapping.py
|
||||
|
||||
用途:验证声明式映射引擎——点路径/数组下标提取、白名单转换函数、最小 Schema 校验。
|
||||
依赖:mapping.py(纯函数);errors.py。
|
||||
逻辑:缺字段且不可满足→MappingInvalidError;非法类型/枚举→MappingInvalidError;
|
||||
表达式超深/超长→MappingInvalidError(fail-closed)。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from decimal import Decimal
|
||||
|
||||
import pytest
|
||||
|
||||
from app.core.errors import AppError
|
||||
from app.services.integration_connector.mapping import MISSING, extract_path, map_response
|
||||
|
||||
|
||||
def test_extract_path_dot():
|
||||
assert extract_path({"a": {"b": 1}}, "a.b") == 1
|
||||
|
||||
|
||||
def test_extract_path_array_index():
|
||||
assert extract_path({"a": [10, 20]}, "a[1]") == 20
|
||||
|
||||
|
||||
def test_extract_path_missing_returns_sentinel():
|
||||
assert extract_path({"a": 1}, "a.b") is MISSING
|
||||
assert extract_path({"a": [1]}, "a[9]") is MISSING
|
||||
|
||||
|
||||
def test_extract_path_depth_limit():
|
||||
deep = {"a": {"b": {"c": {"d": {"e": {"f": {"g": {"h": {"i": 1}}}}}}}}}
|
||||
with pytest.raises(AppError) as exc:
|
||||
extract_path(deep, "a.b.c.d.e.f.g.h.i")
|
||||
assert exc.value.code == "INTEGRATION.MAPPING_INVALID"
|
||||
|
||||
|
||||
def test_extract_path_length_limit():
|
||||
with pytest.raises(AppError) as exc:
|
||||
extract_path({"a": 1}, "a." + "b" * 300)
|
||||
assert exc.value.code == "INTEGRATION.MAPPING_INVALID"
|
||||
|
||||
|
||||
def test_map_response_extract_and_decimal_transform():
|
||||
mapped = map_response(
|
||||
{"qty": {"expr": "rows[0].qty", "transform": "decimal"}},
|
||||
{"rows": [{"qty": "100.5"}]},
|
||||
{"type": "object", "required": ["qty"], "properties": {"qty": {"type": "number"}}},
|
||||
)
|
||||
assert mapped["qty"] == Decimal("100.5")
|
||||
|
||||
|
||||
def test_map_response_default_and_fallback():
|
||||
mapped = map_response(
|
||||
{
|
||||
"a": {"expr": "missing", "transform": "default", "args": {"default": 7}},
|
||||
"b": {"expr": "missing", "transform": "fallback", "args": {"fallback": "X"}},
|
||||
},
|
||||
{},
|
||||
{"type": "object", "properties": {"a": {"type": "number"}, "b": {"type": "string"}}},
|
||||
)
|
||||
assert mapped == {"a": 7, "b": "X"}
|
||||
|
||||
|
||||
def test_map_response_missing_required_raises():
|
||||
with pytest.raises(AppError) as exc:
|
||||
map_response(
|
||||
{"a": {"expr": "missing"}},
|
||||
{},
|
||||
{"type": "object", "required": ["a"], "properties": {"a": {"type": "string"}}},
|
||||
)
|
||||
assert exc.value.code == "INTEGRATION.MAPPING_INVALID"
|
||||
|
||||
|
||||
def test_map_response_wrong_type_raises():
|
||||
with pytest.raises(AppError) as exc:
|
||||
map_response(
|
||||
{"a": {"expr": "x"}},
|
||||
{"x": "not-a-number"},
|
||||
{"type": "object", "required": ["a"], "properties": {"a": {"type": "number"}}},
|
||||
)
|
||||
assert exc.value.code == "INTEGRATION.MAPPING_INVALID"
|
||||
|
||||
|
||||
def test_map_response_enum_violation_raises():
|
||||
with pytest.raises(AppError) as exc:
|
||||
map_response(
|
||||
{"status": {"expr": "s"}},
|
||||
{"s": "banana"},
|
||||
{
|
||||
"type": "object", "required": ["status"],
|
||||
"properties": {"status": {"type": "string", "enum": ["ok", "bad"]}},
|
||||
},
|
||||
)
|
||||
assert exc.value.code == "INTEGRATION.MAPPING_INVALID"
|
||||
@@ -0,0 +1,86 @@
|
||||
"""tests/services/integration_connector/test_migration.py
|
||||
|
||||
用途:验证 Integration Connector 迁移可独立升级与回滚,且正确链在当前 head 之后。
|
||||
依赖:Alembic Operations、SQLAlchemy SQLite、ic1a2b3c4d5f / ix1a2b3c4d5e 迁移。
|
||||
逻辑:空库升级后 5 张表(含索引/约束)存在;回滚后全部删除;down_revision 指向既有 head。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import importlib.util
|
||||
from pathlib import Path
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic.migration import MigrationContext
|
||||
from alembic.operations import Operations
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
EXPECTED_TABLES = {
|
||||
'integration_credential_references',
|
||||
'integration_client_instances',
|
||||
'integration_interface_definitions',
|
||||
'integration_bindings',
|
||||
'integration_calls',
|
||||
}
|
||||
|
||||
VERSIONS_DIR = Path(__file__).parents[3] / 'migrations' / 'versions'
|
||||
|
||||
|
||||
def _load_migration(name: str, filename: str):
|
||||
"""加载指定迁移模块。"""
|
||||
path = VERSIONS_DIR / filename
|
||||
spec = importlib.util.spec_from_file_location(name, path)
|
||||
assert spec is not None and spec.loader is not None
|
||||
module = importlib.util.module_from_spec(spec)
|
||||
spec.loader.exec_module(module)
|
||||
return module
|
||||
|
||||
|
||||
def test_migration_chains_after_head():
|
||||
"""建表迁移必须挂接在既有链 head it1a2b3c4d5e 之后。"""
|
||||
migration = _load_migration('integration_connector_migration', 'ic1a2b3c4d5f_add_integration_connector.py')
|
||||
assert migration.revision == 'ic1a2b3c4d5f'
|
||||
assert migration.down_revision == 'it1a2b3c4d5e'
|
||||
|
||||
|
||||
def test_integration_connector_migration_round_trip():
|
||||
"""空库升级后 5 表存在;回滚后全部删除。"""
|
||||
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')
|
||||
with engine.begin() as connection:
|
||||
context = MigrationContext.configure(connection)
|
||||
operations = Operations(context)
|
||||
base.op = operations
|
||||
split.op = operations
|
||||
|
||||
base.upgrade()
|
||||
split.upgrade()
|
||||
tables = set(sa.inspect(connection).get_table_names())
|
||||
assert EXPECTED_TABLES.issubset(tables)
|
||||
|
||||
inspector = sa.inspect(connection)
|
||||
client_cols = {item['name'] for item in inspector.get_columns('integration_client_instances')}
|
||||
assert 'credential_ref_code' in client_cols
|
||||
assert 'endpoint' in client_cols
|
||||
assert 'timeout_seconds' in client_cols
|
||||
iface_cols = {item['name'] for item in inspector.get_columns('integration_interface_definitions')}
|
||||
assert 'http_method' in iface_cols
|
||||
assert 'request_path' in iface_cols
|
||||
binding_cols = {item['name'] for item in inspector.get_columns('integration_bindings')}
|
||||
assert 'context_source_code' in binding_cols
|
||||
binding_indexes = {item['name'] for item in inspector.get_indexes('integration_bindings')}
|
||||
assert 'ix_integration_bindings_cap_env_status' in binding_indexes
|
||||
|
||||
split.downgrade()
|
||||
base.downgrade()
|
||||
assert EXPECTED_TABLES.isdisjoint(set(sa.inspect(connection).get_table_names()))
|
||||
|
||||
|
||||
def test_split_migration_chains_after_create():
|
||||
"""拆列迁移必须挂接在 ic1a2b3c4d5e 之后(down_revision=iy1a2b3c4d5e)。"""
|
||||
split = _load_migration('integration_connector_columns_migration', 'ix1a2b3c4d5e_split_integration_connector_columns.py')
|
||||
assert split.revision == 'ix1a2b3c4d5e'
|
||||
assert split.down_revision == 'iy1a2b3c4d5e'
|
||||
@@ -0,0 +1,119 @@
|
||||
"""tests/services/integration_connector/test_models.py
|
||||
|
||||
用途:验证 Integration Connector 领域模型的可建表、唯一约束与状态/连接器类型约束。
|
||||
依赖:根 conftest 的 app fixture(SQLite 内存 + db.create_all())。
|
||||
逻辑:create_all 后各表可查询为空;code 唯一冲突抛 IntegrityError;非法
|
||||
connector_type / status 被 CheckConstraint 拒绝。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from app import db
|
||||
from app.models import (
|
||||
IntegrationBinding,
|
||||
IntegrationCall,
|
||||
IntegrationClientInstance,
|
||||
IntegrationCredentialReference,
|
||||
IntegrationInterfaceDefinition,
|
||||
)
|
||||
|
||||
CONNECTOR_MODELS = (
|
||||
IntegrationCredentialReference,
|
||||
IntegrationClientInstance,
|
||||
IntegrationInterfaceDefinition,
|
||||
IntegrationBinding,
|
||||
IntegrationCall,
|
||||
)
|
||||
|
||||
|
||||
def _client(**overrides):
|
||||
values = {
|
||||
"code": "ERP-T100",
|
||||
"name": "T100 ERP",
|
||||
"connector_type": "soap",
|
||||
"environment": "prod",
|
||||
"config_json": {"endpoint": "https://t100.invalid/ws", "timeout_seconds": 60},
|
||||
}
|
||||
values.update(overrides)
|
||||
return IntegrationClientInstance(**values)
|
||||
|
||||
|
||||
def test_all_connector_tables_created_and_empty(app):
|
||||
"""create_all 已随 app fixture 执行,5 张连接器表均可插入且初始为空。"""
|
||||
for model in CONNECTOR_MODELS:
|
||||
assert model.query.count() == 0
|
||||
|
||||
|
||||
def test_client_instance_code_unique_conflict(app):
|
||||
"""同一 code 的第二条记录触发唯一约束。"""
|
||||
db.session.add(_client())
|
||||
db.session.flush()
|
||||
db.session.add(_client())
|
||||
with pytest.raises(IntegrityError):
|
||||
db.session.commit()
|
||||
db.session.rollback()
|
||||
|
||||
|
||||
def test_client_instance_connector_type_check(app):
|
||||
"""connector_type 不在白名单(rest/soap)时被 CheckConstraint 拒绝。"""
|
||||
db.session.add(_client(connector_type="ftp"))
|
||||
with pytest.raises(IntegrityError):
|
||||
db.session.commit()
|
||||
db.session.rollback()
|
||||
|
||||
|
||||
def test_interface_definition_status_check(app):
|
||||
"""InterfaceDefinition.status 非法值被 CheckConstraint 拒绝。"""
|
||||
client = _client()
|
||||
db.session.add(client)
|
||||
db.session.flush()
|
||||
iface = IntegrationInterfaceDefinition(
|
||||
code="ERP-QUERY-STOCK",
|
||||
name="查询库存",
|
||||
client_instance_code=client.code,
|
||||
connector_type="soap",
|
||||
request_spec_json={"template": "{{invoice_no}}"},
|
||||
input_schema_json={},
|
||||
response_mapping_json={},
|
||||
output_schema_json={},
|
||||
version=1,
|
||||
status="banana",
|
||||
)
|
||||
db.session.add(iface)
|
||||
with pytest.raises(IntegrityError):
|
||||
db.session.commit()
|
||||
db.session.rollback()
|
||||
|
||||
|
||||
def test_credential_reference_status_check(app):
|
||||
"""CredentialReference.status 非法值被 CheckConstraint 拒绝。"""
|
||||
db.session.add(IntegrationCredentialReference(
|
||||
code="ERP-CRED-01",
|
||||
secret_ref="ERP_PASSWORD",
|
||||
secret_provider="env",
|
||||
credential_type="password",
|
||||
version=1,
|
||||
status="expired",
|
||||
))
|
||||
with pytest.raises(IntegrityError):
|
||||
db.session.commit()
|
||||
db.session.rollback()
|
||||
|
||||
|
||||
def test_credential_reference_secret_ref_not_returned_in_summary_column(app):
|
||||
"""模型列本身不存明文;secret_ref 是引用键而非真实凭据。"""
|
||||
cred = IntegrationCredentialReference(
|
||||
code="ERP-CRED-01",
|
||||
secret_ref="ERP_PASSWORD",
|
||||
secret_provider="env",
|
||||
credential_type="password",
|
||||
version=1,
|
||||
status="active",
|
||||
)
|
||||
db.session.add(cred)
|
||||
db.session.flush()
|
||||
assert cred.secret_ref == "ERP_PASSWORD"
|
||||
assert "password" not in cred.secret_ref.lower() or cred.secret_ref != "P@ssw0rd!"
|
||||
@@ -0,0 +1,73 @@
|
||||
"""tests/services/integration_connector/test_security.py
|
||||
|
||||
用途:验证凭据引用解析(fail-closed)与敏感字段脱敏。
|
||||
依赖:IntegrationCredentialReference 模型、current_app.config、errors.py。
|
||||
逻辑:secret_ref 指向缺失配置键→CredentialUnresolvedError;sanitize 脱敏敏感键;
|
||||
credential_summary 只含元数据,绝不含明文。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
|
||||
import pytest
|
||||
|
||||
from app import db
|
||||
from app.core.errors import AppError
|
||||
from app.models import IntegrationCredentialReference
|
||||
from app.services.integration_connector.security import credential_summary, resolve_credential, sanitize
|
||||
|
||||
|
||||
def _add_credential(code="ERP-CRED-01", secret_ref="ERP_TEST_CRED", **overrides):
|
||||
cred = IntegrationCredentialReference(
|
||||
code=code, secret_ref=secret_ref, secret_provider="env",
|
||||
credential_type="password", version=1, status="active", **overrides,
|
||||
)
|
||||
db.session.add(cred)
|
||||
db.session.flush()
|
||||
return cred
|
||||
|
||||
|
||||
def test_resolve_credential_returns_secrets(app):
|
||||
"""secret_ref 指向存在的配置键时返回该字典。"""
|
||||
app.config["ERP_TEST_CRED"] = {"username": "u", "password": "p", "endpoint": "https://erp.invalid"}
|
||||
_add_credential()
|
||||
creds = resolve_credential("ERP-CRED-01")
|
||||
assert creds == {"username": "u", "password": "p", "endpoint": "https://erp.invalid"}
|
||||
|
||||
|
||||
def test_resolve_credential_missing_secret_fail_closed(app):
|
||||
"""secret_ref 指向缺失/空配置键时抛 CredentialUnresolvedError。"""
|
||||
_add_credential(secret_ref="MISSING_KEY")
|
||||
with pytest.raises(AppError) as exc:
|
||||
resolve_credential("ERP-CRED-01")
|
||||
assert exc.value.code == "INTEGRATION.CREDENTIAL_UNRESOLVED"
|
||||
|
||||
|
||||
def test_resolve_credential_unknown_ref_fail_closed(app):
|
||||
"""凭据引用不存在时抛 CredentialUnresolvedError。"""
|
||||
with pytest.raises(AppError) as exc:
|
||||
resolve_credential("NOPE")
|
||||
assert exc.value.code == "INTEGRATION.CREDENTIAL_UNRESOLVED"
|
||||
|
||||
|
||||
def test_sanitize_redacts_sensitive_keys():
|
||||
"""sanitize 递归把 password/token/secret 等键替换为 ***。"""
|
||||
data = {"outer": {"password": "s3cret", "keep": "ok"}, "token": "abc", "list": [{"secret": "x"}]}
|
||||
out = sanitize(data)
|
||||
assert out["outer"]["password"] == "***"
|
||||
assert out["outer"]["keep"] == "ok"
|
||||
assert out["token"] == "***"
|
||||
assert out["list"][0]["secret"] == "***"
|
||||
assert "s3cret" not in json.dumps(out)
|
||||
|
||||
|
||||
def test_credential_summary_has_no_plaintext(app):
|
||||
"""credential_summary 只含元数据,不含解析出的明文。"""
|
||||
app.config["ERP_TEST_CRED"] = {"username": "svc_user_erp", "password": "s3cretLY"}
|
||||
cred = _add_credential()
|
||||
resolve_credential("ERP-CRED-01") # 确保能解析
|
||||
summary = credential_summary(cred)
|
||||
assert "s3cretLY" not in json.dumps(summary)
|
||||
assert "svc_user_erp" not in json.dumps(summary)
|
||||
assert summary["version"] == 1
|
||||
@@ -0,0 +1,104 @@
|
||||
"""tests/services/integration_connector/test_transports.py
|
||||
|
||||
用途:验证 REST/SOAP Transport 的请求构造、业务错误映射与 fail-closed;
|
||||
以及结果分类(classify_transport_response)的六态语义。
|
||||
依赖:transports/base.py、transports/rest.py、transports/soap.py、errors.py。
|
||||
逻辑:Transport.call 返回原始 dict;分类器把 dict 归一为 IntegrationCallResult。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import pytest
|
||||
|
||||
from app.services.integration_connector.errors import TransportNotFrozenError
|
||||
from app.services.integration_connector.transports.base import IntegrationCallResult, classify_transport_response
|
||||
from app.services.integration_connector.transports.rest import RestTransport
|
||||
from app.services.integration_connector.transports.soap import SoapTransport
|
||||
|
||||
|
||||
def _resp(status_code, payload=None, text=""):
|
||||
class _Response:
|
||||
def __init__(self):
|
||||
self.status_code = status_code
|
||||
self.text = text
|
||||
self._payload = payload
|
||||
|
||||
def json(self):
|
||||
return self._payload
|
||||
|
||||
return _Response()
|
||||
|
||||
|
||||
def _client(**overrides):
|
||||
cfg = {"endpoint": "https://erp.invalid", "timeout_seconds": 30}
|
||||
cfg.update(overrides)
|
||||
return {"config_json": cfg, "credential": {}}
|
||||
|
||||
|
||||
def test_rest_builds_url_and_sends_request():
|
||||
"""REST Transport 拼接 endpoint+path,按 method/params 发请求并返回 JSON。"""
|
||||
captured = {}
|
||||
|
||||
def fake_http(method, url, **kw):
|
||||
captured.update(method=method, url=url, params=kw.get("params"), json=kw.get("json"))
|
||||
return _resp(200, {"found": True, "quantity": "100"})
|
||||
|
||||
transport = RestTransport(http_request=fake_http)
|
||||
result = transport.call(
|
||||
client=_client(),
|
||||
interface={"request_spec_json": {"method": "GET", "path": "/stock"}},
|
||||
request={"params": {"invoice_no": "INV-001"}},
|
||||
)
|
||||
assert captured["url"] == "https://erp.invalid/stock"
|
||||
assert captured["method"] == "GET"
|
||||
assert captured["params"] == {"invoice_no": "INV-001"}
|
||||
assert result == {"found": True, "quantity": "100"}
|
||||
|
||||
|
||||
def test_rest_business_error_maps_to_dict():
|
||||
"""4xx 映射为 business_failed dict,供上层透传分类。"""
|
||||
|
||||
def fake_http(method, url, **kw):
|
||||
return _resp(404, text="not found")
|
||||
|
||||
transport = RestTransport(http_request=fake_http)
|
||||
result = transport.call(
|
||||
client=_client(),
|
||||
interface={"request_spec_json": {"method": "GET", "path": "/stock"}},
|
||||
request={},
|
||||
)
|
||||
assert result["status"] == "business_failed"
|
||||
assert result["code"] == "HTTP_404"
|
||||
assert "not found" in result["message"]
|
||||
|
||||
|
||||
def test_rest_fail_closed_without_endpoint():
|
||||
"""endpoint 未冻结时 fail-closed 抛 TransportNotFrozenError。"""
|
||||
transport = RestTransport(http_request=lambda *a, **k: None)
|
||||
with pytest.raises(TransportNotFrozenError):
|
||||
transport.call(
|
||||
client={"config_json": {}},
|
||||
interface={"request_spec_json": {"method": "GET", "path": "/stock"}},
|
||||
request={},
|
||||
)
|
||||
|
||||
|
||||
def test_soap_fail_closed_without_wsdl():
|
||||
"""SOAP 无 wsdl 时 fail-closed 抛 TransportNotFrozenError(SOAP 只需 wsdl,不需 endpoint)。"""
|
||||
transport = SoapTransport()
|
||||
with pytest.raises(TransportNotFrozenError):
|
||||
transport.call(
|
||||
client={"config_json": {}},
|
||||
interface={"request_spec_json": {"soap_action": "queryInventory"}},
|
||||
request={},
|
||||
)
|
||||
|
||||
|
||||
def test_classify_transport_response_states():
|
||||
"""结果分类覆盖 success/duplicate_success/business_failed/technical_failed。"""
|
||||
assert classify_transport_response({"status": "success", "document_no": "DOC-1"}).status == "success"
|
||||
assert classify_transport_response({"status": "business_failed", "code": "E1", "message": "reject"}).status == "business_failed"
|
||||
dup = classify_transport_response({"status": "duplicate_success", "verified_posted": True, "document_no": "DOC-9"})
|
||||
assert dup.status == "duplicate_success"
|
||||
unknown = classify_transport_response({})
|
||||
assert unknown.status == "technical_failed"
|
||||
Reference in new issue
Block a user