#!/usr/bin/env python3 """ 创建测试用户 """ import asyncio import os import sys from pathlib import Path # 设置环境变量 os.environ["DATABASE_URL"] = "mysql+aiomysql://root:root@localhost:3306/kaopeilian" os.environ["SECRET_KEY"] = "dev-secret-key-for-testing-only-not-for-production" # 添加项目根目录到Python路径 project_root = Path(__file__).parent sys.path.insert(0, str(project_root)) async def create_test_user(): """创建测试用户""" try: from app.config.database import AsyncSessionLocal from app.models.user import User from app.core.security import create_password_hash from sqlalchemy import select print("🔍 创建测试用户...") async with AsyncSessionLocal() as session: # 检查用户是否已存在 result = await session.execute( select(User).where(User.username == "testuser") ) existing_user = result.scalar_one_or_none() if existing_user: print("⚠️ 用户 'testuser' 已存在") return # 创建新用户 hashed_password = create_password_hash("TestPass123!") user = User( username="testuser", email="test@example.com", password_hash=hashed_password, full_name="Test User", is_active=True, role="trainee" ) session.add(user) await session.commit() await session.refresh(user) print(f"✅ 测试用户创建成功: {user.username} (ID: {user.id})") except Exception as e: print(f"❌ 创建用户失败: {e}") import traceback traceback.print_exc() if __name__ == "__main__": asyncio.run(create_test_user())