test_message_gate.py 4.59 KB
"""MessageGate 激活识别测试。"""
import pytest
from unittest.mock import MagicMock, AsyncMock
from app.service.message_gate import MessageGate, GateDecision


def test_message_gate_can_be_constructed():
    """MessageGate 应能通过依赖注入的方式构造。"""
    gate = MessageGate(
        config_loader=MagicMock(),
        session_service=MagicMock(),
        post_reply_hook=MagicMock(),
        agent_hub=MagicMock(),
        main_agent_key="11",
        model=MagicMock(),
    )
    assert gate is not None


def test_gate_decision_only_intent():
    """GateDecision 只有 intent 字段。"""
    d = GateDecision(intent="chat")
    assert d.intent == "chat"
    assert not hasattr(d, "rewritten_query")
    assert not hasattr(d, "reply")


@pytest.mark.asyncio
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(),
    )
    decision = await gate._classify_and_rewrite(pending=[])
    assert decision.intent == "chat"


@pytest.mark.asyncio
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

    gate = MessageGate(
        config_loader=MagicMock(),
        session_service=MagicMock(),
        post_reply_hook=MagicMock(),
        agent_hub=MagicMock(),
        main_agent_key="11",
        model=mock_model,
    )
    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_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

    gate = MessageGate(
        config_loader=MagicMock(),
        session_service=MagicMock(),
        post_reply_hook=MagicMock(),
        agent_hub=MagicMock(),
        main_agent_key="11",
        model=mock_model,
    )
    pending = [{"msg_type": "text", "msg_content": "谢谢大家"}]
    decision = await gate._classify_and_rewrite(pending=pending)
    assert decision.intent == "chat"


@pytest.mark.asyncio
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()
    sid = "test-chat-session"

    # SessionMemory.add() 要求 session 已存在
    store.set(sid, {"conversation_history": [], "intent_session": ""})

    mock_session_service = MagicMock()
    mock_session_service.save_to_db = MagicMock()

    gate = MessageGate(
        config_loader=MagicMock(),
        session_service=mock_session_service,
        post_reply_hook=MagicMock(),
        agent_hub=MagicMock(),
        main_agent_key="11",
        model=MagicMock(),
    )
    pending = [{"msg_type": "text", "msg_content": "好的"}]

    await gate._handle_chat(session_id=sid, pending=pending)

    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_handle_actionable_calls_agent_hub():
    """_handle_actionable 调用 agent_hub.process_message。"""
    mock_agent_hub = MagicMock()
    mock_agent_hub.process_message = AsyncMock()

    gate = MessageGate(
        config_loader=MagicMock(),
        session_service=MagicMock(),
        post_reply_hook=MagicMock(),
        agent_hub=mock_agent_hub,
        main_agent_key="11",
        model=MagicMock(),
    )
    decision = GateDecision(intent="pass")
    pending = [{"msg_type": "text", "msg_content": "创建任务"}]

    await gate._handle_actionable(
        session_id="test-session",
        room_id="room-1",
        user_id="user-1",
        decision=decision,
        pending=pending,
        bot_id_mapping={"11": "bot_main"},
    )

    mock_agent_hub.process_message.assert_called_once()