integration-test-db.ts 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. import { DataSource } from 'typeorm';
  2. import { beforeEach, afterEach } from 'vitest';
  3. import { UserEntity } from '@/server/modules/users/user.entity';
  4. import { Role } from '@/server/modules/users/role.entity';
  5. import { AppDataSource } from '@/server/data-source';
  6. /**
  7. * 集成测试数据库工具类 - 使用真实PostgreSQL数据库
  8. */
  9. export class IntegrationTestDatabase {
  10. /**
  11. * 清理集成测试数据库
  12. */
  13. static async cleanup(): Promise<void> {
  14. if (AppDataSource.isInitialized) {
  15. await AppDataSource.destroy();
  16. }
  17. }
  18. /**
  19. * 获取当前数据源
  20. */
  21. static async getDataSource(): Promise<DataSource> {
  22. if(!AppDataSource.isInitialized) {
  23. await AppDataSource.initialize();
  24. }
  25. return AppDataSource
  26. }
  27. }
  28. /**
  29. * 测试数据工厂类
  30. */
  31. export class TestDataFactory {
  32. /**
  33. * 创建测试用户数据
  34. */
  35. static createUserData(overrides: Partial<UserEntity> = {}): Partial<UserEntity> {
  36. const timestamp = Date.now();
  37. return {
  38. username: `testuser_${timestamp}`,
  39. password: 'TestPassword123!',
  40. email: `test_${timestamp}@example.com`,
  41. phone: `138${timestamp.toString().slice(-8)}`,
  42. nickname: `Test User ${timestamp}`,
  43. name: `Test Name ${timestamp}`,
  44. isDisabled: 0,
  45. isDeleted: 0,
  46. ...overrides
  47. };
  48. }
  49. /**
  50. * 创建测试角色数据
  51. */
  52. static createRoleData(overrides: Partial<Role> = {}): Partial<Role> {
  53. const timestamp = Date.now();
  54. return {
  55. name: `test_role_${timestamp}`,
  56. description: `Test role description ${timestamp}`,
  57. ...overrides
  58. };
  59. }
  60. /**
  61. * 在数据库中创建测试用户
  62. */
  63. static async createTestUser(dataSource: DataSource, overrides: Partial<UserEntity> = {}): Promise<UserEntity> {
  64. const userData = this.createUserData(overrides);
  65. const userRepository = dataSource.getRepository(UserEntity);
  66. const user = userRepository.create(userData);
  67. return await userRepository.save(user);
  68. }
  69. /**
  70. * 在数据库中创建测试角色
  71. */
  72. static async createTestRole(dataSource: DataSource, overrides: Partial<Role> = {}): Promise<Role> {
  73. const roleData = this.createRoleData(overrides);
  74. const roleRepository = dataSource.getRepository(Role);
  75. const role = roleRepository.create(roleData);
  76. return await roleRepository.save(role);
  77. }
  78. }
  79. /**
  80. * 集成测试数据库生命周期钩子
  81. */
  82. export function setupIntegrationDatabaseHooks() {
  83. beforeEach(async () => {
  84. await IntegrationTestDatabase.getDataSource();
  85. });
  86. afterEach(async () => {
  87. await IntegrationTestDatabase.cleanup();
  88. });
  89. }