mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-27 04:49:47 +01:00
几组用例不再整份跳过,真跑起来
插件自动导入、三个 create_instance、LLM 链路这几组用例以前整份跳过,现在都真跑。LLM 那边装了个假接口,provider 拼请求和解析流式回应那套照跑,不发真请求也不用真 key。data/.config.yaml 缺的时候现造一个,免得用例收集不起来。
This commit is contained in:
parent
b3810fb7cb
commit
e3e043a9ed
4 changed files with 115 additions and 49 deletions
|
|
@ -89,6 +89,13 @@ _CUSTOM_CONFIG = Path(os.environ["PYTEST_CONFIG_FILE"]) if os.environ.get(
|
||||||
"PYTEST_CONFIG_FILE"
|
"PYTEST_CONFIG_FILE"
|
||||||
) else _DEFAULT_CUSTOM
|
) 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:
|
def _load_via_file_merge() -> dict:
|
||||||
"""纯文件合并:config.yaml + data/.config.yaml。和生产单模块部署一致。"""
|
"""纯文件合并:config.yaml + data/.config.yaml。和生产单模块部署一致。"""
|
||||||
|
|
|
||||||
|
|
@ -5,22 +5,13 @@ on disk. We only test:
|
||||||
- the ValueError path for unknown names (no providers need to exist)
|
- the ValueError path for unknown names (no providers need to exist)
|
||||||
- that the signature accepts *args / **kwargs (so all three modules work)
|
- 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` 会触发
|
||||||
`core.utils.intent` triggers `setup_logging()` at module load time, which
|
`setup_logging()`,而它要 `data/.config.yaml` 在场。CI 里这个文件是现造的,
|
||||||
requires `data/.config.yaml` to exist. That file is .gitignore'd and not
|
本地跑 pytest 时 conftest 也会补上,所以那份跳过理由已经不成立了。
|
||||||
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.
|
|
||||||
"""
|
"""
|
||||||
import pytest
|
import pytest
|
||||||
|
|
||||||
pytest.skip(
|
from core.utils import intent, llm, memory
|
||||||
"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)
|
|
||||||
|
|
||||||
|
|
||||||
@pytest.mark.parametrize("factory,module_type", [
|
@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.
|
is variadic. We use a sentinel that will fail the path check.
|
||||||
"""
|
"""
|
||||||
with pytest.raises(ValueError):
|
with pytest.raises(ValueError):
|
||||||
factory("__missing__", "positional-arg", kwarg="value")
|
factory("__missing__", "positional-arg", kwarg="value")
|
||||||
|
|
|
||||||
|
|
@ -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
|
``core/connection.py`` 启动时会调 ``auto_import_modules("plugins_func.functions")``,
|
||||||
import side-effect runs. This protects against accidentally deleting
|
把 ``plugins_func/functions`` 下的模块逐个导入一遍。导入过程中各插件用
|
||||||
`auto_import_modules` from `app.py` startup code.
|
``@register_function`` 把自己登记进注册表。这段自动导入万一被删掉,
|
||||||
|
插件一个都不会被加载,工具链直接空掉,而且不报错,很难发现。这里守住这条链路。
|
||||||
|
|
||||||
NOTE: This test is currently skipped because importing
|
早先这个文件整份跳过,理由是自动导入会拉起一串重量级依赖。CI 里
|
||||||
`plugins_func.functions` triggers heavy module imports (cache_manager,
|
``data/.config.yaml`` 是现造的,那个理由已经不成立了。
|
||||||
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.
|
|
||||||
"""
|
"""
|
||||||
import pytest
|
import sys
|
||||||
|
|
||||||
pytest.skip(
|
from plugins_func.loadplugins import auto_import_modules
|
||||||
"plugins_func.functions import has side effects that need data/.config.yaml; skipped",
|
from plugins_func.register import all_function_registry
|
||||||
allow_module_level=True,
|
|
||||||
)
|
|
||||||
|
|
||||||
from plugins_func.functions import get_time # noqa: F401 (unreachable when skipped)
|
|
||||||
|
|
||||||
|
|
||||||
def test_functions_package_importable():
|
def test_auto_import_loads_plugin_modules():
|
||||||
"""If this test runs, plugins_func.functions.__init__.py has been imported."""
|
"""自动导入跑完之后,插件模块应该已经在 sys.modules 里。"""
|
||||||
import plugins_func.functions as fns
|
auto_import_modules("plugins_func.functions")
|
||||||
assert hasattr(fns, "get_time")
|
|
||||||
|
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
|
||||||
|
|
|
||||||
|
|
@ -1,7 +1,8 @@
|
||||||
"""LLM 链路测试。
|
"""LLM 链路测试。
|
||||||
|
|
||||||
Mock 模式(默认):从 data/.config.yaml 拿配置构造真实 provider,
|
Mock 模式(默认):从 data/.config.yaml 拿配置构造真实 provider,
|
||||||
网络调用走 conftest 注入的 shim —— 不发任何请求。
|
网络那一段换成本文件里的假接口 —— provider 自己拼请求、自己解析
|
||||||
|
流式回应那套代码照跑,只是不发真请求,也不需要真 key。
|
||||||
Live 模式(``RUN_LIVE_API_TESTS=1``):调真实 LLM provider,参考
|
Live 模式(``RUN_LIVE_API_TESTS=1``):调真实 LLM provider,参考
|
||||||
``performance_tester_llm.py`` 的 ThreadPoolExecutor + 10s 超时模式。
|
``performance_tester_llm.py`` 的 ThreadPoolExecutor + 10s 超时模式。
|
||||||
|
|
||||||
|
|
@ -18,6 +19,7 @@ Live 模式(``RUN_LIVE_API_TESTS=1``):调真实 LLM provider,参考
|
||||||
from __future__ import annotations
|
from __future__ import annotations
|
||||||
|
|
||||||
import concurrent.futures
|
import concurrent.futures
|
||||||
|
import json
|
||||||
import sys
|
import sys
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
|
||||||
|
|
@ -34,6 +36,77 @@ from tests.conftest import (
|
||||||
|
|
||||||
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
|
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():
|
def _build_provider():
|
||||||
name = get_selected_provider_name("LLM")
|
name = get_selected_provider_name("LLM")
|
||||||
|
|
@ -43,8 +116,9 @@ def _build_provider():
|
||||||
if not cfg:
|
if not cfg:
|
||||||
pytest.skip(f"LLM provider '{name}' 配置缺失")
|
pytest.skip(f"LLM provider '{name}' 配置缺失")
|
||||||
|
|
||||||
# 任何模式下:key 是占位符 → skip。真请求需要真 key;mock 模式下
|
# 任何模式下:key 是占位符 → 真请求没法发。mock 模式有假接口顶上,
|
||||||
# 没有真 key 跑下去也会撞真 SDK 的网络栈(openai/edge_tts)报错。
|
# 但占位符本身是中文,httpx 拼 Authorization 头的时候会直接报编码错,
|
||||||
|
# 所以 mock 模式把它换成一把假的 ascii key
|
||||||
if name == "CozeLLM":
|
if name == "CozeLLM":
|
||||||
if any(x in cfg.get("bot_id", "") for x in ["你的"]) or any(
|
if any(x in cfg.get("bot_id", "") for x in ["你的"]) or any(
|
||||||
x in cfg.get("user_id", "") for x in ["你的"]
|
x in cfg.get("user_id", "") for x in ["你的"]
|
||||||
|
|
@ -56,22 +130,12 @@ def _build_provider():
|
||||||
elif not has_real_key(cfg, "api_key"):
|
elif not has_real_key(cfg, "api_key"):
|
||||||
if LIVE_API_TESTS:
|
if LIVE_API_TESTS:
|
||||||
pytest.skip(f"LLM '{name}' 的 api_key 未配置")
|
pytest.skip(f"LLM '{name}' 的 api_key 未配置")
|
||||||
else:
|
cfg = dict(cfg)
|
||||||
pytest.skip(
|
cfg["api_key"] = "mock-api-key"
|
||||||
f"LLM '{name}' 的 api_key 是占位符(mock 模式不会真发请求)。"
|
|
||||||
"真请求模式:export RUN_LIVE_API_TESTS=1 并填真 key 后再跑。"
|
|
||||||
)
|
|
||||||
|
|
||||||
ptype = get_provider_type("LLM", name)
|
ptype = get_provider_type("LLM", name)
|
||||||
if not ptype:
|
if not ptype:
|
||||||
pytest.skip(f"LLM '{name}' 的 type 字段缺失")
|
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
|
from core.utils.llm import create_instance
|
||||||
|
|
||||||
return create_instance(ptype, cfg)
|
return create_instance(ptype, cfg)
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue