89 lines
2.6 KiB
Python
89 lines
2.6 KiB
Python
#!/usr/bin/env python
|
||
# -*- coding: utf-8 -*-
|
||
"""
|
||
直接测试同步API的Pydantic序列化
|
||
不通过HTTP,直接模拟返回值构建过程
|
||
"""
|
||
|
||
from database import User, get_db, init_database
|
||
from app import SyncUsersResponse
|
||
from pydantic import ValidationError
|
||
import json
|
||
|
||
def test_sync_response():
|
||
"""测试同步响应的序列化"""
|
||
print("="*60)
|
||
print("测试同步API响应序列化")
|
||
print("="*60)
|
||
|
||
# 初始化数据库
|
||
init_database()
|
||
|
||
# 获取数据库会话
|
||
db = next(get_db())
|
||
|
||
try:
|
||
# 查询所有激活用户
|
||
users = db.query(User).filter(User.is_active == True).all()
|
||
print(f"\n查询到 {len(users)} 个激活用户")
|
||
|
||
# 转换为字典列表
|
||
user_list = []
|
||
for i, user in enumerate(users):
|
||
print(f"\n处理用户 {i+1}: {user.name}")
|
||
user_dict = user.to_dict_with_feature()
|
||
|
||
# 打印字典的键
|
||
print(f" 字典键: {list(user_dict.keys())}")
|
||
|
||
# 检查特征向量
|
||
if 'feature_vector' in user_dict:
|
||
feature = user_dict['feature_vector']
|
||
print(f" 特征向量类型: {type(feature)}")
|
||
print(f" 特征向量长度: {len(feature) if isinstance(feature, list) else 'N/A'}")
|
||
if isinstance(feature, list) and len(feature) > 0:
|
||
print(f" 第一个元素类型: {type(feature[0])}")
|
||
|
||
user_list.append(user_dict)
|
||
|
||
# 尝试构建Pydantic响应
|
||
print("\n" + "="*60)
|
||
print("尝试构建SyncUsersResponse对象...")
|
||
print("="*60)
|
||
|
||
try:
|
||
response = SyncUsersResponse(
|
||
success=True,
|
||
message="同步成功",
|
||
total=len(user_list),
|
||
users=user_list
|
||
)
|
||
print("✅ Pydantic模型验证成功!")
|
||
|
||
# 尝试序列化为JSON
|
||
print("\n尝试序列化为JSON...")
|
||
json_str = response.model_dump_json(indent=2)
|
||
print("✅ JSON序列化成功!")
|
||
print(f"\nJSON长度: {len(json_str)} 字符")
|
||
|
||
# 显示前500个字符
|
||
if len(json_str) > 500:
|
||
print(f"\n前500个字符:\n{json_str[:500]}...")
|
||
else:
|
||
print(f"\n完整JSON:\n{json_str}")
|
||
|
||
except ValidationError as e:
|
||
print("❌ Pydantic验证失败!")
|
||
print(f"错误详情:\n{e}")
|
||
|
||
except Exception as e:
|
||
print(f"❌ JSON序列化失败: {e}")
|
||
import traceback
|
||
traceback.print_exc()
|
||
|
||
finally:
|
||
db.close()
|
||
|
||
if __name__ == "__main__":
|
||
test_sync_response()
|