Commit f92e1eed by sunqi02 Committed by 胡悦

test: rewrite MessageGate tests for activation recognition

1 parent e6dbff47
"""MessageGate 服务的单元测试。"""
"""MessageGate 激活识别测试。"""
import pytest
from unittest.mock import MagicMock, AsyncMock
from app.service.message_gate import MessageGate, GateDecision
......@@ -6,496 +6,141 @@ from app.service.message_gate import MessageGate, GateDecision
def test_message_gate_can_be_constructed():
"""MessageGate 应能通过依赖注入的方式构造。"""
config_loader = MagicMock()
session_service = MagicMock()
post_reply_hook = MagicMock()
agent_hub = MagicMock()
main_agent_key = "main"
gate = MessageGate(
config_loader=config_loader,
session_service=session_service,
post_reply_hook=post_reply_hook,
agent_hub=agent_hub,
main_agent_key=main_agent_key,
model=MagicMock(), # 提供 mock model 避免真实加载 models.json
config_loader=MagicMock(),
session_service=MagicMock(),
post_reply_hook=MagicMock(),
agent_hub=MagicMock(),
main_agent_key="11",
model=MagicMock(),
)
assert gate is not None
assert gate.config_loader is config_loader
assert gate.session_service is session_service
assert gate.agent_hub is agent_hub
def test_gate_decision_dataclass_defaults():
"""GateDecision 默认字段正确。"""
def test_gate_decision_only_intent():
"""GateDecision 只有 intent 字段。"""
d = GateDecision(intent="chat")
assert d.intent == "chat"
import asyncio
from app.service.session_buffer import SessionBuffer
from app.infrastructure.session_store import clear_default_store_for_tests
@pytest.fixture
def message_gate_with_deps():
"""构造一个带假依赖的 MessageGate。"""
config_loader = MagicMock()
session_service = MagicMock()
post_reply_hook = MagicMock()
post_reply_hook.execute = AsyncMock()
agent_hub = MagicMock()
agent_hub.process_message = AsyncMock()
agent_hub.agents = {} # MessageGate._classify_and_rewrite 会读写此属性
# 提供 mock model,避免真实加载 models.json
mock_model = MagicMock()
gate = MessageGate(
config_loader=config_loader,
session_service=session_service,
post_reply_hook=post_reply_hook,
agent_hub=agent_hub,
main_agent_key="main",
model=mock_model,
)
return gate
@pytest.mark.asyncio
async def test_evaluate_pure_file_triggers_wait(message_gate_with_deps):
"""纯 file 消息应等待(用 monkey-patched 短等待避免测试慢)。"""
gate = message_gate_with_deps
# 用 0.1 秒等待代替 6 秒
from app.service import message_gate as mg_module
original_sleep = mg_module.asyncio.sleep
async def fast_sleep(_):
await original_sleep(0.01)
mg_module.asyncio.sleep = fast_sleep
try:
# 模拟 LLM 返回 actionable(patch 内部方法)
gate._classify_and_rewrite = AsyncMock(return_value=GateDecision(
intent="actionable",
rewritten_query="请分析文件 [url]",
))
# 追加 file 消息到 buffer
from app.infrastructure.session_store import SessionStore
clear_default_store_for_tests()
store = SessionStore()
buffer = SessionBuffer(store, "sess_001")
buffer.append({
"msg_id": "m1", "msg_type": "file",
"msg_content": "https://example.com/audio.mp3",
"sender_id": "u1", "msg_time": "t",
})
await gate.evaluate(
session_id="sess_001",
room_id="r1",
user_id="u1",
bot_id_mapping={"main": "bot-001"},
)
# 等待 0.01s 后分类被调用
assert gate._classify_and_rewrite.await_count == 1
finally:
mg_module.asyncio.sleep = original_sleep
assert not hasattr(d, "rewritten_query")
assert not hasattr(d, "reply")
@pytest.mark.asyncio
async def test_classify_casual_intent(message_gate_with_deps, monkeypatch):
"""_classify_and_rewrite 应正确解析 LLM 返回的 casual JSON。"""
gate = message_gate_with_deps
# Mock OpenAIChatModel 返回 casual JSON
fake_response_text = '{"intent": "casual", "reply": "早~"}'
gate.model = AsyncMock(return_value=MagicMock(
content=[{"type": "text", "text": fake_response_text}]
))
pending = [{"msg_id": "m1", "msg_type": "text", "msg_content": "早上好",
"sender_id": "u1", "msg_time": "t"}]
decision = await gate._classify_and_rewrite(
session_id="sess_001",
pending=pending,
agent_codes=["11", "14"],
)
assert decision.intent == "casual"
assert decision.reply == "早~"
@pytest.mark.asyncio
async def test_classify_actionable_with_rewrite(message_gate_with_deps):
"""actionable 分类应包含 rewritten_query。"""
gate = message_gate_with_deps
fake_response_text = '{"intent": "actionable", "rewritten_query": "请总结这个文件"}'
gate.model = AsyncMock(return_value=MagicMock(
content=[{"type": "text", "text": fake_response_text}]
))
pending = [{"msg_id": "m1", "msg_type": "text", "msg_content": "帮我总结",
"sender_id": "u1", "msg_time": "t"}]
decision = await gate._classify_and_rewrite(
session_id="sess_001",
pending=pending,
agent_codes=["11"],
async def test_classify_returns_chat_for_empty_pending():
"""空 pending → 返回 chat。"""
gate = MessageGate(
config_loader=MagicMock(),
session_service=MagicMock(),
post_reply_hook=MagicMock(),
agent_hub=MagicMock(),
main_agent_key="11",
model=MagicMock(),
)
assert decision.intent == "actionable"
assert decision.rewritten_query == "请总结这个文件"
decision = await gate._classify_and_rewrite(pending=[])
assert decision.intent == "chat"
@pytest.mark.asyncio
async def test_actionable_dispatches_to_agent_hub(message_gate_with_deps):
"""actionable 分支应直接 await AgentHub.process_message。"""
gate = message_gate_with_deps
gate.agent_hub.process_message = AsyncMock()
async def test_classify_activation_model_called():
"""LLM 返回 'pass' → GateDecision intent='pass'。"""
mock_model = AsyncMock()
mock_model_response = MagicMock()
mock_model_response.content = [{"type": "text", "text": "pass"}]
mock_model.return_value = mock_model_response
await gate._handle_actionable(
session_id="sess_001",
room_id="r1",
user_id="u1",
decision=GateDecision(intent="actionable", rewritten_query="请分析文件"),
pending=[{"msg_id": "m1", "msg_type": "file", "msg_content": "url",
"sender_id": "u1", "msg_time": "t"}],
bot_id_mapping={"main": "bot-001"},
)
gate.agent_hub.process_message.assert_awaited_once()
@pytest.mark.asyncio
async def test_actionable_extracts_file_url_from_file_type(message_gate_with_deps):
"""file 类型消息的 msg_content 应被提取为 file_url 传给 AgentHub。"""
gate = message_gate_with_deps
gate.agent_hub.process_message = AsyncMock()
await gate._handle_actionable(
session_id="sess_002",
room_id="r1",
user_id="u1",
decision=GateDecision(intent="actionable", rewritten_query="请总结会议"),
pending=[{"msg_id": "m1", "msg_type": "file", "msg_content": "https://oss.example.com/audio.mp3",
"sender_id": "u1", "msg_time": "t"}],
bot_id_mapping={"main": "bot-001"},
gate = MessageGate(
config_loader=MagicMock(),
session_service=MagicMock(),
post_reply_hook=MagicMock(),
agent_hub=MagicMock(),
main_agent_key="11",
model=mock_model,
)
gate.agent_hub.process_message.assert_awaited_once()
# 验证 file_url 参数正确传递
call_kwargs = gate.agent_hub.process_message.call_args.kwargs
assert call_kwargs.get("file_url") == "https://oss.example.com/audio.mp3"
pending = [{"msg_type": "text", "msg_content": "帮我整理会议纪要"}]
decision = await gate._classify_and_rewrite(pending=pending)
assert decision.intent == "pass"
mock_model.assert_called_once()
@pytest.mark.asyncio
async def test_actionable_still_extracts_image_url(message_gate_with_deps):
"""image 类型消息的 msg_content 也应被提取为 file_url(向后兼容)。"""
gate = message_gate_with_deps
gate.agent_hub.process_message = AsyncMock()
async def test_classify_activation_returns_chat_by_default():
"""LLM 返回未知内容 → 兜底 chat。"""
mock_model = AsyncMock()
mock_model_response = MagicMock()
mock_model_response.content = [{"type": "text", "text": "hello"}]
mock_model.return_value = mock_model_response
await gate._handle_actionable(
session_id="sess_003",
room_id="r1",
user_id="u1",
decision=GateDecision(intent="actionable", rewritten_query="这是什么图片"),
pending=[{"msg_id": "m1", "msg_type": "image", "msg_content": "https://oss.example.com/img.jpg",
"sender_id": "u1", "msg_time": "t"}],
bot_id_mapping={"main": "bot-001"},
gate = MessageGate(
config_loader=MagicMock(),
session_service=MagicMock(),
post_reply_hook=MagicMock(),
agent_hub=MagicMock(),
main_agent_key="11",
model=mock_model,
)
call_kwargs = gate.agent_hub.process_message.call_args.kwargs
assert call_kwargs.get("file_url") == "https://oss.example.com/img.jpg"
pending = [{"msg_type": "text", "msg_content": "谢谢大家"}]
decision = await gate._classify_and_rewrite(pending=pending)
assert decision.intent == "chat"
@pytest.mark.asyncio
async def test_incomplete_sends_reply_and_preserves_buffer(message_gate_with_deps):
"""incomplete 分支应发 IM 追问,且不清空 buffer。"""
gate = message_gate_with_deps
from app.infrastructure.session_store import SessionStore
from app.infrastructure.session_store import clear_default_store_for_tests
async def test_handle_chat_adds_user_message_to_history():
"""_handle_chat 追加用户消息到 conversation_history。"""
from app.infrastructure.session_store import SessionStore, clear_default_store_for_tests
clear_default_store_for_tests()
store = SessionStore()
buffer = SessionBuffer(store, "sess_inc")
buffer.append({
"msg_id": "m1", "msg_type": "file",
"msg_content": "https://example.com/audio.mp3",
"sender_id": "u1", "msg_time": "t",
})
sid = "test-chat-session"
await gate._handle_incomplete(
session_id="sess_inc",
room_id="r1",
user_id="u1",
decision=GateDecision(intent="incomplete", reply="这文件是用来做什么的?"),
pending=[{"msg_id": "m1", "msg_type": "file", "msg_content": "https://example.com/audio.mp3",
"sender_id": "u1", "msg_time": "t"}],
bot_id_mapping={"main": "bot-001"},
)
# IM 追问被发送
gate.post_reply_hook.execute.assert_awaited_once()
call_args = gate.post_reply_hook.execute.call_args[0][0]
assert call_args["response_content"] == "这文件是用来做什么的?"
# buffer 未被清空(evaluate 里 incomplete 分支不清空)
remaining = buffer.get_pending()
assert len(remaining) == 1
# SessionMemory.add() 要求 session 已存在
store.set(sid, {"conversation_history": [], "intent_session": ""})
mock_session_service = MagicMock()
mock_session_service.save_to_db = MagicMock()
@pytest.mark.asyncio
async def test_classify_file_only_as_incomplete(message_gate_with_deps):
"""file-only 消息应被 LLM 分类为 incomplete。"""
gate = message_gate_with_deps
fake_response_text = '{"intent": "incomplete", "reply": "这段录音需要转文字,还是做摘要?"}'
gate.model = AsyncMock(return_value=MagicMock(
content=[{"type": "text", "text": fake_response_text}]
))
pending = [{"msg_id": "m1", "msg_type": "file", "msg_content": "https://example.com/audio.mp3",
"sender_id": "u1", "msg_time": "t"}]
decision = await gate._classify_and_rewrite(
session_id="sess_file_only",
pending=pending,
agent_codes=["main"],
gate = MessageGate(
config_loader=MagicMock(),
session_service=mock_session_service,
post_reply_hook=MagicMock(),
agent_hub=MagicMock(),
main_agent_key="11",
model=MagicMock(),
)
assert decision.intent == "incomplete"
assert decision.reply == "这段录音需要转文字,还是做摘要?"
# 验证发给 LLM 的 merged_text 带了类型标注
call_args = gate.model.call_args
messages = call_args[1]["messages"] if "messages" in call_args[1] else call_args[0][0]
user_content = messages[1]["content"]
assert "[文件:" in user_content
@pytest.mark.asyncio
async def test_classify_task_without_resource_is_incomplete(message_gate_with_deps):
"""纯文字 '帮我整理会议纪要' 无文件 → incomplete(不能复用历史链接)。"""
gate = message_gate_with_deps
pending = [{"msg_type": "text", "msg_content": "好的"}]
from app.config.settings import AgentConfig
gate.agent_hub.agents = {
"agent_meeting": AgentConfig(
name="会议Agent", code="17",
prompt="你是广联数科的会议纪要助手,职责包括:音频转写、会议纪要整理。",
is_steward=False, skills=["meeting_minutes"],
),
}
await gate._handle_chat(session_id=sid, pending=pending)
fake_response = '{"intent": "incomplete", "reply": "请提供需要处理的音频文件"}'
gate.model = AsyncMock(return_value=MagicMock(
content=[{"type": "text", "text": fake_response}]
))
pending = [{"msg_id": "m1", "msg_type": "text", "msg_content": "帮我整理成会议纪要",
"sender_id": "u1", "msg_time": "t"}]
decision = await gate._classify_and_rewrite(
session_id="sess_002",
pending=pending,
agent_codes=["agent_meeting"],
)
assert decision.intent == "incomplete"
assert "音频" in (decision.reply or "")
# 验证 system prompt 注入了 agent 职责
call_args = gate.model.call_args
messages = call_args[1]["messages"] if "messages" in call_args[1] else call_args[0][0]
system_content = messages[0]["content"]
assert "音频转写" in system_content
data = store.get(sid)
history = data.get("conversation_history", [])
assert len(history) == 1
assert history[0]["role"] == "user"
assert history[0]["content"] == "好的"
mock_session_service.save_to_db.assert_called_once_with(sid)
@pytest.mark.asyncio
async def test_classify_actionable_with_resource_present(message_gate_with_deps):
"""有文件+意图 → actionable(文件在文本消息中作为 URL)。"""
gate = message_gate_with_deps
from app.config.settings import AgentConfig
gate.agent_hub.agents = {
"agent_meeting": AgentConfig(
name="会议Agent", code="17",
prompt="你是广联数科的会议纪要助手,职责包括:音频转写。",
is_steward=False, skills=["meeting_minutes"],
),
}
fake_response = '{"intent": "actionable", "rewritten_query": "将音频转文字并整理会议纪要"}'
gate.model = AsyncMock(return_value=MagicMock(
content=[{"type": "text", "text": fake_response}]
))
async def test_handle_actionable_calls_agent_hub():
"""_handle_actionable 调用 agent_hub.process_message。"""
mock_agent_hub = MagicMock()
mock_agent_hub.process_message = AsyncMock()
pending = [
{"msg_id": "m1", "msg_type": "text", "msg_content": "https://example.com/audio.mp3",
"sender_id": "u1", "msg_time": "t"},
{"msg_id": "m2", "msg_type": "text", "msg_content": "帮我整理成会议纪要",
"sender_id": "u1", "msg_time": "t"},
]
decision = await gate._classify_and_rewrite(
session_id="sess_003",
pending=pending,
agent_codes=["agent_meeting"],
gate = MessageGate(
config_loader=MagicMock(),
session_service=MagicMock(),
post_reply_hook=MagicMock(),
agent_hub=mock_agent_hub,
main_agent_key="11",
model=MagicMock(),
)
assert decision.intent == "actionable"
assert "音频" in (decision.rewritten_query or "")
@pytest.mark.asyncio
async def test_steward_agent_excluded_from_prompt(message_gate_with_deps):
"""is_steward=True 的主 agent 不注入 system prompt。"""
gate = message_gate_with_deps
decision = GateDecision(intent="pass")
pending = [{"msg_type": "text", "msg_content": "创建任务"}]
from app.config.settings import AgentConfig
gate.agent_hub.agents = {
"agent_main": AgentConfig(
name="管家Agent", code="11",
prompt="你是管家,负责协调各岗位Agent。",
is_steward=True, skills=[],
),
"agent_meeting": AgentConfig(
name="会议Agent", code="17",
prompt="会议纪要助手,职责:音频转写。",
is_steward=False, skills=["meeting_minutes"],
),
}
fake_response = '{"intent": "incomplete", "reply": "请提供音频文件"}'
gate.model = AsyncMock(return_value=MagicMock(
content=[{"type": "text", "text": fake_response}]
))
pending = [{"msg_id": "m1", "msg_type": "text", "msg_content": "帮我整理纪要",
"sender_id": "u1", "msg_time": "t"}]
await gate._classify_and_rewrite(
session_id="sess_004",
await gate._handle_actionable(
session_id="test-session",
room_id="room-1",
user_id="user-1",
decision=decision,
pending=pending,
agent_codes=["agent_main", "agent_meeting"],
bot_id_mapping={"11": "bot_main"},
)
# 验证 system prompt 不含管家 agent 的 prompt
call_args = gate.model.call_args
messages = call_args[1]["messages"] if "messages" in call_args[1] else call_args[0][0]
system_content = messages[0]["content"]
assert "音频转写" in system_content # 子 agent 注入
assert "协调各岗位" not in system_content # 主 agent 不注入
class TestMergeTextFromPending:
"""测试 _merge_text_from_pending 辅助方法。"""
def test_text_messages_concatenated(self):
from app.service.message_gate import MessageGate
pending = [
{"msg_type": "text", "msg_content": "第一行"},
{"msg_type": "text", "msg_content": "第二行"},
]
result = MessageGate._merge_text_from_pending(pending)
assert result == "第一行\n第二行"
def test_non_text_tagged_as_file(self):
from app.service.message_gate import MessageGate
pending = [
{"msg_type": "file", "msg_content": "https://example.com/audio.wav"},
]
result = MessageGate._merge_text_from_pending(pending)
assert result == "[文件: https://example.com/audio.wav]"
def test_mixed_text_and_file(self):
from app.service.message_gate import MessageGate
pending = [
{"msg_type": "text", "msg_content": "请总结这个录音"},
{"msg_type": "audio", "msg_content": "https://example.com/audio.wav"},
]
result = MessageGate._merge_text_from_pending(pending)
assert "请总结这个录音" in result
assert "[文件: https://example.com/audio.wav]" in result
def test_empty_pending(self):
from app.service.message_gate import MessageGate
result = MessageGate._merge_text_from_pending([])
assert result == ""
def test_empty_content_skipped(self):
from app.service.message_gate import MessageGate
pending = [
{"msg_type": "text", "msg_content": ""},
{"msg_type": "text", "msg_content": "有效内容"},
]
result = MessageGate._merge_text_from_pending(pending)
assert result == "有效内容"
class TestHandleActionableContentPreservation:
"""测试 _handle_actionable 的原文合并逻辑。"""
@pytest.mark.asyncio
async def test_handle_actionable_preserves_original_text(self, message_gate_with_deps):
"""rewritten_query 使用指代时,原文应被合并到 query 中。"""
gate = message_gate_with_deps
pending = [
{"msg_type": "text", "msg_content": "130行的转写文本内容..."},
]
decision = GateDecision(
intent="actionable",
rewritten_query="请将上面提供的对话记录整理成会议纪要",
)
await gate._handle_actionable(
session_id="sess_test",
room_id="room1",
user_id="u1",
decision=decision,
pending=pending,
bot_id_mapping={"agent_meeting": "bot_123"},
)
call_args = gate.agent_hub.process_message.call_args
query = call_args.kwargs["user_query"]
assert "请将上面提供的对话记录整理成会议纪要" in query
assert "130行的转写文本内容..." in query
@pytest.mark.asyncio
async def test_handle_actionable_no_duplicate_when_rewritten_contains_original(self, message_gate_with_deps):
"""rewritten_query 已包含原文时,不重复拼接。"""
gate = message_gate_with_deps
pending = [
{"msg_type": "text", "msg_content": "你好"},
]
decision = GateDecision(
intent="actionable",
rewritten_query="你好,请帮我查一下天气",
)
await gate._handle_actionable(
session_id="sess_test",
room_id="room1",
user_id="u1",
decision=decision,
pending=pending,
bot_id_mapping={},
)
call_args = gate.agent_hub.process_message.call_args
query = call_args.kwargs["user_query"]
assert query.count("你好") == 1
@pytest.mark.asyncio
async def test_handle_actionable_empty_rewritten_uses_original(self, message_gate_with_deps):
"""rewritten_query 为空时,用原文兜底。"""
gate = message_gate_with_deps
pending = [
{"msg_type": "text", "msg_content": "请总结这个录音"},
]
decision = GateDecision(intent="actionable", rewritten_query="")
await gate._handle_actionable(
session_id="sess_test",
room_id="room1",
user_id="u1",
decision=decision,
pending=pending,
bot_id_mapping={},
)
call_args = gate.agent_hub.process_message.call_args
query = call_args.kwargs["user_query"]
assert query == "请总结这个录音"
\ No newline at end of file
mock_agent_hub.process_message.assert_called_once()
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!