setup-test-db.ts 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. import { DataSource } from 'typeorm';
  2. import { AppDataSource } from '../src/server/data-source';
  3. import { UserEntity as User } from '../src/server/modules/users/user.entity';
  4. import { Role } from '../src/server/modules/users/role.entity';
  5. import * as bcrypt from 'bcrypt';
  6. async function setupTestDatabase() {
  7. console.log('Setting up test database...');
  8. // 使用测试数据库配置
  9. const testDataSource = new DataSource({
  10. ...dataSource.options,
  11. database: process.env.MYSQL_DATABASE || 'test_d8dai',
  12. });
  13. try {
  14. await testDataSource.initialize();
  15. console.log('Test database connected');
  16. // 清空测试数据
  17. await testDataSource.transaction(async (transactionalEntityManager) => {
  18. await transactionalEntityManager.query('SET FOREIGN_KEY_CHECKS = 0');
  19. const entities = testDataSource.entityMetadatas;
  20. for (const entity of entities) {
  21. const repository = transactionalEntityManager.getRepository(entity.name);
  22. await repository.clear();
  23. }
  24. await transactionalEntityManager.query('SET FOREIGN_KEY_CHECKS = 1');
  25. });
  26. console.log('Test database cleared');
  27. // 创建测试角色
  28. const adminRole = testDataSource.getRepository(Role).create({
  29. name: 'admin',
  30. description: 'Administrator role',
  31. });
  32. const userRole = testDataSource.getRepository(Role).create({
  33. name: 'user',
  34. description: 'Regular user role',
  35. });
  36. await testDataSource.getRepository(Role).save([adminRole, userRole]);
  37. // 创建测试用户
  38. const hashedPassword = await bcrypt.hash('admin123', 10);
  39. const adminUser = testDataSource.getRepository(User).create({
  40. username: 'admin',
  41. password: hashedPassword,
  42. nickname: 'Administrator',
  43. email: 'admin@example.com',
  44. roles: [adminRole],
  45. isDisabled: 0,
  46. });
  47. const testUser = testDataSource.getRepository(User).create({
  48. username: 'testuser',
  49. password: await bcrypt.hash('test123', 10),
  50. nickname: 'Test User',
  51. email: 'testuser@example.com',
  52. roles: [userRole],
  53. isDisabled: 0,
  54. });
  55. await testDataSource.getRepository(User).save([adminUser, testUser]);
  56. console.log('Test data created successfully');
  57. console.log('Admin user: admin / admin123');
  58. console.log('Test user: testuser / test123');
  59. } catch (error) {
  60. console.error('Error setting up test database:', error);
  61. throw error;
  62. } finally {
  63. await testDataSource.destroy();
  64. }
  65. }
  66. // 如果是直接运行此脚本
  67. if (require.main === module) {
  68. setupTestDatabase()
  69. .then(() => process.exit(0))
  70. .catch((error) => {
  71. console.error(error);
  72. process.exit(1);
  73. });
  74. }
  75. export { setupTestDatabase };