Files
aitsc/test_history_feature.py
2025-10-10 23:39:54 +08:00

331 lines
11 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
优化历史功能测试脚本
测试历史记录的CRUD操作、搜索、筛选、导出等功能
"""
import requests
import json
import time
from datetime import datetime, timedelta
# 测试配置
BASE_URL = "http://localhost:5002"
TEST_USER_ID = 1
def test_api_endpoint(endpoint, method="GET", data=None, expected_status=200):
"""测试API端点"""
url = f"{BASE_URL}{endpoint}"
try:
if method == "GET":
response = requests.get(url, timeout=10)
elif method == "POST":
response = requests.post(url, json=data, timeout=10)
elif method == "PUT":
response = requests.put(url, json=data, timeout=10)
elif method == "DELETE":
response = requests.delete(url, timeout=10)
else:
raise ValueError(f"不支持的HTTP方法: {method}")
print(f"{method} {endpoint} - 状态码: {response.status_code}")
if response.status_code == expected_status:
try:
result = response.json()
print(f" 响应: {json.dumps(result, ensure_ascii=False, indent=2)[:200]}...")
return result
except:
print(f" 响应: {response.text[:200]}...")
return response.text
else:
print(f"❌ 期望状态码 {expected_status}, 实际状态码 {response.status_code}")
print(f" 错误信息: {response.text}")
return None
except requests.exceptions.RequestException as e:
print(f"❌ 请求失败: {str(e)}")
return None
def test_history_crud():
"""测试历史记录CRUD操作"""
print("\n" + "="*50)
print("测试历史记录CRUD操作")
print("="*50)
# 1. 测试保存历史记录
print("\n1. 测试保存历史记录")
history_data = {
"original_input": "请帮我写一个关于人工智能的提示词",
"generated_prompt": "你是一位专业的人工智能专家,请详细分析人工智能的发展趋势、应用领域和未来前景。",
"template_id": 1,
"template_name": "AI专家助手",
"generation_time": 1500,
"satisfaction_rating": 4,
"tags": ["AI", "技术", "分析"],
"is_favorite": False
}
result = test_api_endpoint("/api/history/save", "POST", history_data, 200)
if result and result.get("success"):
history_id = result["data"]["id"]
print(f" 历史记录ID: {history_id}")
return history_id
else:
print(" 保存历史记录失败")
return None
def test_get_history_list():
"""测试获取历史记录列表"""
print("\n2. 测试获取历史记录列表")
# 基本查询
result = test_api_endpoint("/api/history", "GET", expected_status=200)
if result and result.get("success"):
history_list = result["data"]["history"]
print(f" 获取到 {len(history_list)} 条历史记录")
if history_list:
first_history = history_list[0]
print(f" 第一条记录: {first_history['original_input'][:50]}...")
return first_history["id"]
return None
def test_search_and_filter():
"""测试搜索和筛选功能"""
print("\n3. 测试搜索和筛选功能")
# 测试关键词搜索
print("\n3.1 测试关键词搜索")
result = test_api_endpoint("/api/history?search=人工智能", "GET", expected_status=200)
if result and result.get("success"):
print(f" 搜索结果: {len(result['data']['history'])} 条记录")
# 测试模板筛选
print("\n3.2 测试模板筛选")
result = test_api_endpoint("/api/history?template_id=1", "GET", expected_status=200)
if result and result.get("success"):
print(f" 模板筛选结果: {len(result['data']['history'])} 条记录")
# 测试收藏筛选
print("\n3.3 测试收藏筛选")
result = test_api_endpoint("/api/history?is_favorite=true", "GET", expected_status=200)
if result and result.get("success"):
print(f" 收藏筛选结果: {len(result['data']['history'])} 条记录")
# 测试排序
print("\n3.4 测试排序")
result = test_api_endpoint("/api/history?sort=rating", "GET", expected_status=200)
if result and result.get("success"):
print(f" 按评分排序结果: {len(result['data']['history'])} 条记录")
def test_update_history(history_id):
"""测试更新历史记录"""
print("\n4. 测试更新历史记录")
if not history_id:
print(" 跳过测试没有可用的历史记录ID")
return
update_data = {
"satisfaction_rating": 5,
"is_favorite": True,
"tags": ["AI", "技术", "分析", "重要"]
}
result = test_api_endpoint(f"/api/history/{history_id}", "PUT", update_data, 200)
if result and result.get("success"):
print(" 更新历史记录成功")
print(f" 更新后评分: {result['data']['satisfaction_rating']}")
print(f" 更新后收藏状态: {result['data']['is_favorite']}")
else:
print(" 更新历史记录失败")
def test_get_history_detail(history_id):
"""测试获取历史记录详情"""
print("\n5. 测试获取历史记录详情")
if not history_id:
print(" 跳过测试没有可用的历史记录ID")
return
result = test_api_endpoint(f"/api/history/{history_id}", "GET", expected_status=200)
if result and result.get("success"):
history = result["data"]
print(" 获取历史记录详情成功")
print(f" 原始输入: {history['original_input'][:50]}...")
print(f" 生成提示词: {history['generated_prompt'][:50]}...")
print(f" 模板名称: {history['template_name']}")
print(f" 生成时间: {history['created_at']}")
else:
print(" 获取历史记录详情失败")
def test_statistics():
"""测试统计功能"""
print("\n6. 测试统计功能")
result = test_api_endpoint("/api/history/statistics", "GET", expected_status=200)
if result and result.get("success"):
stats = result["data"]
print(" 获取统计信息成功")
print(f" 总生成数: {stats['total_generations']}")
print(f" 收藏数: {stats['favorite_count']}")
print(f" 平均评分: {stats['avg_rating']}")
print(f" 最后生成时间: {stats['last_generation_at']}")
else:
print(" 获取统计信息失败")
def test_templates():
"""测试模板列表"""
print("\n7. 测试模板列表")
result = test_api_endpoint("/api/history/templates", "GET", expected_status=200)
if result and result.get("success"):
templates = result["data"]["templates"]
print(f" 获取模板列表成功: {len(templates)} 个模板")
if templates:
first_template = templates[0]
print(f" 第一个模板: {first_template['name']}")
else:
print(" 获取模板列表失败")
def test_export():
"""测试导出功能"""
print("\n8. 测试导出功能")
# 测试JSON导出
print("\n8.1 测试JSON导出")
result = test_api_endpoint("/api/history/export?format=json", "GET", expected_status=200)
if result and result.get("success"):
print(f" JSON导出成功: {result['count']} 条记录")
else:
print(" JSON导出失败")
# 测试CSV导出
print("\n8.2 测试CSV导出")
try:
response = requests.get(f"{BASE_URL}/api/history/export?format=csv", timeout=10)
if response.status_code == 200:
print(" CSV导出成功")
print(f" CSV内容预览: {response.text[:100]}...")
else:
print(f" CSV导出失败: 状态码 {response.status_code}")
except Exception as e:
print(f" CSV导出失败: {str(e)}")
def test_batch_operations():
"""测试批量操作"""
print("\n9. 测试批量操作")
# 先获取一些历史记录ID
result = test_api_endpoint("/api/history", "GET", expected_status=200)
if not result or not result.get("success"):
print(" 跳过测试:无法获取历史记录列表")
return
history_list = result["data"]["history"]
if len(history_list) < 2:
print(" 跳过测试:历史记录数量不足")
return
# 获取前两个记录的ID
history_ids = [h["id"] for h in history_list[:2]]
# 测试批量收藏
print("\n9.1 测试批量收藏")
batch_data = {
"operation": "favorite",
"history_ids": history_ids
}
result = test_api_endpoint("/api/history/batch", "POST", batch_data, 200)
if result and result.get("success"):
print(" 批量收藏成功")
else:
print(" 批量收藏失败")
# 测试批量取消收藏
print("\n9.2 测试批量取消收藏")
batch_data = {
"operation": "unfavorite",
"history_ids": history_ids
}
result = test_api_endpoint("/api/history/batch", "POST", batch_data, 200)
if result and result.get("success"):
print(" 批量取消收藏成功")
else:
print(" 批量取消收藏失败")
def test_delete_history(history_id):
"""测试删除历史记录"""
print("\n10. 测试删除历史记录")
if not history_id:
print(" 跳过测试没有可用的历史记录ID")
return
result = test_api_endpoint(f"/api/history/{history_id}", "DELETE", expected_status=200)
if result and result.get("success"):
print(" 删除历史记录成功")
else:
print(" 删除历史记录失败")
def test_history_page():
"""测试历史记录页面"""
print("\n11. 测试历史记录页面")
try:
response = requests.get(f"{BASE_URL}/history", timeout=10)
if response.status_code == 200:
print(" 历史记录页面访问成功")
if "优化历史" in response.text:
print(" 页面内容正确")
else:
print(" 页面内容可能有问题")
else:
print(f" 历史记录页面访问失败: 状态码 {response.status_code}")
except Exception as e:
print(f" 历史记录页面访问失败: {str(e)}")
def main():
"""主测试函数"""
print("🚀 开始测试优化历史功能")
print("="*60)
# 检查服务器是否运行
try:
response = requests.get(f"{BASE_URL}/", timeout=5)
if response.status_code != 200:
print("❌ 服务器未运行或无法访问")
return
except:
print("❌ 无法连接到服务器,请确保服务器正在运行")
return
print("✅ 服务器连接正常")
# 执行测试
history_id = test_history_crud()
test_get_history_list()
test_search_and_filter()
test_update_history(history_id)
test_get_history_detail(history_id)
test_statistics()
test_templates()
test_export()
test_batch_operations()
test_history_page()
# 最后删除测试数据
if history_id:
test_delete_history(history_id)
print("\n" + "="*60)
print("🎉 优化历史功能测试完成!")
print("="*60)
if __name__ == "__main__":
main()