conftest.py 2.06 KB
"""测试公共装置。

所有单测都不依赖 MySQL 和外网:上游 HTTP 用 respx 打桩,
上游凭证用 fake_credentials 注入(不查数据库)。
"""

from __future__ import annotations

import os

import pytest

# 必须在导入任何 mcp_hive 模块之前设好,配置是进程级缓存的。
# 数据库故意留空:单测不该碰真实的库。
os.environ.setdefault("DB_HOST", "")
os.environ.setdefault("DB_NAME", "")
os.environ.setdefault("DB_USER", "")
os.environ.setdefault("SESSION_SECRET", "test-session-secret")
os.environ.setdefault("CONSOLE_PASSWORD", "123456")

TEST_BASE_URL = "http://upstream.test/facade"
TEST_APP_KEY = "test-app-key"
TEST_SECRET = "test-secret"
TEST_GW_APP_ID = "test-gw-app"
TEST_GW_SECRET = "test-gw-secret"


@pytest.fixture(autouse=True)
def _no_dotenv(monkeypatch):
    """禁止单测加载本机真实的 .env,避免真实凭证影响测试结果。"""
    monkeypatch.setattr("mcp_hive.core.config.settings._load_env_file", lambda: None)
    from mcp_hive.core.config.settings import get_app_settings

    get_app_settings.cache_clear()
    yield
    get_app_settings.cache_clear()


@pytest.fixture
def app_settings():
    from mcp_hive.core.config.settings import get_app_settings

    return get_app_settings()


@pytest.fixture
def credentials():
    from mcp_hive.core.config.settings import BackendCredentials

    return BackendCredentials(
        base_url=TEST_BASE_URL,
        app_key=TEST_APP_KEY,
        secret=TEST_SECRET,
        gw_app_id=TEST_GW_APP_ID,
        gw_secret=TEST_GW_SECRET,
    )


@pytest.fixture
def fake_credentials(monkeypatch, credentials):
    """把凭证读取换成固定值,这样 SignedApiClient 的单测不需要数据库。

    打桩打在 `core.http.client` 的引用上而不是 credentials 模块里的定义上 ——
    client 是 `from ... import get_credentials` 导入的,替换定义处不生效。
    """

    async def _fake(_service_key: str):
        return credentials

    monkeypatch.setattr("mcp_hive.core.http.client.get_credentials", _fake)
    return credentials