integration-test-db.ts 2.5 KB

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