@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,567 @@
1
+ /**
2
+ * Redis Test Utilities
3
+ *
4
+ * Enterprise-grade testing utilities for Redis-based components
5
+ * Provides comprehensive fixtures and helpers for testing Redis functionality
6
+ */
7
+
8
+ import { Redis, RedisOptions } from 'ioredis';
9
+ import { RedisManager } from '@omnitron-dev/titan-redis';
10
+ import { RedisService } from '@omnitron-dev/titan-redis';
11
+ import { EventEmitter } from '@omnitron-dev/eventemitter';
12
+ import { Errors } from '@omnitron-dev/titan/errors';
13
+ import type { ILogger } from '@omnitron-dev/titan/module/logger';
14
+
15
+ /**
16
+ * Create a null logger for testing
17
+ */
18
+ function createTestNullLogger(): ILogger {
19
+ const noop = () => {};
20
+ return {
21
+ trace: noop,
22
+ debug: noop,
23
+ info: noop,
24
+ warn: noop,
25
+ error: noop,
26
+ fatal: noop,
27
+ child: () => createTestNullLogger(),
28
+ time: () => noop,
29
+ isLevelEnabled: () => false,
30
+ setLevel: noop,
31
+ getLevel: () => 'silent',
32
+ } as unknown as ILogger;
33
+ }
34
+
35
+ /**
36
+ * Redis test fixture configuration
37
+ */
38
+ export interface RedisTestFixtureOptions {
39
+ withManager?: boolean;
40
+ withService?: boolean;
41
+ db?: number;
42
+ host?: string;
43
+ port?: number;
44
+ namespace?: string;
45
+ password?: string;
46
+ lazyConnect?: boolean;
47
+ enableReadyCheck?: boolean;
48
+ maxRetriesPerRequest?: number;
49
+ retryStrategy?: () => null;
50
+ }
51
+
52
+ /**
53
+ * Redis test fixture containing all necessary components
54
+ */
55
+ export interface RedisTestFixture {
56
+ client: Redis;
57
+ manager?: RedisManager;
58
+ service?: RedisService;
59
+ cleanup: () => Promise<void>;
60
+ options: RedisOptions;
61
+ }
62
+
63
+ /**
64
+ * Create a Redis test fixture with proper cleanup
65
+ */
66
+ export async function createRedisTestFixture(options: RedisTestFixtureOptions = {}): Promise<RedisTestFixture> {
67
+ const {
68
+ withManager = false,
69
+ withService = false,
70
+ db = 15, // Use test database
71
+ host = 'localhost',
72
+ port = 6379,
73
+ namespace = 'test',
74
+ lazyConnect = false,
75
+ enableReadyCheck = true,
76
+ maxRetriesPerRequest = 1,
77
+ retryStrategy = () => null, // Disable retries in tests
78
+ } = options;
79
+
80
+ const redisOptions: RedisOptions = {
81
+ host,
82
+ port,
83
+ db,
84
+ password: options.password,
85
+ lazyConnect,
86
+ enableReadyCheck,
87
+ maxRetriesPerRequest,
88
+ retryStrategy,
89
+ };
90
+
91
+ // Create primary client
92
+ const client = new Redis(redisOptions);
93
+
94
+ // Wait for connection if not lazy
95
+ if (!lazyConnect) {
96
+ await new Promise<void>((resolve, reject) => {
97
+ const timeout = setTimeout(() => {
98
+ client.removeAllListeners();
99
+ reject(Errors.timeout('Redis connection in test fixture', 10000));
100
+ }, 10000); // 10 second timeout
101
+
102
+ client.once('ready', () => {
103
+ clearTimeout(timeout);
104
+ resolve();
105
+ });
106
+ client.once('error', (error) => {
107
+ clearTimeout(timeout);
108
+ reject(error);
109
+ });
110
+
111
+ // Ensure connection starts
112
+ if (client.status === 'wait') {
113
+ client.connect().catch(reject);
114
+ }
115
+ });
116
+ }
117
+
118
+ let manager: RedisManager | undefined;
119
+ let service: RedisService | undefined;
120
+
121
+ // Create manager if requested
122
+ if (withManager) {
123
+ // Use type assertion to avoid ioredis version compatibility issues
124
+ const clientConfigs = [
125
+ {
126
+ namespace: 'default',
127
+ ...redisOptions,
128
+ db: redisOptions.db, // Use the test DB
129
+ },
130
+ {
131
+ namespace,
132
+ ...redisOptions,
133
+ db: redisOptions.db, // Use the test DB
134
+ },
135
+ ...(namespace !== 'cache'
136
+ ? [
137
+ {
138
+ namespace: 'cache',
139
+ ...redisOptions,
140
+ db: 14, // Use different DB for cache namespace
141
+ },
142
+ ]
143
+ : []),
144
+ ] as any;
145
+
146
+ manager = new RedisManager({ clients: clientConfigs }, createTestNullLogger());
147
+ await manager.onModuleInit();
148
+ }
149
+
150
+ // Create service if requested
151
+ if (withService && manager) {
152
+ service = new RedisService(manager);
153
+ }
154
+
155
+ // Cleanup function
156
+ const cleanup = async () => {
157
+ try {
158
+ // Clear all data in test database
159
+ await client.flushdb();
160
+
161
+ // Cleanup manager
162
+ if (manager) {
163
+ await manager.onModuleDestroy();
164
+ }
165
+
166
+ // Close client
167
+ client.disconnect();
168
+
169
+ // Remove all listeners
170
+ client.removeAllListeners();
171
+ } catch (error) {
172
+ console.error('Cleanup error:', error);
173
+ }
174
+ };
175
+
176
+ return {
177
+ client,
178
+ manager,
179
+ service,
180
+ cleanup,
181
+ options: redisOptions,
182
+ };
183
+ }
184
+
185
+ /**
186
+ * Cleanup Redis test fixture
187
+ */
188
+ export async function cleanupRedisTestFixture(fixture: RedisTestFixture): Promise<void> {
189
+ if (fixture && fixture.cleanup) {
190
+ await fixture.cleanup();
191
+ }
192
+ }
193
+
194
+ /**
195
+ * Wait for Redis operation to complete
196
+ */
197
+ export async function waitForRedis(operation: () => Promise<any>, timeout = 5000): Promise<any> {
198
+ return Promise.race([
199
+ operation(),
200
+ new Promise((_, reject) => setTimeout(() => reject(Errors.timeout('Redis operation', timeout)), timeout)),
201
+ ]);
202
+ }
203
+
204
+ /**
205
+ * Create mock Redis client for unit tests
206
+ */
207
+ export function createMockRedis(): any {
208
+ const data = new Map<string, any>();
209
+ const pubsub = new EventEmitter();
210
+ const locks = new Map<string, { token: string; ttl: number }>();
211
+
212
+ const mock = {
213
+ // Connection
214
+ connect: vi.fn().mockResolvedValue(undefined),
215
+ disconnect: vi.fn().mockImplementation(() => {
216
+ mock.emit('close');
217
+ }),
218
+ quit: vi.fn().mockResolvedValue('OK'),
219
+ ping: vi.fn().mockResolvedValue('PONG'),
220
+
221
+ // Basic operations
222
+ get: vi.fn().mockImplementation(async (key: string) => data.get(key) ?? null),
223
+
224
+ set: vi.fn().mockImplementation(async (key: string, value: any, ...args: any[]) => {
225
+ data.set(key, typeof value === 'object' ? JSON.stringify(value) : String(value));
226
+
227
+ // Handle TTL
228
+ if (args[0] === 'EX' && args[1]) {
229
+ setTimeout(() => data.delete(key), args[1] * 1000);
230
+ } else if (args[0] === 'PX' && args[1]) {
231
+ setTimeout(() => data.delete(key), args[1]);
232
+ }
233
+
234
+ return 'OK';
235
+ }),
236
+
237
+ setex: vi.fn().mockImplementation(async (key: string, ttl: number, value: any) => {
238
+ data.set(key, String(value));
239
+ setTimeout(() => data.delete(key), ttl * 1000);
240
+ return 'OK';
241
+ }),
242
+
243
+ del: vi.fn().mockImplementation(async (...keys: string[]) => {
244
+ let count = 0;
245
+ for (const key of keys) {
246
+ if (data.delete(key)) count++;
247
+ }
248
+ return count;
249
+ }),
250
+
251
+ exists: vi.fn().mockImplementation(async (...keys: string[]) => keys.filter((k) => data.has(k)).length),
252
+
253
+ expire: vi.fn().mockImplementation(async (key: string, ttl: number) => {
254
+ if (data.has(key)) {
255
+ setTimeout(() => data.delete(key), ttl * 1000);
256
+ return 1;
257
+ }
258
+ return 0;
259
+ }),
260
+
261
+ ttl: vi.fn().mockImplementation(async (key: string) => (data.has(key) ? -1 : -2)),
262
+
263
+ keys: vi.fn().mockImplementation(async (pattern: string) => {
264
+ if (pattern === '*') return Array.from(data.keys());
265
+ const regex = new RegExp(pattern.replace('*', '.*'));
266
+ return Array.from(data.keys()).filter((k) => regex.test(k));
267
+ }),
268
+
269
+ // Hash operations
270
+ hget: vi.fn().mockImplementation(async (key: string, field: string) => {
271
+ const hash = data.get(key);
272
+ if (!hash || typeof hash !== 'object') return null;
273
+ return hash[field] ?? null;
274
+ }),
275
+
276
+ hset: vi.fn().mockImplementation(async (key: string, field: string, value: any) => {
277
+ let hash = data.get(key);
278
+ if (!hash || typeof hash !== 'object') {
279
+ hash = {};
280
+ data.set(key, hash);
281
+ }
282
+ const isNew = !(field in hash);
283
+ hash[field] = value;
284
+ return isNew ? 1 : 0;
285
+ }),
286
+
287
+ hgetall: vi.fn().mockImplementation(async (key: string) => {
288
+ const hash = data.get(key);
289
+ return hash && typeof hash === 'object' ? hash : {};
290
+ }),
291
+
292
+ // List operations
293
+ lpush: vi.fn().mockImplementation(async (key: string, ...values: any[]) => {
294
+ let list = data.get(key);
295
+ if (!Array.isArray(list)) {
296
+ list = [];
297
+ data.set(key, list);
298
+ }
299
+ list.unshift(...values);
300
+ return list.length;
301
+ }),
302
+
303
+ rpush: vi.fn().mockImplementation(async (key: string, ...values: any[]) => {
304
+ let list = data.get(key);
305
+ if (!Array.isArray(list)) {
306
+ list = [];
307
+ data.set(key, list);
308
+ }
309
+ list.push(...values);
310
+ return list.length;
311
+ }),
312
+
313
+ lpop: vi.fn().mockImplementation(async (key: string) => {
314
+ const list = data.get(key);
315
+ if (!Array.isArray(list) || list.length === 0) return null;
316
+ return list.shift();
317
+ }),
318
+
319
+ rpop: vi.fn().mockImplementation(async (key: string) => {
320
+ const list = data.get(key);
321
+ if (!Array.isArray(list) || list.length === 0) return null;
322
+ return list.pop();
323
+ }),
324
+
325
+ lrange: vi.fn().mockImplementation(async (key: string, start: number, stop: number) => {
326
+ const list = data.get(key);
327
+ if (!Array.isArray(list)) return [];
328
+ return list.slice(start, stop + 1);
329
+ }),
330
+
331
+ // Set operations
332
+ sadd: vi.fn().mockImplementation(async (key: string, ...members: any[]) => {
333
+ let set = data.get(key);
334
+ if (!set || !(set instanceof Set)) {
335
+ set = new Set();
336
+ data.set(key, set);
337
+ }
338
+ let added = 0;
339
+ for (const member of members) {
340
+ if (!set.has(member)) {
341
+ set.add(member);
342
+ added++;
343
+ }
344
+ }
345
+ return added;
346
+ }),
347
+
348
+ smembers: vi.fn().mockImplementation(async (key: string) => {
349
+ const set = data.get(key);
350
+ if (!set || !(set instanceof Set)) return [];
351
+ return Array.from(set);
352
+ }),
353
+
354
+ sismember: vi.fn().mockImplementation(async (key: string, member: any) => {
355
+ const set = data.get(key);
356
+ if (!set || !(set instanceof Set)) return 0;
357
+ return set.has(member) ? 1 : 0;
358
+ }),
359
+
360
+ // Pub/Sub
361
+ subscribe: vi.fn().mockImplementation(async (...channels: string[]) => {
362
+ for (const channel of channels) {
363
+ pubsub.on(channel, () => {});
364
+ }
365
+ return channels.length;
366
+ }),
367
+
368
+ unsubscribe: vi.fn().mockImplementation(async (...channels: string[]) => {
369
+ for (const channel of channels) {
370
+ pubsub.removeAllListeners(channel);
371
+ }
372
+ return channels.length;
373
+ }),
374
+
375
+ publish: vi.fn().mockImplementation(async (channel: string, message: string) => {
376
+ const listeners = pubsub.listenerCount(channel);
377
+ pubsub.emit(channel, message);
378
+ return listeners;
379
+ }),
380
+
381
+ // Transactions
382
+ multi: vi.fn().mockImplementation(() => {
383
+ const commands: any[] = [];
384
+ const multi = {
385
+ get: (key: string) => {
386
+ commands.push(['get', key]);
387
+ return multi;
388
+ },
389
+ set: (key: string, value: any) => {
390
+ commands.push(['set', key, value]);
391
+ return multi;
392
+ },
393
+ del: (...keys: string[]) => {
394
+ commands.push(['del', ...keys]);
395
+ return multi;
396
+ },
397
+ exec: vi.fn().mockImplementation(async () => {
398
+ const results = [];
399
+ for (const [cmd, ...args] of commands) {
400
+ try {
401
+ const result = await (mock as any)[cmd](...args);
402
+ results.push([null, result]);
403
+ } catch (error) {
404
+ results.push([error, null]);
405
+ }
406
+ }
407
+ return results;
408
+ }),
409
+ };
410
+ return multi;
411
+ }),
412
+
413
+ // Lock operations (for RedisLock decorator)
414
+ eval: vi.fn().mockImplementation(async (script: string, ...args: any[]) => {
415
+ // Simple lock implementation
416
+ const [numKeys, ...params] = args;
417
+ const keys = params.slice(0, numKeys);
418
+ const values = params.slice(numKeys);
419
+
420
+ if (script.includes('redis.call("set"')) {
421
+ // Lock acquisition script
422
+ const [key] = keys;
423
+ const [token, ttl] = values;
424
+
425
+ if (locks.has(key)) {
426
+ return 0; // Lock already held
427
+ }
428
+
429
+ locks.set(key, { token, ttl: parseInt(ttl) });
430
+ setTimeout(() => {
431
+ const lock = locks.get(key);
432
+ if (lock && lock.token === token) {
433
+ locks.delete(key);
434
+ }
435
+ }, parseInt(ttl));
436
+
437
+ return 1; // Lock acquired
438
+ } else if (script.includes('redis.call("del"')) {
439
+ // Lock release script
440
+ const [key] = keys;
441
+ const [token] = values;
442
+
443
+ const lock = locks.get(key);
444
+ if (lock && lock.token === token) {
445
+ locks.delete(key);
446
+ return 1; // Lock released
447
+ }
448
+
449
+ return 0; // Lock not held or wrong token
450
+ }
451
+
452
+ return null;
453
+ }),
454
+
455
+ // Utility
456
+ flushdb: vi.fn().mockImplementation(async () => {
457
+ data.clear();
458
+ locks.clear();
459
+ return 'OK';
460
+ }),
461
+
462
+ flushall: vi.fn().mockImplementation(async () => {
463
+ data.clear();
464
+ locks.clear();
465
+ return 'OK';
466
+ }),
467
+
468
+ // Event emitter methods
469
+ on: vi.fn().mockImplementation((event: string, handler: (...args: any[]) => any) => {
470
+ pubsub.on(event, handler);
471
+ return mock;
472
+ }),
473
+
474
+ once: vi.fn().mockImplementation((event: string, handler: (...args: any[]) => any) => {
475
+ pubsub.once(event, handler);
476
+ return mock;
477
+ }),
478
+
479
+ off: vi.fn().mockImplementation((event: string, handler: (...args: any[]) => any) => {
480
+ pubsub.off(event, handler);
481
+ return mock;
482
+ }),
483
+
484
+ emit: vi.fn().mockImplementation((event: string, ...args: any[]) => {
485
+ pubsub.emit(event, ...args);
486
+ return true;
487
+ }),
488
+
489
+ removeAllListeners: vi.fn().mockImplementation((event?: string) => {
490
+ if (event) {
491
+ pubsub.removeAllListeners(event);
492
+ } else {
493
+ pubsub.removeAllListeners();
494
+ }
495
+ return mock;
496
+ }),
497
+
498
+ // Duplicate for creating subscriber clients
499
+ duplicate: vi.fn().mockImplementation(() => createMockRedis()),
500
+
501
+ // Status
502
+ status: 'ready',
503
+
504
+ // Internal access for testing
505
+ __data: data,
506
+ __locks: locks,
507
+ __pubsub: pubsub,
508
+ };
509
+
510
+ // Emit ready event on next tick
511
+ process.nextTick(() => {
512
+ mock.emit('ready');
513
+ });
514
+
515
+ return mock;
516
+ }
517
+
518
+ /**
519
+ * Redis performance testing utilities
520
+ */
521
+ export class RedisPerformanceTester {
522
+ private metrics: Map<string, { count: number; totalTime: number }> = new Map();
523
+
524
+ async measure<T>(operation: string, fn: () => Promise<T>): Promise<T> {
525
+ const start = process.hrtime.bigint();
526
+ try {
527
+ const result = await fn();
528
+ const end = process.hrtime.bigint();
529
+ const duration = Number(end - start) / 1_000_000; // Convert to ms
530
+
531
+ const metric = this.metrics.get(operation) || { count: 0, totalTime: 0 };
532
+ metric.count++;
533
+ metric.totalTime += duration;
534
+ this.metrics.set(operation, metric);
535
+
536
+ return result;
537
+ } catch (error) {
538
+ const end = process.hrtime.bigint();
539
+ const duration = Number(end - start) / 1_000_000;
540
+
541
+ const metric = this.metrics.get(operation) || { count: 0, totalTime: 0 };
542
+ metric.count++;
543
+ metric.totalTime += duration;
544
+ this.metrics.set(operation, metric);
545
+
546
+ throw error;
547
+ }
548
+ }
549
+
550
+ getMetrics() {
551
+ const results: Record<string, any> = {};
552
+
553
+ for (const [operation, metric] of this.metrics) {
554
+ results[operation] = {
555
+ count: metric.count,
556
+ totalTime: metric.totalTime,
557
+ avgTime: metric.totalTime / metric.count,
558
+ };
559
+ }
560
+
561
+ return results;
562
+ }
563
+
564
+ reset() {
565
+ this.metrics.clear();
566
+ }
567
+ }
@@ -0,0 +1,154 @@
1
+ /**
2
+ * Test Application Utilities
3
+ *
4
+ * Provides utilities for creating and managing test applications
5
+ * in Titan framework tests.
6
+ */
7
+
8
+ import { Application } from '@omnitron-dev/titan/application';
9
+ import type { IApplicationOptions } from '@omnitron-dev/titan/application';
10
+ import { Container } from '@omnitron-dev/titan/nexus';
11
+ import { Errors } from '@omnitron-dev/titan/errors';
12
+
13
+ /**
14
+ * Test application builder with simplified API
15
+ */
16
+ export class TestApplication {
17
+ private app: Application | null = null;
18
+ private container: Container;
19
+ private cleanupFns: (() => Promise<void> | void)[] = [];
20
+
21
+ constructor(private options: Partial<IApplicationOptions> = {}) {
22
+ this.container = new Container();
23
+ }
24
+
25
+ /**
26
+ * Create test application with modules
27
+ */
28
+ static async create(rootModule: any, options: Partial<IApplicationOptions> = {}): Promise<TestApplication> {
29
+ const testApp = new TestApplication(options);
30
+ await testApp.bootstrap(rootModule);
31
+ return testApp;
32
+ }
33
+
34
+ /**
35
+ * Bootstrap the application
36
+ */
37
+ async bootstrap(rootModule: any): Promise<void> {
38
+ // Create application with test defaults
39
+ this.app = await Application.create({
40
+ ...this.options,
41
+ modules: [rootModule],
42
+ logger: (this.options as any)['logger'] ?? false, // Disable logging by default in tests
43
+ gracefulShutdown: false,
44
+ disableCoreModules: !(this.options as any)['registerCoreModules'],
45
+ });
46
+
47
+ // Store container reference - use public getter
48
+ this.container = this.app.container;
49
+ }
50
+
51
+ /**
52
+ * Get service instance from container
53
+ */
54
+ get<T>(token: any): T {
55
+ if (!this.container) {
56
+ throw Errors.internal('Application not initialized');
57
+ }
58
+ return this.container.resolve<T>(token);
59
+ }
60
+
61
+ /**
62
+ * Check if service exists in container
63
+ */
64
+ has(token: any): boolean {
65
+ if (!this.container) {
66
+ return false;
67
+ }
68
+ return this.container.has(token);
69
+ }
70
+
71
+ /**
72
+ * Get the application instance
73
+ */
74
+ getApplication(): Application {
75
+ if (!this.app) {
76
+ throw Errors.internal('Application not initialized');
77
+ }
78
+ return this.app;
79
+ }
80
+
81
+ /**
82
+ * Get the container instance
83
+ */
84
+ getContainer(): Container {
85
+ return this.container;
86
+ }
87
+
88
+ /**
89
+ * Register cleanup function
90
+ */
91
+ addCleanup(fn: () => Promise<void> | void): void {
92
+ this.cleanupFns.push(fn);
93
+ }
94
+
95
+ /**
96
+ * Close application and cleanup
97
+ */
98
+ async close(): Promise<void> {
99
+ // Run custom cleanup functions
100
+ for (const fn of this.cleanupFns.reverse()) {
101
+ await fn();
102
+ }
103
+
104
+ // Close application
105
+ if (this.app) {
106
+ await this.app.stop();
107
+ this.app = null;
108
+ }
109
+ }
110
+
111
+ /**
112
+ * Create spy for service method
113
+ */
114
+ spyOn<T>(service: T, method: keyof T): any {
115
+ const spy = vi.spyOn(service as any, method as any);
116
+ this.addCleanup(() => spy.mockRestore());
117
+ return spy;
118
+ }
119
+
120
+ /**
121
+ * Mock service in container
122
+ */
123
+ mock<T>(token: any, mockImplementation: Partial<T>): void {
124
+ const original = this.container.resolve<T>(token);
125
+ Object.assign(original as any, mockImplementation);
126
+
127
+ this.addCleanup(() => {
128
+ // Restore original implementation
129
+ for (const key in mockImplementation) {
130
+ delete (original as any)[key];
131
+ }
132
+ });
133
+ }
134
+
135
+ /**
136
+ * Override provider in container
137
+ */
138
+ override<T>(token: any, value: T): void {
139
+ const originalBinding = (this.container as any).bindings.get(token);
140
+ (this.container as any).bindings.set(token, {
141
+ token,
142
+ useValue: value,
143
+ scope: 'singleton',
144
+ });
145
+
146
+ this.addCleanup(() => {
147
+ if (originalBinding) {
148
+ (this.container as any).bindings.set(token, originalBinding);
149
+ } else {
150
+ (this.container as any).bindings.delete(token);
151
+ }
152
+ });
153
+ }
154
+ }