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(): ...@@ -56,6 +56,27 @@ def _make_test_hub():
test_hub = _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(): def _override_get_agent_hub():
return test_hub return test_hub
...@@ -87,9 +108,8 @@ def clean_session_tables(): ...@@ -87,9 +108,8 @@ def clean_session_tables():
class TestChatCompletionsAPI: class TestChatCompletionsAPI:
def test_default_routing_to_main(self): def test_default_routing_to_main(self):
"""未 @提及 且 session 无继承 → 路由到 main""" """未 @提及 且 session 无继承 → 路由到 main"""
with patch.object(test_hub, "_call_model", new_callable=AsyncMock) as mock_call: with patch.object(test_hub, 'model', new=_make_mock_model_reply("你好,我是智能助手,有什么可以帮助你的?")):
mock_call.return_value = "你好,我是智能助手,有什么可以帮助你的?" with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
resp = client.post( resp = client.post(
"/api/v1/chat/completions", "/api/v1/chat/completions",
json={ json={
...@@ -109,9 +129,8 @@ class TestChatCompletionsAPI: ...@@ -109,9 +129,8 @@ class TestChatCompletionsAPI:
def test_mention_routing_to_sub_agent(self): def test_mention_routing_to_sub_agent(self):
"""@提及 meeting → 直接路由到 meeting""" """@提及 meeting → 直接路由到 meeting"""
with patch.object(test_hub, "_call_model", new_callable=AsyncMock) as mock_call: with patch.object(test_hub, 'model', new=_make_mock_model_reply("已为你整理上次会议纪要如下:1. 项目进度讨论...")):
mock_call.return_value = "已为你整理上次会议纪要如下:1. 项目进度讨论..." with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
resp = client.post( resp = client.post(
"/api/v1/chat/completions", "/api/v1/chat/completions",
json={ json={
...@@ -130,9 +149,8 @@ class TestChatCompletionsAPI: ...@@ -130,9 +149,8 @@ class TestChatCompletionsAPI:
def test_inheritance_routing(self): def test_inheritance_routing(self):
"""首次 @meeting,第二次不 @mention → 继承 meeting""" """首次 @meeting,第二次不 @mention → 继承 meeting"""
with patch.object(test_hub, "_call_model", new_callable=AsyncMock) as mock_call: with patch.object(test_hub, 'model', new=_make_mock_model_reply("会议纪要内容...")):
mock_call.return_value = "会议纪要内容..." with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
# 请求 1:@mention # 请求 1:@mention
r1 = client.post( r1 = client.post(
"/api/v1/chat/completions", "/api/v1/chat/completions",
...@@ -163,9 +181,8 @@ class TestChatCompletionsAPI: ...@@ -163,9 +181,8 @@ class TestChatCompletionsAPI:
def test_messages_accumulate_in_session(self): def test_messages_accumulate_in_session(self):
"""同一 session 多次请求,消息累积""" """同一 session 多次请求,消息累积"""
with patch.object(test_hub, "_call_model", new_callable=AsyncMock) as mock_call: with patch.object(test_hub, 'model', new=_make_mock_model_reply("回复内容")):
mock_call.return_value = "回复内容" with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
for i in range(3): for i in range(3):
resp = client.post( resp = client.post(
"/api/v1/chat/completions", "/api/v1/chat/completions",
...@@ -184,11 +201,11 @@ class TestChatCompletionsAPI: ...@@ -184,11 +201,11 @@ class TestChatCompletionsAPI:
def test_model_error_returns_502(self): def test_model_error_returns_502(self):
"""模型调用失败 → 502 Bad Gateway""" """模型调用失败 → 502 Bad Gateway"""
from app.service.agent_hub import AgentHubError mock_model = AsyncMock(side_effect=AgentHubError("模型API返回错误: 500"))
mock_model.stream = False
with patch.object(test_hub, "_call_model", new_callable=AsyncMock) as mock_call:
mock_call.side_effect = AgentHubError("模型API返回错误: 500")
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( resp = client.post(
"/api/v1/chat/completions", "/api/v1/chat/completions",
json={ json={
...@@ -211,9 +228,8 @@ class TestChatCompletionsAPI: ...@@ -211,9 +228,8 @@ class TestChatCompletionsAPI:
def test_channel_default_value(self): def test_channel_default_value(self):
"""channel 字段默认为 wechat_group""" """channel 字段默认为 wechat_group"""
with patch.object(test_hub, "_call_model", new_callable=AsyncMock) as mock_call: with patch.object(test_hub, 'model', new=_make_mock_model_reply("收到")):
mock_call.return_value = "收到" with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
resp = client.post( resp = client.post(
"/api/v1/chat/completions", "/api/v1/chat/completions",
json={ json={
...@@ -346,9 +362,8 @@ class TestAgentHubRouting: ...@@ -346,9 +362,8 @@ class TestAgentHubRouting:
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_process_message_returns_routing_metadata(self): async def test_process_message_returns_routing_metadata(self):
"""验证返回结构包含所有必需字段""" """验证返回结构包含所有必需字段"""
with patch.object(test_hub, "_call_model", new_callable=AsyncMock) as mock_call: with patch.object(test_hub, 'model', new=_make_mock_model_reply("回复内容")):
mock_call.return_value = "回复内容" with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
result = await test_hub.process_message( result = await test_hub.process_message(
session_id="sess_meta_001", session_id="sess_meta_001",
room_id="room_001", room_id="room_001",
...@@ -366,9 +381,8 @@ class TestAgentHubRouting: ...@@ -366,9 +381,8 @@ class TestAgentHubRouting:
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_preserves_session_across_calls(self): async def test_preserves_session_across_calls(self):
"""同一 session_id 多次调用,消息累积在同一 session""" """同一 session_id 多次调用,消息累积在同一 session"""
with patch.object(test_hub, "_call_model", new_callable=AsyncMock) as mock_call: with patch.object(test_hub, 'model', new=_make_mock_model_reply("回复")):
mock_call.return_value = "回复" with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
sid = "sess_persist_001" sid = "sess_persist_001"
await test_hub.process_message( await test_hub.process_message(
session_id=sid, room_id="r1", user_id="u1", user_query="Q1" session_id=sid, room_id="r1", user_id="u1", user_query="Q1"
...@@ -422,11 +436,11 @@ class TestCollaboration: ...@@ -422,11 +436,11 @@ class TestCollaboration:
return "待办: 1.提交Q2预算 2.人员调整方案" return "待办: 1.提交Q2预算 2.人员调整方案"
return "" return ""
async def noop_format(msgs): model_mock = AsyncMock(side_effect=model_side_effect)
return msgs model_mock.stream = False
with patch.object(test_hub, 'model', new=AsyncMock(side_effect=model_side_effect)): 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.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
with patch.object(test_hub, '_call_sub_agent', new=AsyncMock(side_effect=mock_sub_call)): with patch.object(test_hub, '_call_sub_agent', new=AsyncMock(side_effect=mock_sub_call)):
result = await test_hub.process_message( result = await test_hub.process_message(
session_id="sess_collab_001", session_id="sess_collab_001",
...@@ -438,30 +452,36 @@ class TestCollaboration: ...@@ -438,30 +452,36 @@ class TestCollaboration:
@pytest.mark.asyncio @pytest.mark.asyncio
async def test_max_iterations_limit(self): 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 = [ tool_call_blocks = [
{"type": "tool_use", "id": "call_x", "name": "call_sub_agent", {"type": "tool_use", "id": "call_x", "name": "call_sub_agent",
"input": {"agent_code": "meeting", "instruction": "x"}} "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 = MagicMock()
if tools is None:
# _summarizing() call — return text
r.content = [{"type": "text", "text": "已达最大迭代次数,总结当前情况。"}]
else:
r.content = tool_call_blocks r.content = tool_call_blocks
return r return r
async def mock_sub_call(*args, **kwargs): async def mock_sub_call(*args, **kwargs):
return "result" return "result"
async def noop_format(msgs): model_mock_2 = AsyncMock(side_effect=model_side_effect)
return msgs model_mock_2.stream = False
with patch.object(test_hub, 'model', new=AsyncMock(side_effect=model_side_effect)): 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.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
with patch.object(test_hub, '_call_sub_agent', new=AsyncMock(side_effect=mock_sub_call)): with patch.object(test_hub, '_call_sub_agent', new=AsyncMock(side_effect=mock_sub_call)):
with pytest.raises(AgentHubError, match="最大次数"): result = await test_hub.process_message(
await test_hub.process_message(
session_id="sess_limit_001", session_id="sess_limit_001",
room_id="room_001", room_id="room_001",
user_id="u1", user_id="u1",
user_query="test", 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!