test_agent_hub.py
28.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
from fastapi.testclient import TestClient
from app.main import app as fastapi_app
# ── AgentHub 测试实例 ────────────────────────────────────────────
from app.config.loader import ConfigLoader
from app.service.active_session_service import ActiveSessionService
from app.service.agent_hub import AgentHub, AgentHubError
from app.service.memory import SessionMemory
def _make_test_hub():
session_service = ActiveSessionService()
im_service = MagicMock()
im_service.send_message = AsyncMock(return_value={"code": 200})
return AgentHub(
config_loader=ConfigLoader(),
session_service=session_service,
im_service=im_service,
)
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
from app.api.v1.endpoints.agent_hub import get_agent_hub
fastapi_app.dependency_overrides[get_agent_hub] = _override_get_agent_hub
client = TestClient(fastapi_app)
# ── Helper: 构造新格式请求体 ──
def _make_request(
query: str = "你好",
agents: list = None,
group_contact_id: str = "room_001",
sender_id: str = "user_001",
extra_messages: list = None,
) -> dict:
"""构造符合新 API 格式的请求体。session_id = group_contact_id。"""
body = {
"group": {
"group_contact_id": group_contact_id,
"group_name": "测试群",
"bot_code": "test_bot",
},
"position": {
"position_id": 1,
"position_code": "store_sales",
"position_name": "驻店销售岗",
},
"agents": agents or [{"agent_id": 14, "agent_name": "会议纪要 Agent"}],
"messages": [
{
"msg_id": "m1",
"msg_time": "2026-05-23T10:00:00Z",
"sender_id": sender_id,
"sender_name": "测试用户",
"msg_type": "text",
"msg_content": query,
"payload": {},
}
],
}
if extra_messages:
body["messages"].extend(extra_messages)
return body
def _get_session_messages(session_id: str) -> list:
"""Helper: 从 SessionStore 获取消息历史"""
data = test_hub.session_service.store.get(session_id)
if data:
return data.get("conversation_history", [])
return []
# ═══════════════════════════════════════════════════════════════════
# API 层集成测试 — POST /api/v1/chat/completions (新异步格式)
# ═══════════════════════════════════════════════════════════════════
class TestChatCompletionsAPI:
def test_returns_200_with_new_format(self):
"""新格式请求 → 立即返回 200 + session_id (=group_contact_id)"""
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=_make_request(group_contact_id="sess_api_001", query="你好"),
)
assert resp.status_code == 200
data = resp.json()["data"]
assert data["status"] == "ok"
assert data["session_id"] == "sess_api_001"
def test_session_created_from_group_contact_id(self):
"""group_contact_id → session_id + room_id, 会话被创建"""
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=_make_request(
query="测试",
group_contact_id="grp_room_99",
),
)
assert resp.status_code == 200
data = resp.json()["data"]
assert data["session_id"] == "grp_room_99"
session_data = test_hub.session_service.store.get("grp_room_99")
assert session_data is not None
assert session_data["room_id"] == "grp_room_99"
def test_user_id_from_last_message_sender(self):
"""user_id 从 messages 最后一条消息的 sender_id 推导"""
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=_make_request(
group_contact_id="sess_api_003",
query="你好",
extra_messages=[
{
"msg_id": "m2",
"msg_time": "2026-05-23T10:01:00Z",
"sender_id": "user_last",
"sender_name": "最后发言者",
"msg_type": "text",
"msg_content": "第二条消息",
"payload": {},
}
],
),
)
assert resp.status_code == 200
# 验证后台处理时 user_id 使用了最后一条 sender
messages = _get_session_messages("sess_api_003")
# 至少有 user 消息被存储
assert len(messages) >= 1
def test_image_message_extracts_file_url(self):
"""image 类型消息的 msg_content 作为图片 URL 传给 Agent"""
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={
"group": {"group_contact_id": "sess_img_001"},
"messages": [
{
"msg_id": "m1",
"msg_time": "2026-05-23T10:00:00Z",
"sender_id": "user_001",
"msg_type": "text",
"msg_content": "这张图片是什么",
"payload": {},
},
{
"msg_id": "m2",
"msg_time": "2026-05-23T10:00:01Z",
"sender_id": "user_001",
"msg_type": "image",
"msg_content": "https://oss.example.com/img/photo.jpg",
"payload": {},
},
],
},
)
assert resp.status_code == 200
def test_agents_filter_allowed_codes(self):
"""agents 数组中的 agent_id 映射为 allowed_agent_codes"""
with patch.object(test_hub, 'model', new=_make_mock_model_reply("回复")):
with patch.object(test_hub.formatter, 'format', new=AsyncMock(side_effect=_noop_format)):
# agents 中包含 agent_id=14(meeting agent)
resp = client.post(
"/api/v1/chat/completions",
json=_make_request(
group_contact_id="sess_agent_filter",
query="你好",
agents=[{"agent_id": 14, "agent_name": "会议纪要 Agent"}],
),
)
assert resp.status_code == 200
def test_missing_messages_returns_400(self):
"""缺少 messages 字段 → 400"""
resp = client.post(
"/api/v1/chat/completions",
json={"group": {"group_contact_id": "grp_no_msg"}},
)
assert resp.status_code == 400
def test_empty_messages_returns_400(self):
"""空 messages 数组 → 400"""
resp = client.post(
"/api/v1/chat/completions",
json={
"group": {"group_contact_id": "grp_empty_msg"},
"messages": [],
},
)
assert resp.status_code == 400
def test_text_only_messages_returns_400(self):
"""只有 image 消息没有 text → 400"""
resp = client.post(
"/api/v1/chat/completions",
json={
"group": {"group_contact_id": "grp_img_only"},
"messages": [
{
"msg_id": "m1",
"msg_time": "2026-05-23T10:00:00Z",
"sender_id": "user_001",
"msg_type": "image",
"msg_content": "https://example.com/img.jpg",
"payload": {},
},
],
},
)
assert resp.status_code == 400
def test_missing_group_contact_id_returns_400(self):
"""不传 group.group_contact_id → 400"""
resp = client.post(
"/api/v1/chat/completions",
json={
"messages": [
{
"msg_id": "m1",
"msg_time": "2026-05-23T10:00:00Z",
"sender_id": "u1",
"msg_type": "text",
"msg_content": "你好",
"payload": {},
}
],
},
)
assert resp.status_code == 400
def test_agents_without_name(self):
"""agents 不含 agent_name → 不报错"""
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={
"group": {"group_contact_id": "grp_no_name"},
"agents": [{"agent_id": 14}],
"messages": [
{
"msg_id": "m1",
"msg_time": "2026-05-23T10:00:00Z",
"sender_id": "u1",
"msg_type": "text",
"msg_content": "你好",
"payload": {},
}
],
},
)
assert resp.status_code == 200
def test_agents_with_bot_id_and_steward(self):
"""agents 含 bot_id 和 is_steward → 正确接收"""
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={
"group": {"group_contact_id": "grp_steward"},
"agents": [
{"agent_id": 14, "bot_id": "bot_001", "is_steward": True},
{"agent_id": 102, "bot_id": "bot_002", "is_steward": False},
],
"messages": [
{
"msg_id": "m1",
"msg_time": "2026-05-23T10:00:00Z",
"sender_id": "u1",
"msg_type": "text",
"msg_content": "你好",
"payload": {},
}
],
},
)
assert resp.status_code == 200
# ═══════════════════════════════════════════════════════════════════
# PostReplyHook 单元测试
# ═══════════════════════════════════════════════════════════════════
class TestPostReplyHook:
@pytest.mark.asyncio
async def test_strips_thinking_blocks_before_send(self):
from app.hooks.post_reply import PostReplyHook
mock_im = AsyncMock()
mock_im.send_message.return_value = {"code": 200}
hook = PostReplyHook(
im_service=mock_im, account_mapping={"main": "bot_main_001"}
)
await hook.execute(
{
"agent_name": "main",
"response_content": "正常回复<thinking>内部思考</thinking>继续回复",
"room_id": "room_001",
"mentioned_list": ["user_001"],
}
)
sent = mock_im.send_message.call_args[1]["content"]
assert "<thinking>" not in sent
assert "正常回复" in sent
assert "继续回复" in sent
@pytest.mark.asyncio
async def test_skips_when_agent_name_missing(self):
from app.hooks.post_reply import PostReplyHook
mock_im = AsyncMock()
hook = PostReplyHook(
im_service=mock_im, account_mapping={"main": "bot_main_001"}
)
result = await hook.execute(
{"response_content": "内容", "room_id": "room_001"}
)
assert result is None
mock_im.send_message.assert_not_called()
@pytest.mark.asyncio
async def test_skips_when_response_content_missing(self):
from app.hooks.post_reply import PostReplyHook
mock_im = AsyncMock()
hook = PostReplyHook(
im_service=mock_im, account_mapping={"main": "bot_main_001"}
)
result = await hook.execute(
{"agent_name": "main", "room_id": "room_001"}
)
assert result is None
mock_im.send_message.assert_not_called()
@pytest.mark.asyncio
async def test_skips_for_unmapped_agent(self):
from app.hooks.post_reply import PostReplyHook
mock_im = AsyncMock()
hook = PostReplyHook(
im_service=mock_im, account_mapping={"main": "bot_main_001"}
)
result = await hook.execute(
{
"agent_name": "unknown_agent",
"response_content": "回复",
"room_id": "room_001",
"mentioned_list": [],
}
)
assert result is None
mock_im.send_message.assert_not_called()
@pytest.mark.asyncio
async def test_skips_when_content_empty_after_strip(self):
from app.hooks.post_reply import PostReplyHook
mock_im = AsyncMock()
hook = PostReplyHook(
im_service=mock_im, account_mapping={"main": "bot_main_001"}
)
result = await hook.execute(
{
"agent_name": "main",
"response_content": "<thinking>只有思考</thinking>",
"room_id": "room_001",
"mentioned_list": [],
}
)
assert result is None
mock_im.send_message.assert_not_called()
# ═══════════════════════════════════════════════════════════════════
# AgentHub 路由逻辑测试(直接调用 process_message)
# ═══════════════════════════════════════════════════════════════════
class TestAgentHubRouting:
@pytest.mark.asyncio
async def test_process_message_returns_routing_metadata(self):
"""验证返回结构包含所有必需字段"""
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, '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"
)
messages = _get_session_messages(sid)
assert len(messages) == 4 # 2 user + 2 assistant
@pytest.mark.asyncio
async def test_default_routing_to_main(self):
"""未指定 agent → 路由到 main"""
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_route_001",
room_id="room_001",
user_id="user_001",
user_query="你好",
)
assert result["response_agent_code"] == "main"
assert result["routing_reason"] == "default"
assert len(result["response_content"]) > 0
@pytest.mark.asyncio
async def test_mention_routing_always_main(self):
"""即使传入 mentioned_agent_code,也始终路由到 main"""
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_route_002",
room_id="room_001",
user_id="user_001",
user_query="整理会议纪要",
mentioned_agent_code="meeting",
)
assert result["response_agent_code"] == "main"
assert result["routing_reason"] == "default"
@pytest.mark.asyncio
async def test_no_sticky_routing(self):
"""不再粘性继承 agent,每次始终路由 main"""
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_route_003"
r1 = await test_hub.process_message(
session_id=sid,
room_id="room_001",
user_id="user_001",
user_query="查会议纪要",
mentioned_agent_code="meeting",
)
assert r1["response_agent_code"] == "main"
r2 = await test_hub.process_message(
session_id=sid,
room_id="room_001",
user_id="user_001",
user_query="再查一个",
)
assert r2["response_agent_code"] == "main"
assert r2["routing_reason"] == "default"
@pytest.mark.asyncio
async def test_messages_accumulate(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)):
sid = "sess_accumulate"
for i in range(3):
await test_hub.process_message(
session_id=sid,
room_id="room_001",
user_id="user_001",
user_query=f"问题{i + 1}",
)
messages = _get_session_messages(sid)
assert len(messages) == 6 # 3 user + 3 assistant
@pytest.mark.asyncio
async def test_channel_default_value(self):
"""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)):
await test_hub.process_message(
session_id="sess_channel",
room_id="room_001",
user_id="user_001",
user_query="测试",
)
session_data = test_hub.session_service.store.get("sess_channel")
assert session_data is not None
assert session_data["channel"] == "wechat_group"
@pytest.mark.asyncio
async def test_image_url_appended_to_query(self):
"""file_url 不为空时,图片 URL 追加到 query 中"""
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_img",
room_id="room_001",
user_id="user_001",
user_query="这张图片是什么",
file_url="https://oss.example.com/img/photo.jpg",
)
assert result["response_content"] is not None
@pytest.mark.asyncio
async def test_allowed_agent_codes_still_routes_main(self):
"""allowed_agent_codes 不影响路由(始终 main),仅影响 prompt 中 advertised 的子 agent"""
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_restricted",
room_id="room_001",
user_id="user_001",
user_query="整理会议纪要",
mentioned_agent_code="meeting",
allowed_agent_codes=[],
)
assert result["response_agent_code"] == "main"
assert result["routing_reason"] == "default"
# ═══════════════════════════════════════════════════════════════════
# 协作层集成测试 — call_sub_agent 串行链
# ═══════════════════════════════════════════════════════════════════
class TestCollaboration:
"""Serial chain collaboration integration tests — simulate multi-call ReAct with call_sub_agent."""
@pytest.mark.asyncio
async def test_serial_chain_two_sub_agents(self):
"""Simulate: model calls meeting → then task → then returns integrated result."""
# Three model calls: tool_call(meeting) → tool_call(task) → text reply
responses = [
[{"type": "tool_use", "id": "call_1", "name": "call_sub_agent",
"input": {"agent_code": "meeting", "instruction": "整理纪要"}}],
[{"type": "tool_use", "id": "call_2", "name": "call_sub_agent",
"input": {"agent_code": "task", "instruction": "提取待办"}}],
[{"type": "text", "text": "已整理纪要并提取待办:1.提交方案 2.确认预算"}],
]
call_count = [0]
def _make_resp(blocks):
r = MagicMock()
r.content = blocks
return r
async def model_side_effect(*args, **kwargs):
idx = min(call_count[0], len(responses) - 1)
result = _make_resp(responses[idx])
call_count[0] += 1
return result
async def mock_sub_call(agent_code, instruction):
if agent_code == "meeting":
return "纪要: 讨论了Q2预算和团队调整"
elif agent_code == "task":
return "待办: 1.提交Q2预算 2.人员调整方案"
return ""
model_mock = AsyncMock(side_effect=model_side_effect)
model_mock.stream = False
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",
room_id="room_001",
user_id="u1",
user_query="整理纪要并提取待办",
)
assert "已整理" in result["response_content"]
@pytest.mark.asyncio
async def test_max_iterations_limit(self):
"""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(prompt, tools=None, **kwargs):
r = MagicMock()
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"
model_mock_2 = AsyncMock(side_effect=model_side_effect)
model_mock_2.stream = False
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)):
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