几组用例不再整份跳过,真跑起来

插件自动导入、三个 create_instance、LLM 链路这几组用例以前整份跳过,现在都真跑。LLM 那边装了个假接口,provider 拼请求和解析流式回应那套照跑,不发真请求也不用真 key。data/.config.yaml 缺的时候现造一个,免得用例收集不起来。
This commit is contained in:
hrz 2026-10-24 07:27:06 +00:00
parent b3810fb7cb
commit e3e043a9ed
4 changed files with 115 additions and 49 deletions

View file

@ -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。和生产单模块部署一致。"""

View file

@ -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")
factory("__missing__", "positional-arg", kwarg="value")

View file

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

View file

@ -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)