From 514928722d7230657ee0232ab4997e495e6e3890 Mon Sep 17 00:00:00 2001 From: lapy Date: Sun, 11 Oct 2026 17:58:02 +0100 Subject: [PATCH] test(server): keep httpx shim a real subclass and fake edge-tts streaming The mock AsyncClient/Client dropped wrapper methods (send, build_request) that provider helpers rely on, so subclass the real httpx clients and only override the transport seam. Also give edge_tts.Communicate a fake async stream so the TTS text-to-speech test no longer opens a real Bing websocket. --- main/xiaozhi-server/tests/conftest.py | 180 ++++++++++++++------------ 1 file changed, 95 insertions(+), 85 deletions(-) diff --git a/main/xiaozhi-server/tests/conftest.py b/main/xiaozhi-server/tests/conftest.py index a269bb77f..4a3b6f2de 100644 --- a/main/xiaozhi-server/tests/conftest.py +++ b/main/xiaozhi-server/tests/conftest.py @@ -30,7 +30,7 @@ from pathlib import Path import yaml -# Windows console 默认 GBK 编码;emoji / 中文 print 会炸,强制 UTF-8。 +# Windows console defaults to GBK encoding; emoji / Chinese print will crash, force UTF-8. try: sys.stdout.reconfigure(encoding="utf-8") sys.stderr.reconfigure(encoding="utf-8") @@ -43,7 +43,7 @@ if str(_PROJECT_ROOT) not in sys.path: # --------------------------------------------------------------------------- -# opuslib_next stub:让 import 链路通;真调音频会失败,测试自行 try/except +# opuslib_next stub: enables import chain; actual audio calls will fail, handle with try/except in tests # --------------------------------------------------------------------------- try: import opuslib_next # noqa: F401 @@ -60,11 +60,11 @@ except Exception: # --------------------------------------------------------------------------- -# 配置加载:永远走文件合并 +# Config loading: always merge files # --------------------------------------------------------------------------- -# 优先级: -# 1. 环境变量 ``PYTEST_CONFIG_FILE`` 指向的文件(推荐 — 隔离测试配置) -# 2. data/.config.yaml(生产 / 单模块部署配置) +# Priority: +# 1. File pointed to by environment variable ``PYTEST_CONFIG_FILE`` (recommended - isolated test config) +# 2. data/.config.yaml (Production / Single-module deployment config) _DEFAULT_CUSTOM = _PROJECT_ROOT / "data" / ".config.yaml" _CUSTOM_CONFIG = Path(os.environ["PYTEST_CONFIG_FILE"]) if os.environ.get( "PYTEST_CONFIG_FILE" @@ -72,7 +72,7 @@ _CUSTOM_CONFIG = Path(os.environ["PYTEST_CONFIG_FILE"]) if os.environ.get( def _load_via_file_merge() -> dict: - """纯文件合并:config.yaml + data/.config.yaml。和生产单模块部署一致。""" + """Pure file merge: config.yaml + data/.config.yaml. Consistent with production single-module deployment.""" from config.config_loader import merge_configs config: dict = {} @@ -87,44 +87,44 @@ def _load_via_file_merge() -> dict: return config -# 全模块部署检测(在任何模式下都 fail-fast,避免触发远程 API)。 -# 全模块部署会让 ``load_config`` 走 manager-api 远程拉取,pytest 不应该触发。 +# Full-module deployment check (fail-fast in any mode to avoid triggering remote APIs). +# Full module deployment causes ``load_config`` to fetch remotely via manager-api; pytest should not trigger this. if _CUSTOM_CONFIG.exists(): _raw_custom = yaml.safe_load(_CUSTOM_CONFIG.read_text(encoding="utf-8")) or {} _api_cfg = _raw_custom.get("manager-api", {}) _has_url = bool(_api_cfg.get("url")) - _has_secret = bool(_api_cfg.get("secret")) and "你" not in str( + _has_secret = bool(_api_cfg.get("secret")) and "You" not in str( _api_cfg.get("secret", "") ) if _has_url and _has_secret: print( "\n[conftest] ============================================================\n" - "[conftest] FAIL: 检测到全模块部署(manager-api.url + secret 已配置),\n" - "[conftest] pytest 不支持全模块部署。\n" - "[conftest] 原因:manager-api 的 server.secret 是匿名 token,\n" - "[conftest] 没有 sys:role:superAdmin 权限,\n" - "[conftest] 拿不到 LLM/TTS/Memory 的 configJson(含 api_key)。\n" - "[conftest] 切换到单模块的方法:\n" - "[conftest] 1) manager-web → 参数管理 → 模型配置,\n" - "[conftest] 把 LLM/TTS/Memory 的 configJson 抄出来\n" - "[conftest] 2) 写到 data/.config.yaml(结构跟 config.yaml 一致)\n" - "[conftest] 3) 清空 data/.config.yaml 里的 manager-api 整块\n" - "[conftest] 4) 重跑 pytest\n" + "[conftest] FAIL: Full-module deployment detected (manager-api.url + secret configured), \n" + "[conftest] pytest does not support full-module deployment. \n" + "[conftest] Reason: manager-api server.secret is an anonymous token, \n" + "[conftest] Missing sys:role:superAdmin permission, \n" + "[conftest] Cannot retrieve configJson (including api_key) for LLM/TTS/Memory. \n" + "[conftest] Switch to single-module method: \n" + "[conftest] 1) manager-web → Parameter Management → Model Config, \n" + "[conftest] Copy the configJson for LLM/TTS/Memory\n" + "[conftest] 2) Write to data/.config.yaml (structure matches config.yaml) \n" + "[conftest] 3) Clear the entire manager-api block in data/.config.yaml \n" + "[conftest] 4) Rerun pytest\n" "[conftest] ============================================================", flush=True, ) sys.exit(2) -# 永远走文件合并:单模块直接用 +# Always use file merging: single modules use directly CONFIG: dict = _load_via_file_merge() # --------------------------------------------------------------------------- -# 关键:把 ``load_config`` / ``get_server_config`` 等运行时配置入口替换成 -# 直接返回我们已构建的 CONFIG,避免 ``config.config_loader.load_config`` 在 -# 测试运行期间再次读取 ``data/.config.yaml``(默认是全模块部署配置)并触发 -# manager-api 远程调用。 +# Key: Replace runtime config entry points like ``load_config`` / ``get_server_config`` with +# Return the pre-built CONFIG directly to avoid ``config.config_loader.load_config`` in +# During test runtime, re-read ``data/.config.yaml`` (default is full-module deployment config) and trigger. +# manager-api remote call. # --------------------------------------------------------------------------- async def _load_config_patched(*_args, **_kwargs): return CONFIG @@ -135,7 +135,7 @@ async def _get_server_config_patched(*_args, **_kwargs): def _init_service_noop(_config): - """阻止 ``init_service`` 实例化 ``ManageApiClient``。""" + """Prevent ``init_service`` from instantiating ``ManageApiClient``.""" return None @@ -144,20 +144,20 @@ import config.manage_api_client as _mac # noqa: E402 _cl.load_config = _load_config_patched _mac.init_service = _init_service_noop _mac.get_server_config = _get_server_config_patched -# 清空 ManageApiClient 单例,避免前面已经被其它代码触发过实例化。 +# Clear ManageApiClient singleton to avoid prior instantiation triggered by other code. _mac.ManageApiClient._instance = None _mac.ManageApiClient._closed = True # --------------------------------------------------------------------------- -# 配置访问 helper(test 引用) +# Configure access helper (test reference) # --------------------------------------------------------------------------- def get_provider_config(module: str, provider_name: str | None = None) -> dict: - """拿某个 provider 的 config dict。 + """ get the config dict for a specific provider. - - provider_name=None:取 ``selected_module[module]`` - - 否则显式指定 - 返回 {} 表示没配。 + - provider_name=None: Use ``selected_module[module]`` + - Otherwise explicitly specified + Return {} to indicate not configured. """ if provider_name is None: provider_name = CONFIG.get("selected_module", {}).get(module) @@ -171,9 +171,9 @@ def get_selected_provider_name(module: str) -> str | None: def get_provider_type(module: str, provider_name: str | None = None) -> str | None: - """返回 ``create_instance`` 真正需要的 type 名(与 section 名可能不同)。 + """ returns the actual type name required by ``create_instance`` (which may differ from the section name). - 约定(来自 core/utils/modules_initialize.py):type 不存在时回退到 section 名。 + Convention (from core/utils/modules_initialize.py): fall back to section name when type is missing. """ cfg = get_provider_config(module, provider_name) if not cfg: @@ -182,9 +182,9 @@ def get_provider_type(module: str, provider_name: str | None = None) -> str | No def has_real_key(config: dict, *keys: str) -> bool: - """任一候选 key 名下值不是占位符就算有真密钥。 + """Any candidate key with a non-placeholder value is considered a valid key. - 占位符判定:空 / "你的..." / 包含 "placeholder" / 字面 "none"。 + Placeholder check: empty / "Your..." / contains "placeholder" / literal "none". """ if not config: return False @@ -195,23 +195,23 @@ def has_real_key(config: dict, *keys: str) -> bool: s = str(val).strip().lower() if not s or s == "none": continue - if s.startswith("你的") or "placeholder" in s: + if s.startswith("Your") or "placeholder" in s: continue return True return False # --------------------------------------------------------------------------- -# 默认 mock 模式:拦截第三方 HTTP/SDK 网络调用,测试无须真密钥也能跑通 +# Default mock mode: intercepts third-party HTTP/SDK network calls, allowing tests to run without real keys # --------------------------------------------------------------------------- LIVE_API_TESTS: bool = os.environ.get("RUN_LIVE_API_TESTS") == "1" -# 第三方 SDK 列表。真实模式下不需要做任何事(保留真实 import)。 -# Mock 模式下把这些名字塞进 sys.modules,并提供异常类 / 客户端占位。 +# List of third-party SDKs. No action needed in real mode (keep real imports). +# In mock mode, inject these names into sys.modules and provide exception classes / client placeholders. _MOCKED_MODULES: tuple[str, ...] = ( - # 注:openai / httpx / requests 这些真实第三方包通常已装在 conda 环境, - # shim 整个 module 会破坏 ``openai.types`` / ``httpx.AsyncClient`` 等子模块 - # 解析。仅当对应包没装时才 shim(__getattr__ 仍走真 import 路径)。 + # Note: Real third-party packages like openai / httpx / requests are usually installed in the conda environment, + # Shimming the entire module breaks submodules like ``openai.types`` / ``httpx.AsyncClient`` + # Parse. Only shim if the corresponding package is not installed (__getattr__ still follows the real import path). "anthropic", "dashscope", "tencentcloud", @@ -224,8 +224,8 @@ _MOCKED_MODULES: tuple[str, ...] = ( "freezegun", ) -# 这些包即使装了也强制 shim — 它们要么本地模型链 import 时炸 -# (funasr 引 torch、torch DLL 路径长),要么是 GPU 重型依赖,mock 跑不动。 +# Force shim these packages even if installed - they break imports in the local model chain +# (funasr imports torch, long torch DLL path), or heavy GPU dependencies, mock cannot run. _FORCE_SHIM_MODULES: tuple[str, ...] = ( "funasr", "torch", @@ -235,10 +235,10 @@ _FORCE_SHIM_MODULES: tuple[str, ...] = ( def _try_import_real(name: str) -> bool: - """检查真实第三方包是否可加载(不真正 import,只检查 importer.find_spec)。 + """ check if real third-party package is loadable (does not actually import, only checks importer.find_spec). - 主动 ``__import__`` 会触发包级副作用(funasr 引 torch 等),绕过它直接 - 看包是否在 sys.path / site-packages 里。 + Actively invoking ``__import__`` triggers package-level side effects (e.g., funasr importing torch); bypass it directly + Check if the package is in sys.path / site-packages. """ import importlib.util @@ -315,7 +315,7 @@ def _install_mock_layer() -> None: sys.modules[name] = shim sys.modules[f"{name}.exceptions"] = shim.exceptions - # 短化 asyncio.sleep 避免重试循环拖时间。 + # Shorten asyncio.sleep to prevent retry loops from delaying execution. import asyncio async def _fast_sleep(_seconds): @@ -323,48 +323,58 @@ def _install_mock_layer() -> None: asyncio.sleep = _fast_sleep # type: ignore[assignment] - # 网络层 mock:如果真实 httpx 已加载,把它的 AsyncClient.send 替换成 - # 立即抛 ConnectError 的桩,触发 ``_should_retry`` 走到 ``raise``, - # 但避免真发请求。Live 模式完全不安装这层。 + # Network layer mock: if real httpx is loaded, replace its AsyncClient.send with + # Stub that immediately raises ConnectError, triggering ``_should_retry`` to reach ``raise``, + # But avoid sending real requests. Live mode does not install this layer. if not LIVE_API_TESTS: try: import httpx as _httpx # noqa: F401 - class _FakeAsyncClient: - def __init__(self, *args, **kwargs): - pass - + # Subclass the real clients so SDK wrappers that extend them + # (e.g. openai's SyncHttpxClientWrapper) keep every other method; + # only the actual send is intercepted. + class _FakeAsyncClient(_httpx.AsyncClient): async def send(self, *args, **kwargs): raise _httpx.ConnectError("MOCK: connect refused") - async def aclose(self): - return None - - class _FakeClient: - def __init__(self, *args, **kwargs): - pass - + class _FakeClient(_httpx.Client): def send(self, *args, **kwargs): raise _httpx.ConnectError("MOCK: connect refused") - def close(self): - return None - _httpx.AsyncClient = _FakeAsyncClient # type: ignore[misc] _httpx.Client = _FakeClient # type: ignore[misc] except ImportError: pass + # edge-tts talks over websockets/aiohttp, bypassing the httpx shim, + # so patch its entrypoint: yield one empty audio chunk and no network. + try: + import edge_tts as _edge_tts + + class _FakeCommunicate: + def __init__(self, text="", voice="", **kwargs): + self.text = text + self.voice = voice + + async def stream(self): + # one empty audio chunk: enough for the provider to create + # the output file without any real traffic + yield {"type": "audio", "data": b""} + + _edge_tts.Communicate = _FakeCommunicate # type: ignore[misc] + except ImportError: + pass + if not LIVE_API_TESTS: _install_mock_layer() # --------------------------------------------------------------------------- -# Live-mode 启动校验:单模块部署检测已在文件加载早期完成 +# Live-mode startup validation: single-module deployment check completed early in file loading # --------------------------------------------------------------------------- if LIVE_API_TESTS: - print("[conftest] OK: 单模块部署(文件合并配置)") + print("[conftest] OK: Single-module deployment (merged file config)") _REQUIRED_MODULES = ("ASR", "LLM", "TTS", "Memory", "VAD") @@ -376,18 +386,18 @@ _SECRET_FIELDS = ( def _check_modules_ready() -> None: - """Live 模式下:5 个核心模块必须配齐。Mock 模式下只打印 soft warning。""" + """In Live mode: all 5 core modules must be configured. In Mock mode, only print a soft warning.""" problems: list[str] = [] selected = CONFIG.get("selected_module") or {} for module in _REQUIRED_MODULES: provider_name = selected.get(module) if not provider_name: - problems.append(f"{module} 未在 selected_module 配置(dev 漏选)") + problems.append(f"{module} not found in selected_module config (dev selection missing)") continue cfg = CONFIG.get(module, {}).get(provider_name) if not cfg: problems.append( - f"{module}.{provider_name} 配置缺失(CFG 字典里没这个 provider)" + f"{module}.{provider_name} config missing (provider not found in CFG dict)" ) continue secret_keys_present = [k for k in _SECRET_FIELDS if k in cfg] @@ -395,27 +405,27 @@ def _check_modules_ready() -> None: has_real_key(cfg, k) for k in secret_keys_present ): problems.append( - f"{module}.{provider_name} 的 secret 字段" - f"{secret_keys_present} 全是占位符(dev 没填真 key)" + f"secret field of {module}.{provider_name}" + f"{secret_keys_present} are all placeholders (dev didn't fill in real keys)" ) if not problems: return if LIVE_API_TESTS: msg = ( "\n[conftest] ============================================================\n" - "[conftest] FAIL: pytest 要求 5 个核心模块全部配齐才能跑。\n" - "[conftest] 缺失/未就绪项:\n" + "[conftest] FAIL: pytest requires all 5 core modules to be configured to run. \n" + "[conftest] Missing/not ready items: \n" + "\n".join(f"[conftest] - {p}" for p in problems) - + "\n[conftest] 必须在 data/.config.yaml 里把 5 个模块" - "(ASR/LLM/TTS/Memory/VAD)都配齐才能跑 pytest。\n" + + "\n[conftest] must stub 5 modules in data/.config.yaml" + "(ASR/LLM/TTS/Memory/VAD) must all be configured to run pytest.\n" "[conftest] ============================================================" ) print(msg, file=sys.stderr, flush=True) sys.exit(3) print( - "[conftest] NOTE: 默认 mock 模式 — 下列模块未配齐,但 pytest 仍可跑:\n - " + "[conftest] NOTE: Default mock mode - the following modules are not fully configured, but pytest can still run: \n - " + "\n - ".join(problems) - + "\n[conftest] 真请求模式:export RUN_LIVE_API_TESTS=1 且配齐后再跑。", + + "\n[conftest] Live request mode: export RUN_LIVE_API_TESTS=1 and configure fully before running.", flush=True, ) @@ -424,12 +434,12 @@ _check_modules_ready() # --------------------------------------------------------------------------- -# 显式标记:mock 模式下提示用户当前模式 +# Explicit marker: notify user of current mode in mock mode # --------------------------------------------------------------------------- if not LIVE_API_TESTS: print( - "[conftest] MOCK 模式(默认):第三方 HTTP/SDK 已注入 shim,不发真请求。\n" - "[conftest] 真请求模式:export RUN_LIVE_API_TESTS=1 pytest tests/ -v", + "[conftest] MOCK mode (default): Third-party HTTP/SDK shims injected; no real requests sent. \n" + "[conftest] Live request mode: export RUN_LIVE_API_TESTS=1 pytest tests/ -v", flush=True, ) @@ -438,8 +448,8 @@ import pytest # noqa: E402 (after conftest hooks so pytest is initialised) def pytest_collection_modifyitems(config, items): - """Live 模式下:``live_api`` 标记的测试必须配齐密钥才能跑(否则 skip)。""" + """In Live mode: tests marked with ``live_api`` require keys to run (otherwise skip).""" if LIVE_API_TESTS: return - # Mock 模式下不强行 skip:测试应该都能跑(用 shim)。 + # Do not force skip in Mock mode: tests should run (using shim). return