test_registry.py 3.69 KB
"""服务自动发现与装配隔离。

核心诉求:这个系统要接入很多条业务线,所以「加一个服务」必须只等于
「新建目录 + 写 manifest.py」,且任何一个服务出问题都不能影响其他服务和宿主进程。
"""

from __future__ import annotations

import pytest

from mcp_hive.core.mcp.manifest import ServiceInstance, ServiceManifest
from mcp_hive.core.registry import discover_manifests, get_manifest


def test_used_car_is_discovered_without_any_registration_code():
    keys = [m.key for m in discover_manifests()]
    assert "used_car" in keys


def test_get_manifest_by_key():
    manifest = get_manifest("used_car")
    assert manifest is not None
    assert manifest.display_name


def test_unknown_key_returns_none():
    assert get_manifest("does_not_exist") is None


def test_manifests_are_sorted_for_stable_ui_order():
    keys = [m.key for m in discover_manifests()]
    assert keys == sorted(keys)


def test_every_manifest_has_the_required_wiring():
    for manifest in discover_manifests():
        assert manifest.display_name
        assert manifest.description
        assert callable(manifest.register_tools)
        path, body = manifest.probe_target
        assert path.startswith("/")
        assert isinstance(body, dict)


def test_manifest_rejects_invalid_key():
    with pytest.raises(ValueError, match="合法标识符"):
        ServiceManifest(
            key="not a key",
            display_name="x",
            description="x",
            register_tools=lambda mcp: None,
            probe_target=("/x", {}),
        )


# ------------------------------------------------------------------ 装配隔离


def _broken_manifest() -> ServiceManifest:
    def blow_up(_mcp: object) -> None:
        raise RuntimeError("工具注册炸了")

    return ServiceManifest(
        key="broken",
        display_name="坏掉的服务",
        description="用来验证隔离性",
        register_tools=blow_up,
        probe_target=("/x", {}),
    )


def test_broken_service_is_marked_unavailable_not_raised(app_settings):
    """一个服务装配失败,只能让它自己不可用,不能把宿主进程拖垮。"""
    from mcp_hive.core.mcp.host import build_instance

    instance = build_instance(_broken_manifest(), app_settings)
    assert instance.ok is False
    assert "工具注册炸了" in instance.error
    assert instance.mcp is None


def test_healthy_service_assembles_with_its_tools(app_settings):
    """装配不读凭证(凭证在数据库里、随时可改),所以没配库也能装配成功。"""
    from mcp_hive.core.mcp.host import build_instance

    instance = build_instance(get_manifest("used_car"), app_settings)
    assert instance.ok, instance.error


def test_service_summary_never_exposes_upstream_details(app_settings):
    """summary() 会通过宿主**无鉴权**的 /healthz 对外暴露,
    绝不能带密钥,也不能带内网上游地址。"""
    from mcp_hive.core.mcp.host import build_instance

    summary = build_instance(get_manifest("used_car"), app_settings).summary()
    text = repr(summary)
    assert "secret" not in text
    assert "base_url" not in summary
    assert "http" not in text


def test_credentials_repr_masks_the_secret(credentials):
    assert "test-secret" not in repr(credentials)


def test_app_settings_repr_masks_console_password(app_settings):
    assert app_settings.console_password not in repr(app_settings)
    assert app_settings.session_secret not in repr(app_settings)


def test_instance_summary_shape():
    summary = ServiceInstance(manifest=_broken_manifest(), error="boom").summary()
    assert summary["key"] == "broken"
    assert summary["ok"] is False
    assert summary["error"] == "boom"