Commit 7f24fd58 by sunqi02

功能更新,进行了架构测试,等待与API调度管理衔接

1 parent f2108776
# 测试验证环境修改记录
> 本文件记录了为验证端到端流程所做的临时修改,后续开发时需要还原或调整。
## 1. main.py — 启动时自动建表
**位置:** `app/main.py:23`
```python
Base.metadata.create_all(bind=engine)
```
**还原:** 删除该行,后续数据库表由 migrations 管理。
## 2. main.py — ConsoleIMService(默认)
**位置:** `app/main.py:27-34`
生产环境需要调用真实 IM 服务,当前默认使用 `ConsoleIMService` 打印到控制台。
**还原:** 启动时设置环境变量 `USE_CONSOLE_IM=false`,并指定 `IM_BASE_URL`、`IM_API_KEY`。
```bash
USE_CONSOLE_IM=false IM_BASE_URL=http://your-im:8080 IM_API_KEY=xxx python -m app.main
```
## 3. database.py — SQLite 默认
**位置:** `app/infrastructure/database.py:6-8`
当前默认连接 SQLite(`dev.db`),避免本地没有 MySQL 时启动失败。
**还原:** 启动时设置 `DATABASE_URL` 环境变量指向 MySQL。
```bash
DATABASE_URL=mysql+pymysql://root:123456@localhost:3306/agent_admin?charset=utf8mb4 python -m app.main
```
## 4. 测试脚本
`send_test.sh` + `test_request.json` — 开发验证用,可保留。
...@@ -57,6 +57,7 @@ class PostReplyHook(Hook): ...@@ -57,6 +57,7 @@ class PostReplyHook(Hook):
def _strip_thinking_blocks(self, content: str) -> str: def _strip_thinking_blocks(self, content: str) -> str:
"""Remove thinking/tool_use blocks, keep only natural language.""" """Remove thinking/tool_use blocks, keep only natural language."""
patterns = [ patterns = [
r'\s*<think>.*?</think>\s*',
r'\s*<thinking>.*?</thinking>\s*', r'\s*<thinking>.*?</thinking>\s*',
r'\s*\[TOOL_USE\].*?\[/TOOL_USE\]\s*', r'\s*\[TOOL_USE\].*?\[/TOOL_USE\]\s*',
r'\s*```tool.*?```\s*', r'\s*```tool.*?```\s*',
......
...@@ -3,9 +3,15 @@ from sqlalchemy import create_engine ...@@ -3,9 +3,15 @@ from sqlalchemy import create_engine
import os import os
# 数据库连接配置,实际开发中应从 config 读取 # 数据库连接配置,实际开发中应从 config 读取
SQLALCHEMY_DATABASE_URL = os.getenv("DATABASE_URL", "mysql+pymysql://root:123456@localhost:3306/agent_admin?charset=utf8mb4") SQLALCHEMY_DATABASE_URL = os.getenv(
"DATABASE_URL",
"sqlite:///./dev.db"
)
engine = create_engine(SQLALCHEMY_DATABASE_URL) engine = create_engine(
SQLALCHEMY_DATABASE_URL,
connect_args={"check_same_thread": False} if SQLALCHEMY_DATABASE_URL.startswith("sqlite") else {}
)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine) SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
Base = declarative_base() Base = declarative_base()
......
"""Console IM service — prints hook output instead of sending to real IM."""
import json
from typing import Dict, List, Any, Optional
class ConsoleIMService:
"""IMService replacement that prints to console for testing."""
def __init__(self):
self._client = None
async def send_message(
self,
account: str,
content: str,
room_id: str,
mentioned_list: Optional[List[str]] = None,
) -> Dict[str, Any]:
payload = {
"account": account,
"content": content,
"room_id": room_id,
"mentioned_list": mentioned_list or [],
}
print("\n" + "=" * 50)
print(" [Hook: post_reply] → 计划发送到 IM")
print("=" * 50)
print(json.dumps(payload, ensure_ascii=False, indent=2))
print("=" * 50 + "\n")
return {"status": "printed", "account": account}
async def close(self):
pass
No preview for this file type
#!/bin/bash
# 模拟用户消息发送到 Agent 服务
# 用法: ./send_test.sh "你的问题"
# 例如: ./send_test.sh "帮我整理上周的会议纪要"
# ./send_test.sh "@meeting 帮我整理会议纪要"
QUERY="${1:-你好,请问你能帮我什么?}"
API_URL="${API_URL:-http://localhost:8000/api/v1/chat/completions}"
echo "=========================================="
echo " 发送测试消息到 AgentHub"
echo "=========================================="
echo ""
echo "提问: ${QUERY}"
echo ""
# 用 jq 替换 query 字段(如果安装了 jq),否则用 sed
if command -v jq &> /dev/null; then
PAYLOAD=$(jq --arg q "${QUERY}" '.query = $q' test_request.json)
else
PAYLOAD=$(sed "s/{{QUERY}}/${QUERY}/g" test_request.json)
fi
echo "--- 请求体 ---"
echo "${PAYLOAD}" | python3 -m json.tool 2>/dev/null || echo "${PAYLOAD}"
echo ""
echo "--- 开始请求 ---"
echo "POST ${API_URL}"
echo ""
HTTP_CODE=$(curl -s -w "\n%{http_code}" -X POST "${API_URL}" \
-H "Content-Type: application/json" \
-d "${PAYLOAD}")
# 分离 body 和 status code
BODY=$(echo "${HTTP_CODE}" | sed '$d')
STATUS=$(echo "${HTTP_CODE}" | tail -n1)
echo "--- 响应 (HTTP ${STATUS}) ---"
echo "${BODY}" | python3 -m json.tool 2>/dev/null || echo "${BODY}"
echo ""
echo "=========================================="
echo " 完成"
echo "=========================================="
skills 将会存放在这里
\ No newline at end of file \ No newline at end of file
{
"session_id": "test_sess_001",
"user_id": "test_user_001",
"room_id": "test_room_001",
"channel": "wechat_group",
"query": "{{QUERY}}",
"mentioned_agent_code": null,
"file_url": null
}
import pytest
from unittest.mock import AsyncMock, MagicMock, patch
from fastapi.testclient import TestClient
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy.pool import StaticPool
from app.infrastructure.database import Base, get_db
from app.model.session import Session, SessionMessage, SessionStatus
from app.main import app as fastapi_app
# ── SQLite 内存测试库 ────────────────────────────────────────────
SQLALCHEMY_DATABASE_URL = "sqlite://"
engine = create_engine(
SQLALCHEMY_DATABASE_URL,
connect_args={"check_same_thread": False},
poolclass=StaticPool,
)
TestingSessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
# 确保所有模型表注册到 Base.metadata(agent 模型通过 agent_service 间接导入)
from app.model.agent import Agent, AgentPosition, AgentSkill # noqa: E402
from app.model.position_tag import PositionTag, OfficialTab # noqa: E402
from app.model.agent_group import QrcodeChannel # noqa: E402
Base.metadata.create_all(bind=engine)
def override_get_db():
try:
db = TestingSessionLocal()
yield db
finally:
db.close()
fastapi_app.dependency_overrides[get_db] = override_get_db
# ── 创建测试 AgentHub(共享同一个测试 DB)─────────────────────────
from app.config.loader import ConfigLoader
from app.service.session_service import SessionService
from app.service.agent_hub import AgentHub
def _make_test_hub():
db = TestingSessionLocal()
session_service = SessionService(db)
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 _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)
# ── Fixtures ──────────────────────────────────────────────────────
@pytest.fixture(autouse=True)
def clean_session_tables():
"""每个测试后清理 Session 相关表"""
db = TestingSessionLocal()
db.query(SessionMessage).delete()
db.query(Session).delete()
db.commit()
db.close()
yield
# ═══════════════════════════════════════════════════════════════════
# API 层集成测试 — POST /api/v1/chat/completions
# ═══════════════════════════════════════════════════════════════════
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()
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()
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()["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()["response_agent_code"] == "meeting"
assert r2.json()["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 = "回复内容"
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
db = TestingSessionLocal()
messages = (
db.query(SessionMessage)
.join(Session)
.filter(Session.session_id == "sess_api_004")
.all()
)
assert len(messages) == 6 # 3 user + 3 assistant
db.close()
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")
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
def test_missing_required_fields(self):
"""缺少必填字段 → 422"""
resp = client.post(
"/api/v1/chat/completions",
json={"session_id": "sess_incomplete"},
)
assert resp.status_code == 422
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
# 验证 session 的 channel 为默认值
db = TestingSessionLocal()
session = (
db.query(Session)
.filter(Session.session_id == "sess_api_005")
.first()
)
assert session.channel == "wechat_group"
db.close()
# ═══════════════════════════════════════════════════════════════════
# SessionService 单元测试
# ═══════════════════════════════════════════════════════════════════
class TestSessionService:
def test_create_new_session(self):
db = TestingSessionLocal()
svc = SessionService(db)
session = svc.get_or_create_session(
session_id="new_sess_001", room_id="room_001", user_id="user_001"
)
assert session.session_id == "new_sess_001"
assert session.room_id == "room_001"
assert session.user_id == "user_001"
assert session.channel == "wechat_group"
assert session.status == SessionStatus.active
assert session.is_deleted is False
db.close()
def test_get_existing_session(self):
db = TestingSessionLocal()
svc = SessionService(db)
s1 = svc.get_or_create_session("dup_sess", "room_001", "user_001")
s2 = svc.get_or_create_session("dup_sess", "room_002", "user_002")
assert s1.id == s2.id
db.close()
def test_auto_generate_session_id_when_empty(self):
db = TestingSessionLocal()
svc = SessionService(db)
session = svc.get_or_create_session(
session_id="", room_id="room_001", user_id="user_001"
)
assert session.session_id.startswith("sess_")
assert len(session.session_id) > 5
db.close()
def test_add_and_retrieve_messages(self):
db = TestingSessionLocal()
svc = SessionService(db)
session = svc.get_or_create_session("msg_sess", "room_001", "user_001")
svc.add_message(session.id, "user", "用户问题", agent_code="main")
svc.add_message(session.id, "assistant", "助手回复", agent_code="main")
messages = svc.get_session_messages(session.id)
assert len(messages) == 2
assert messages[0].role == "user"
assert messages[0].content == "用户问题"
assert messages[1].role == "assistant"
assert messages[1].content == "助手回复"
db.close()
def test_trim_messages_to_max_50(self):
db = TestingSessionLocal()
svc = SessionService(db)
session = svc.get_or_create_session("trim_sess", "room_001", "user_001")
# 用递增的 role 字段模拟时间顺序(SQLite func.now() 精度不足)
for i in range(55):
svc.add_message(
session.id,
"user" if i % 2 == 0 else "assistant",
f"消息{i}",
)
messages = svc.get_session_messages(session.id)
assert len(messages) == 50 # 裁剪到上限
# 注意:SQLite 的 func.now() 秒级精度导致 created_at 相同时排序不确定
# 在实际 MySQL 环境中按真实时间戳排序,行为正确
db.close()
def test_get_session_by_uuid(self):
db = TestingSessionLocal()
svc = SessionService(db)
svc.get_or_create_session("uuid_test_001", "room_001", "user_001")
found = svc.get_session_by_uuid("uuid_test_001")
assert found is not None
assert found.session_id == "uuid_test_001"
not_found = svc.get_session_by_uuid("nonexistent")
assert not_found is None
db.close()
def test_update_current_agent(self):
db = TestingSessionLocal()
svc = SessionService(db)
session = svc.get_or_create_session("agent_sess", "room_001", "user_001")
assert session.current_agent_code is None
svc.update_current_agent(session.id, "meeting")
updated = svc.get_session(session.id)
assert updated.current_agent_code == "meeting"
db.close()
# ═══════════════════════════════════════════════════════════════════
# 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 路由逻辑测试
# ═══════════════════════════════════════════════════════════════════
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
@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"
)
db = TestingSessionLocal()
messages = (
db.query(SessionMessage)
.join(Session)
.filter(Session.session_id == sid)
.all()
)
assert len(messages) == 4 # 2 user + 2 assistant
db.close()
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!