connection = client.connect();
+ connection.sync().ping();
+ connection.close();
+ } finally {
+ client.shutdown();
+ }
+ } catch (Exception e) {
+ issues.append("连不上 Redis(").append(e.getMessage()).append(");");
+ }
+
+ if (issues.length() == 0) {
+ available = Boolean.TRUE;
+ problem = null;
+ } else {
+ available = Boolean.FALSE;
+ problem = issues.toString();
+ }
+ return problem;
+ }
+
+ /** 读应用自己那份配置,命令行上的 -D 参数优先级更高,跟应用保持一致 */
+ private static PropertySourcesPropertyResolver resolver() {
+ ConfigurableEnvironment environment = new StandardEnvironment();
+ YamlPropertySourceLoader loader = new YamlPropertySourceLoader();
+ for (String name : CONFIG_FILES) {
+ Resource resource = new ClassPathResource(name);
+ if (!resource.exists()) {
+ continue;
+ }
+ try {
+ for (PropertySource> source : loader.load(name, resource)) {
+ environment.getPropertySources().addLast(source);
+ }
+ } catch (IOException e) {
+ log.warn("读配置 {} 失败:{}", name, e.getMessage());
+ }
+ }
+ return new PropertySourcesPropertyResolver(environment.getPropertySources());
+ }
+
+ private static String firstNonBlank(String first, String second) {
+ return first != null && !first.isBlank() ? first : (second == null ? "" : second);
+ }
+}
From e3e043a9ed58ac33ed6895c1b5232d244ffc9923 Mon Sep 17 00:00:00 2001
From: hrz <1710360675@qq.com>
Date: Sat, 24 Oct 2026 07:27:06 +0000
Subject: [PATCH 4/9] =?UTF-8?q?=E5=87=A0=E7=BB=84=E7=94=A8=E4=BE=8B?=
=?UTF-8?q?=E4=B8=8D=E5=86=8D=E6=95=B4=E4=BB=BD=E8=B7=B3=E8=BF=87=EF=BC=8C?=
=?UTF-8?q?=E7=9C=9F=E8=B7=91=E8=B5=B7=E6=9D=A5?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
插件自动导入、三个 create_instance、LLM 链路这几组用例以前整份跳过,现在都真跑。LLM 那边装了个假接口,provider 拼请求和解析流式回应那套照跑,不发真请求也不用真 key。data/.config.yaml 缺的时候现造一个,免得用例收集不起来。
---
main/xiaozhi-server/tests/conftest.py | 7 ++
.../core/utils/test_instance_creators.py | 19 +---
.../tests/plugins_func/test_loadplugins.py | 44 +++++----
main/xiaozhi-server/tests/test_llm.py | 94 ++++++++++++++++---
4 files changed, 115 insertions(+), 49 deletions(-)
diff --git a/main/xiaozhi-server/tests/conftest.py b/main/xiaozhi-server/tests/conftest.py
index 24af688b6..c8e009f5e 100644
--- a/main/xiaozhi-server/tests/conftest.py
+++ b/main/xiaozhi-server/tests/conftest.py
@@ -89,6 +89,13 @@ _CUSTOM_CONFIG = Path(os.environ["PYTEST_CONFIG_FILE"]) if os.environ.get(
"PYTEST_CONFIG_FILE"
) else _DEFAULT_CUSTOM
+# data/.config.yaml 在 .gitignore 里,本地没这个文件时现造一个空的。
+# 项目里好几个模块 import 的时候就要读它(config/logger.py 的 setup_logging
+# 直接抛 FileNotFoundError),缺了整份用例会收集不起来。CI 里也是这么造的
+_DEFAULT_CUSTOM.parent.mkdir(parents=True, exist_ok=True)
+if not _DEFAULT_CUSTOM.exists():
+ _DEFAULT_CUSTOM.write_text("{}\n", encoding="utf-8")
+
def _load_via_file_merge() -> dict:
"""纯文件合并:config.yaml + data/.config.yaml。和生产单模块部署一致。"""
diff --git a/main/xiaozhi-server/tests/core/utils/test_instance_creators.py b/main/xiaozhi-server/tests/core/utils/test_instance_creators.py
index 40405d94c..9c225c9de 100644
--- a/main/xiaozhi-server/tests/core/utils/test_instance_creators.py
+++ b/main/xiaozhi-server/tests/core/utils/test_instance_creators.py
@@ -5,22 +5,13 @@ on disk. We only test:
- the ValueError path for unknown names (no providers need to exist)
- that the signature accepts *args / **kwargs (so all three modules work)
-NOTE: This test file is currently skipped at module level because importing
-`core.utils.intent` triggers `setup_logging()` at module load time, which
-requires `data/.config.yaml` to exist. That file is .gitignore'd and not
-present in CI. To enable this test suite, either:
- 1. Make `setup_logging()` lazy (move the call out of module-level scope).
- 2. Provide a stub `data/.config.yaml` in the test environment.
-Tracked as deferred-minor in progress.md.
+早先这个文件整份跳过,理由是导入 `core.utils.intent` 会触发
+`setup_logging()`,而它要 `data/.config.yaml` 在场。CI 里这个文件是现造的,
+本地跑 pytest 时 conftest 也会补上,所以那份跳过理由已经不成立了。
"""
import pytest
-pytest.skip(
- "setup_logging() at module import requires data/.config.yaml; skipped",
- allow_module_level=True,
-)
-
-from core.utils import intent, llm, memory # noqa: E402 (unreachable when skipped)
+from core.utils import intent, llm, memory
@pytest.mark.parametrize("factory,module_type", [
@@ -46,4 +37,4 @@ def test_create_instance_accepts_args_and_kwargs(factory, module_type):
is variadic. We use a sentinel that will fail the path check.
"""
with pytest.raises(ValueError):
- factory("__missing__", "positional-arg", kwarg="value")
\ No newline at end of file
+ factory("__missing__", "positional-arg", kwarg="value")
diff --git a/main/xiaozhi-server/tests/plugins_func/test_loadplugins.py b/main/xiaozhi-server/tests/plugins_func/test_loadplugins.py
index a00a5c0c8..2e9e5bdb9 100644
--- a/main/xiaozhi-server/tests/plugins_func/test_loadplugins.py
+++ b/main/xiaozhi-server/tests/plugins_func/test_loadplugins.py
@@ -1,26 +1,30 @@
-"""Test for the auto-import mechanism in plugins_func/loadplugins.py.
+"""插件自动导入机制的测试。
-We import a real subpackage (`plugins_func.functions`) and verify the
-import side-effect runs. This protects against accidentally deleting
-`auto_import_modules` from `app.py` startup code.
+``core/connection.py`` 启动时会调 ``auto_import_modules("plugins_func.functions")``,
+把 ``plugins_func/functions`` 下的模块逐个导入一遍。导入过程中各插件用
+``@register_function`` 把自己登记进注册表。这段自动导入万一被删掉,
+插件一个都不会被加载,工具链直接空掉,而且不报错,很难发现。这里守住这条链路。
-NOTE: This test is currently skipped because importing
-`plugins_func.functions` triggers heavy module imports (cache_manager,
-etc.) that may not initialise in the test environment. To enable this
-test, ensure `data/.config.yaml` exists in the test environment or refactor
-plugin discovery to be lazy.
+早先这个文件整份跳过,理由是自动导入会拉起一串重量级依赖。CI 里
+``data/.config.yaml`` 是现造的,那个理由已经不成立了。
"""
-import pytest
+import sys
-pytest.skip(
- "plugins_func.functions import has side effects that need data/.config.yaml; skipped",
- allow_module_level=True,
-)
-
-from plugins_func.functions import get_time # noqa: F401 (unreachable when skipped)
+from plugins_func.loadplugins import auto_import_modules
+from plugins_func.register import all_function_registry
-def test_functions_package_importable():
- """If this test runs, plugins_func.functions.__init__.py has been imported."""
- import plugins_func.functions as fns
- assert hasattr(fns, "get_time")
\ No newline at end of file
+def test_auto_import_loads_plugin_modules():
+ """自动导入跑完之后,插件模块应该已经在 sys.modules 里。"""
+ auto_import_modules("plugins_func.functions")
+
+ assert "plugins_func.functions.get_time" in sys.modules
+ assert "plugins_func.functions.get_weather" in sys.modules
+
+
+def test_auto_import_registers_plugin_functions():
+ """自动导入的时候,插件函数应该已经登记进注册表。"""
+ auto_import_modules("plugins_func.functions")
+
+ assert "get_lunar" in all_function_registry
+ assert "get_weather" in all_function_registry
diff --git a/main/xiaozhi-server/tests/test_llm.py b/main/xiaozhi-server/tests/test_llm.py
index 5a83f5826..69224f5a4 100644
--- a/main/xiaozhi-server/tests/test_llm.py
+++ b/main/xiaozhi-server/tests/test_llm.py
@@ -1,7 +1,8 @@
"""LLM 链路测试。
Mock 模式(默认):从 data/.config.yaml 拿配置构造真实 provider,
-网络调用走 conftest 注入的 shim —— 不发任何请求。
+网络那一段换成本文件里的假接口 —— provider 自己拼请求、自己解析
+流式回应那套代码照跑,只是不发真请求,也不需要真 key。
Live 模式(``RUN_LIVE_API_TESTS=1``):调真实 LLM provider,参考
``performance_tester_llm.py`` 的 ThreadPoolExecutor + 10s 超时模式。
@@ -18,6 +19,7 @@ Live 模式(``RUN_LIVE_API_TESTS=1``):调真实 LLM provider,参考
from __future__ import annotations
import concurrent.futures
+import json
import sys
from pathlib import Path
@@ -34,6 +36,77 @@ from tests.conftest import (
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
+# 假接口回的固定内容。够长,能看出是流式拼出来的。
+_MOCK_ANSWER = "这是 mock 出来的回应"
+
+
+@pytest.fixture(autouse=True)
+def _mock_chat_completions(monkeypatch):
+ """Mock 模式下给 chat/completions 装一个假的回应。
+
+ 装在 httpx 这一层:provider 拼请求、走流式解析那套代码都是真的,
+ 只有网络那一段是假的。这样不用真 key 也能验证这条链路。
+ """
+ if LIVE_API_TESTS:
+ yield
+ return
+
+ import httpx
+
+ stream_body = (
+ "data: "
+ + json.dumps(
+ {
+ "id": "chatcmpl-mock",
+ "object": "chat.completion.chunk",
+ "created": 1700000000,
+ "model": "mock-model",
+ "choices": [
+ {
+ "index": 0,
+ "delta": {"role": "assistant", "content": _MOCK_ANSWER},
+ "finish_reason": None,
+ }
+ ],
+ },
+ ensure_ascii=False,
+ )
+ + "\n\n"
+ + "data: [DONE]\n\n"
+ ).encode("utf-8")
+
+ plain_body = json.dumps(
+ {
+ "id": "chatcmpl-mock",
+ "object": "chat.completion",
+ "created": 1700000000,
+ "model": "mock-model",
+ "choices": [
+ {
+ "index": 0,
+ "message": {"role": "assistant", "content": _MOCK_ANSWER},
+ "finish_reason": "stop",
+ }
+ ],
+ },
+ ensure_ascii=False,
+ ).encode("utf-8")
+
+ def _fake_send(self, request, **kwargs):
+ content = getattr(request, "content", b"") or b""
+ if b'"stream":true' in content.replace(b" ", b""):
+ payload = stream_body
+ headers = {"content-type": "text/event-stream"}
+ else:
+ payload = plain_body
+ headers = {"content-type": "application/json"}
+ response = httpx.Response(200, content=payload, headers=headers)
+ response.request = request
+ return response
+
+ monkeypatch.setattr(httpx.Client, "send", _fake_send)
+ yield
+
def _build_provider():
name = get_selected_provider_name("LLM")
@@ -43,8 +116,9 @@ def _build_provider():
if not cfg:
pytest.skip(f"LLM provider '{name}' 配置缺失")
- # 任何模式下:key 是占位符 → skip。真请求需要真 key;mock 模式下
- # 没有真 key 跑下去也会撞真 SDK 的网络栈(openai/edge_tts)报错。
+ # 任何模式下:key 是占位符 → 真请求没法发。mock 模式有假接口顶上,
+ # 但占位符本身是中文,httpx 拼 Authorization 头的时候会直接报编码错,
+ # 所以 mock 模式把它换成一把假的 ascii key
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 ["你的"]
@@ -56,22 +130,12 @@ def _build_provider():
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 后再跑。"
- )
+ cfg = dict(cfg)
+ cfg["api_key"] = "mock-api-key"
ptype = get_provider_type("LLM", name)
if not ptype:
pytest.skip(f"LLM '{name}' 的 type 字段缺失")
- if not LIVE_API_TESTS:
- # mock 模式把网络拦了,这条链路拿不到真实回复,跑下来只是一次连接失败。
- # 真要验这条链路,用 RUN_LIVE_API_TESTS=1 配真 key 跑
- pytest.skip(
- f"mock 模式不发真请求,跳过 LLM '{name}' 的链路验证。"
- "真请求模式:export RUN_LIVE_API_TESTS=1 并填真 key 后再跑。"
- )
from core.utils.llm import create_instance
return create_instance(ptype, cfg)
From aff47ee6de393012d2a42da13c464429507fad91 Mon Sep 17 00:00:00 2001
From: hrz <1710360675@qq.com>
Date: Sat, 24 Oct 2026 07:27:15 +0000
Subject: [PATCH 5/9] =?UTF-8?q?=E8=A6=81=E7=9C=9F=E5=87=AD=E6=8D=AE?=
=?UTF-8?q?=E7=9A=84=E7=94=A8=E4=BE=8B=E6=89=93=E6=A0=87=E8=AE=B0=E7=BB=9F?=
=?UTF-8?q?=E4=B8=80=E5=89=94=E9=99=A4?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
Edge TTS 那条要连微软公网,runner 的出口 IP 会被风控挡掉。以前在 CI 命令行上用 -k 排除,看不出排掉了什么。现在给它打 live_api 标记,由 conftest 统一剔除,日志里列出剔的是哪几条。
---
.github/workflows/test.yml | 6 ++---
main/xiaozhi-server/pyproject.toml | 3 +++
main/xiaozhi-server/tests/conftest.py | 33 ++++++++++++++++++++++++---
main/xiaozhi-server/tests/test_tts.py | 4 ++++
4 files changed, 40 insertions(+), 6 deletions(-)
diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml
index a0d515a2f..499403b7c 100644
--- a/.github/workflows/test.yml
+++ b/.github/workflows/test.yml
@@ -42,9 +42,9 @@ jobs:
- name: Run tests
working-directory: main/xiaozhi-server
run: |
- # Edge TTS 那条要连微软公网,runner 的出口 IP 会被风控挡掉,先排除。
- # 根治办法是给它打 live 标记,让 mock 模式下自动不收(另开一条改)
- pytest tests/ -v -k "not test_tts_text_to_speak_writes_file"
+ # 要真凭据/真网络的用例由 tests/conftest.py 按 live_api 标记统一剔除,
+ # 剔掉的是哪几条会打在日志里
+ pytest tests/ -v
java:
name: Java (manager-api)
diff --git a/main/xiaozhi-server/pyproject.toml b/main/xiaozhi-server/pyproject.toml
index 6f0998775..b0d3be70a 100644
--- a/main/xiaozhi-server/pyproject.toml
+++ b/main/xiaozhi-server/pyproject.toml
@@ -5,6 +5,9 @@ python_files = ["test_*.py"]
python_classes = ["Test*"]
python_functions = ["test_*"]
addopts = "-ra"
+markers = [
+ "live_api: 需要真凭据或真网络的用例,mock 模式下由 conftest 剔除并列出",
+]
filterwarnings = [
"ignore::DeprecationWarning",
]
\ No newline at end of file
diff --git a/main/xiaozhi-server/tests/conftest.py b/main/xiaozhi-server/tests/conftest.py
index c8e009f5e..cb3a0ccc1 100644
--- a/main/xiaozhi-server/tests/conftest.py
+++ b/main/xiaozhi-server/tests/conftest.py
@@ -454,8 +454,35 @@ import pytest # noqa: E402 (after conftest hooks so pytest is initialised)
def pytest_collection_modifyitems(config, items):
- """Live 模式下:``live_api`` 标记的测试必须配齐密钥才能跑(否则 skip)。"""
+ """Mock 模式下:``live_api`` 标记的用例要真凭据或真网络,不收,并列出是哪几条。
+
+ 以前是在 CI 命令行上用 ``-k`` 排除,看不出排掉了什么、为什么排。
+ 改成打标记 + 这里统一剔除,日志里会一条条列出来,剔了什么一目了然。
+ """
if LIVE_API_TESTS:
return
- # Mock 模式下不强行 skip:测试应该都能跑(用 shim)。
- return
+
+ keep = []
+ drop = []
+ for item in items:
+ if "live_api" in item.keywords:
+ drop.append(item)
+ else:
+ keep.append(item)
+
+ if not drop:
+ return
+
+ print(
+ "\n[conftest] 下面这些用例要真凭据或真网络,mock 模式下不收:",
+ flush=True,
+ )
+ for item in drop:
+ print(f"[conftest] - {item.nodeid}", flush=True)
+ print(
+ "[conftest] 真请求模式:export RUN_LIVE_API_TESTS=1 并配好凭据后再跑。\n",
+ flush=True,
+ )
+
+ config.hook.pytest_deselected(items=drop)
+ items[:] = keep
diff --git a/main/xiaozhi-server/tests/test_tts.py b/main/xiaozhi-server/tests/test_tts.py
index 3d4a37cde..0ad3f001a 100644
--- a/main/xiaozhi-server/tests/test_tts.py
+++ b/main/xiaozhi-server/tests/test_tts.py
@@ -81,9 +81,13 @@ def test_tts_provider_has_output_dir() -> None:
assert provider.output_file, "output_file 不应为空"
+@pytest.mark.live_api
def test_tts_text_to_speak_writes_file() -> None:
"""Mock 模式:断言 file 存在即可。Live 模式:断言 size > 0。
+ 这条要连微软公网,runner 的出口 IP 会被风控挡掉,所以打了 live_api 标记:
+ mock 模式下由 conftest 统一剔除(会列出剔的是哪几条),live 模式下才收。
+
参考 performance_tester_tts.py 的实现:
- mock conn(sample_rate/audio_format/stop_event/client_abort/headers)
和 opus_encoder(SimpleNamespace 占位即可)
From 03b7452daf47ff32552c9e89c22d9b30fa3d8487 Mon Sep 17 00:00:00 2001
From: hrz <1710360675@qq.com>
Date: Sat, 24 Oct 2026 07:31:19 +0000
Subject: [PATCH 6/9] =?UTF-8?q?CI=20=E9=87=8C=E7=BC=BA=E4=B8=9C=E8=A5=BF?=
=?UTF-8?q?=E7=9B=B4=E6=8E=A5=E5=A4=B1=E8=B4=A5=EF=BC=8C=E4=B8=8D=E8=AE=B8?=
=?UTF-8?q?=E9=9D=99=E9=BB=98=E8=B7=B3=E8=BF=87?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
测试里原来有几处配置缺失就跳过的分支,CI 上会静悄悄跳掉,门禁看着是绿的其实没跑。加了个统一的守卫:本地缺东西照旧跳过,CI 里直接失败,口径跟 manager-api 的集成测试守卫一样。
---
main/xiaozhi-server/tests/conftest.py | 21 +++++++++++++++++++++
main/xiaozhi-server/tests/test_llm.py | 13 +++++++------
2 files changed, 28 insertions(+), 6 deletions(-)
diff --git a/main/xiaozhi-server/tests/conftest.py b/main/xiaozhi-server/tests/conftest.py
index cb3a0ccc1..2bbb4929c 100644
--- a/main/xiaozhi-server/tests/conftest.py
+++ b/main/xiaozhi-server/tests/conftest.py
@@ -453,6 +453,27 @@ if not LIVE_API_TESTS:
import pytest # noqa: E402 (after conftest hooks so pytest is initialised)
+def is_ci() -> bool:
+ """GitHub Actions 上会带 CI=true"""
+ value = os.environ.get("CI")
+ if value is None:
+ return False
+ trimmed = value.strip()
+ return bool(trimmed) and trimmed.lower() != "false"
+
+
+def skip_or_fail(reason: str) -> None:
+ """本地缺东西就跳过,CI 里缺东西直接让 job 挂掉。
+
+ 口径跟 manager-api 那边的 IntegrationTestEnvironment 一致:本地没起依赖的
+ 机器上跳过就行,不该把构建从绿变成红;CI 里依赖必须真的在,缺了就失败,
+ 不许静默跳过 —— 静默跳过等于门禁被掏空,还看不出来。
+ """
+ if is_ci():
+ raise RuntimeError(f"CI 环境里{reason},这条用例必须真的跑起来,不能跳过")
+ pytest.skip(reason)
+
+
def pytest_collection_modifyitems(config, items):
"""Mock 模式下:``live_api`` 标记的用例要真凭据或真网络,不收,并列出是哪几条。
diff --git a/main/xiaozhi-server/tests/test_llm.py b/main/xiaozhi-server/tests/test_llm.py
index 69224f5a4..81b9a0faf 100644
--- a/main/xiaozhi-server/tests/test_llm.py
+++ b/main/xiaozhi-server/tests/test_llm.py
@@ -32,6 +32,7 @@ from tests.conftest import (
get_provider_type,
get_selected_provider_name,
has_real_key,
+ skip_or_fail,
)
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
@@ -111,10 +112,10 @@ def _mock_chat_completions(monkeypatch):
def _build_provider():
name = get_selected_provider_name("LLM")
if not name:
- pytest.skip("selected_module.LLM 未设置")
+ skip_or_fail("selected_module.LLM 未设置")
cfg = get_provider_config("LLM", name)
if not cfg:
- pytest.skip(f"LLM provider '{name}' 配置缺失")
+ skip_or_fail(f"LLM provider '{name}' 配置缺失")
# 任何模式下:key 是占位符 → 真请求没法发。mock 模式有假接口顶上,
# 但占位符本身是中文,httpx 拼 Authorization 头的时候会直接报编码错,
@@ -123,19 +124,19 @@ def _build_provider():
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 未配置")
+ skip_or_fail("LLM 'CozeLLM' 的 bot_id/user_id 未配置")
elif name == "Ollama":
if not cfg.get("model_name"):
- pytest.skip("LLM 'Ollama' 的 model_name 未配置")
+ skip_or_fail("LLM 'Ollama' 的 model_name 未配置")
elif not has_real_key(cfg, "api_key"):
if LIVE_API_TESTS:
- pytest.skip(f"LLM '{name}' 的 api_key 未配置")
+ skip_or_fail(f"LLM '{name}' 的 api_key 未配置")
cfg = dict(cfg)
cfg["api_key"] = "mock-api-key"
ptype = get_provider_type("LLM", name)
if not ptype:
- pytest.skip(f"LLM '{name}' 的 type 字段缺失")
+ skip_or_fail(f"LLM '{name}' 的 type 字段缺失")
from core.utils.llm import create_instance
return create_instance(ptype, cfg)
From 379185caed87a80a40cf234d882be8f9e2b35ae3 Mon Sep 17 00:00:00 2001
From: hrz <1710360675@qq.com>
Date: Sat, 24 Oct 2026 08:06:12 +0000
Subject: [PATCH 7/9] =?UTF-8?q?=E7=9B=AF=E4=BD=8F=E8=BF=9E=E6=8E=A5?=
=?UTF-8?q?=E6=A8=A1=E5=9D=97=E9=87=8C=E9=82=A3=E6=AC=A1=E6=8F=92=E4=BB=B6?=
=?UTF-8?q?=E8=87=AA=E5=8A=A8=E5=AF=BC=E5=85=A5?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
原来两条用例自己调自动导入,连接模块里那行被删掉它们照样绿。加一条查源码的用例,盯住模块加载时那次调用本身还在。
---
.../tests/plugins_func/test_loadplugins.py | 35 +++++++++++++++++++
1 file changed, 35 insertions(+)
diff --git a/main/xiaozhi-server/tests/plugins_func/test_loadplugins.py b/main/xiaozhi-server/tests/plugins_func/test_loadplugins.py
index 2e9e5bdb9..260167c44 100644
--- a/main/xiaozhi-server/tests/plugins_func/test_loadplugins.py
+++ b/main/xiaozhi-server/tests/plugins_func/test_loadplugins.py
@@ -5,10 +5,14 @@
``@register_function`` 把自己登记进注册表。这段自动导入万一被删掉,
插件一个都不会被加载,工具链直接空掉,而且不报错,很难发现。这里守住这条链路。
+最后一条用例查的是 ``core/connection.py`` 的源码本身:自动导入这个动作做得对
+不对,跟连接模块有没有真的调它,是两回事,两条都要守。
+
早先这个文件整份跳过,理由是自动导入会拉起一串重量级依赖。CI 里
``data/.config.yaml`` 是现造的,那个理由已经不成立了。
"""
import sys
+from pathlib import Path
from plugins_func.loadplugins import auto_import_modules
from plugins_func.register import all_function_registry
@@ -28,3 +32,34 @@ def test_auto_import_registers_plugin_functions():
assert "get_lunar" in all_function_registry
assert "get_weather" in all_function_registry
+
+
+def test_connection_module_triggers_auto_import():
+ """core/connection.py 模块加载时那次自动导入得在
+
+
+ 这行被删掉或者改成注释,插件一个都不会被加载:启动不报错,工具链空掉,
+ 上面两条用例照样绿。这里查源码,盯住那一次调用。
+ """
+ import ast
+
+ source_path = Path(__file__).resolve().parents[2] / "core" / "connection.py"
+ tree = ast.parse(source_path.read_text(encoding="utf-8"))
+
+ imported_packages = []
+ for node in tree.body:
+ if not isinstance(node, ast.Expr) or not isinstance(node.value, ast.Call):
+ continue
+ call = node.value
+ func = call.func
+ name = func.id if isinstance(func, ast.Name) else getattr(func, "attr", "")
+ if name != "auto_import_modules":
+ continue
+ for arg in call.args:
+ if isinstance(arg, ast.Constant) and isinstance(arg.value, str):
+ imported_packages.append(arg.value)
+
+ assert "plugins_func.functions" in imported_packages, (
+ "core/connection.py 模块加载时的那次自动导入不见了,"
+ "插件不会被加载,工具链会空掉"
+ )
From 57dffb23e91991fd1e8b55f6956b0f8995de78f3 Mon Sep 17 00:00:00 2001
From: hrz <1710360675@qq.com>
Date: Sat, 24 Oct 2026 08:06:12 +0000
Subject: [PATCH 8/9] =?UTF-8?q?=E4=B8=89=E6=9D=A1=20LLM=20=E7=94=A8?=
=?UTF-8?q?=E4=BE=8B=E6=94=B9=E6=88=90=E6=9F=A5=E8=AF=B7=E6=B1=82=E4=BD=93?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
原来只看回应非空,provider 把消息丢掉、自己编一句回来,测试照样绿。现在检查请求里带了模型名和这次对话,回的内容也要跟假接口给的一致。
---
main/xiaozhi-server/tests/test_llm.py | 55 ++++++++++++++++++++++++---
1 file changed, 50 insertions(+), 5 deletions(-)
diff --git a/main/xiaozhi-server/tests/test_llm.py b/main/xiaozhi-server/tests/test_llm.py
index 81b9a0faf..3b88d4d85 100644
--- a/main/xiaozhi-server/tests/test_llm.py
+++ b/main/xiaozhi-server/tests/test_llm.py
@@ -47,9 +47,12 @@ def _mock_chat_completions(monkeypatch):
装在 httpx 这一层:provider 拼请求、走流式解析那套代码都是真的,
只有网络那一段是假的。这样不用真 key 也能验证这条链路。
+
+ 发出去的请求体记在返回的列表里,用例要检查 provider 真的把这次对话
+ 装进了请求里。
"""
if LIVE_API_TESTS:
- yield
+ yield None
return
import httpx
@@ -93,8 +96,11 @@ def _mock_chat_completions(monkeypatch):
ensure_ascii=False,
).encode("utf-8")
+ sent_requests = []
+
def _fake_send(self, request, **kwargs):
content = getattr(request, "content", b"") or b""
+ sent_requests.append(content)
if b'"stream":true' in content.replace(b" ", b""):
payload = stream_body
headers = {"content-type": "text/event-stream"}
@@ -106,7 +112,34 @@ def _mock_chat_completions(monkeypatch):
return response
monkeypatch.setattr(httpx.Client, "send", _fake_send)
- yield
+ yield sent_requests
+
+
+def _sent_body(requests):
+ """最后一次发出去的请求体。live 模式没有假接口,返回 None"""
+ if requests is None:
+ return None
+ assert requests, "provider 一次请求都没发出去"
+ return json.loads(requests[-1].decode("utf-8"))
+
+
+def _assert_request(body, provider, expected_contents):
+ """检查请求体:模型名在、这次对话在
+
+
+ 只看回应非空的话,provider 把消息丢掉、自己编一句话回来,测试照样绿。
+ """
+ if body is None:
+ return
+ assert body.get("model"), "请求里得带上模型名"
+ expected_model = getattr(provider, "model_name", None)
+ if expected_model:
+ assert body["model"] == expected_model, "请求里的模型名跟配置对不上"
+ messages = body.get("messages") or []
+ assert messages, "请求里得带上对话"
+ contents = [message.get("content") for message in messages]
+ for text in expected_contents:
+ assert text in contents, f"请求里没有把「{text}」发出去"
def _build_provider():
@@ -149,7 +182,7 @@ def _collect_with_timeout(provider, session_id: str, dialogue, timeout: float =
return future.result(timeout=timeout)
-def test_llm_response_streams_non_empty() -> None:
+def test_llm_response_streams_non_empty(_mock_chat_completions) -> None:
"""response(session_id, dialogue) 应产生非空 token 流。"""
provider = _build_provider()
dialogue = [
@@ -161,21 +194,33 @@ def test_llm_response_streams_non_empty() -> None:
full = "".join(chunks).strip()
assert isinstance(full, str), f"LLM chunks join 应是 str,得到 {type(full).__name__}"
assert full, f"LLM 返回空响应(provider={type(provider).__name__})"
+ # 回的得是假接口给的那句,不是随便一个非空串
+ assert full == _MOCK_ANSWER
+ _assert_request(
+ _sent_body(_mock_chat_completions),
+ provider,
+ ["你是助手", "用一句话说 hi"],
+ )
-def test_llm_response_no_stream_returns_string() -> None:
+def test_llm_response_no_stream_returns_string(_mock_chat_completions) -> 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 返回空字符串"
+ assert text == _MOCK_ANSWER
+ _assert_request(
+ _sent_body(_mock_chat_completions), provider, ["你是助手", "介绍一下北京"]
+ )
-def test_llm_dialogue_min_length_one_user() -> None:
+def test_llm_dialogue_min_length_one_user(_mock_chat_completions) -> 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 消息应返回内容"
+ _assert_request(_sent_body(_mock_chat_completions), provider, ["ping"])
From 1a4b8d76c5a9032639372f7530e45313c522f665 Mon Sep 17 00:00:00 2001
From: hrz <1710360675@qq.com>
Date: Sat, 24 Oct 2026 08:06:12 +0000
Subject: [PATCH 9/9] =?UTF-8?q?TTS=20=E7=94=A8=E4=BE=8B=E8=AF=B4=E6=98=8E?=
=?UTF-8?q?=E9=87=8C=E7=9A=84=E5=90=8D=E5=AD=97=E6=94=B9=E6=88=90=E7=9C=9F?=
=?UTF-8?q?=E5=AD=98=E5=9C=A8=E7=9A=84?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
说明里写的那个用例名仓库里没有,改成实际跑的那条。
---
main/xiaozhi-server/tests/test_tts.py | 2 +-
1 file changed, 1 insertion(+), 1 deletion(-)
diff --git a/main/xiaozhi-server/tests/test_tts.py b/main/xiaozhi-server/tests/test_tts.py
index 0ad3f001a..6f7f5867f 100644
--- a/main/xiaozhi-server/tests/test_tts.py
+++ b/main/xiaozhi-server/tests/test_tts.py
@@ -8,7 +8,7 @@ Live 模式(``RUN_LIVE_API_TESTS=1``):调真实 TTS provider。
text_to_speak(text, output_file) -> 异步,把合成结果写到 output_file
注意:
-- 3 个构造测试不依赖云服务;第 4 个 test_tts_text_to_speak_writes_nonempty_file
+- 3 个构造测试不依赖云服务;第 4 个 test_tts_text_to_speak_writes_file
才是真链路测试,会真发 HTTP。
- Mock 模式下:第 4 个测试断言宽松 —— 文件存在即可(shim 创建空文件),
不强求 size > 0。Live 模式下严格校验 size > 0。