@omnitron-dev/testing 0.1.1

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