-
-
Notifications
You must be signed in to change notification settings - Fork 28
Expand file tree
/
Copy pathtest-api.js
More file actions
executable file
·359 lines (301 loc) · 11.3 KB
/
test-api.js
File metadata and controls
executable file
·359 lines (301 loc) · 11.3 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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
#!/usr/bin/env node
/**
* API Testing Script for Cronjob Manager
*
* This script tests all API endpoints and provides clear reporting on what's working and what's broken.
* Usage: node test-api.js [baseUrl]
* Example: node test-api.js http://localhost:3000
*
* Running it with params: AUTH_PASSWORD=<password> node test-api.js http://localhost:<port>
*/
const https = require('https');
const http = require('http');
class APITester {
constructor(baseUrl = 'http://localhost:3000') {
this.baseUrl = baseUrl.replace(/\/$/, '');
this.sessionCookie = null;
this.testResults = {
passed: 0,
failed: 0,
total: 0,
details: []
};
}
async makeRequest(method, path, options = {}) {
return new Promise((resolve, reject) => {
const url = new URL(path, this.baseUrl);
const isHttps = url.protocol === 'https:';
const client = isHttps ? https : http;
const requestOptions = {
hostname: url.hostname,
port: url.port,
path: url.pathname + url.search,
method: method.toUpperCase(),
headers: {
'Content-Type': 'application/json',
'User-Agent': 'API-Test-Script/1.0',
...options.headers
}
};
if (this.sessionCookie && !options.skipAuth) {
requestOptions.headers.Cookie = this.sessionCookie;
}
const req = client.request(requestOptions, (res) => {
let data = '';
res.on('data', (chunk) => {
data += chunk;
});
res.on('end', () => {
try {
const response = {
status: res.statusCode,
headers: res.headers,
data: data ? JSON.parse(data) : null,
rawData: data
};
resolve(response);
} catch (error) {
resolve({
status: res.statusCode,
headers: res.headers,
data: null,
rawData: data,
parseError: error.message
});
}
});
});
req.on('error', (error) => {
reject(error);
});
if (options.body) {
req.write(JSON.stringify(options.body));
}
req.end();
});
}
async login(password = process.env.AUTH_PASSWORD || 'admin') {
try {
console.log('\n🔐 Testing login...');
const response = await this.makeRequest('POST', '/api/auth/login', {
body: { password },
skipAuth: true
});
if (response.status === 200 && response.data?.success) {
const setCookieHeader = response.headers['set-cookie'];
if (setCookieHeader) {
const sessionMatch = setCookieHeader.find(cookie => cookie.startsWith('cronmaster-session='));
if (sessionMatch) {
this.sessionCookie = sessionMatch.split(';')[0];
console.log('✅ Login successful, session cookie set');
return true;
}
}
}
console.log('❌ Login failed:', response.data?.message || 'Unknown error');
return false;
} catch (error) {
console.log('❌ Login error:', error.message);
return false;
}
}
recordResult(testName, passed, details = '') {
this.testResults.total++;
if (passed) {
this.testResults.passed++;
console.log(`✅ ${testName}`);
} else {
this.testResults.failed++;
console.log(`❌ ${testName}`);
if (details) console.log(` Details: ${details}`);
}
this.testResults.details.push({ testName, passed, details });
}
async testEndpoint(testName, method, path, options = {}) {
try {
const response = await this.makeRequest(method, path, options);
const expectedStatus = options.expectedStatus || (method === 'GET' ? 200 : 201);
const statusOk = response.status === expectedStatus;
let dataOk = true;
if (options.expectedDataShape) {
dataOk = this.checkDataShape(response.data, options.expectedDataShape);
}
const passed = statusOk && dataOk;
let details = '';
if (!statusOk) {
details += `Expected status ${expectedStatus}, got ${response.status}. `;
}
if (!dataOk) {
details += 'Response data shape mismatch. ';
}
if (response.parseError) {
details += `JSON parse error: ${response.parseError}. `;
}
if (response.data?.error) {
details += `API error: ${response.data.error}. `;
}
this.recordResult(testName, passed, details);
return response;
} catch (error) {
this.recordResult(testName, false, `Request failed: ${error.message}`);
return null;
}
}
async testSSEEndpoint(testName, path, options = {}) {
return new Promise((resolve) => {
const url = new URL(path, this.baseUrl);
const isHttps = url.protocol === 'https:';
const client = isHttps ? https : http;
const requestOptions = {
hostname: url.hostname,
port: url.port,
path: url.pathname + url.search,
method: 'GET',
headers: {
'User-Agent': 'API-Test-Script/1.0',
}
};
if (this.sessionCookie && !options.skipAuth) {
requestOptions.headers.Cookie = this.sessionCookie;
}
const timeout = setTimeout(() => {
req.destroy();
this.recordResult(testName, true, 'SSE connection established (timed out as expected)');
resolve(null);
}, 2000);
const req = client.request(requestOptions, (res) => {
clearTimeout(timeout);
const expectedStatus = options.expectedStatus || 200;
const statusOk = res.statusCode === expectedStatus;
if (statusOk) {
res.destroy();
this.recordResult(testName, true, 'SSE connection established successfully');
} else {
this.recordResult(testName, false, `Expected status ${expectedStatus}, got ${res.statusCode}`);
}
resolve(null);
});
req.on('error', (error) => {
clearTimeout(timeout);
this.recordResult(testName, false, `SSE connection failed: ${error.message}`);
resolve(null);
});
req.end();
});
}
checkDataShape(data, shape) {
if (!data) return false;
for (const [key, type] of Object.entries(shape)) {
if (!(key in data)) return false;
if (type === 'array' && !Array.isArray(data[key])) return false;
if (type === 'object' && (typeof data[key] !== 'object' || Array.isArray(data[key]))) return false;
if (type === 'string' && typeof data[key] !== 'string') return false;
if (type === 'boolean' && typeof data[key] !== 'boolean') return false;
if (type === 'number' && typeof data[key] !== 'number') return false;
}
return true;
}
async runTests() {
console.log(`🚀 Starting API tests for ${this.baseUrl}`);
console.log('=' .repeat(60));
const loginSuccess = await this.login();
if (!loginSuccess) {
console.log('\n❌ Cannot proceed without authentication. Please check AUTH_PASSWORD environment variable.');
return;
}
await this.testEndpoint('GET /api/auth/check-session', 'GET', '/api/auth/check-session', {
expectedDataShape: { valid: 'boolean' }
});
const cronjobsResponse = await this.testEndpoint('GET /api/cronjobs', 'GET', '/api/cronjobs', {
expectedDataShape: { success: 'boolean', data: 'array' }
});
let cronJobId = null;
if (cronjobsResponse?.data?.success && cronjobsResponse.data.data.length > 0) {
cronJobId = cronjobsResponse.data.data[0].id;
await this.testEndpoint(`GET /api/cronjobs/${cronJobId}`, 'GET', `/api/cronjobs/${cronJobId}`, {
expectedDataShape: { success: 'boolean', data: 'object' }
});
await this.testEndpoint(`GET /api/cronjobs/${cronJobId}/execute`, 'GET', `/api/cronjobs/${cronJobId}/execute`, {
expectedDataShape: { success: 'boolean' }
});
await this.testEndpoint(`GET /api/cronjobs/${cronJobId}/execute?runInBackground=false`, 'GET', `/api/cronjobs/${cronJobId}/execute?runInBackground=false`, {
expectedDataShape: { success: 'boolean' }
});
} else {
console.log('ℹ️ No cronjobs found, skipping individual cronjob tests');
}
await this.testEndpoint('GET /api/scripts', 'GET', '/api/scripts', {
expectedDataShape: { success: 'boolean', data: 'array' }
});
await this.testEndpoint('GET /api/system-stats', 'GET', '/api/system-stats', {
expectedDataShape: { uptime: 'string', memory: 'object', cpu: 'object' }
});
await this.testSSEEndpoint('GET /api/events', '/api/events', {
expectedStatus: 200
});
await this.testEndpoint('POST /api/auth/logout', 'POST', '/api/auth/logout', {
expectedStatus: 200,
expectedDataShape: { success: 'boolean' }
});
await this.testEndpoint('GET /api/auth/check-session (after logout)', 'GET', '/api/auth/check-session', {
expectedStatus: 401,
expectedDataShape: { valid: 'boolean' }
});
await this.testEndpoint('GET /api/logs/stream (without runId)', 'GET', '/api/logs/stream', {
expectedStatus: 400
});
console.log('\n' + '='.repeat(60));
console.log('📊 TEST RESULTS SUMMARY');
console.log('='.repeat(60));
console.log(`Total tests: ${this.testResults.total}`);
console.log(`✅ Passed: ${this.testResults.passed}`);
console.log(`❌ Failed: ${this.testResults.failed}`);
console.log(`Success rate: ${((this.testResults.passed / this.testResults.total) * 100).toFixed(1)}%`);
if (this.testResults.failed > 0) {
console.log('\n🔍 FAILED TESTS DETAILS:');
this.testResults.details
.filter(test => !test.passed)
.forEach(test => {
console.log(`❌ ${test.testName}`);
if (test.details) console.log(` ${test.details}`);
});
}
console.log('\n🎯 REMOVED ENDPOINTS VERIFICATION:');
console.log('The following POST endpoints should return 405 Method Not Allowed:');
const removedEndpoints = [
'/api/cronjobs',
'/api/scripts'
];
for (const endpoint of removedEndpoints) {
try {
const response = await this.makeRequest('POST', endpoint, { skipAuth: true });
if (response.status === 405) {
console.log(`✅ ${endpoint} - Correctly returns 405 Method Not Allowed`);
} else {
console.log(`❌ ${endpoint} - Returns ${response.status}, expected 405`);
}
} catch (error) {
console.log(`❓ ${endpoint} - Could not test (connection error)`);
}
}
if (cronJobId) {
try {
const response = await this.makeRequest('POST', `/api/cronjobs/${cronJobId}/execute`, { skipAuth: true });
if (response.status === 405) {
console.log(`✅ /api/cronjobs/${cronJobId}/execute - Correctly returns 405 Method Not Allowed (now GET only)`);
} else {
console.log(`❌ /api/cronjobs/${cronJobId}/execute - Returns ${response.status}, expected 405 for POST`);
}
} catch (error) {
console.log(`❓ /api/cronjobs/${cronJobId}/execute - Could not test (connection error)`);
}
}
process.exit(this.testResults.failed > 0 ? 1 : 0);
}
}
const baseUrl = process.argv[2] || 'http://localhost:3000';
const tester = new APITester(baseUrl);
tester.runTests().catch(error => {
console.error('💥 Test runner failed:', error.message);
process.exit(1);
});