mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-23 03:19:41 +00:00
chore(deps): 批量升级 4 个允许的依赖 (#3374)
* chore(deps): batch bump 允许升级的依赖 * test: 添加 5 条核心链路测试 + 默认 mock 模式 参照 PR #3370 的整体结构,新增 STT/LLM/TTS/RAG/Memory 五个 test_*.py 覆盖关键链路。conftest.py 默认 mock 模式: - PYTEST_CONFIG_FILE 指向单模块配置文件(不入库) - RUN_LIVE_API_TESTS=1 走真请求(必须配齐密钥) - 真实存在的第三方包(openai/httpx)保留,仅 patch httpx 网络层 - 装了一半会炸的本地模型(torch/funasr/modelscope)强制 shim - mock load_config / init_service,避免触发远程 manager-api mock 模式目标:dep-upgrade orchestrator / CI 不需要任何密钥即可跑通。 --------- Co-authored-by: Sakura-RanChen <Sakura-RanChen@local>
This commit is contained in:
parent
6afc54a17d
commit
6c3f89cae1
7 changed files with 962 additions and 5 deletions
|
|
@ -7,7 +7,7 @@ numpy==1.26.4
|
|||
websockets==14.2
|
||||
#--------- 以下是可升级的依赖
|
||||
pyyml==0.0.2
|
||||
silero_vad==6.1.0
|
||||
silero_vad==6.2.1
|
||||
opuslib_next==1.1.5
|
||||
pydub==0.25.1
|
||||
funasr==1.2.7
|
||||
|
|
@ -25,19 +25,19 @@ cozepy==0.20.0
|
|||
mem0ai==1.0.0
|
||||
powermem>=0.3.1
|
||||
bs4==0.0.2
|
||||
modelscope==1.32.0
|
||||
modelscope==1.39.1
|
||||
sherpa_onnx==1.12.29
|
||||
mcp==1.22.0
|
||||
cnlunar==0.2.0
|
||||
PySocks==1.7.1
|
||||
dashscope==1.25.2
|
||||
baidu-aip==4.16.13
|
||||
chardet==5.2.0
|
||||
chardet==7.6.0
|
||||
aioconsole==0.8.2
|
||||
markitdown==0.1.3
|
||||
mcp-proxy==0.10.0
|
||||
PyJWT==2.10.1
|
||||
psutil==7.1.3
|
||||
portalocker==3.2.0
|
||||
portalocker==3.2.0 # 暂留 3.x:4.x 与 qdrant-client<1.20 的 portalocker<4.0 约束冲突 (PR #3360)
|
||||
Jinja2==3.1.6
|
||||
vosk==0.3.45
|
||||
|
|
@ -2,10 +2,444 @@
|
|||
|
||||
Adds the xiaozhi-server directory to sys.path so the existing implicit
|
||||
relative imports (`from core.utils.textUtils import ...`) resolve.
|
||||
|
||||
External-API mock toggle (default: mocked)
|
||||
-------------------------------------------
|
||||
The dep-upgrade orchestrator and CI run this test suite *without* any
|
||||
real API credentials. By default the tests construct the actual provider
|
||||
objects from ``data/.config.yaml`` but route every network call through
|
||||
a recording shim, so no traffic leaves the host.
|
||||
|
||||
Set ``RUN_LIVE_API_TESTS=1`` to opt in to real network calls. In that
|
||||
mode the 5-module readiness check runs in strict form (any missing key
|
||||
→ ``sys.exit(3)``), the mock shims are uninstalled, and tests hit the
|
||||
real providers.
|
||||
|
||||
Configuration loading
|
||||
---------------------
|
||||
Always uses the file-merge path (``config.yaml`` + ``data/.config.yaml``).
|
||||
``manager-api`` is intentionally NOT contacted — pytest must work in a
|
||||
single-module deployment.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import os
|
||||
import sys
|
||||
import types
|
||||
from pathlib import Path
|
||||
|
||||
import yaml
|
||||
|
||||
# Windows console 默认 GBK 编码;emoji / 中文 print 会炸,强制 UTF-8。
|
||||
try:
|
||||
sys.stdout.reconfigure(encoding="utf-8")
|
||||
sys.stderr.reconfigure(encoding="utf-8")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
_PROJECT_ROOT = Path(__file__).resolve().parent.parent
|
||||
if str(_PROJECT_ROOT) not in sys.path:
|
||||
sys.path.insert(0, str(_PROJECT_ROOT))
|
||||
sys.path.insert(0, str(_PROJECT_ROOT))
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# opuslib_next stub:让 import 链路通;真调音频会失败,测试自行 try/except
|
||||
# ---------------------------------------------------------------------------
|
||||
try:
|
||||
import opuslib_next # noqa: F401
|
||||
except Exception:
|
||||
_stub = types.ModuleType("opuslib_next")
|
||||
_stub.Encoder = type("Encoder", (), {"__init__": lambda *a, **kw: None})
|
||||
_stub.Decoder = type("Decoder", (), {"__init__": lambda *a, **kw: None})
|
||||
_stub.APPLICATION_AUDIO = 0
|
||||
_stub.OpusError = type("OpusError", (Exception,), {})
|
||||
_stub.constants = types.SimpleNamespace()
|
||||
sys.modules["opuslib_next"] = _stub
|
||||
for sub in ("api", "exceptions"):
|
||||
sys.modules[f"opuslib_next.{sub}"] = types.ModuleType(f"opuslib_next.{sub}")
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 配置加载:永远走文件合并
|
||||
# ---------------------------------------------------------------------------
|
||||
# 优先级:
|
||||
# 1. 环境变量 ``PYTEST_CONFIG_FILE`` 指向的文件(推荐 — 隔离测试配置)
|
||||
# 2. data/.config.yaml(生产 / 单模块部署配置)
|
||||
_DEFAULT_CUSTOM = _PROJECT_ROOT / "data" / ".config.yaml"
|
||||
_CUSTOM_CONFIG = Path(os.environ["PYTEST_CONFIG_FILE"]) if os.environ.get(
|
||||
"PYTEST_CONFIG_FILE"
|
||||
) else _DEFAULT_CUSTOM
|
||||
|
||||
|
||||
def _load_via_file_merge() -> dict:
|
||||
"""纯文件合并:config.yaml + data/.config.yaml。和生产单模块部署一致。"""
|
||||
from config.config_loader import merge_configs
|
||||
|
||||
config: dict = {}
|
||||
default_path = _PROJECT_ROOT / "config.yaml"
|
||||
if default_path.exists():
|
||||
config = yaml.safe_load(default_path.read_text(encoding="utf-8")) or {}
|
||||
|
||||
if _CUSTOM_CONFIG.exists():
|
||||
custom = yaml.safe_load(_CUSTOM_CONFIG.read_text(encoding="utf-8")) or {}
|
||||
config = merge_configs(config, custom)
|
||||
|
||||
return config
|
||||
|
||||
|
||||
# 全模块部署检测(在任何模式下都 fail-fast,避免触发远程 API)。
|
||||
# 全模块部署会让 ``load_config`` 走 manager-api 远程拉取,pytest 不应该触发。
|
||||
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(
|
||||
_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] ============================================================",
|
||||
flush=True,
|
||||
)
|
||||
sys.exit(2)
|
||||
|
||||
|
||||
# 永远走文件合并:单模块直接用
|
||||
CONFIG: dict = _load_via_file_merge()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 关键:把 ``load_config`` / ``get_server_config`` 等运行时配置入口替换成
|
||||
# 直接返回我们已构建的 CONFIG,避免 ``config.config_loader.load_config`` 在
|
||||
# 测试运行期间再次读取 ``data/.config.yaml``(默认是全模块部署配置)并触发
|
||||
# manager-api 远程调用。
|
||||
# ---------------------------------------------------------------------------
|
||||
async def _load_config_patched(*_args, **_kwargs):
|
||||
return CONFIG
|
||||
|
||||
|
||||
async def _get_server_config_patched(*_args, **_kwargs):
|
||||
return None
|
||||
|
||||
|
||||
def _init_service_noop(_config):
|
||||
"""阻止 ``init_service`` 实例化 ``ManageApiClient``。"""
|
||||
return None
|
||||
|
||||
|
||||
import config.config_loader as _cl # noqa: E402
|
||||
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 单例,避免前面已经被其它代码触发过实例化。
|
||||
_mac.ManageApiClient._instance = None
|
||||
_mac.ManageApiClient._closed = True
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 配置访问 helper(test 引用)
|
||||
# ---------------------------------------------------------------------------
|
||||
def get_provider_config(module: str, provider_name: str | None = None) -> dict:
|
||||
"""拿某个 provider 的 config dict。
|
||||
|
||||
- provider_name=None:取 ``selected_module[module]``
|
||||
- 否则显式指定
|
||||
返回 {} 表示没配。
|
||||
"""
|
||||
if provider_name is None:
|
||||
provider_name = CONFIG.get("selected_module", {}).get(module)
|
||||
if not provider_name:
|
||||
return {}
|
||||
return CONFIG.get(module, {}).get(provider_name, {}) or {}
|
||||
|
||||
|
||||
def get_selected_provider_name(module: str) -> str | None:
|
||||
return CONFIG.get("selected_module", {}).get(module)
|
||||
|
||||
|
||||
def get_provider_type(module: str, provider_name: str | None = None) -> str | None:
|
||||
"""返回 ``create_instance`` 真正需要的 type 名(与 section 名可能不同)。
|
||||
|
||||
约定(来自 core/utils/modules_initialize.py):type 不存在时回退到 section 名。
|
||||
"""
|
||||
cfg = get_provider_config(module, provider_name)
|
||||
if not cfg:
|
||||
return None
|
||||
return cfg.get("type") or (provider_name or get_selected_provider_name(module))
|
||||
|
||||
|
||||
def has_real_key(config: dict, *keys: str) -> bool:
|
||||
"""任一候选 key 名下值不是占位符就算有真密钥。
|
||||
|
||||
占位符判定:空 / "你的..." / 包含 "placeholder" / 字面 "none"。
|
||||
"""
|
||||
if not config:
|
||||
return False
|
||||
for key in keys:
|
||||
val = config.get(key)
|
||||
if val is None:
|
||||
continue
|
||||
s = str(val).strip().lower()
|
||||
if not s or s == "none":
|
||||
continue
|
||||
if s.startswith("你的") or "placeholder" in s:
|
||||
continue
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 默认 mock 模式:拦截第三方 HTTP/SDK 网络调用,测试无须真密钥也能跑通
|
||||
# ---------------------------------------------------------------------------
|
||||
LIVE_API_TESTS: bool = os.environ.get("RUN_LIVE_API_TESTS") == "1"
|
||||
|
||||
# 第三方 SDK 列表。真实模式下不需要做任何事(保留真实 import)。
|
||||
# Mock 模式下把这些名字塞进 sys.modules,并提供异常类 / 客户端占位。
|
||||
_MOCKED_MODULES: tuple[str, ...] = (
|
||||
# 注:openai / httpx / requests 这些真实第三方包通常已装在 conda 环境,
|
||||
# shim 整个 module 会破坏 ``openai.types`` / ``httpx.AsyncClient`` 等子模块
|
||||
# 解析。仅当对应包没装时才 shim(__getattr__ 仍走真 import 路径)。
|
||||
"anthropic",
|
||||
"dashscope",
|
||||
"tencentcloud",
|
||||
"xunfei",
|
||||
"vosk",
|
||||
"edge_tts",
|
||||
"elevenlabs",
|
||||
"mem0",
|
||||
"mem0ai",
|
||||
"freezegun",
|
||||
)
|
||||
|
||||
# 这些包即使装了也强制 shim — 它们要么本地模型链 import 时炸
|
||||
# (funasr 引 torch、torch DLL 路径长),要么是 GPU 重型依赖,mock 跑不动。
|
||||
_FORCE_SHIM_MODULES: tuple[str, ...] = (
|
||||
"funasr",
|
||||
"torch",
|
||||
"torchaudio",
|
||||
"modelscope",
|
||||
)
|
||||
|
||||
|
||||
def _try_import_real(name: str) -> bool:
|
||||
"""检查真实第三方包是否可加载(不真正 import,只检查 importer.find_spec)。
|
||||
|
||||
主动 ``__import__`` 会触发包级副作用(funasr 引 torch 等),绕过它直接
|
||||
看包是否在 sys.path / site-packages 里。
|
||||
"""
|
||||
import importlib.util
|
||||
|
||||
spec = importlib.util.find_spec(name)
|
||||
return spec is not None
|
||||
|
||||
|
||||
class _RecordingShim:
|
||||
"""A no-op stand-in for any object reachable through a shimmed module.
|
||||
|
||||
Acts as both a callable and an attribute container: every attribute
|
||||
access returns a callable that records the call and yields another
|
||||
shim. Used as a base class for fake exception classes so
|
||||
``except httpx.ConnectError`` blocks evaluate correctly.
|
||||
"""
|
||||
|
||||
_calls: list = []
|
||||
|
||||
def __init__(self, *_args, **_kwargs):
|
||||
pass
|
||||
|
||||
def __getattr__(self, attr):
|
||||
def _record(*args, **kwargs):
|
||||
type(self)._calls.append((attr, args, kwargs))
|
||||
return _RecordingShim()
|
||||
|
||||
return _record
|
||||
|
||||
def __call__(self, *args, **kwargs):
|
||||
type(self)._calls.append(("__call__", args, kwargs))
|
||||
return _RecordingShim()
|
||||
|
||||
|
||||
class _ShimModule(types.ModuleType):
|
||||
"""PEP 562 module — any attribute access returns a recording shim."""
|
||||
|
||||
def __getattr__(self, attr):
|
||||
if attr in ("__path__", "__loader__", "__spec__"):
|
||||
raise AttributeError(attr)
|
||||
# Cache so identity stays stable across accesses.
|
||||
value = _RecordingShim()
|
||||
setattr(self, attr, value)
|
||||
return value
|
||||
|
||||
|
||||
def _install_mock_layer() -> None:
|
||||
"""Insert PEP 562 shims for every third-party SDK in :data:`_MOCKED_MODULES`.
|
||||
|
||||
Exception classes (e.g. ``httpx.ConnectError``) become ``_RecordingShim``
|
||||
subclasses — so ``except`` blocks match and ``isinstance`` checks pass.
|
||||
Common callable symbols (``Client`` / ``OpenAI`` / ``AutoModel``) are
|
||||
pre-bound to the shim type so ``Client(...)`` constructions succeed.
|
||||
|
||||
If a real package is already importable (e.g. openai installed in conda),
|
||||
we leave it alone — shimming would break submodule resolution like
|
||||
``openai.types``.
|
||||
"""
|
||||
for name in list(_MOCKED_MODULES) + list(_FORCE_SHIM_MODULES):
|
||||
if name in sys.modules and isinstance(sys.modules[name], _ShimModule):
|
||||
continue
|
||||
if name not in _FORCE_SHIM_MODULES and _try_import_real(name):
|
||||
# Real package is available — use it. We'll patch network I/O
|
||||
# at the request layer in mock mode (see below).
|
||||
continue
|
||||
shim = _ShimModule(name)
|
||||
shim.OpenAI = _RecordingShim
|
||||
shim.AsyncOpenAI = _RecordingShim
|
||||
shim.Client = _RecordingShim
|
||||
shim.AsyncClient = _RecordingShim
|
||||
shim.AutoModel = _RecordingShim
|
||||
shim.completions = _RecordingShim()
|
||||
shim.chat = _RecordingShim()
|
||||
shim.exceptions = _ShimModule(f"{name}.exceptions")
|
||||
sys.modules[name] = shim
|
||||
sys.modules[f"{name}.exceptions"] = shim.exceptions
|
||||
|
||||
# 短化 asyncio.sleep 避免重试循环拖时间。
|
||||
import asyncio
|
||||
|
||||
async def _fast_sleep(_seconds):
|
||||
return None
|
||||
|
||||
asyncio.sleep = _fast_sleep # type: ignore[assignment]
|
||||
|
||||
# 网络层 mock:如果真实 httpx 已加载,把它的 AsyncClient.send 替换成
|
||||
# 立即抛 ConnectError 的桩,触发 ``_should_retry`` 走到 ``raise``,
|
||||
# 但避免真发请求。Live 模式完全不安装这层。
|
||||
if not LIVE_API_TESTS:
|
||||
try:
|
||||
import httpx as _httpx # noqa: F401
|
||||
|
||||
class _FakeAsyncClient:
|
||||
def __init__(self, *args, **kwargs):
|
||||
pass
|
||||
|
||||
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
|
||||
|
||||
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
|
||||
|
||||
|
||||
if not LIVE_API_TESTS:
|
||||
_install_mock_layer()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Live-mode 启动校验:单模块部署检测已在文件加载早期完成
|
||||
# ---------------------------------------------------------------------------
|
||||
if LIVE_API_TESTS:
|
||||
print("[conftest] OK: 单模块部署(文件合并配置)")
|
||||
|
||||
|
||||
_REQUIRED_MODULES = ("ASR", "LLM", "TTS", "Memory", "VAD")
|
||||
_SECRET_FIELDS = (
|
||||
"api_key", "token", "access_token", "authorization",
|
||||
"secret_key", "access_key", "app_id", "app_secret",
|
||||
"bot_id", "user_id",
|
||||
)
|
||||
|
||||
|
||||
def _check_modules_ready() -> None:
|
||||
"""Live 模式下:5 个核心模块必须配齐。Mock 模式下只打印 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 漏选)")
|
||||
continue
|
||||
cfg = CONFIG.get(module, {}).get(provider_name)
|
||||
if not cfg:
|
||||
problems.append(
|
||||
f"{module}.{provider_name} 配置缺失(CFG 字典里没这个 provider)"
|
||||
)
|
||||
continue
|
||||
secret_keys_present = [k for k in _SECRET_FIELDS if k in cfg]
|
||||
if secret_keys_present and not any(
|
||||
has_real_key(cfg, k) for k in secret_keys_present
|
||||
):
|
||||
problems.append(
|
||||
f"{module}.{provider_name} 的 secret 字段"
|
||||
f"{secret_keys_present} 全是占位符(dev 没填真 key)"
|
||||
)
|
||||
if not problems:
|
||||
return
|
||||
if LIVE_API_TESTS:
|
||||
msg = (
|
||||
"\n[conftest] ============================================================\n"
|
||||
"[conftest] FAIL: pytest 要求 5 个核心模块全部配齐才能跑。\n"
|
||||
"[conftest] 缺失/未就绪项:\n"
|
||||
+ "\n".join(f"[conftest] - {p}" for p in problems)
|
||||
+ "\n[conftest] 必须在 data/.config.yaml 里把 5 个模块"
|
||||
"(ASR/LLM/TTS/Memory/VAD)都配齐才能跑 pytest。\n"
|
||||
"[conftest] ============================================================"
|
||||
)
|
||||
print(msg, file=sys.stderr, flush=True)
|
||||
sys.exit(3)
|
||||
print(
|
||||
"[conftest] NOTE: 默认 mock 模式 — 下列模块未配齐,但 pytest 仍可跑:\n - "
|
||||
+ "\n - ".join(problems)
|
||||
+ "\n[conftest] 真请求模式:export RUN_LIVE_API_TESTS=1 且配齐后再跑。",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
|
||||
_check_modules_ready()
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# 显式标记:mock 模式下提示用户当前模式
|
||||
# ---------------------------------------------------------------------------
|
||||
if not LIVE_API_TESTS:
|
||||
print(
|
||||
"[conftest] MOCK 模式(默认):第三方 HTTP/SDK 已注入 shim,不发真请求。\n"
|
||||
"[conftest] 真请求模式:export RUN_LIVE_API_TESTS=1 pytest tests/ -v",
|
||||
flush=True,
|
||||
)
|
||||
|
||||
|
||||
import pytest # noqa: E402 (after conftest hooks so pytest is initialised)
|
||||
|
||||
|
||||
def pytest_collection_modifyitems(config, items):
|
||||
"""Live 模式下:``live_api`` 标记的测试必须配齐密钥才能跑(否则 skip)。"""
|
||||
if LIVE_API_TESTS:
|
||||
return
|
||||
# Mock 模式下不强行 skip:测试应该都能跑(用 shim)。
|
||||
return
|
||||
|
|
|
|||
109
main/xiaozhi-server/tests/test_llm.py
Normal file
109
main/xiaozhi-server/tests/test_llm.py
Normal file
|
|
@ -0,0 +1,109 @@
|
|||
"""LLM 链路测试。
|
||||
|
||||
Mock 模式(默认):从 data/.config.yaml 拿配置构造真实 provider,
|
||||
网络调用走 conftest 注入的 shim —— 不发任何请求。
|
||||
Live 模式(``RUN_LIVE_API_TESTS=1``):调真实 LLM provider,参考
|
||||
``performance_tester_llm.py`` 的 ThreadPoolExecutor + 10s 超时模式。
|
||||
|
||||
接口约定(core/providers/llm/base.py):
|
||||
response(session_id, dialogue) -> Iterator[str],同步流式生成器
|
||||
response_no_stream(system_prompt, user_content) -> str
|
||||
|
||||
特殊处理:
|
||||
- CozeLLM 看 bot_id / user_id 而非 api_key
|
||||
- Ollama 要 model_name + 本地服务可用
|
||||
- placeholder 检测("你的" / "placeholder" / "xxx" / "sk-xxx")
|
||||
- 因为 LLM 是同步 generator,不能直接 asyncio.wait_for → 线程池
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import concurrent.futures
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.conftest import (
|
||||
CONFIG,
|
||||
LIVE_API_TESTS,
|
||||
get_provider_config,
|
||||
get_provider_type,
|
||||
get_selected_provider_name,
|
||||
has_real_key,
|
||||
)
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
|
||||
def _build_provider():
|
||||
name = get_selected_provider_name("LLM")
|
||||
if not name:
|
||||
pytest.skip("selected_module.LLM 未设置")
|
||||
cfg = get_provider_config("LLM", name)
|
||||
if not cfg:
|
||||
pytest.skip(f"LLM provider '{name}' 配置缺失")
|
||||
|
||||
# 任何模式下:key 是占位符 → skip。真请求需要真 key;mock 模式下
|
||||
# 没有真 key 跑下去也会撞真 SDK 的网络栈(openai/edge_tts)报错。
|
||||
if name == "CozeLLM":
|
||||
if any(x in cfg.get("bot_id", "") for x in ["你的"]) or any(
|
||||
x in cfg.get("user_id", "") for x in ["你的"]
|
||||
):
|
||||
pytest.skip("LLM 'CozeLLM' 的 bot_id/user_id 未配置")
|
||||
elif name == "Ollama":
|
||||
if not cfg.get("model_name"):
|
||||
pytest.skip("LLM 'Ollama' 的 model_name 未配置")
|
||||
elif not has_real_key(cfg, "api_key"):
|
||||
if LIVE_API_TESTS:
|
||||
pytest.skip(f"LLM '{name}' 的 api_key 未配置")
|
||||
else:
|
||||
pytest.skip(
|
||||
f"LLM '{name}' 的 api_key 是占位符(mock 模式不会真发请求)。"
|
||||
"真请求模式:export RUN_LIVE_API_TESTS=1 并填真 key 后再跑。"
|
||||
)
|
||||
|
||||
ptype = get_provider_type("LLM", name)
|
||||
if not ptype:
|
||||
pytest.skip(f"LLM '{name}' 的 type 字段缺失")
|
||||
from core.utils.llm import create_instance
|
||||
|
||||
return create_instance(ptype, cfg)
|
||||
|
||||
|
||||
def _collect_with_timeout(provider, session_id: str, dialogue, timeout: float = 10.0):
|
||||
"""调同步 generator response(),用线程池加 10s 超时。"""
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=1) as executor:
|
||||
future = executor.submit(lambda: list(provider.response(session_id, dialogue)))
|
||||
return future.result(timeout=timeout)
|
||||
|
||||
|
||||
def test_llm_response_streams_non_empty() -> None:
|
||||
"""response(session_id, dialogue) 应产生非空 token 流。"""
|
||||
provider = _build_provider()
|
||||
dialogue = [
|
||||
{"role": "system", "content": "你是助手"},
|
||||
{"role": "user", "content": "用一句话说 hi"},
|
||||
]
|
||||
chunks = _collect_with_timeout(provider, "test-session", dialogue, timeout=10.0)
|
||||
|
||||
full = "".join(chunks).strip()
|
||||
assert isinstance(full, str), f"LLM chunks join 应是 str,得到 {type(full).__name__}"
|
||||
assert full, f"LLM 返回空响应(provider={type(provider).__name__})"
|
||||
|
||||
|
||||
def test_llm_response_no_stream_returns_string() -> None:
|
||||
"""response_no_stream 应返回非空字符串。"""
|
||||
provider = _build_provider()
|
||||
text = provider.response_no_stream("你是助手", "介绍一下北京").strip()
|
||||
|
||||
assert isinstance(text, str), f"response_no_stream 应返回 str,得到 {type(text).__name__}"
|
||||
assert text, "response_no_stream 返回空字符串"
|
||||
|
||||
|
||||
def test_llm_dialogue_min_length_one_user() -> None:
|
||||
"""至少一条 user 消息的 dialogue 应能跑通。"""
|
||||
provider = _build_provider()
|
||||
dialogue = [{"role": "user", "content": "ping"}]
|
||||
chunks = _collect_with_timeout(provider, "s1", dialogue, timeout=10.0)
|
||||
|
||||
assert "".join(chunks).strip(), "单 user 消息应返回内容"
|
||||
81
main/xiaozhi-server/tests/test_memory.py
Normal file
81
main/xiaozhi-server/tests/test_memory.py
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
"""Memory 链路测试。
|
||||
|
||||
Mock 模式(默认):从 data/.config.yaml 拿配置构造真实 provider;外部
|
||||
SDK 调用(mem0ai / powermem 客户端)走 shim,不会真发请求。
|
||||
Live 模式(``RUN_LIVE_API_TESTS=1``):调真实 Memory provider。
|
||||
|
||||
接口约定(core/providers/memory/base.py):
|
||||
async save_memory(msgs, session_id=None) -> str
|
||||
async query_memory(query: str) -> str
|
||||
|
||||
默认 selected_module.Memory = nomem(不开启记忆,本地即可)。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.conftest import (
|
||||
get_provider_config,
|
||||
get_provider_type,
|
||||
get_selected_provider_name,
|
||||
)
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
|
||||
def _build_provider():
|
||||
name = get_selected_provider_name("Memory")
|
||||
if not name:
|
||||
pytest.skip("selected_module.Memory 未设置")
|
||||
cfg = get_provider_config("Memory", name)
|
||||
if not cfg:
|
||||
pytest.skip(f"Memory provider '{name}' 配置缺失")
|
||||
ptype = get_provider_type("Memory", name)
|
||||
if not ptype:
|
||||
pytest.skip(f"Memory '{name}' 的 type 字段缺失")
|
||||
from core.utils.memory import create_instance
|
||||
|
||||
return create_instance(ptype, cfg, None)
|
||||
|
||||
|
||||
def test_memory_provider_constructs_from_config() -> None:
|
||||
"""从 config 应该能实例化出 MemoryProviderBase 子类。"""
|
||||
provider = _build_provider()
|
||||
from core.providers.memory.base import MemoryProviderBase
|
||||
|
||||
assert isinstance(provider, MemoryProviderBase), (
|
||||
f"Memory provider 类型错:{type(provider).__name__}"
|
||||
)
|
||||
|
||||
|
||||
def test_memory_provider_exposes_save_and_query() -> None:
|
||||
"""provider 必须实现 save_memory / query_memory。"""
|
||||
provider = _build_provider()
|
||||
assert hasattr(provider, "save_memory"), (
|
||||
f"{type(provider).__name__} 缺少 save_memory 方法"
|
||||
)
|
||||
assert hasattr(provider, "query_memory"), (
|
||||
f"{type(provider).__name__} 缺少 query_memory 方法"
|
||||
)
|
||||
|
||||
|
||||
def test_memory_save_and_query_roundtrip() -> None:
|
||||
"""save 后 query 应该不抛异常;nomem 返回 None/空串都算通过。"""
|
||||
provider = _build_provider()
|
||||
msgs = [{"role": "user", "content": "test message"}]
|
||||
|
||||
async def run():
|
||||
mid = await provider.save_memory(msgs, "test-session")
|
||||
result = await provider.query_memory("test")
|
||||
return mid, result
|
||||
|
||||
mid, result = asyncio.run(run())
|
||||
# nomem 等"不开记忆"实现可能返回 None;真实记忆服务应返回 str ID
|
||||
assert mid is None or isinstance(mid, str), (
|
||||
f"save_memory 应返回 str 或 None,得到 {type(mid).__name__}"
|
||||
)
|
||||
assert isinstance(result, str), "query_memory 应返回 str"
|
||||
78
main/xiaozhi-server/tests/test_rag.py
Normal file
78
main/xiaozhi-server/tests/test_rag.py
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
"""RAG(检索增强生成)链路测试。
|
||||
|
||||
xiaozhi-esp32-server 项目里没有独立的 RAG provider —— RAG 由
|
||||
MemoryProvider(mem0ai / powermem)的 ``query_memory`` 配合 LLM 工具
|
||||
调用实现。本测试聚焦「save → query → 拿到检索结果」这一核心链路。
|
||||
|
||||
Mock 模式(默认):mem0/powermem 等云调用走 shim,不发请求。
|
||||
Live 模式(``RUN_LIVE_API_TESTS=1``):真发请求到所选 memory provider。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.conftest import (
|
||||
get_provider_config,
|
||||
get_provider_type,
|
||||
get_selected_provider_name,
|
||||
)
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
|
||||
def _build_memory_provider():
|
||||
name = get_selected_provider_name("Memory")
|
||||
if not name:
|
||||
pytest.skip("selected_module.Memory 未设置")
|
||||
cfg = get_provider_config("Memory", name)
|
||||
if not cfg:
|
||||
pytest.skip(f"Memory provider '{name}' 配置缺失")
|
||||
ptype = get_provider_type("Memory", name)
|
||||
if not ptype:
|
||||
pytest.skip(f"Memory '{name}' 的 type 字段缺失")
|
||||
from core.utils.memory import create_instance
|
||||
|
||||
return create_instance(ptype, cfg, None)
|
||||
|
||||
|
||||
def test_rag_query_after_save_returns_string() -> None:
|
||||
"""保存后 query_memory 应返回字符串(nomem 返回空串也合法)。"""
|
||||
provider = _build_memory_provider()
|
||||
msgs = [
|
||||
{"role": "user", "content": "我喜欢喝咖啡"},
|
||||
{"role": "assistant", "content": "好的记住了"},
|
||||
]
|
||||
|
||||
async def run():
|
||||
await provider.save_memory(msgs, "rag-session")
|
||||
return await provider.query_memory("咖啡")
|
||||
|
||||
result = asyncio.run(run())
|
||||
assert isinstance(result, str), f"query_memory 应返回 str,得到 {type(result).__name__}"
|
||||
|
||||
|
||||
def test_rag_query_no_match_returns_empty() -> None:
|
||||
"""query 不存在内容时返回空字符串,不抛异常。"""
|
||||
provider = _build_memory_provider()
|
||||
|
||||
async def run():
|
||||
return await provider.query_memory("完全不存在的关键词xyz")
|
||||
|
||||
result = asyncio.run(run())
|
||||
assert isinstance(result, str)
|
||||
|
||||
|
||||
def test_rag_empty_query_handled() -> None:
|
||||
"""空 query 不应抛异常。"""
|
||||
provider = _build_memory_provider()
|
||||
|
||||
async def run():
|
||||
await provider.save_memory([{"role": "user", "content": "测试"}], "s")
|
||||
return await provider.query_memory("")
|
||||
|
||||
result = asyncio.run(run())
|
||||
assert isinstance(result, str)
|
||||
128
main/xiaozhi-server/tests/test_stt.py
Normal file
128
main/xiaozhi-server/tests/test_stt.py
Normal file
|
|
@ -0,0 +1,128 @@
|
|||
"""ASR(语音识别)链路测试。
|
||||
|
||||
Mock 模式(默认):从 data/.config.yaml 拿配置构造真实 ASR provider;
|
||||
所有外部 HTTP/SDK 调用走 conftest 注入的 shim,不发真请求。
|
||||
Live 模式(``RUN_LIVE_API_TESTS=1``):调真实 ASR provider。
|
||||
|
||||
接口约定(core/providers/asr/base.py):
|
||||
async speech_to_text_wrapper(pcm_data, session_id) -> Tuple[Optional[str], Optional[str]]
|
||||
async speech_to_text(opus_data, session_id, artifacts) -> Tuple[Optional[str], Optional[str]]
|
||||
|
||||
注意:
|
||||
- performance_tester_asr.py 用 3-arg 调 wrapper 是错的(base 只接 2 个),
|
||||
这里用 2-arg 正确版本
|
||||
- FunASR 是本地模型:构造时会加载 model_dir 的模型文件;
|
||||
如果模型没下载,`__init__` 直接抛异常,测试会 skip
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.conftest import (
|
||||
get_provider_config,
|
||||
get_provider_type,
|
||||
get_selected_provider_name,
|
||||
)
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
_ASSETS_DIR = Path(__file__).resolve().parent.parent / "config" / "assets"
|
||||
|
||||
|
||||
def _build_provider():
|
||||
name = get_selected_provider_name("ASR")
|
||||
if not name:
|
||||
pytest.skip("selected_module.ASR 未设置")
|
||||
cfg = get_provider_config("ASR", name)
|
||||
if not cfg:
|
||||
pytest.skip(f"ASR provider '{name}' 配置缺失")
|
||||
ptype = get_provider_type("ASR", name)
|
||||
if not ptype:
|
||||
pytest.skip(f"ASR '{name}' 的 type 字段缺失")
|
||||
from core.utils.asr import create_instance
|
||||
|
||||
return create_instance(ptype, cfg, True)
|
||||
|
||||
|
||||
def _find_test_audio() -> Path:
|
||||
"""从 config/assets/ 找 >300KB 的 wav 当测试音频。"""
|
||||
if not _ASSETS_DIR.exists():
|
||||
pytest.skip(f"音频目录不存在:{_ASSETS_DIR}")
|
||||
wavs = sorted(
|
||||
(p for p in _ASSETS_DIR.glob("*.wav") if p.stat().st_size > 300 * 1024),
|
||||
key=lambda p: p.stat().st_size,
|
||||
reverse=True, # 最大的优先
|
||||
)
|
||||
if not wavs:
|
||||
pytest.skip(f"config/assets/ 下没有 >300KB 的 wav 文件")
|
||||
return wavs[0]
|
||||
|
||||
|
||||
def test_asr_provider_constructs_from_config() -> None:
|
||||
"""从 config 应该能实例化出 ASRProviderBase 子类。"""
|
||||
provider = _build_provider()
|
||||
from core.providers.asr.base import ASRProviderBase
|
||||
|
||||
assert isinstance(provider, ASRProviderBase), (
|
||||
f"ASR provider 类型错:{type(provider).__name__}"
|
||||
)
|
||||
|
||||
|
||||
def test_asr_provider_exposes_speech_to_text() -> None:
|
||||
"""provider 必须实现 speech_to_text 方法。"""
|
||||
provider = _build_provider()
|
||||
assert hasattr(provider, "speech_to_text"), (
|
||||
f"{type(provider).__name__} 缺少 speech_to_text 方法"
|
||||
)
|
||||
assert callable(provider.speech_to_text)
|
||||
|
||||
|
||||
def test_asr_provider_has_output_dir() -> None:
|
||||
"""provider 应有 output_dir 属性(写入识别结果用)。"""
|
||||
provider = _build_provider()
|
||||
assert hasattr(provider, "output_dir"), (
|
||||
f"{type(provider).__name__} 缺少 output_dir 属性"
|
||||
)
|
||||
|
||||
|
||||
def test_asr_speech_to_text_wrapper_returns_text() -> None:
|
||||
"""真发一次 ASR 请求(live 模式),断言返回识别结果。
|
||||
|
||||
Mock 模式下也照常调,但 shim 返回空 dict/text,断言宽松:
|
||||
text 可以是 None / str / dict,只要不抛异常就算通过。
|
||||
|
||||
参考 performance_tester_asr.py:
|
||||
- 喂真实 wav 文件 bytes 给 speech_to_text_wrapper
|
||||
- 10s 超时
|
||||
- 返回的 text 可能是 None(识别失败)/ str(部分 provider)/ dict(FunASR 等带 emotion/language 的)
|
||||
"""
|
||||
provider = _build_provider()
|
||||
# Mock 模式下没有 wav 资产也能跑(shim 不读文件)。
|
||||
from tests.conftest import LIVE_API_TESTS
|
||||
if LIVE_API_TESTS:
|
||||
wav_path = _find_test_audio()
|
||||
audio_data = wav_path.read_bytes()
|
||||
else:
|
||||
# Mock 模式:喂占位 bytes,shim 不会真去解码。
|
||||
audio_data = b"\x00" * 1024
|
||||
|
||||
async def run():
|
||||
return await asyncio.wait_for(
|
||||
provider.speech_to_text_wrapper([audio_data], "test-session"),
|
||||
timeout=10.0,
|
||||
)
|
||||
|
||||
text, file_path = asyncio.run(run())
|
||||
# ASR 结果兼容性:None / str / dict(FunASR 返回 {content, language, emotion})
|
||||
assert text is None or isinstance(text, (str, dict)), (
|
||||
f"speech_to_text_wrapper 应返回 (None/str/dict, str|None),"
|
||||
f"得到 text 类型 {type(text).__name__}"
|
||||
)
|
||||
if isinstance(text, dict):
|
||||
# FunASR 风格:取 content 字段(live 模式才严格校验)。
|
||||
if LIVE_API_TESTS:
|
||||
assert text.get("content"), f"ASR dict 结果缺少 content:{text!r}"
|
||||
127
main/xiaozhi-server/tests/test_tts.py
Normal file
127
main/xiaozhi-server/tests/test_tts.py
Normal file
|
|
@ -0,0 +1,127 @@
|
|||
"""TTS(语音合成)链路测试。
|
||||
|
||||
Mock 模式(默认):从 data/.config.yaml 拿配置构造真实 TTS provider;
|
||||
所有外部 HTTP/SDK 调用走 conftest 注入的 shim,不发真请求。
|
||||
Live 模式(``RUN_LIVE_API_TESTS=1``):调真实 TTS provider。
|
||||
|
||||
接口约定(core/providers/tts/base.py):
|
||||
text_to_speak(text, output_file) -> 异步,把合成结果写到 output_file
|
||||
|
||||
注意:
|
||||
- 3 个构造测试不依赖云服务;第 4 个 test_tts_text_to_speak_writes_nonempty_file
|
||||
才是真链路测试,会真发 HTTP。
|
||||
- Mock 模式下:第 4 个测试断言宽松 —— 文件存在即可(shim 创建空文件),
|
||||
不强求 size > 0。Live 模式下严格校验 size > 0。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
from pathlib import Path
|
||||
from types import SimpleNamespace
|
||||
|
||||
import pytest
|
||||
|
||||
from tests.conftest import (
|
||||
LIVE_API_TESTS,
|
||||
get_provider_config,
|
||||
get_provider_type,
|
||||
get_selected_provider_name,
|
||||
)
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
||||
|
||||
|
||||
def _build_provider():
|
||||
name = get_selected_provider_name("TTS")
|
||||
if not name:
|
||||
pytest.skip("selected_module.TTS 未设置")
|
||||
cfg = get_provider_config("TTS", name)
|
||||
if not cfg:
|
||||
pytest.skip(f"TTS provider '{name}' 配置缺失")
|
||||
ptype = get_provider_type("TTS", name)
|
||||
if not ptype:
|
||||
pytest.skip(f"TTS '{name}' 的 type 字段缺失")
|
||||
from core.utils.tts import create_instance
|
||||
|
||||
return create_instance(ptype, cfg, True)
|
||||
|
||||
|
||||
def test_tts_provider_constructs_from_config() -> None:
|
||||
"""从 config 应该能实例化出 TTSProviderBase 子类。"""
|
||||
provider = _build_provider()
|
||||
from core.providers.tts.base import TTSProviderBase
|
||||
|
||||
assert isinstance(provider, TTSProviderBase), (
|
||||
f"TTS provider 类型错:{type(provider).__name__}"
|
||||
)
|
||||
|
||||
|
||||
def test_tts_provider_exposes_to_tts() -> None:
|
||||
"""provider 必须实现 to_tts / to_tts_stream 之一。"""
|
||||
provider = _build_provider()
|
||||
has_sync = hasattr(provider, "to_tts") and callable(provider.to_tts)
|
||||
has_stream = hasattr(provider, "to_tts_stream") and callable(
|
||||
provider.to_tts_stream
|
||||
)
|
||||
assert has_sync or has_stream, (
|
||||
f"{type(provider).__name__} 缺少 to_tts / to_tts_stream 方法"
|
||||
)
|
||||
|
||||
|
||||
def test_tts_provider_has_output_dir() -> None:
|
||||
"""provider 应有 output_file 属性(合成结果写到哪)。"""
|
||||
provider = _build_provider()
|
||||
assert hasattr(provider, "output_file"), (
|
||||
f"{type(provider).__name__} 缺少 output_file 属性"
|
||||
)
|
||||
assert isinstance(provider.output_file, str)
|
||||
assert provider.output_file, "output_file 不应为空"
|
||||
|
||||
|
||||
def test_tts_text_to_speak_writes_file() -> None:
|
||||
"""Mock 模式:断言 file 存在即可。Live 模式:断言 size > 0。
|
||||
|
||||
参考 performance_tester_tts.py 的实现:
|
||||
- mock conn(sample_rate/audio_format/stop_event/client_abort/headers)
|
||||
和 opus_encoder(SimpleNamespace 占位即可)
|
||||
- generate_filename() 拿输出路径
|
||||
- text_to_speak() 异步调云服务,写文件
|
||||
- 10s 超时
|
||||
- 用完删掉测试文件,避免 tmp/ 目录堆积
|
||||
"""
|
||||
provider = _build_provider()
|
||||
|
||||
# 参考 performance_tester_tts.py:部分 provider 内部访问 self.conn.sample_rate 等
|
||||
if not hasattr(provider, "conn") or provider.conn is None:
|
||||
provider.conn = SimpleNamespace(
|
||||
sample_rate=16000,
|
||||
audio_format="pcm",
|
||||
stop_event=threading.Event(),
|
||||
client_abort=False,
|
||||
headers={},
|
||||
)
|
||||
if not hasattr(provider, "opus_encoder") or provider.opus_encoder is None:
|
||||
provider.opus_encoder = SimpleNamespace()
|
||||
|
||||
out_file = provider.generate_filename()
|
||||
try:
|
||||
async def run():
|
||||
await asyncio.wait_for(
|
||||
provider.text_to_speak("测试一下", out_file),
|
||||
timeout=10.0,
|
||||
)
|
||||
|
||||
asyncio.run(run())
|
||||
|
||||
assert os.path.exists(out_file), f"输出文件不存在:{out_file}"
|
||||
if LIVE_API_TESTS:
|
||||
assert os.path.getsize(out_file) > 0, f"输出文件为空:{out_file}"
|
||||
finally:
|
||||
if os.path.exists(out_file):
|
||||
try:
|
||||
os.remove(out_file)
|
||||
except OSError:
|
||||
pass
|
||||
Loading…
Reference in a new issue