xiaozhi-esp32-server/main/xiaozhi-server/tests/test_tts.py
Sakura-RanChen 6c3f89cae1
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>
2026-09-17 15:57:43 +08:00

127 lines
4.2 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""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