Files
yixiaogao/database/test_user_db.py
2025-12-02 14:58:52 +08:00

94 lines
3.3 KiB
Python
Raw Permalink Blame History

This file contains invisible Unicode characters

This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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.

import os
import sys
from user_database import UserDatabase
def test_user_database():
# 获取数据库路径
db_path = os.path.join(os.path.dirname(__file__), 'users.db')
print(f"测试数据库路径: {db_path}")
try:
# 初始化数据库
db = UserDatabase(db_path)
print("✅ 数据库初始化成功")
# 测试用户创建
test_username = "testuser"
test_email = "test@example.com"
test_password = "Test123456"
# 先尝试删除测试用户(如果存在)
try:
user = db.get_user_by_username(test_username)
if user:
print(f"⚠️ 测试用户 '{test_username}' 已存在,尝试创建新的测试用户")
test_username = "testuser_new"
test_email = "test_new@example.com"
except Exception as e:
print(f" 检查用户时发生错误: {e}")
# 创建新用户
print(f"\n🔄 创建测试用户: {test_username}")
user_id = db.create_user(test_username, test_password, test_email)
print(f"✅ 用户创建成功! 用户ID: {user_id}")
# 测试获取用户信息
print(f"\n🔄 测试获取用户信息")
user = db.get_user_by_username(test_username)
if user:
print(f"✅ 用户信息获取成功!")
print(f" - 用户ID: {user['user_id']}")
print(f" - 用户名: {user['username']}")
print(f" - 邮箱: {user['email']}")
print(f" - 创建时间: {user['created_at']}")
else:
print(f"❌ 无法获取用户信息")
# 测试密码验证
print(f"\n🔄 测试密码验证")
# 正确密码
valid_user = db.verify_password(test_username, test_password)
if valid_user:
print(f"✅ 正确密码验证成功")
else:
print(f"❌ 正确密码验证失败")
# 错误密码
invalid_user = db.verify_password(test_username, "WrongPassword")
if not invalid_user:
print(f"✅ 错误密码验证正确返回None")
else:
print(f"❌ 错误密码验证失败应返回None")
# 测试更新登录时间
print(f"\n🔄 测试更新登录时间")
if db.update_login_time(user_id):
print(f"✅ 登录时间更新成功")
# 验证更新是否成功
updated_user = db.get_user_by_id(user_id)
print(f" - 更新后的最后登录时间: {updated_user['last_login_at']}")
else:
print(f"❌ 登录时间更新失败")
print("\n🎉 所有测试完成!")
return True
except Exception as e:
print(f"❌ 测试失败: {str(e)}")
import traceback
traceback.print_exc()
return False
finally:
if 'db' in locals():
try:
db.close()
print(" 数据库连接已关闭")
except:
pass
if __name__ == "__main__":
print("====================================")
print("用户数据库功能测试")
print("====================================")
success = test_user_database()
sys.exit(0 if success else 1)