| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166 |
- import { DataSource } from 'typeorm';
- import { beforeEach, afterEach, afterAll } from 'vitest';
- import { UserEntity } from '../modules/users/user.entity';
- import { Role } from '../modules/users/role.entity';
- import { AppDataSource } from '../data-source';
- /**
- * 集成测试数据库工具类 - 使用真实PostgreSQL数据库
- */
- export class IntegrationTestDatabase {
- // private static initializationPromise: Promise<DataSource> | null = null;
- // /**
- // * 初始化集成测试数据库
- // */
- // static async initialize(): Promise<DataSource> {
- // // if (!AppDataSource.isInitialized) {
- // // if (!this.initializationPromise) {
- // // this.initializationPromise = (async () => {
- // // try {
- // // await AppDataSource.initialize();
- // // return AppDataSource;
- // // } catch (error) {
- // // this.initializationPromise = null;
- // // throw error;
- // // }
- // // })();
- // // }
- // // return await this.initializationPromise;
- // // }
- // // if(!AppDataSource.isInitialized) {
- // // await AppDataSource.initialize();
- // // }
- // return AppDataSource;
- // }
- /**
- * 清理集成测试数据库
- */
- static async cleanup(): Promise<void> {
- if (AppDataSource.isInitialized) {
- console.debug('测试数据库断开')
- await AppDataSource.destroy();
- }
- }
- /**
- * 获取当前数据源
- */
- static async getDataSource(): Promise<DataSource> {
- if(!AppDataSource.isInitialized) {
- console.debug('测试数据库初始化')
- await AppDataSource.initialize();
- }
- return AppDataSource
- }
- // /**
- // * 清空所有表数据
- // */
- // static async clearAllData(): Promise<void> {
- // if (!AppDataSource.isInitialized) {
- // return;
- // }
- // const queryRunner = AppDataSource.createQueryRunner();
- // await queryRunner.connect();
- // try {
- // // 获取所有实体
- // const entities = AppDataSource.entityMetadatas;
- // // 按依赖关系排序(先删除子表,再删除父表)
- // const sortedEntities = entities.sort((a, b) => {
- // if (a.foreignKeys.some(fk => fk.referencedEntityMetadata.name === b.name)) {
- // return 1; // a 依赖于 b,a 应该排在后面
- // }
- // if (b.foreignKeys.some(fk => fk.referencedEntityMetadata.name === a.name)) {
- // return -1; // b 依赖于 a,a 应该排在前面
- // }
- // return 0;
- // });
- // // 使用TRUNCATE CASCADE来清空所有表数据(包括有外键约束的表)
- // for (const entity of sortedEntities) {
- // await queryRunner.query(`TRUNCATE TABLE "${entity.tableName}" CASCADE`);
- // }
- // } finally {
- // await queryRunner.release();
- // }
- // }
- }
- /**
- * 测试数据工厂类
- */
- export class TestDataFactory {
- /**
- * 创建测试用户数据
- */
- static createUserData(overrides: Partial<UserEntity> = {}): Partial<UserEntity> {
- const timestamp = Date.now();
- return {
- username: `testuser_${timestamp}`,
- password: 'TestPassword123!',
- email: `test_${timestamp}@example.com`,
- phone: `138${timestamp.toString().slice(-8)}`,
- nickname: `Test User ${timestamp}`,
- name: `Test Name ${timestamp}`,
- isDisabled: 0,
- isDeleted: 0,
- ...overrides
- };
- }
- /**
- * 创建测试角色数据
- */
- static createRoleData(overrides: Partial<Role> = {}): Partial<Role> {
- const timestamp = Date.now();
- return {
- name: `test_role_${timestamp}`,
- description: `Test role description ${timestamp}`,
- ...overrides
- };
- }
- /**
- * 在数据库中创建测试用户
- */
- static async createTestUser(dataSource: DataSource, overrides: Partial<UserEntity> = {}): Promise<UserEntity> {
- const userData = this.createUserData(overrides);
- const userRepository = dataSource.getRepository(UserEntity);
- const user = userRepository.create(userData);
- return await userRepository.save(user);
- }
- /**
- * 在数据库中创建测试角色
- */
- static async createTestRole(dataSource: DataSource, overrides: Partial<Role> = {}): Promise<Role> {
- const roleData = this.createRoleData(overrides);
- const roleRepository = dataSource.getRepository(Role);
- const role = roleRepository.create(roleData);
- return await roleRepository.save(role);
- }
- }
- /**
- * 集成测试数据库生命周期钩子
- */
- export function setupIntegrationDatabaseHooks() {
- beforeEach(async () => {
- await IntegrationTestDatabase.getDataSource();
- });
- // afterEach(async () => {
- // await IntegrationTestDatabase.clearAllData();
- // });
- afterEach(async () => {
- console.debug('测试数据库断开')
- await IntegrationTestDatabase.cleanup();
- });
- }
|