import { DataSource } from 'typeorm'; import { AppDataSource } from '../src/server/data-source'; import { UserEntity as User } from '../src/server/modules/users/user.entity'; import { Role } from '../src/server/modules/users/role.entity'; import * as bcrypt from 'bcrypt'; async function setupTestDatabase() { console.log('Setting up test database...'); // 使用测试数据库配置 const testDataSource = new DataSource({ ...dataSource.options, database: process.env.MYSQL_DATABASE || 'test_d8dai', }); try { await testDataSource.initialize(); console.log('Test database connected'); // 清空测试数据 await testDataSource.transaction(async (transactionalEntityManager) => { await transactionalEntityManager.query('SET FOREIGN_KEY_CHECKS = 0'); const entities = testDataSource.entityMetadatas; for (const entity of entities) { const repository = transactionalEntityManager.getRepository(entity.name); await repository.clear(); } await transactionalEntityManager.query('SET FOREIGN_KEY_CHECKS = 1'); }); console.log('Test database cleared'); // 创建测试角色 const adminRole = testDataSource.getRepository(Role).create({ name: 'admin', description: 'Administrator role', }); const userRole = testDataSource.getRepository(Role).create({ name: 'user', description: 'Regular user role', }); await testDataSource.getRepository(Role).save([adminRole, userRole]); // 创建测试用户 const hashedPassword = await bcrypt.hash('admin123', 10); const adminUser = testDataSource.getRepository(User).create({ username: 'admin', password: hashedPassword, nickname: 'Administrator', email: 'admin@example.com', roles: [adminRole], isDisabled: 0, }); const testUser = testDataSource.getRepository(User).create({ username: 'testuser', password: await bcrypt.hash('test123', 10), nickname: 'Test User', email: 'testuser@example.com', roles: [userRole], isDisabled: 0, }); await testDataSource.getRepository(User).save([adminUser, testUser]); console.log('Test data created successfully'); console.log('Admin user: admin / admin123'); console.log('Test user: testuser / test123'); } catch (error) { console.error('Error setting up test database:', error); throw error; } finally { await testDataSource.destroy(); } } // 如果是直接运行此脚本 if (require.main === module) { setupTestDatabase() .then(() => process.exit(0)) .catch((error) => { console.error(error); process.exit(1); }); } export { setupTestDatabase };