210 lines
6.6 KiB
Python
210 lines
6.6 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
测试聊天 API 脚本
|
|
用途:验证后端聊天功能是否正常工作
|
|
"""
|
|
import requests
|
|
import json
|
|
import sys
|
|
|
|
BASE_URL = "http://127.0.0.1:5002"
|
|
|
|
def test_login():
|
|
"""测试登录 API"""
|
|
print("=" * 50)
|
|
print("任务一:测试登录 API")
|
|
print("=" * 50)
|
|
|
|
url = f"{BASE_URL}/api/user/login"
|
|
data = {"username": "admin", "password": "Hxit@54321"}
|
|
|
|
print(f"请求 URL: {url}")
|
|
print(f"请求参数: {json.dumps(data, ensure_ascii=False)}")
|
|
|
|
try:
|
|
response = requests.post(url, json=data, timeout=10)
|
|
print(f"响应状态码: {response.status_code}")
|
|
print(f"响应内容: {json.dumps(response.json(), ensure_ascii=False, indent=2)}")
|
|
|
|
if response.status_code == 200:
|
|
user_data = response.json()
|
|
return {
|
|
"user_id": user_data.get("id"),
|
|
"username": user_data.get("username"),
|
|
"role": user_data.get("role")
|
|
}
|
|
except Exception as e:
|
|
print(f"错误: {e}")
|
|
|
|
return None
|
|
|
|
def test_chat_sessions(user_info, agent_id):
|
|
"""测试获取聊天会话列表"""
|
|
print("\n" + "=" * 50)
|
|
print(f"任务二:测试获取聊天会话列表 (agent_id={agent_id})")
|
|
print("=" * 50)
|
|
|
|
url = f"{BASE_URL}/api/chat/sessions"
|
|
headers = {
|
|
"X-Username": user_info["username"],
|
|
"X-Role": user_info["role"],
|
|
"X-User-Id": str(user_info["user_id"])
|
|
}
|
|
|
|
params = {"agent_id": agent_id}
|
|
|
|
print(f"请求 URL: {url}")
|
|
print(f"请求 Headers: {headers}")
|
|
print(f"请求参数: {params}")
|
|
|
|
try:
|
|
response = requests.get(url, headers=headers, params=params, timeout=10)
|
|
print(f"响应状态码: {response.status_code}")
|
|
print(f"响应内容: {json.dumps(response.json(), ensure_ascii=False, indent=2)}")
|
|
return response.status_code == 200
|
|
except Exception as e:
|
|
print(f"错误: {e}")
|
|
return False
|
|
|
|
def test_chat_completions(user_info, agent_id):
|
|
"""测试发送聊天消息"""
|
|
print("\n" + "=" * 50)
|
|
print(f"任务三:测试发送聊天消息 (agent_id={agent_id})")
|
|
print("=" * 50)
|
|
|
|
url = f"{BASE_URL}/api/chat/completions"
|
|
headers = {
|
|
"X-Username": user_info["username"],
|
|
"X-Role": user_info["role"],
|
|
"X-User-Id": str(user_info["user_id"]),
|
|
"Accept": "text/event-stream"
|
|
}
|
|
data = {
|
|
"query": "年假有多少天?",
|
|
"agent_id": agent_id,
|
|
"conversation_id": ""
|
|
}
|
|
|
|
print(f"请求 URL: {url}")
|
|
print(f"请求 Headers: {headers}")
|
|
print(f"请求体: {json.dumps(data, ensure_ascii=False)}")
|
|
|
|
full_response = []
|
|
error_count = 0
|
|
message_count = 0
|
|
|
|
try:
|
|
response = requests.post(url, headers=headers, json=data, stream=True, timeout=60)
|
|
print(f"响应状态码: {response.status_code}")
|
|
print("-" * 30)
|
|
print("流式响应内容:")
|
|
print("-" * 30)
|
|
|
|
for line in response.iter_lines():
|
|
if line:
|
|
decoded_line = line.decode('utf-8')
|
|
print(decoded_line)
|
|
full_response.append(decoded_line)
|
|
|
|
if decoded_line.startswith('data: '):
|
|
try:
|
|
json_str = decoded_line[6:]
|
|
event_data = json.loads(json_str)
|
|
event = event_data.get("event")
|
|
|
|
if event == "message":
|
|
message_count += 1
|
|
answer = event_data.get("data", {}).get("answer", "")
|
|
if answer:
|
|
print(f"\n>>> 第 {message_count} 条消息: {answer[:100]}...")
|
|
elif event == "error":
|
|
error_count += 1
|
|
error_msg = event_data.get("message", "")
|
|
print(f"\n!!! 错误事件: {error_msg}")
|
|
except json.JSONDecodeError:
|
|
pass
|
|
|
|
print("-" * 30)
|
|
print(f"消息计数: {message_count}")
|
|
print(f"错误计数: {error_count}")
|
|
|
|
if message_count > 0:
|
|
print("\n✅ 聊天功能测试成功!")
|
|
return True
|
|
elif error_count > 0:
|
|
print("\n⚠️ 聊天功能返回了错误,但连接正常")
|
|
return True
|
|
else:
|
|
print("\n❌ 聊天功能测试失败:无消息返回")
|
|
return False
|
|
|
|
except requests.exceptions.Timeout:
|
|
print("❌ 错误: 请求超时")
|
|
return False
|
|
except requests.exceptions.ConnectionError as e:
|
|
print(f"❌ 错误: 连接失败 - {e}")
|
|
return False
|
|
except Exception as e:
|
|
print(f"❌ 错误: {e}")
|
|
return False
|
|
|
|
def test_without_auth():
|
|
"""测试未带认证头的请求"""
|
|
print("\n" + "=" * 50)
|
|
print("任务四:测试未带认证头的请求")
|
|
print("=" * 50)
|
|
|
|
url = f"{BASE_URL}/api/chat/sessions?agent_id=3"
|
|
|
|
print(f"请求 URL: {url}")
|
|
print("请求 Headers: (无)")
|
|
|
|
try:
|
|
response = requests.get(url, timeout=10)
|
|
print(f"响应状态码: {response.status_code}")
|
|
print(f"响应内容: {json.dumps(response.json(), ensure_ascii=False, indent=2)}")
|
|
|
|
if response.status_code == 403:
|
|
print("✅ 未带认证头时正确返回 403 权限错误(预期行为)")
|
|
return True
|
|
except Exception as e:
|
|
print(f"错误: {e}")
|
|
|
|
return False
|
|
|
|
def main():
|
|
print("=" * 60)
|
|
print("hxops 聊天功能测试脚本")
|
|
print("=" * 60)
|
|
|
|
# 测试一:登录
|
|
user_info = test_login()
|
|
if not user_info:
|
|
print("\n❌ 登录失败,请检查后端服务是否运行")
|
|
sys.exit(1)
|
|
|
|
print(f"\n✅ 登录成功,用户: {user_info['username']}, 角色: {user_info['role']}")
|
|
|
|
# 测试二:获取聊天会话列表
|
|
agent_id = 3 # 人事规章 Agent
|
|
if not test_chat_sessions(user_info, agent_id):
|
|
print("\n❌ 获取聊天会话列表失败")
|
|
sys.exit(1)
|
|
|
|
print(f"\n✅ 获取聊天会话列表成功")
|
|
|
|
# 测试三:发送聊天消息
|
|
if not test_chat_completions(user_info, agent_id):
|
|
print("\n❌ 发送聊天消息失败")
|
|
sys.exit(1)
|
|
|
|
# 测试四:未带认证头
|
|
test_without_auth()
|
|
|
|
print("\n" + "=" * 60)
|
|
print("所有测试完成!")
|
|
print("=" * 60)
|
|
|
|
if __name__ == "__main__":
|
|
main()
|