Commit e8e5062b by sunqi02

test: adapt mocks from _call_model to model+formatter for ReActAgent

ReActAgent internally calls shared model and formatter singletons.
Mock at that level instead of the removed _call_model method.
Key fix: set mock_model.stream = False so ReActAgent uses non-streaming path.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
1 parent d41eb336
......@@ -56,6 +56,27 @@ def _make_test_hub():
test_hub = _make_test_hub()
def _make_mock_model_reply(text: str):
"""创建一个返回纯文本的 mock model,供 ReActAgent 内部调用。"""
def _make_resp(blocks):
r = MagicMock()
r.content = blocks
return r
async def side_effect(*args, **kwargs):
return _make_resp([{"type": "text", "text": text}])
mock = AsyncMock(side_effect=side_effect)
mock.stream = False # 关键:让 ReActAgent 走非流式路径
return mock
async def _noop_format(msgs):
"""透传 formatter,让 ReActAgent 直接传递 Msg 列表给 mock model。"""
return msgs
def _override_get_agent_hub():
return test_hub
......@@ -87,119 +108,115 @@ def clean_session_tables():
class TestChatCompletionsAPI:
def test_default_routing_to_main(self):
"""未 @提及 且 session 无继承 → 路由到 main"""
with patch.object(test_hub, "_call_model", new_callable=AsyncMock) as mock_call:
mock_call.return_value = "你好,我是智能助手,有什么可以帮助你的?"
resp = client.post(
"/api/v1/chat/completions",
json={
"session_id": "sess_api_001",
"user_id": "user_001",
"room_id": "room_001",
"query": "你好",
},
)
assert resp.status_code == 200
data = resp.json()["data"]
assert data["response_agent_code"] == "main"
assert data["routing_reason"] == "default"
assert len(data["response_content"]) > 0
assert data["processing_time_ms"] > 0
with patch.object(test_hub, 'model', new=_make_mock_model_reply("你好,我是智能助手,有什么可以帮助你的?")):
with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
resp = client.post(
"/api/v1/chat/completions",
json={
"session_id": "sess_api_001",
"user_id": "user_001",
"room_id": "room_001",
"query": "你好",
},
)
assert resp.status_code == 200
data = resp.json()["data"]
assert data["response_agent_code"] == "main"
assert data["routing_reason"] == "default"
assert len(data["response_content"]) > 0
assert data["processing_time_ms"] > 0
def test_mention_routing_to_sub_agent(self):
"""@提及 meeting → 直接路由到 meeting"""
with patch.object(test_hub, "_call_model", new_callable=AsyncMock) as mock_call:
mock_call.return_value = "已为你整理上次会议纪要如下:1. 项目进度讨论..."
resp = client.post(
"/api/v1/chat/completions",
json={
"session_id": "sess_api_002",
"user_id": "user_001",
"room_id": "room_001",
"query": "整理会议纪要",
"mentioned_agent_code": "meeting",
},
)
assert resp.status_code == 200
data = resp.json()["data"]
assert data["response_agent_code"] == "meeting"
assert data["routing_reason"] == "mention"
with patch.object(test_hub, 'model', new=_make_mock_model_reply("已为你整理上次会议纪要如下:1. 项目进度讨论...")):
with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
resp = client.post(
"/api/v1/chat/completions",
json={
"session_id": "sess_api_002",
"user_id": "user_001",
"room_id": "room_001",
"query": "整理会议纪要",
"mentioned_agent_code": "meeting",
},
)
assert resp.status_code == 200
data = resp.json()["data"]
assert data["response_agent_code"] == "meeting"
assert data["routing_reason"] == "mention"
def test_inheritance_routing(self):
"""首次 @meeting,第二次不 @mention → 继承 meeting"""
with patch.object(test_hub, "_call_model", new_callable=AsyncMock) as mock_call:
mock_call.return_value = "会议纪要内容..."
# 请求 1:@mention
r1 = client.post(
"/api/v1/chat/completions",
json={
"session_id": "sess_api_003",
"user_id": "user_001",
"room_id": "room_001",
"query": "查会议纪要",
"mentioned_agent_code": "meeting",
},
)
assert r1.status_code == 200
assert r1.json()["data"]["response_agent_code"] == "meeting"
# 请求 2:无 mention,应继承 meeting
r2 = client.post(
"/api/v1/chat/completions",
json={
"session_id": "sess_api_003",
"user_id": "user_001",
"room_id": "room_001",
"query": "再查一个",
},
)
assert r2.status_code == 200
assert r2.json()["data"]["response_agent_code"] == "meeting"
assert r2.json()["data"]["routing_reason"] == "inheritance"
def test_messages_accumulate_in_session(self):
"""同一 session 多次请求,消息累积"""
with patch.object(test_hub, "_call_model", new_callable=AsyncMock) as mock_call:
mock_call.return_value = "回复内容"
with patch.object(test_hub, 'model', new=_make_mock_model_reply("会议纪要内容...")):
with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
# 请求 1:@mention
r1 = client.post(
"/api/v1/chat/completions",
json={
"session_id": "sess_api_003",
"user_id": "user_001",
"room_id": "room_001",
"query": "查会议纪要",
"mentioned_agent_code": "meeting",
},
)
assert r1.status_code == 200
assert r1.json()["data"]["response_agent_code"] == "meeting"
for i in range(3):
resp = client.post(
# 请求 2:无 mention,应继承 meeting
r2 = client.post(
"/api/v1/chat/completions",
json={
"session_id": "sess_api_004",
"session_id": "sess_api_003",
"user_id": "user_001",
"room_id": "room_001",
"query": f"问题{i + 1}",
"query": "再查一个",
},
)
assert resp.status_code == 200
assert r2.status_code == 200
assert r2.json()["data"]["response_agent_code"] == "meeting"
assert r2.json()["data"]["routing_reason"] == "inheritance"
# Task 0: messages are in KV store, verify via SessionService
messages = test_hub.session_service.get_session_messages("sess_api_004")
assert len(messages) == 6 # 3 user + 3 assistant
def test_messages_accumulate_in_session(self):
"""同一 session 多次请求,消息累积"""
with patch.object(test_hub, 'model', new=_make_mock_model_reply("回复内容")):
with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
for i in range(3):
resp = client.post(
"/api/v1/chat/completions",
json={
"session_id": "sess_api_004",
"user_id": "user_001",
"room_id": "room_001",
"query": f"问题{i + 1}",
},
)
assert resp.status_code == 200
# Task 0: messages are in KV store, verify via SessionService
messages = test_hub.session_service.get_session_messages("sess_api_004")
assert len(messages) == 6 # 3 user + 3 assistant
def test_model_error_returns_502(self):
"""模型调用失败 → 502 Bad Gateway"""
from app.service.agent_hub import AgentHubError
with patch.object(test_hub, "_call_model", new_callable=AsyncMock) as mock_call:
mock_call.side_effect = AgentHubError("模型API返回错误: 500")
mock_model = AsyncMock(side_effect=AgentHubError("模型API返回错误: 500"))
mock_model.stream = False
resp = client.post(
"/api/v1/chat/completions",
json={
"session_id": "sess_err_001",
"user_id": "user_001",
"room_id": "room_001",
"query": "触发错误",
},
)
with patch.object(test_hub, 'model', new=mock_model):
with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
resp = client.post(
"/api/v1/chat/completions",
json={
"session_id": "sess_err_001",
"user_id": "user_001",
"room_id": "room_001",
"query": "触发错误",
},
)
assert resp.status_code == 502
assert resp.status_code == 502
def test_missing_required_fields(self):
"""缺少必填字段 → 400(自定义异常处理器将 422 转为 400)"""
......@@ -211,24 +228,23 @@ class TestChatCompletionsAPI:
def test_channel_default_value(self):
"""channel 字段默认为 wechat_group"""
with patch.object(test_hub, "_call_model", new_callable=AsyncMock) as mock_call:
mock_call.return_value = "收到"
resp = client.post(
"/api/v1/chat/completions",
json={
"session_id": "sess_api_005",
"user_id": "user_001",
"room_id": "room_001",
"query": "测试",
},
)
assert resp.status_code == 200
# Task 0: verify channel from KV store, not DB
session = test_hub.session_service.get_session("sess_api_005")
assert session is not None
assert session.channel == "wechat_group"
with patch.object(test_hub, 'model', new=_make_mock_model_reply("收到")):
with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
resp = client.post(
"/api/v1/chat/completions",
json={
"session_id": "sess_api_005",
"user_id": "user_001",
"room_id": "room_001",
"query": "测试",
},
)
assert resp.status_code == 200
# Task 0: verify channel from KV store, not DB
session = test_hub.session_service.get_session("sess_api_005")
assert session is not None
assert session.channel == "wechat_group"
# ═══════════════════════════════════════════════════════════════════
......@@ -346,40 +362,38 @@ class TestAgentHubRouting:
@pytest.mark.asyncio
async def test_process_message_returns_routing_metadata(self):
"""验证返回结构包含所有必需字段"""
with patch.object(test_hub, "_call_model", new_callable=AsyncMock) as mock_call:
mock_call.return_value = "回复内容"
result = await test_hub.process_message(
session_id="sess_meta_001",
room_id="room_001",
user_id="user_001",
user_query="测试问题",
)
assert "session_id" in result
assert result["response_agent_code"] == "main"
assert result["routing_reason"] == "default"
assert result["response_content"] == "回复内容"
assert isinstance(result["processing_time_ms"], float)
assert result["processing_time_ms"] >= 0
with patch.object(test_hub, 'model', new=_make_mock_model_reply("回复内容")):
with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
result = await test_hub.process_message(
session_id="sess_meta_001",
room_id="room_001",
user_id="user_001",
user_query="测试问题",
)
assert "session_id" in result
assert result["response_agent_code"] == "main"
assert result["routing_reason"] == "default"
assert result["response_content"] == "回复内容"
assert isinstance(result["processing_time_ms"], float)
assert result["processing_time_ms"] >= 0
@pytest.mark.asyncio
async def test_preserves_session_across_calls(self):
"""同一 session_id 多次调用,消息累积在同一 session"""
with patch.object(test_hub, "_call_model", new_callable=AsyncMock) as mock_call:
mock_call.return_value = "回复"
sid = "sess_persist_001"
await test_hub.process_message(
session_id=sid, room_id="r1", user_id="u1", user_query="Q1"
)
await test_hub.process_message(
session_id=sid, room_id="r1", user_id="u1", user_query="Q2"
)
with patch.object(test_hub, 'model', new=_make_mock_model_reply("回复")):
with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
sid = "sess_persist_001"
await test_hub.process_message(
session_id=sid, room_id="r1", user_id="u1", user_query="Q1"
)
await test_hub.process_message(
session_id=sid, room_id="r1", user_id="u1", user_query="Q2"
)
# Task 0: messages are in KV store
messages = test_hub.session_service.get_session_messages(sid)
assert len(messages) == 4 # 2 user + 2 assistant
# Task 0: messages are in KV store
messages = test_hub.session_service.get_session_messages(sid)
assert len(messages) == 4 # 2 user + 2 assistant
# ═══════════════════════════════════════════════════════════════════
......@@ -422,11 +436,11 @@ class TestCollaboration:
return "待办: 1.提交Q2预算 2.人员调整方案"
return ""
async def noop_format(msgs):
return msgs
model_mock = AsyncMock(side_effect=model_side_effect)
model_mock.stream = False
with patch.object(test_hub, 'model', new=AsyncMock(side_effect=model_side_effect)):
with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=noop_format)):
with patch.object(test_hub, 'model', new=model_mock):
with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
with patch.object(test_hub, '_call_sub_agent', new=AsyncMock(side_effect=mock_sub_call)):
result = await test_hub.process_message(
session_id="sess_collab_001",
......@@ -438,30 +452,36 @@ class TestCollaboration:
@pytest.mark.asyncio
async def test_max_iterations_limit(self):
"""Loop exceeding 10 iterations should raise AgentHubError."""
"""Loop exceeding 10 iterations — ReActAgent generates summary, no exception."""
tool_call_blocks = [
{"type": "tool_use", "id": "call_x", "name": "call_sub_agent",
"input": {"agent_code": "meeting", "instruction": "x"}}
]
async def model_side_effect(*args, **kwargs):
async def model_side_effect(prompt, tools=None, **kwargs):
r = MagicMock()
r.content = tool_call_blocks
if tools is None:
# _summarizing() call — return text
r.content = [{"type": "text", "text": "已达最大迭代次数,总结当前情况。"}]
else:
r.content = tool_call_blocks
return r
async def mock_sub_call(*args, **kwargs):
return "result"
async def noop_format(msgs):
return msgs
model_mock_2 = AsyncMock(side_effect=model_side_effect)
model_mock_2.stream = False
with patch.object(test_hub, 'model', new=AsyncMock(side_effect=model_side_effect)):
with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=noop_format)):
with patch.object(test_hub, 'model', new=model_mock_2):
with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
with patch.object(test_hub, '_call_sub_agent', new=AsyncMock(side_effect=mock_sub_call)):
with pytest.raises(AgentHubError, match="最大次数"):
await test_hub.process_message(
session_id="sess_limit_001",
room_id="room_001",
user_id="u1",
user_query="test",
)
result = await test_hub.process_message(
session_id="sess_limit_001",
room_id="room_001",
user_id="u1",
user_query="test",
)
# ReActAgent hits max_iters and _summarizing() generates text
assert result["response_content"] is not None
assert len(result["response_content"]) > 0
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!