@omnitron-dev/testing 0.4.2 → 0.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/dist/titan/container-utils.d.ts +20 -0
  2. package/dist/titan/container-utils.js +78 -0
  3. package/dist/titan/container-utils.js.map +1 -0
  4. package/dist/titan/database/database-testing.module.d.ts +81 -0
  5. package/dist/titan/database/database-testing.module.js +419 -0
  6. package/dist/titan/database/database-testing.module.js.map +1 -0
  7. package/dist/titan/database/index.d.ts +3 -0
  8. package/dist/titan/database/index.js +4 -0
  9. package/dist/titan/database/index.js.map +1 -0
  10. package/dist/titan/database/test-utilities.d.ts +31 -0
  11. package/dist/titan/database/test-utilities.js +145 -0
  12. package/dist/titan/database/test-utilities.js.map +1 -0
  13. package/dist/titan/index.d.ts +14 -0
  14. package/dist/titan/index.js +10 -0
  15. package/dist/titan/index.js.map +1 -0
  16. package/dist/titan/nexus/index.d.ts +3 -0
  17. package/dist/titan/nexus/index.js +4 -0
  18. package/dist/titan/nexus/index.js.map +1 -0
  19. package/dist/titan/nexus/mock-provider.d.ts +41 -0
  20. package/dist/titan/nexus/mock-provider.js +127 -0
  21. package/dist/titan/nexus/mock-provider.js.map +1 -0
  22. package/dist/titan/nexus/test-container.d.ts +120 -0
  23. package/dist/titan/nexus/test-container.js +559 -0
  24. package/dist/titan/nexus/test-container.js.map +1 -0
  25. package/dist/titan/nexus/test-utilities.d.ts +135 -0
  26. package/dist/titan/nexus/test-utilities.js +484 -0
  27. package/dist/titan/nexus/test-utilities.js.map +1 -0
  28. package/dist/titan/pm/index.d.ts +4 -0
  29. package/dist/titan/pm/index.js +4 -0
  30. package/dist/titan/pm/index.js.map +1 -0
  31. package/dist/titan/pm/mock-process-spawner.d.ts +60 -0
  32. package/dist/titan/pm/mock-process-spawner.js +321 -0
  33. package/dist/titan/pm/mock-process-spawner.js.map +1 -0
  34. package/dist/titan/pm/mock-spawner.d.ts +27 -0
  35. package/dist/titan/pm/mock-spawner.js +99 -0
  36. package/dist/titan/pm/mock-spawner.js.map +1 -0
  37. package/dist/titan/pm/test-process-manager.d.ts +49 -0
  38. package/dist/titan/pm/test-process-manager.js +188 -0
  39. package/dist/titan/pm/test-process-manager.js.map +1 -0
  40. package/dist/titan/redis-test-utils.d.ts +33 -0
  41. package/dist/titan/redis-test-utils.js +415 -0
  42. package/dist/titan/redis-test-utils.js.map +1 -0
  43. package/dist/titan/test-application.d.ts +21 -0
  44. package/dist/titan/test-application.js +90 -0
  45. package/dist/titan/test-application.js.map +1 -0
  46. package/dist/titan/test-fixtures.d.ts +97 -0
  47. package/dist/titan/test-fixtures.js +223 -0
  48. package/dist/titan/test-fixtures.js.map +1 -0
  49. package/dist/titan/test-mocks.d.ts +29 -0
  50. package/dist/titan/test-mocks.js +262 -0
  51. package/dist/titan/test-mocks.js.map +1 -0
  52. package/dist/titan/test-module.d.ts +47 -0
  53. package/dist/titan/test-module.js +120 -0
  54. package/dist/titan/test-module.js.map +1 -0
  55. package/package.json +15 -4
  56. package/src/titan/database/database-testing.module.ts +831 -0
  57. package/src/titan/database/index.ts +30 -0
  58. package/src/titan/database/test-utilities.ts +337 -0
  59. package/src/titan/index.ts +89 -1
  60. package/src/titan/nexus/index.ts +3 -0
  61. package/src/titan/nexus/mock-provider.ts +189 -0
  62. package/src/titan/nexus/test-container.ts +887 -0
  63. package/src/titan/nexus/test-utilities.ts +796 -0
  64. package/src/titan/pm/index.ts +22 -0
  65. package/src/titan/pm/mock-process-spawner.ts +481 -0
  66. package/src/titan/pm/mock-spawner.ts +156 -0
  67. package/src/titan/pm/test-process-manager.ts +345 -0
  68. package/src/titan/redis-test-utils.ts +3 -2
  69. package/src/titan/test-application.ts +2 -2
  70. package/src/titan/test-fixtures.ts +2 -1
  71. package/src/titan/test-module.ts +5 -3
@@ -0,0 +1,831 @@
1
+ /**
2
+ * Database Testing Module
3
+ *
4
+ * Provides utilities and configuration for testing database operations
5
+ * with automatic rollback, seeding, and cleanup capabilities
6
+ */
7
+
8
+ import { DynamicModule, IModule } from '@omnitron-dev/titan/nexus';
9
+ import { Module, Injectable, Inject } from '@omnitron-dev/titan/decorators';
10
+ import { Kysely, Transaction, sql } from 'kysely';
11
+ import { TitanDatabaseModule } from '@omnitron-dev/titan/module/database';
12
+ import { DatabaseManager } from '@omnitron-dev/titan/module/database';
13
+ import { MigrationRunner } from '@omnitron-dev/titan/module/database';
14
+ import { TransactionManager } from '@omnitron-dev/titan/module/database';
15
+ import { Errors } from '@omnitron-dev/titan/errors';
16
+ // @kysera/testing utilities (moved from @kysera/core in 0.7.0)
17
+ import {
18
+ testInTransaction,
19
+ testWithSavepoints,
20
+ testWithIsolation,
21
+ cleanDatabase as kyseraCleanDatabase,
22
+ seedDatabase as kyseraSeedDatabase,
23
+ snapshotTable,
24
+ countRows,
25
+ waitFor,
26
+ createFactory as kyseraCreateFactory,
27
+ type CleanupStrategy,
28
+ type IsolationLevel,
29
+ } from '@kysera/testing';
30
+ import {
31
+ DATABASE_MANAGER,
32
+ DATABASE_MIGRATION_SERVICE,
33
+ DATABASE_TRANSACTION_MANAGER,
34
+ DATABASE_TESTING_SERVICE,
35
+ } from '@omnitron-dev/titan/module/database';
36
+ import type { DatabaseModuleOptions } from '@omnitron-dev/titan/module/database';
37
+
38
+ export interface DatabaseTestingOptions extends Partial<DatabaseModuleOptions> {
39
+ /**
40
+ * Auto-rollback transactions after each test
41
+ */
42
+ transactional?: boolean;
43
+
44
+ /**
45
+ * Auto-migrate database before tests
46
+ */
47
+ autoMigrate?: boolean;
48
+
49
+ /**
50
+ * Auto-seed database with fixtures
51
+ */
52
+ autoSeed?: boolean;
53
+
54
+ /**
55
+ * Seed data or seed function
56
+ */
57
+ seeds?: any[] | (() => Promise<void>);
58
+
59
+ /**
60
+ * Clean database before each test
61
+ */
62
+ autoClean?: boolean;
63
+
64
+ /**
65
+ * Tables to preserve during cleanup
66
+ */
67
+ preserveTables?: string[];
68
+
69
+ /**
70
+ * Use isolated schema for each test suite
71
+ */
72
+ isolatedSchema?: boolean;
73
+
74
+ /**
75
+ * Schema name prefix for isolated schemas
76
+ */
77
+ schemaPrefix?: string;
78
+
79
+ /**
80
+ * Verbose logging for debugging
81
+ */
82
+ verbose?: boolean;
83
+ }
84
+
85
+ /**
86
+ * Database Testing Service
87
+ *
88
+ * Provides utilities for database testing
89
+ */
90
+ @Injectable()
91
+ export class DatabaseTestingService {
92
+ private currentTransaction?: Transaction<unknown>;
93
+ private schemaName?: string;
94
+ private isInitialized = false;
95
+
96
+ constructor(
97
+ @Inject(DATABASE_MANAGER) private manager: DatabaseManager,
98
+ @Inject('DATABASE_TESTING_OPTIONS') private options: DatabaseTestingOptions,
99
+ @Inject(DATABASE_MIGRATION_SERVICE) private migrationRunner?: MigrationRunner,
100
+ @Inject(DATABASE_TRANSACTION_MANAGER) private transactionManager?: TransactionManager
101
+ ) {}
102
+
103
+ /**
104
+ * Initialize test database
105
+ */
106
+ async initialize(): Promise<void> {
107
+ if (this.isInitialized) return;
108
+
109
+ const db = await this.manager.getConnection();
110
+
111
+ // Create isolated schema if needed
112
+ if (this.options.isolatedSchema) {
113
+ await this.createIsolatedSchema(db as Kysely<Record<string, unknown>>);
114
+ }
115
+
116
+ // Run migrations if enabled
117
+ if (this.options.autoMigrate && this.migrationRunner) {
118
+ await this.migrationRunner.migrate();
119
+ }
120
+
121
+ // Seed database if enabled
122
+ if (this.options.autoSeed && this.options.seeds) {
123
+ await this.seedDatabase();
124
+ }
125
+
126
+ this.isInitialized = true;
127
+ }
128
+
129
+ /**
130
+ * Setup before each test
131
+ */
132
+ async beforeEach(): Promise<void> {
133
+ const db = await this.manager.getConnection();
134
+
135
+ // Clean database if enabled
136
+ if (this.options.autoClean) {
137
+ await this.cleanDatabase();
138
+ }
139
+
140
+ // Start transaction if transactional mode is enabled
141
+ // Note: We don't actually start a transaction here for SQLite in-memory
142
+ // because it would require wrapping all test operations, which is complex.
143
+ // Instead, we rely on autoClean to reset state between tests.
144
+ // For PostgreSQL/MySQL, transactions could be supported in the future.
145
+ if (this.options.transactional) {
146
+ // For now, transactional mode just ensures autoClean is enabled
147
+ // Future enhancement: Implement proper transaction wrapping
148
+ }
149
+
150
+ // Re-seed if needed
151
+ if (this.options.autoSeed && this.options.seeds && this.options.autoClean) {
152
+ await this.seedDatabase();
153
+ }
154
+ }
155
+
156
+ /**
157
+ * Cleanup after each test
158
+ */
159
+ async afterEach(): Promise<void> {
160
+ // Rollback transaction if in transactional mode
161
+ if (this.options.transactional && this.currentTransaction) {
162
+ // Transaction will automatically rollback when not committed
163
+ this.currentTransaction = undefined;
164
+ }
165
+ }
166
+
167
+ /**
168
+ * Cleanup after all tests
169
+ */
170
+ async afterAll(): Promise<void> {
171
+ if (this.options.isolatedSchema && this.schemaName) {
172
+ await this.dropIsolatedSchema();
173
+ }
174
+ this.isInitialized = false;
175
+ }
176
+
177
+ /**
178
+ * Clean all data from database
179
+ */
180
+ async cleanDatabase(): Promise<void> {
181
+ const db = (await this.manager.getConnection()) as Kysely<Record<string, unknown>>;
182
+ const dialect = this.getDialect(db);
183
+ const preserveTables = this.options.preserveTables || [];
184
+
185
+ // Get all tables
186
+ const tables = await this.getAllTables(db, dialect);
187
+
188
+ // Clean tables in reverse order to handle foreign keys
189
+ for (const table of tables.reverse()) {
190
+ if (preserveTables.includes(table)) continue;
191
+
192
+ try {
193
+ if (dialect === 'postgres') {
194
+ await sql`TRUNCATE TABLE ${sql.table(table)} RESTART IDENTITY CASCADE`.execute(db);
195
+ } else if (dialect === 'mysql') {
196
+ await sql`SET FOREIGN_KEY_CHECKS = 0`.execute(db);
197
+ await sql`TRUNCATE TABLE ${sql.table(table)}`.execute(db);
198
+ await sql`SET FOREIGN_KEY_CHECKS = 1`.execute(db);
199
+ } else {
200
+ // SQLite
201
+ await sql`DELETE FROM ${sql.table(table)}`.execute(db);
202
+ // Reset autoincrement
203
+ await sql`DELETE FROM sqlite_sequence WHERE name = ${table}`.execute(db);
204
+ }
205
+ } catch (error) {
206
+ if (this.options.verbose) {
207
+ console.warn(`Failed to clean table ${table}:`, error);
208
+ }
209
+ }
210
+ }
211
+ }
212
+
213
+ /**
214
+ * Seed database with test data
215
+ */
216
+ async seedDatabase(seeds?: Array<{ table: string; data: unknown }>): Promise<void> {
217
+ const seedData = seeds || this.options.seeds;
218
+
219
+ if (!seedData) return;
220
+
221
+ if (typeof seedData === 'function') {
222
+ await seedData();
223
+ } else if (Array.isArray(seedData)) {
224
+ await this.insertSeeds(seedData);
225
+ }
226
+ }
227
+
228
+ /**
229
+ * Insert seed data
230
+ */
231
+ private async insertSeeds(seeds: Array<{ table: string; data: unknown }>): Promise<void> {
232
+ const db = this.currentTransaction || (await this.manager.getConnection());
233
+
234
+ for (const seed of seeds) {
235
+ if (!seed.table || !seed.data) continue;
236
+
237
+ try {
238
+ const records = Array.isArray(seed.data) ? seed.data : [seed.data];
239
+
240
+ for (const record of records) {
241
+ await (db as Kysely<Record<string, unknown>>)
242
+ .insertInto(seed.table)
243
+ .values(record)
244
+ .execute();
245
+ }
246
+ } catch (error) {
247
+ if (this.options.verbose) {
248
+ console.error(`Failed to seed table ${seed.table}:`, error);
249
+ }
250
+ }
251
+ }
252
+ }
253
+
254
+ /**
255
+ * Create isolated schema for testing
256
+ */
257
+ private async createIsolatedSchema(db: Kysely<Record<string, unknown>>): Promise<void> {
258
+ const dialect = this.getDialect(db);
259
+
260
+ if (dialect === 'postgres') {
261
+ const prefix = this.options.schemaPrefix || 'test';
262
+ this.schemaName = `${prefix}_${Date.now()}_${Math.random().toString(36).substring(7)}`;
263
+
264
+ await sql`CREATE SCHEMA IF NOT EXISTS ${sql.ref(this.schemaName)}`.execute(db);
265
+ await sql`SET search_path TO ${sql.ref(this.schemaName)}`.execute(db);
266
+ }
267
+ // MySQL and SQLite don't support schemas the same way
268
+ }
269
+
270
+ /**
271
+ * Drop isolated schema
272
+ */
273
+ private async dropIsolatedSchema(): Promise<void> {
274
+ if (!this.schemaName) return;
275
+
276
+ const db = (await this.manager.getConnection()) as Kysely<Record<string, unknown>>;
277
+ const dialect = this.getDialect(db);
278
+
279
+ if (dialect === 'postgres') {
280
+ await sql`DROP SCHEMA IF EXISTS ${sql.ref(this.schemaName)} CASCADE`.execute(db);
281
+ await sql`SET search_path TO public`.execute(db);
282
+ }
283
+ }
284
+
285
+ /**
286
+ * Get all tables in database
287
+ */
288
+ private async getAllTables(
289
+ db: Kysely<Record<string, unknown>>,
290
+ dialect: string
291
+ ): Promise<string[]> {
292
+ interface TableRow {
293
+ table_name: string;
294
+ }
295
+
296
+ let result: { rows: TableRow[] };
297
+
298
+ if (dialect === 'postgres') {
299
+ result = await sql<TableRow>`
300
+ SELECT table_name
301
+ FROM information_schema.tables
302
+ WHERE table_schema = ${this.schemaName || 'public'}
303
+ AND table_type = 'BASE TABLE'
304
+ `.execute(db);
305
+ return result.rows.map((r) => r.table_name);
306
+ } else if (dialect === 'mysql') {
307
+ result = await sql<TableRow>`
308
+ SELECT TABLE_NAME as table_name
309
+ FROM INFORMATION_SCHEMA.TABLES
310
+ WHERE TABLE_SCHEMA = DATABASE()
311
+ AND TABLE_TYPE = 'BASE TABLE'
312
+ `.execute(db);
313
+ return result.rows.map((r) => r.table_name);
314
+ } else {
315
+ // SQLite
316
+ result = await sql<TableRow>`
317
+ SELECT name as table_name
318
+ FROM sqlite_master
319
+ WHERE type = 'table'
320
+ AND name NOT LIKE 'sqlite_%'
321
+ `.execute(db);
322
+ return result.rows.map((r) => r.table_name);
323
+ }
324
+ }
325
+
326
+ /**
327
+ * Get database dialect
328
+ */
329
+ private getDialect(db: Kysely<Record<string, unknown>>): string {
330
+ // Try to determine dialect from the connection
331
+ const dbWithDialect = db as unknown as {
332
+ dialect?: { name?: string };
333
+ _dialect?: { name?: string };
334
+ driver?: { postgres?: unknown; mysql?: unknown };
335
+ };
336
+
337
+ const dialectName = dbWithDialect.dialect?.name || dbWithDialect._dialect?.name;
338
+
339
+ if (dialectName) return dialectName;
340
+
341
+ // Fallback to checking the driver
342
+ if (dbWithDialect.driver?.postgres) return 'postgres';
343
+ if (dbWithDialect.driver?.mysql) return 'mysql';
344
+
345
+ return 'sqlite';
346
+ }
347
+
348
+ /**
349
+ * Create a savepoint for nested testing
350
+ */
351
+ async createSavepoint(name: string): Promise<void> {
352
+ if (!this.currentTransaction) {
353
+ throw Errors.conflict('Savepoints require transactional mode');
354
+ }
355
+
356
+ await sql`SAVEPOINT ${sql.ref(name)}`.execute(this.currentTransaction);
357
+ }
358
+
359
+ /**
360
+ * Rollback to savepoint
361
+ */
362
+ async rollbackToSavepoint(name: string): Promise<void> {
363
+ if (!this.currentTransaction) {
364
+ throw Errors.conflict('Savepoints require transactional mode');
365
+ }
366
+
367
+ await sql`ROLLBACK TO SAVEPOINT ${sql.ref(name)}`.execute(this.currentTransaction);
368
+ }
369
+
370
+ /**
371
+ * Execute a query in test context
372
+ */
373
+ async execute<T>(query: (db: Kysely<Record<string, unknown>>) => Promise<T>): Promise<T> {
374
+ const db = this.currentTransaction || (await this.manager.getConnection());
375
+ return query(db as Kysely<Record<string, unknown>>);
376
+ }
377
+
378
+ /**
379
+ * Get test database connection
380
+ */
381
+ getTestConnection(): Kysely<Record<string, unknown>> | Transaction<unknown> {
382
+ return (this.currentTransaction || this.manager.getConnection()) as
383
+ | Kysely<Record<string, unknown>>
384
+ | Transaction<unknown>;
385
+ }
386
+
387
+ /**
388
+ * Factory method to create test data
389
+ */
390
+ async factory<T extends Record<string, unknown>>(
391
+ table: string,
392
+ generator: () => Partial<T> | Promise<Partial<T>>,
393
+ count: number = 1
394
+ ): Promise<T[]> {
395
+ const db = this.getTestConnection();
396
+ const results: T[] = [];
397
+
398
+ for (let i = 0; i < count; i++) {
399
+ const data = await generator();
400
+ const result = await (db as Kysely<Record<string, unknown>>)
401
+ .insertInto(table)
402
+ .values(data)
403
+ .returningAll()
404
+ .executeTakeFirst();
405
+
406
+ if (result) {
407
+ results.push(result as T);
408
+ }
409
+ }
410
+
411
+ return results;
412
+ }
413
+
414
+ /**
415
+ * Assert database state
416
+ */
417
+ async assertDatabaseHas(table: string, data: Record<string, unknown>): Promise<boolean> {
418
+ const db = this.getTestConnection() as Kysely<Record<string, unknown>>;
419
+
420
+ let query = db.selectFrom(table).selectAll();
421
+
422
+ for (const [key, value] of Object.entries(data)) {
423
+ // Use type assertion to bypass strict type checking for dynamic queries
424
+ query = query.where(key as never, '=', value as never);
425
+ }
426
+
427
+ const result = await query.executeTakeFirst();
428
+ return result !== undefined;
429
+ }
430
+
431
+ /**
432
+ * Assert database doesn't have specific data
433
+ */
434
+ async assertDatabaseMissing(table: string, data: Record<string, unknown>): Promise<boolean> {
435
+ const has = await this.assertDatabaseHas(table, data);
436
+ return !has;
437
+ }
438
+
439
+ /**
440
+ * Count records in table
441
+ */
442
+ async assertDatabaseCount(table: string, count: number): Promise<boolean> {
443
+ const db = this.getTestConnection();
444
+
445
+ const result = await (db as Kysely<Record<string, unknown>>)
446
+ .selectFrom(table)
447
+ .select(sql<number>`count(*)`.as('count'))
448
+ .executeTakeFirst();
449
+
450
+ return result?.count === count;
451
+ }
452
+
453
+ // ============================================================================
454
+ // KYSERA-CORE TESTING UTILITIES INTEGRATION
455
+ // ============================================================================
456
+
457
+ /**
458
+ * Run test in a transaction that automatically rolls back
459
+ * Uses @kysera/core testInTransaction for automatic cleanup
460
+ *
461
+ * @example
462
+ * ```typescript
463
+ * await testingService.runInTransaction(async (trx) => {
464
+ * await trx.insertInto('users').values({ name: 'test' }).execute();
465
+ * // Transaction auto-rolls back after test
466
+ * });
467
+ * ```
468
+ */
469
+ async runInTransaction<T>(
470
+ fn: (trx: Transaction<unknown>) => Promise<T>
471
+ ): Promise<void> {
472
+ const db = await this.manager.getConnection();
473
+ await testInTransaction(db, fn);
474
+ }
475
+
476
+ /**
477
+ * Run test with savepoints for nested transaction testing
478
+ * Uses @kysera/core testWithSavepoints
479
+ *
480
+ * @example
481
+ * ```typescript
482
+ * await testingService.runWithSavepoints(async (trx) => {
483
+ * await trx.insertInto('users').values({ name: 'test' }).execute();
484
+ * // Savepoint created and rolled back automatically
485
+ * });
486
+ * ```
487
+ */
488
+ async runWithSavepoints<T>(
489
+ fn: (trx: Transaction<unknown>) => Promise<T>
490
+ ): Promise<void> {
491
+ const db = await this.manager.getConnection();
492
+ await testWithSavepoints(db, fn);
493
+ }
494
+
495
+ /**
496
+ * Run test with specific isolation level
497
+ * Uses @kysera/core testWithIsolation
498
+ *
499
+ * @param isolationLevel - 'read uncommitted' | 'read committed' | 'repeatable read' | 'serializable'
500
+ *
501
+ * @example
502
+ * ```typescript
503
+ * await testingService.runWithIsolation('serializable', async (trx) => {
504
+ * // Test concurrent access scenarios
505
+ * });
506
+ * ```
507
+ */
508
+ async runWithIsolation<T>(
509
+ isolationLevel: IsolationLevel,
510
+ fn: (trx: Transaction<unknown>) => Promise<T>
511
+ ): Promise<void> {
512
+ const db = await this.manager.getConnection();
513
+ await testWithIsolation(db, isolationLevel, fn);
514
+ }
515
+
516
+ /**
517
+ * Clean database using @kysera/core cleanup strategies
518
+ *
519
+ * @param strategy - 'truncate' | 'transaction' | 'delete'
520
+ * @param tables - Optional list of tables to clean (cleans all if not specified)
521
+ *
522
+ * @example
523
+ * ```typescript
524
+ * await testingService.cleanWithKysera('truncate', ['users', 'posts']);
525
+ * ```
526
+ */
527
+ async cleanWithKysera(
528
+ strategy: CleanupStrategy = 'delete',
529
+ tables?: string[]
530
+ ): Promise<void> {
531
+ const db = await this.manager.getConnection();
532
+ await kyseraCleanDatabase(db, strategy, tables);
533
+ }
534
+
535
+ /**
536
+ * Seed database using @kysera/core seedDatabase
537
+ *
538
+ * @example
539
+ * ```typescript
540
+ * await testingService.seedWithKysera(async (trx) => {
541
+ * await trx.insertInto('users').values([...]).execute();
542
+ * });
543
+ * ```
544
+ */
545
+ async seedWithKysera(
546
+ fn: (trx: Transaction<unknown>) => Promise<void>
547
+ ): Promise<void> {
548
+ const db = await this.manager.getConnection();
549
+ await kyseraSeedDatabase(db, fn);
550
+ }
551
+
552
+ /**
553
+ * Take a snapshot of table data for comparison
554
+ * Uses @kysera/core snapshotTable
555
+ *
556
+ * @example
557
+ * ```typescript
558
+ * const before = await testingService.snapshotTable('users');
559
+ * // ... perform operations
560
+ * const after = await testingService.snapshotTable('users');
561
+ * expect(after.length).toBe(before.length + 1);
562
+ * ```
563
+ */
564
+ async snapshotTable<T = unknown>(table: string): Promise<T[]> {
565
+ const db = await this.manager.getConnection();
566
+ return snapshotTable(db, table) as Promise<T[]>;
567
+ }
568
+
569
+ /**
570
+ * Count rows in a table using @kysera/core countRows
571
+ *
572
+ * @example
573
+ * ```typescript
574
+ * const count = await testingService.countRows('users');
575
+ * expect(count).toBe(5);
576
+ * ```
577
+ */
578
+ async countTableRows(table: string): Promise<number> {
579
+ const db = await this.manager.getConnection();
580
+ return countRows(db, table);
581
+ }
582
+
583
+ /**
584
+ * Wait for a condition to become true
585
+ * Uses @kysera/core waitFor - useful for async operations
586
+ *
587
+ * @example
588
+ * ```typescript
589
+ * await testingService.waitForCondition(
590
+ * async () => (await testingService.countTableRows('events')) > 0,
591
+ * { timeout: 5000, interval: 100 }
592
+ * );
593
+ * ```
594
+ */
595
+ async waitForCondition(
596
+ condition: () => Promise<boolean> | boolean,
597
+ options?: { timeout?: number; interval?: number; timeoutMessage?: string }
598
+ ): Promise<void> {
599
+ await waitFor(condition, options);
600
+ }
601
+
602
+ /**
603
+ * Create a test data factory using @kysera/core createFactory
604
+ *
605
+ * @example
606
+ * ```typescript
607
+ * const createUser = testingService.createDataFactory({
608
+ * id: 1,
609
+ * email: () => `user${Date.now()}@test.com`,
610
+ * name: 'Test User',
611
+ * });
612
+ *
613
+ * const user1 = createUser(); // Uses defaults
614
+ * const user2 = createUser({ name: 'Custom Name' }); // Override name
615
+ * ```
616
+ */
617
+ createDataFactory<T extends Record<string, unknown>>(
618
+ defaults: { [K in keyof T]: T[K] | (() => T[K]) }
619
+ ): (overrides?: Partial<T>) => T {
620
+ return kyseraCreateFactory(defaults);
621
+ }
622
+
623
+ /**
624
+ * Create multiple test records using factory pattern
625
+ *
626
+ * @example
627
+ * ```typescript
628
+ * const createUser = testingService.createDataFactory({ ... });
629
+ * const users = await testingService.createManyFromFactory('users', createUser, 10);
630
+ * ```
631
+ */
632
+ async createManyFromFactory<T extends Record<string, unknown>>(
633
+ table: string,
634
+ factory: (overrides?: Partial<T>) => T,
635
+ count: number,
636
+ overrides?: Partial<T>
637
+ ): Promise<T[]> {
638
+ const db = this.getTestConnection() as Kysely<Record<string, unknown>>;
639
+ const results: T[] = [];
640
+
641
+ for (let i = 0; i < count; i++) {
642
+ const data = factory(overrides);
643
+ const result = await db
644
+ .insertInto(table)
645
+ .values(data)
646
+ .returningAll()
647
+ .executeTakeFirst();
648
+
649
+ if (result) {
650
+ results.push(result as T);
651
+ }
652
+ }
653
+
654
+ return results;
655
+ }
656
+ }
657
+
658
+ /**
659
+ * Database Testing Module
660
+ */
661
+ @Module({})
662
+ export class DatabaseTestingModule {
663
+ /**
664
+ * Create testing module with configuration
665
+ */
666
+ static forTest(options: DatabaseTestingOptions = {}): DynamicModule {
667
+ const defaultOptions: DatabaseTestingOptions = {
668
+ transactional: true,
669
+ autoMigrate: true,
670
+ autoClean: true,
671
+ verbose: false,
672
+ ...options,
673
+ };
674
+
675
+ // Override connection to use in-memory SQLite by default
676
+ // Use a named shared memory database so all connections within the same process
677
+ // share the same database instance
678
+ if (!options.connection) {
679
+ const dbName = `test_${Date.now()}_${Math.random().toString(36).substring(7)}`;
680
+ defaultOptions.connection = {
681
+ dialect: 'sqlite',
682
+ connection: `file:${dbName}?mode=memory&cache=shared`,
683
+ };
684
+ }
685
+
686
+ const providers = [
687
+ {
688
+ provide: 'DATABASE_TESTING_OPTIONS',
689
+ useValue: defaultOptions,
690
+ },
691
+ {
692
+ provide: DATABASE_TESTING_SERVICE,
693
+ useFactory: async (manager: DatabaseManager) =>
694
+ new DatabaseTestingService(
695
+ manager,
696
+ defaultOptions,
697
+ undefined, // migrationRunner (optional)
698
+ undefined // transactionManager (optional)
699
+ ),
700
+ inject: [DATABASE_MANAGER],
701
+ async: true,
702
+ },
703
+ // Alias registration for DatabaseTestingService class (allows resolving by class)
704
+ {
705
+ provide: DatabaseTestingService,
706
+ useFactory: async (service: DatabaseTestingService) => service,
707
+ inject: [DATABASE_TESTING_SERVICE],
708
+ async: true,
709
+ },
710
+ ];
711
+
712
+ const databaseModule = TitanDatabaseModule.forRoot({
713
+ ...defaultOptions,
714
+ isGlobal: true,
715
+ });
716
+
717
+ return {
718
+ module: DatabaseTestingModule,
719
+ global: true,
720
+ imports: [databaseModule as unknown as IModule],
721
+ providers,
722
+ exports: [DATABASE_TESTING_SERVICE],
723
+ } as DynamicModule;
724
+ }
725
+
726
+ /**
727
+ * Create isolated testing module for parallel tests
728
+ *
729
+ * Creates a completely isolated database testing environment suitable for
730
+ * running tests in parallel. Each isolated module gets its own schema (if supported)
731
+ * and independent service instances.
732
+ */
733
+ static async createIsolatedModule(
734
+ options: DatabaseTestingOptions = {}
735
+ ): Promise<{
736
+ module: DynamicModule;
737
+ service?: DatabaseTestingService;
738
+ cleanup: () => Promise<void>;
739
+ }> {
740
+ // Generate unique schema name for this isolated module
741
+ const schemaPrefix = options.schemaPrefix || 'test_isolated';
742
+ const uniqueSuffix = `${Date.now()}_${Math.random().toString(36).substring(7)}`;
743
+ const isolatedSchemaName = `${schemaPrefix}_${uniqueSuffix}`;
744
+
745
+ // Create isolated module with unique schema
746
+ const isolatedOptions: DatabaseTestingOptions = {
747
+ ...options,
748
+ isolatedSchema: true,
749
+ schemaPrefix: isolatedSchemaName,
750
+ transactional: options.transactional ?? true,
751
+ autoMigrate: options.autoMigrate ?? false,
752
+ autoClean: options.autoClean ?? true,
753
+ };
754
+
755
+ // Override connection to use unique database/schema if not provided
756
+ if (!isolatedOptions.connection) {
757
+ // Use unique file-based SQLite for true isolation
758
+ // :memory: databases are shared if the connection string is the same
759
+ isolatedOptions.connection = {
760
+ dialect: 'sqlite',
761
+ connection: `file:${isolatedSchemaName}?mode=memory&cache=shared`,
762
+ };
763
+ }
764
+
765
+ const module = DatabaseTestingModule.forTest(isolatedOptions);
766
+
767
+ // Store service reference for cleanup
768
+ let serviceInstance: DatabaseTestingService | undefined;
769
+
770
+ // Return module with enhanced cleanup that properly disposes the service
771
+ return {
772
+ module,
773
+ get service() {
774
+ return serviceInstance;
775
+ },
776
+ cleanup: async () => {
777
+ try {
778
+ // If service was injected, clean it up
779
+ if (serviceInstance) {
780
+ await serviceInstance.afterAll();
781
+ }
782
+
783
+ // Find and cleanup the service from the module's container if it exists
784
+ // This handles cases where the service was created but not stored in serviceInstance
785
+ const providers = (module as any).providers || [];
786
+ for (const provider of providers) {
787
+ if (
788
+ typeof provider === 'object' &&
789
+ provider &&
790
+ 'provide' in provider &&
791
+ provider.provide === DATABASE_TESTING_SERVICE
792
+ ) {
793
+ // Provider cleanup handled by afterAll above
794
+ break;
795
+ }
796
+ }
797
+ } catch (error) {
798
+ if (isolatedOptions.verbose) {
799
+ console.warn('Error during isolated module cleanup:', error);
800
+ }
801
+ }
802
+ },
803
+ };
804
+ }
805
+
806
+ /**
807
+ * Helper to inject the DatabaseTestingService into an isolated module result
808
+ * This should be called after the application/container is created
809
+ */
810
+ static async injectServiceIntoIsolatedModule(
811
+ isolatedModuleResult: {
812
+ module: DynamicModule;
813
+ service?: DatabaseTestingService;
814
+ cleanup: () => Promise<void>;
815
+ },
816
+ container: { resolveAsync: (token: any) => Promise<any> }
817
+ ): Promise<void> {
818
+ try {
819
+ const service = (await container.resolveAsync(DATABASE_TESTING_SERVICE)) as DatabaseTestingService;
820
+ // Store the service reference in the result object
821
+ Object.defineProperty(isolatedModuleResult, 'service', {
822
+ value: service,
823
+ writable: true,
824
+ configurable: true,
825
+ });
826
+ await service.initialize();
827
+ } catch (error) {
828
+ console.warn('Failed to inject DatabaseTestingService:', error);
829
+ }
830
+ }
831
+ }