mirror of
https://github.com/xinnan-tech/xiaozhi-esp32-server.git
synced 2026-11-23 03:19:41 +00:00
Merge a47790cddd into 3219a28039
This commit is contained in:
commit
d151e3d4ec
4 changed files with 163 additions and 14 deletions
|
|
@ -7,8 +7,6 @@ from config.manage_api_client import (
|
|||
get_server_config,
|
||||
get_agent_models,
|
||||
get_correct_words,
|
||||
DeviceNotFoundException,
|
||||
DeviceBindException,
|
||||
)
|
||||
|
||||
|
||||
|
|
@ -94,13 +92,11 @@ async def get_private_config_from_api(config, device_id, client_id):
|
|||
agent_result = results[0]
|
||||
correct_words = results[1] if not isinstance(results[1], Exception) else None
|
||||
|
||||
# 抛出业务异常
|
||||
if isinstance(agent_result, DeviceNotFoundException):
|
||||
raise agent_result
|
||||
if isinstance(agent_result, DeviceBindException):
|
||||
# 设备配置是必需的,不能将请求失败当成空配置继续使用公共模型。
|
||||
if isinstance(agent_result, Exception):
|
||||
raise agent_result
|
||||
|
||||
private_config = agent_result if not isinstance(agent_result, Exception) else {}
|
||||
private_config = agent_result
|
||||
if correct_words:
|
||||
private_config["correct_words"] = correct_words
|
||||
return private_config
|
||||
|
|
|
|||
|
|
@ -795,7 +795,8 @@ class ConnectionHandler:
|
|||
# 在线程池中初始化组件
|
||||
self.executor.submit(self._initialize_components)
|
||||
except Exception as e:
|
||||
self.logger.bind(tag=TAG).error(f"后台初始化失败: {e}")
|
||||
self.logger.bind(tag=TAG).error(f"后台初始化失败,关闭连接: {e}")
|
||||
await self.close()
|
||||
|
||||
async def _initialize_private_config_async(self):
|
||||
"""从接口异步获取差异化配置(异步版本,不阻塞主循环)"""
|
||||
|
|
@ -824,10 +825,6 @@ class ConnectionHandler:
|
|||
self.need_bind = True
|
||||
self.bind_code = e.bind_code
|
||||
private_config = {}
|
||||
except Exception as e:
|
||||
self.need_bind = True
|
||||
self.logger.bind(tag=TAG).error(f"异步获取差异化配置失败: {e}")
|
||||
private_config = {}
|
||||
|
||||
init_llm, init_tts, init_memory, init_intent = (
|
||||
False,
|
||||
|
|
|
|||
|
|
@ -1,5 +1,12 @@
|
|||
"""Tests for the recursive config merge in config/config_loader.py."""
|
||||
"""Tests for configuration merging and device configuration failures."""
|
||||
from unittest.mock import AsyncMock
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from config import config_loader
|
||||
from config.config_loader import merge_configs
|
||||
from config.manage_api_client import DeviceBindException, DeviceNotFoundException
|
||||
|
||||
|
||||
def test_merge_simple_override():
|
||||
|
|
@ -43,3 +50,52 @@ def test_merge_does_not_mutate_defaults():
|
|||
custom = {"a": {"c": 2}}
|
||||
merge_configs(default, custom)
|
||||
assert default == {"a": {"b": 1}} # unchanged
|
||||
|
||||
|
||||
@pytest.mark.parametrize("error", [
|
||||
httpx.ReadTimeout("agent config timed out"),
|
||||
httpx.ConnectError("manager API unavailable"),
|
||||
RuntimeError("API returned an error"),
|
||||
DeviceNotFoundException("unknown device"),
|
||||
DeviceBindException("123456"),
|
||||
])
|
||||
async def test_private_config_propagates_agent_errors(monkeypatch, error):
|
||||
monkeypatch.setattr(config_loader, "get_agent_models", AsyncMock(side_effect=error))
|
||||
monkeypatch.setattr(config_loader, "get_correct_words", AsyncMock(return_value=None))
|
||||
|
||||
with pytest.raises(type(error)) as raised:
|
||||
await config_loader.get_private_config_from_api(
|
||||
{"selected_module": {"ASR": "FunASR"}}, "device", "client"
|
||||
)
|
||||
|
||||
assert raised.value is error
|
||||
|
||||
|
||||
@pytest.mark.parametrize("correct_words", [None, {"小志": "小智"}])
|
||||
async def test_private_config_keeps_agent_selection(monkeypatch, correct_words):
|
||||
agent_config = {"selected_module": {"ASR": "DoubaoStreamASR"}}
|
||||
get_models = AsyncMock(return_value=agent_config)
|
||||
monkeypatch.setattr(config_loader, "get_agent_models", get_models)
|
||||
monkeypatch.setattr(config_loader, "get_correct_words", AsyncMock(return_value=correct_words))
|
||||
selected = {"ASR": "FunASR"}
|
||||
|
||||
result = await config_loader.get_private_config_from_api(
|
||||
{"selected_module": selected}, "device", "client"
|
||||
)
|
||||
|
||||
get_models.assert_awaited_once_with("device", "client", selected)
|
||||
assert result["selected_module"]["ASR"] == "DoubaoStreamASR"
|
||||
assert result.get("correct_words") == correct_words
|
||||
|
||||
|
||||
async def test_private_config_tolerates_optional_correct_words_failure(monkeypatch):
|
||||
agent_config = {"selected_module": {"ASR": "DoubaoStreamASR"}}
|
||||
monkeypatch.setattr(config_loader, "get_agent_models", AsyncMock(return_value=agent_config))
|
||||
monkeypatch.setattr(config_loader, "get_correct_words", AsyncMock(side_effect=RuntimeError("unavailable")))
|
||||
|
||||
result = await config_loader.get_private_config_from_api(
|
||||
{"selected_module": {}}, "device", "client"
|
||||
)
|
||||
|
||||
assert result == agent_config
|
||||
assert "correct_words" not in result
|
||||
|
|
|
|||
100
main/xiaozhi-server/tests/core/test_connection_config.py
Normal file
100
main/xiaozhi-server/tests/core/test_connection_config.py
Normal file
|
|
@ -0,0 +1,100 @@
|
|||
"""Device config errors must not start a session with public model settings."""
|
||||
import asyncio
|
||||
import copy
|
||||
from unittest.mock import AsyncMock, Mock
|
||||
|
||||
import httpx
|
||||
import pytest
|
||||
|
||||
from config import config_loader
|
||||
from config.manage_api_client import DeviceBindException, DeviceNotFoundException
|
||||
from core import connection
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def conn(monkeypatch):
|
||||
# Exercise the real initialization methods without loading models or hardware.
|
||||
conn = object.__new__(connection.ConnectionHandler)
|
||||
conn.read_config_from_api = True
|
||||
conn.common_config = {
|
||||
"selected_module": {"ASR": "FunASR"},
|
||||
"ASR": {"FunASR": {"type": "fun_local"}},
|
||||
}
|
||||
conn.config = copy.deepcopy(conn.common_config)
|
||||
conn.headers = {"device-id": "device", "client-id": "client"}
|
||||
conn.need_bind = False
|
||||
conn.bind_code = None
|
||||
conn.bind_completed_event = asyncio.Event()
|
||||
conn.logger = Mock()
|
||||
conn.logger.bind.return_value = conn.logger
|
||||
conn.executor = Mock()
|
||||
conn._initialize_components = Mock()
|
||||
conn.close = AsyncMock()
|
||||
monkeypatch.setattr(connection, "initialize_modules", Mock(return_value={}))
|
||||
monkeypatch.setattr(config_loader, "get_correct_words", AsyncMock(return_value=None))
|
||||
return conn
|
||||
|
||||
|
||||
@pytest.mark.parametrize("error", [
|
||||
httpx.ReadTimeout("agent config timed out"),
|
||||
RuntimeError("API returned an error"),
|
||||
])
|
||||
async def test_config_failure_closes_without_starting_or_requesting_binding(conn, monkeypatch, error):
|
||||
conn.loop = asyncio.get_running_loop()
|
||||
monkeypatch.setattr(config_loader, "get_agent_models", AsyncMock(side_effect=error))
|
||||
|
||||
await conn._background_initialize()
|
||||
|
||||
conn.close.assert_awaited_once_with()
|
||||
conn.executor.submit.assert_not_called()
|
||||
connection.initialize_modules.assert_not_called()
|
||||
assert conn.need_bind is False
|
||||
assert not conn.bind_completed_event.is_set()
|
||||
conn.logger.info.assert_not_called()
|
||||
assert any(str(error) in call.args[0] for call in conn.logger.error.call_args_list)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("error", [
|
||||
DeviceNotFoundException("unknown device"), DeviceBindException("123456"),
|
||||
])
|
||||
async def test_binding_errors_keep_existing_binding_flow(conn, monkeypatch, error):
|
||||
conn.loop = asyncio.get_running_loop()
|
||||
monkeypatch.setattr(config_loader, "get_agent_models", AsyncMock(side_effect=error))
|
||||
|
||||
await conn._background_initialize()
|
||||
|
||||
assert conn.need_bind is True
|
||||
assert conn.bind_code == getattr(error, "bind_code", None)
|
||||
conn.executor.submit.assert_called_once_with(conn._initialize_components)
|
||||
conn.close.assert_not_awaited()
|
||||
conn.logger.info.assert_not_called()
|
||||
|
||||
|
||||
async def test_success_applies_agent_config_before_initializing(conn, monkeypatch):
|
||||
conn.loop = asyncio.get_running_loop()
|
||||
monkeypatch.setattr(config_loader, "get_agent_models", AsyncMock(return_value={
|
||||
"selected_module": {"ASR": "DoubaoStreamASR"},
|
||||
"ASR": {"DoubaoStreamASR": {"type": "doubao_stream"}},
|
||||
}))
|
||||
|
||||
await conn._background_initialize()
|
||||
|
||||
assert conn.config["selected_module"]["ASR"] == "DoubaoStreamASR"
|
||||
assert conn.need_bind is False
|
||||
assert conn.bind_completed_event.is_set()
|
||||
conn.executor.submit.assert_called_once_with(conn._initialize_components)
|
||||
conn.close.assert_not_awaited()
|
||||
|
||||
|
||||
async def test_local_config_does_not_request_agent_config(conn, monkeypatch):
|
||||
conn.read_config_from_api = False
|
||||
get_models = AsyncMock()
|
||||
monkeypatch.setattr(config_loader, "get_agent_models", get_models)
|
||||
|
||||
await conn._background_initialize()
|
||||
|
||||
get_models.assert_not_awaited()
|
||||
assert conn.config == conn.common_config
|
||||
assert conn.bind_completed_event.is_set()
|
||||
conn.executor.submit.assert_called_once_with(conn._initialize_components)
|
||||
conn.close.assert_not_awaited()
|
||||
Loading…
Reference in a new issue