@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,162 @@
1
+ /**
2
+ * Mock Process Spawner for Testing
3
+ *
4
+ * This spawner runs processes in the same thread for testing purposes.
5
+ * It maintains the same interface but doesn't actually spawn separate processes.
6
+ */
7
+
8
+ import { EventEmitter } from 'events';
9
+ import { Netron } from '@omnitron-dev/titan/netron';
10
+ import { Errors } from '@omnitron-dev/titan/errors';
11
+ import type { ProcessMethod } from '@omnitron-dev/titan-pm';
12
+ import type { ILogger } from '@omnitron-dev/titan/module/logger';
13
+ import type { IProcessOptions, IProcessManagerConfig } from '@omnitron-dev/titan-pm';
14
+ import { PROCESS_METHOD_METADATA_KEY } from '@omnitron-dev/titan-pm';
15
+
16
+ /**
17
+ * Mock worker that runs in the same thread
18
+ */
19
+ class MockWorker extends EventEmitter {
20
+ public threadId = Math.floor(Math.random() * 10000);
21
+ public pid = process.pid;
22
+ private instance: any;
23
+ private publicMethods: Map<string, ProcessMethod> = new Map();
24
+
25
+ constructor(ProcessClass: new (...args: any[]) => any) {
26
+ super();
27
+
28
+ // Create instance of the process class
29
+ this.instance = new ProcessClass();
30
+
31
+ // Extract public methods from metadata
32
+ const prototype = ProcessClass.prototype;
33
+ const propertyNames = Object.getOwnPropertyNames(prototype);
34
+
35
+ for (const propertyName of propertyNames) {
36
+ if (propertyName === 'constructor') continue;
37
+
38
+ const descriptor = Object.getOwnPropertyDescriptor(prototype, propertyName);
39
+ if (!descriptor || typeof descriptor.value !== 'function') continue;
40
+
41
+ // Check if method is marked as public
42
+ const metadata = Reflect.getMetadata(PROCESS_METHOD_METADATA_KEY, prototype, propertyName);
43
+ if (metadata?.public) {
44
+ this.publicMethods.set(propertyName, descriptor.value.bind(this.instance));
45
+ }
46
+ }
47
+
48
+ // Add health check method if it exists
49
+ if (typeof this.instance.checkHealth === 'function') {
50
+ this.publicMethods.set('checkHealth', this.instance.checkHealth.bind(this.instance));
51
+ }
52
+
53
+ // Add internal methods
54
+ this.publicMethods.set('__getProcessMetrics', async () => ({
55
+ cpu: 0.1,
56
+ memory: process.memoryUsage().heapUsed,
57
+ requests: 0,
58
+ errors: 0,
59
+ uptime: process.uptime(),
60
+ }));
61
+
62
+ this.publicMethods.set('__getProcessHealth', async () => {
63
+ if (typeof this.instance.checkHealth === 'function') {
64
+ return await this.instance.checkHealth();
65
+ }
66
+ return {
67
+ status: 'healthy' as const,
68
+ checks: [],
69
+ timestamp: Date.now(),
70
+ };
71
+ });
72
+
73
+ // Don't emit ready here - let the spawner call notifyReady() after setup
74
+ }
75
+
76
+ /**
77
+ * Notify that the worker is ready (called by spawner after listener is attached)
78
+ */
79
+ notifyReady(): void {
80
+ setImmediate(() => {
81
+ this.emit('message', { type: 'ready' });
82
+ });
83
+ }
84
+
85
+ async callMethod(methodName: string, args: any[]): Promise<any> {
86
+ const method = this.publicMethods.get(methodName);
87
+ if (!method) {
88
+ throw Errors.notFound('Method', methodName);
89
+ }
90
+ return await method(...args);
91
+ }
92
+
93
+ postMessage(message: any): void {
94
+ if (message.type === 'shutdown') {
95
+ this.emit('exit', 0);
96
+ }
97
+ }
98
+
99
+ terminate(): Promise<number> {
100
+ this.emit('exit', 0);
101
+ return Promise.resolve(0);
102
+ }
103
+ }
104
+
105
+ /**
106
+ * Mock Process Spawner for testing
107
+ */
108
+ export class MockProcessSpawner {
109
+ private mockWorkers = new Map<string, MockWorker>();
110
+
111
+ constructor(
112
+ private readonly logger: ILogger,
113
+ private readonly config: IProcessManagerConfig = {}
114
+ ) {}
115
+
116
+ /**
117
+ * Spawn a mock process (runs in same thread)
118
+ */
119
+ async spawn(
120
+ ProcessClass: new (...args: any[]) => any,
121
+ processId: string,
122
+ options: IProcessOptions
123
+ ): Promise<{ worker: MockWorker; netron: Netron; transportUrl: string }> {
124
+ // Create mock worker
125
+ const worker = new MockWorker(ProcessClass);
126
+ this.mockWorkers.set(processId, worker);
127
+
128
+ // Create mock Netron that directly calls the worker
129
+ const netron = new Netron(this.logger as any, {
130
+ id: `mock-${processId}`,
131
+ });
132
+
133
+ // Override Netron's call method to directly call the worker
134
+ (netron as any).mockCall = async (methodName: string, args: any[]) => worker.callMethod(methodName, args);
135
+
136
+ // Create a mock peer
137
+ (netron as any).peer = {
138
+ call: async (serviceName: string, methodName: string, args: any[]) => worker.callMethod(methodName, args),
139
+ expose: async () => {},
140
+ start: async () => {},
141
+ stop: async () => {},
142
+ connect: async () => {},
143
+ disconnect: async () => {},
144
+ listen: async () => {},
145
+ };
146
+
147
+ const transportUrl = `mock://${processId}`;
148
+
149
+ return { worker, netron, transportUrl };
150
+ }
151
+
152
+ /**
153
+ * Clean up mock process
154
+ */
155
+ async cleanup(processId: string): Promise<void> {
156
+ const worker = this.mockWorkers.get(processId);
157
+ if (worker) {
158
+ await worker.terminate();
159
+ this.mockWorkers.delete(processId);
160
+ }
161
+ }
162
+ }
@@ -0,0 +1,352 @@
1
+ /**
2
+ * Test Process Manager
3
+ *
4
+ * Specialized ProcessManager for testing with additional features
5
+ * for simulating failures, controlling timing, and verifying behavior.
6
+ */
7
+
8
+ import { Errors } from '@omnitron-dev/titan/errors';
9
+ import { ProcessManager, ProcessSpawnerFactory } from '@omnitron-dev/titan-pm';
10
+ import { ProcessStatus } from '@omnitron-dev/titan-pm';
11
+ import type { IProcessOptions, IProcessInfo, ServiceProxy, IProcessManagerConfig } from '@omnitron-dev/titan-pm';
12
+ import { createNullLogger } from '@omnitron-dev/titan/module/logger';
13
+ import { MockProcessSpawner } from './mock-process-spawner.js';
14
+
15
+ /**
16
+ * Test process manager configuration
17
+ */
18
+ export interface ITestProcessManagerConfig extends IProcessManagerConfig {
19
+ /** Use mock spawner for faster tests */
20
+ mock?: boolean;
21
+ /** Control time for testing */
22
+ controlTime?: boolean;
23
+ /** Record all operations for verification */
24
+ recordOperations?: boolean;
25
+ }
26
+
27
+ /**
28
+ * Operation record for verification
29
+ */
30
+ export interface IOperationRecord {
31
+ type: 'spawn' | 'kill' | 'restart' | 'health' | 'metrics';
32
+ processId?: string;
33
+ processClass?: string;
34
+ timestamp: number;
35
+ data?: any;
36
+ }
37
+
38
+ /**
39
+ * Test Process Manager with additional testing capabilities
40
+ */
41
+ export class TestProcessManager extends ProcessManager {
42
+ private operations: IOperationRecord[] = [];
43
+ private simulatedFailures = new Map<string, Error>();
44
+ private simulatedMetrics = new Map<string, any>();
45
+ private simulatedHealth = new Map<string, any>();
46
+ private timeOffset = 0;
47
+ private crashHandlers = new Map<string, () => void>();
48
+ private recoveryHandlers = new Map<string, () => void>();
49
+
50
+ constructor(config: ITestProcessManagerConfig = {}) {
51
+ // Use null logger for tests - silent by default
52
+ const logger = createNullLogger();
53
+
54
+ // Register MockProcessSpawner before creating ProcessManager
55
+ // This ensures the factory can use it when useMockSpawner is true
56
+ if (config.mock !== false) {
57
+ ProcessSpawnerFactory.setMockSpawner(MockProcessSpawner);
58
+ }
59
+
60
+ super(logger, {
61
+ ...config,
62
+ testing: {
63
+ ...config.testing,
64
+ useMockSpawner: config.mock !== false,
65
+ },
66
+ });
67
+
68
+ // Setup test event handlers
69
+ this.setupTestHandlers();
70
+ }
71
+
72
+ /**
73
+ * Setup test-specific event handlers
74
+ */
75
+ private setupTestHandlers(): void {
76
+ this.on('process:crash', (info: IProcessInfo, error: Error) => {
77
+ const handler = this.crashHandlers.get(info.id);
78
+ if (handler) {
79
+ handler();
80
+ }
81
+ });
82
+
83
+ this.on('process:ready', (info: IProcessInfo) => {
84
+ const handler = this.recoveryHandlers.get(info.id);
85
+ if (handler) {
86
+ handler();
87
+ }
88
+ });
89
+ }
90
+
91
+ /**
92
+ * Spawn a process with test recording
93
+ */
94
+ override async spawn<T>(
95
+ ProcessClass: new (...args: any[]) => T,
96
+ options: IProcessOptions = {}
97
+ ): Promise<ServiceProxy<T>> {
98
+ this.recordOperation('spawn', undefined, ProcessClass.name, options);
99
+
100
+ // Check for simulated failure
101
+ const failureKey = `spawn:${ProcessClass.name}`;
102
+ if (this.simulatedFailures.has(failureKey)) {
103
+ throw this.simulatedFailures.get(failureKey)!;
104
+ }
105
+
106
+ return super.spawn(ProcessClass, options);
107
+ }
108
+
109
+ /**
110
+ * Simulate a process crash
111
+ */
112
+ async simulateCrash(processOrId: ServiceProxy<any> | string): Promise<void> {
113
+ const processId = typeof processOrId === 'string' ? processOrId : (processOrId as any).__processId;
114
+
115
+ const info = this.getProcess(processId);
116
+ if (!info) {
117
+ throw Errors.notFound('Process', processId);
118
+ }
119
+
120
+ // Emit crash event
121
+ const error = new Error('Simulated crash for testing');
122
+ this.emit('process:crash', info, error);
123
+
124
+ // Kill the actual process if it exists but preserve CRASHED status
125
+ try {
126
+ await this.kill(processId, 'SIGKILL');
127
+ } catch (_e) {
128
+ // Ignore errors during simulated crash
129
+ }
130
+
131
+ // Update status AFTER kill to ensure it stays CRASHED
132
+ (info as any).status = ProcessStatus.CRASHED;
133
+ }
134
+
135
+ /**
136
+ * Wait for a process to recover
137
+ */
138
+ async waitForRecovery(processOrId: ServiceProxy<any> | string, timeout: number = 5000): Promise<boolean> {
139
+ const processId = typeof processOrId === 'string' ? processOrId : (processOrId as any).__processId;
140
+
141
+ return new Promise((resolve) => {
142
+ const timer = setTimeout(() => {
143
+ this.recoveryHandlers.delete(processId);
144
+ resolve(false);
145
+ }, timeout);
146
+
147
+ this.recoveryHandlers.set(processId, () => {
148
+ clearTimeout(timer);
149
+ this.recoveryHandlers.delete(processId);
150
+ resolve(true);
151
+ });
152
+
153
+ // Check if already recovered
154
+ const info = this.getProcess(processId);
155
+ if (info && info.status === ProcessStatus.RUNNING) {
156
+ clearTimeout(timer);
157
+ this.recoveryHandlers.delete(processId);
158
+ resolve(true);
159
+ }
160
+ });
161
+ }
162
+
163
+ /**
164
+ * Simulate metrics for a process
165
+ */
166
+ setMetrics(processId: string, metrics: any): void {
167
+ this.simulatedMetrics.set(processId, metrics);
168
+ }
169
+
170
+ /**
171
+ * Get metrics with simulated values
172
+ */
173
+ override async getMetrics(processId: string): Promise<any> {
174
+ if (this.simulatedMetrics.has(processId)) {
175
+ return this.simulatedMetrics.get(processId);
176
+ }
177
+ return super.getMetrics(processId);
178
+ }
179
+
180
+ /**
181
+ * Simulate health status for a process
182
+ */
183
+ setHealth(processId: string, health: any): void {
184
+ this.simulatedHealth.set(processId, health);
185
+ }
186
+
187
+ /**
188
+ * Get health with simulated values
189
+ */
190
+ override async getHealth(processId: string): Promise<any> {
191
+ if (this.simulatedHealth.has(processId)) {
192
+ return this.simulatedHealth.get(processId);
193
+ }
194
+ return super.getHealth(processId);
195
+ }
196
+
197
+ /**
198
+ * Simulate a failure for next operation
199
+ */
200
+ simulateFailure(operation: string, error: Error): void {
201
+ this.simulatedFailures.set(operation, error);
202
+ }
203
+
204
+ /**
205
+ * Clear simulated failures
206
+ */
207
+ clearFailures(): void {
208
+ this.simulatedFailures.clear();
209
+ }
210
+
211
+ /**
212
+ * Advance simulated time
213
+ */
214
+ advanceTime(ms: number): void {
215
+ this.timeOffset += ms;
216
+ }
217
+
218
+ /**
219
+ * Reset simulated time
220
+ */
221
+ resetTime(): void {
222
+ this.timeOffset = 0;
223
+ }
224
+
225
+ /**
226
+ * Get current time with offset
227
+ */
228
+ getCurrentTime(): number {
229
+ return Date.now() + this.timeOffset;
230
+ }
231
+
232
+ /**
233
+ * Get operation history
234
+ */
235
+ getOperations(): IOperationRecord[] {
236
+ return [...this.operations];
237
+ }
238
+
239
+ /**
240
+ * Clear operation history
241
+ */
242
+ clearOperations(): void {
243
+ this.operations = [];
244
+ }
245
+
246
+ /**
247
+ * Verify operation occurred
248
+ */
249
+ verifyOperation(type: string, predicate?: (op: IOperationRecord) => boolean): boolean {
250
+ return this.operations.some((op) => op.type === type && (!predicate || predicate(op)));
251
+ }
252
+
253
+ /**
254
+ * Wait for a specific operation
255
+ */
256
+ async waitForOperation(type: string, timeout: number = 5000): Promise<IOperationRecord | null> {
257
+ const startTime = Date.now();
258
+
259
+ while (Date.now() - startTime < timeout) {
260
+ const op = this.operations.find((o) => o.type === type);
261
+ if (op) return op;
262
+ await new Promise((resolve) => setTimeout(resolve, 100));
263
+ }
264
+
265
+ return null;
266
+ }
267
+
268
+ /**
269
+ * Record an operation for verification
270
+ */
271
+ private recordOperation(type: any, processId?: string, processClass?: string, data?: any): void {
272
+ this.operations.push({
273
+ type,
274
+ processId,
275
+ processClass,
276
+ timestamp: this.getCurrentTime(),
277
+ data,
278
+ });
279
+ }
280
+
281
+ /**
282
+ * Clean up test resources
283
+ */
284
+ async cleanup(): Promise<void> {
285
+ this.clearFailures();
286
+ this.clearOperations();
287
+ this.resetTime();
288
+ this.simulatedMetrics.clear();
289
+ this.simulatedHealth.clear();
290
+ this.crashHandlers.clear();
291
+ this.recoveryHandlers.clear();
292
+ await this.shutdown();
293
+ }
294
+
295
+ /**
296
+ * Create a spy for a process method
297
+ */
298
+ spyOnMethod<T>(proxy: ServiceProxy<T>, methodName: keyof T): any {
299
+ const original = (proxy as any)[methodName];
300
+ const calls: any[] = [];
301
+
302
+ (proxy as any)[methodName] = async (...args: any[]) => {
303
+ calls.push({ args, timestamp: this.getCurrentTime() });
304
+ return original.apply(proxy, args);
305
+ };
306
+
307
+ // Return spy-like interface
308
+ return {
309
+ calls,
310
+ mockClear: () => (calls.length = 0),
311
+ mockRestore: () => ((proxy as any)[methodName] = original),
312
+ };
313
+ }
314
+
315
+ /**
316
+ * Assert process state
317
+ */
318
+ assertProcessState(processId: string, expectedStatus: ProcessStatus): void {
319
+ const info = this.getProcess(processId);
320
+ if (!info) {
321
+ throw Errors.notFound('Process', processId);
322
+ }
323
+ if (info.status !== expectedStatus) {
324
+ throw Errors.badRequest(`Expected process ${processId} to have status ${expectedStatus}, but got ${info.status}`);
325
+ }
326
+ }
327
+
328
+ /**
329
+ * Get all processes of a specific class
330
+ */
331
+ getProcessesByClass<T>(ProcessClass: new (...args: any[]) => T): IProcessInfo[] {
332
+ return this.listProcesses().filter((info) => info.name === ProcessClass.name);
333
+ }
334
+
335
+ /**
336
+ * Count processes by status
337
+ */
338
+ countByStatus(status: ProcessStatus): number {
339
+ return this.listProcesses().filter((info) => info.status === status).length;
340
+ }
341
+ }
342
+
343
+ /**
344
+ * Create a test process manager with defaults
345
+ */
346
+ export function createTestProcessManager(config?: ITestProcessManagerConfig): TestProcessManager {
347
+ return new TestProcessManager({
348
+ mock: true,
349
+ recordOperations: true,
350
+ ...config,
351
+ });
352
+ }