forked from ruvnet/ruflo
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_error_handling.js
More file actions
333 lines (269 loc) · 11.6 KB
/
test_error_handling.js
File metadata and controls
333 lines (269 loc) · 11.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
#!/usr/bin/env node
/**
* Error Handling Test for Claude-Flow Console
* Tests various failure scenarios and recovery mechanisms
*/
import WebSocket from 'ws';
async function testErrorHandling() {
console.log('🛠️ Testing Error Handling and Recovery Mechanisms...\n');
const testResults = {
connectionRecovery: false,
invalidCommands: 0,
malformedMessages: 0,
timeoutHandling: 0,
gracefulFailures: 0,
totalTests: 0,
errors: []
};
// Test 1: Invalid commands
console.log('📋 Testing Invalid Command Handling...');
await testInvalidCommands(testResults);
// Test 2: Malformed WebSocket messages
console.log('\n🔧 Testing Malformed Message Handling...');
await testMalformedMessages(testResults);
// Test 3: Connection recovery
console.log('\n🔄 Testing Connection Recovery...');
await testConnectionRecovery(testResults);
// Test 4: Server errors
console.log('\n⚠️ Testing Server Error Handling...');
await testServerErrors(testResults);
generateErrorReport(testResults);
}
async function testInvalidCommands(results) {
return new Promise((resolve) => {
const ws = new WebSocket('ws://localhost:3000');
const invalidCommands = [
'completely_invalid_command',
'agent spawn nonexistent_type',
'memory get missing_key',
'config set invalid.path value'
];
let testIndex = 0;
let gracefulHandling = 0;
ws.on('open', () => {
sendNextInvalidCommand();
});
function sendNextInvalidCommand() {
if (testIndex >= invalidCommands.length) {
results.invalidCommands = gracefulHandling;
results.totalTests += invalidCommands.length;
ws.close();
return;
}
const command = invalidCommands[testIndex++];
console.log(` 🚀 Testing invalid command: "${command}"`);
ws.send(JSON.stringify({
type: 'command',
data: command
}));
let hasOutput = false;
let hasCompletion = false;
const messageHandler = (data) => {
const message = JSON.parse(data);
if (message.type === 'output') {
hasOutput = true;
}
if (message.type === 'command_complete') {
hasCompletion = true;
ws.off('message', messageHandler);
if (hasOutput && hasCompletion) {
gracefulHandling++;
console.log(` ✅ Handled gracefully`);
} else {
console.log(` ❌ Poor error handling`);
}
setTimeout(sendNextInvalidCommand, 500);
}
};
ws.on('message', messageHandler);
}
ws.on('close', () => {
resolve();
});
ws.on('error', (error) => {
results.errors.push(`Invalid command test error: ${error.message}`);
resolve();
});
});
}
async function testMalformedMessages(results) {
return new Promise((resolve) => {
const ws = new WebSocket('ws://localhost:3000');
const malformedMessages = [
'not valid json',
'{"type": "invalid_type"}',
'{"type": "command"}', // missing data
'{"data": "test"}', // missing type
'{"type": "command", "data": null}'
];
let testIndex = 0;
let gracefulHandling = 0;
ws.on('open', () => {
sendNextMalformedMessage();
});
function sendNextMalformedMessage() {
if (testIndex >= malformedMessages.length) {
results.malformedMessages = gracefulHandling;
results.totalTests += malformedMessages.length;
ws.close();
return;
}
const message = malformedMessages[testIndex++];
console.log(` 🔧 Testing malformed message: ${message.substring(0, 30)}...`);
try {
ws.send(message);
gracefulHandling++; // If it doesn't crash, it's handling it
console.log(` ✅ Server didn't crash`);
} catch (error) {
console.log(` ❌ Client-side error: ${error.message}`);
}
setTimeout(sendNextMalformedMessage, 500);
}
ws.on('error', (error) => {
console.log(` ⚠️ WebSocket error (expected): ${error.message}`);
// This might be expected for malformed messages
});
ws.on('close', () => {
resolve();
});
});
}
async function testConnectionRecovery(results) {
return new Promise((resolve) => {
console.log(' 🔌 Testing connection drop and recovery...');
let ws = new WebSocket('ws://localhost:3000');
let reconnectAttempted = false;
ws.on('open', () => {
console.log(' ✅ Initial connection established');
// Send a command then immediately close
ws.send(JSON.stringify({
type: 'command',
data: 'status'
}));
setTimeout(() => {
ws.close(); // Simulate connection drop
}, 100);
});
ws.on('close', () => {
if (!reconnectAttempted) {
console.log(' 🔄 Attempting reconnection...');
reconnectAttempted = true;
// Try to reconnect
setTimeout(() => {
const newWs = new WebSocket('ws://localhost:3000');
newWs.on('open', () => {
console.log(' ✅ Reconnection successful');
results.connectionRecovery = true;
newWs.close();
resolve();
});
newWs.on('error', (error) => {
console.log(' ❌ Reconnection failed:', error.message);
results.errors.push(`Reconnection failed: ${error.message}`);
resolve();
});
}, 1000);
}
});
ws.on('error', (error) => {
console.log(' ⚠️ Connection error:', error.message);
results.errors.push(`Connection error: ${error.message}`);
});
});
}
async function testServerErrors(results) {
return new Promise((resolve) => {
const ws = new WebSocket('ws://localhost:3000');
console.log(' ⚠️ Testing server error scenarios...');
ws.on('open', () => {
// Test command that might cause server-side issues
const stressCommands = [
'very_long_command_' + 'x'.repeat(1000),
'agent spawn ' + 'invalid_type_'.repeat(100),
'memory store ' + 'key '.repeat(50) + ' value'
];
let commandIndex = 0;
let serverErrorsHandled = 0;
function sendStressCommand() {
if (commandIndex >= stressCommands.length) {
results.gracefulFailures = serverErrorsHandled;
results.totalTests += stressCommands.length;
ws.close();
return;
}
const command = stressCommands[commandIndex++];
console.log(` 🚀 Testing stress command ${commandIndex}`);
ws.send(JSON.stringify({
type: 'command',
data: command
}));
const messageHandler = (data) => {
const message = JSON.parse(data);
if (message.type === 'command_complete' || message.type === 'error') {
serverErrorsHandled++;
console.log(` ✅ Server handled stress gracefully`);
ws.off('message', messageHandler);
setTimeout(sendStressCommand, 200);
}
};
ws.on('message', messageHandler);
// Timeout handling
setTimeout(() => {
ws.off('message', messageHandler);
console.log(` ⏰ Command timeout (acceptable)`);
sendStressCommand();
}, 5000);
}
sendStressCommand();
});
ws.on('close', () => {
resolve();
});
ws.on('error', (error) => {
results.errors.push(`Server error test: ${error.message}`);
resolve();
});
});
}
function generateErrorReport(results) {
console.log('\n📊 Error Handling Test Results');
console.log('===============================');
console.log(`🔧 Invalid Commands Handled: ${results.invalidCommands}/4`);
console.log(`📨 Malformed Messages Handled: ${results.malformedMessages}/5`);
console.log(`🔄 Connection Recovery: ${results.connectionRecovery ? 'PASSED' : 'FAILED'}`);
console.log(`⚠️ Server Errors Handled: ${results.gracefulFailures}/3`);
console.log(`❌ Total Errors Logged: ${results.errors.length}`);
if (results.errors.length > 0) {
console.log('\n❌ Errors Encountered:');
results.errors.forEach((error, index) => {
console.log(` ${index + 1}. ${error}`);
});
}
const totalScore = results.invalidCommands + results.malformedMessages +
(results.connectionRecovery ? 1 : 0) + results.gracefulFailures;
const maxScore = 13; // 4 + 5 + 1 + 3
const percentage = Math.round((totalScore / maxScore) * 100);
console.log(`\n🎯 Error Handling Score: ${totalScore}/${maxScore} (${percentage}%)`);
if (percentage >= 90) {
console.log('🛡️ EXCELLENT! Error handling is very robust');
} else if (percentage >= 75) {
console.log('✅ GOOD! Error handling is solid with room for improvement');
} else if (percentage >= 60) {
console.log('⚠️ FAIR! Error handling needs attention');
} else {
console.log('❌ POOR! Error handling requires significant improvement');
}
console.log('\n🔍 Error Handling Assessment:');
console.log(`• Invalid Command Recovery: ${results.invalidCommands >= 3 ? '✅ Excellent' : '⚠️ Needs work'}`);
console.log(`• Malformed Message Handling: ${results.malformedMessages >= 4 ? '✅ Excellent' : '⚠️ Needs work'}`);
console.log(`• Connection Resilience: ${results.connectionRecovery ? '✅ Robust' : '❌ Fragile'}`);
console.log(`• Server Error Recovery: ${results.gracefulFailures >= 2 ? '✅ Good' : '⚠️ Limited'}`);
}
// Run the test
testErrorHandling().then(() => {
console.log('\n✅ Error handling test completed');
process.exit(0);
}).catch(error => {
console.error('❌ Test failed:', error.message);
process.exit(1);
});