-
Notifications
You must be signed in to change notification settings - Fork 58
Expand file tree
/
Copy pathtest-tags-validation.js
More file actions
656 lines (552 loc) · 20.3 KB
/
test-tags-validation.js
File metadata and controls
656 lines (552 loc) · 20.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
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
#!/usr/bin/env node
/**
* Tags API Validation Test Suite - Story 2.3
*
* Validates all 5 Tags API methods against live n8n instance:
* - get_tags (GET /tags) - List all tags with pagination
* - get_tag (GET /tags/{id}) - Get specific tag
* - create_tag (POST /tags) - Create new tag
* - update_tag (PUT /tags/{id}) - Update tag name
* - delete_tag (DELETE /tags/{id}) - Delete tag
*
* Test Categories:
* - Tag listing with pagination
* - Tag CRUD operations
* - Tag name uniqueness validation
* - Error handling and edge cases
* - Multi-instance routing
*/
const axios = require('axios');
const crypto = require('crypto');
// ========================================
// Configuration
// ========================================
const config = {
mcpServerUrl: 'http://localhost:3456/mcp',
healthCheckUrl: 'http://localhost:3456/health',
testTagPrefix: 'ValidTest',
testFlags: {
runListTests: true,
runGetTests: true,
runCreateTests: true,
runUpdateTests: true,
runDeleteTests: true,
runCleanup: true
}
};
// ========================================
// Logger Utility
// ========================================
const logger = {
info: (msg) => console.error(`[INFO] ${msg}`),
test: (name, passed, details = '') => {
const status = passed ? '✓ PASS' : '✗ FAIL';
const message = details ? ` - ${details}` : '';
console.error(`[TEST] ${name}: ${status}${message}`);
},
warn: (msg) => console.error(`[WARN] ⚠️ ${msg}`),
error: (msg) => console.error(`[ERROR] ❌ ${msg}`),
success: (msg) => console.error(`[SUCCESS] ✓ ${msg}`),
debug: (msg, data) => {
if (process.env.DEBUG) {
console.error(`[DEBUG] ${msg}`, data ? JSON.stringify(data, null, 2) : '');
}
}
};
// ========================================
// MCP Communication
// ========================================
let requestId = 1;
async function sendMcpRequest(method, params = {}) {
try {
const response = await axios.post(config.mcpServerUrl, {
jsonrpc: '2.0',
id: requestId++,
method,
params
});
logger.debug(`MCP Response for ${method}:`, response.data);
return response.data.result;
} catch (error) {
logger.error(`MCP request failed: ${method}`);
if (error.response) {
logger.error(`Status: ${error.response.status}`);
logger.error(`Data: ${JSON.stringify(error.response.data)}`);
}
throw error;
}
}
async function callTool(name, args = {}, maxRetries = 3) {
let lastError;
// Don't retry create operations to avoid 409 conflicts
const isCreateOperation = name === 'create_tag' || name === 'create_workflow';
const actualRetries = isCreateOperation ? 1 : maxRetries;
for (let attempt = 1; attempt <= actualRetries; attempt++) {
try {
const result = await sendMcpRequest('tools/call', { name, arguments: args });
// Check if MCP tool returned an error
if (result.isError) {
const errorMessage = result.content && result.content[0] && result.content[0].text
? result.content[0].text
: 'Unknown MCP tool error';
throw new Error(errorMessage);
}
return result;
} catch (error) {
lastError = error;
// Don't retry on 409 Conflict errors (resource already exists)
if (error.message && error.message.includes('409')) {
throw error;
}
if (attempt < actualRetries) {
logger.warn(`Retrying tools/call (${actualRetries - attempt} attempts remaining)`);
await sleep(1000 * attempt);
}
}
}
throw lastError;
}
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
// ========================================
// Test State Management
// ========================================
const testState = {
createdTags: [],
testTagIds: []
};
// ========================================
// Test Suite: get_tags (List Tags)
// ========================================
async function testGetTags() {
logger.info('\n--- Task 2: Validate get_tags ---\n');
let testsPassed = 0;
let testsTotal = 0;
// Test 2.1: List all tags
testsTotal++;
try {
const result = await callTool('get_tags', {});
const data = JSON.parse(result.content[0].text);
const isValid = data && Array.isArray(data.data);
logger.test(
'get_tags - List all tags',
isValid,
isValid ? `Found ${data.data.length} tags` : 'Invalid response structure'
);
if (isValid) testsPassed++;
// Store tag IDs for later tests
if (data.data.length > 0) {
testState.testTagIds = data.data.slice(0, 3).map(t => t.id);
}
} catch (error) {
logger.test('get_tags - List all tags', false, error.message);
}
// Test 2.2: Response structure validation
testsTotal++;
try {
const result = await callTool('get_tags', { limit: 5 });
const data = JSON.parse(result.content[0].text);
if (data.data && data.data.length > 0) {
const tag = data.data[0];
const hasRequiredFields =
tag.hasOwnProperty('id') &&
tag.hasOwnProperty('name') &&
tag.hasOwnProperty('createdAt') &&
tag.hasOwnProperty('updatedAt');
logger.test(
'get_tags - Response structure validation',
hasRequiredFields,
hasRequiredFields ? 'All required fields present' : 'Missing required fields'
);
if (hasRequiredFields) testsPassed++;
} else {
logger.test('get_tags - Response structure validation', true, 'No tags to validate (empty list is valid)');
testsPassed++;
}
} catch (error) {
logger.test('get_tags - Response structure validation', false, error.message);
}
// Test 2.3: Pagination with limit
testsTotal++;
try {
const result = await callTool('get_tags', { limit: 3 });
const data = JSON.parse(result.content[0].text);
const isValid = data.data && data.data.length <= 3;
logger.test(
'get_tags - Pagination limit',
isValid,
isValid ? `Returned ${data.data.length} tags (limit: 3)` : 'Limit not respected'
);
if (isValid) testsPassed++;
} catch (error) {
logger.test('get_tags - Pagination limit', false, error.message);
}
// Test 2.4: Cursor-based pagination
testsTotal++;
try {
const firstPage = await callTool('get_tags', { limit: 2 });
const firstData = JSON.parse(firstPage.content[0].text);
if (firstData.nextCursor) {
const secondPage = await callTool('get_tags', {
limit: 2,
cursor: firstData.nextCursor
});
const secondData = JSON.parse(secondPage.content[0].text);
const isValid = secondData.data && secondData.data.length > 0;
logger.test(
'get_tags - Cursor pagination',
isValid,
isValid ? `Next page retrieved with ${secondData.data.length} tags` : 'Cursor pagination failed'
);
if (isValid) testsPassed++;
} else {
logger.test('get_tags - Cursor pagination', true, 'No next cursor (all tags fit in first page)');
testsPassed++;
}
} catch (error) {
logger.test('get_tags - Cursor pagination', false, error.message);
}
return { passed: testsPassed, total: testsTotal };
}
// ========================================
// Test Suite: create_tag
// ========================================
async function testCreateTag() {
logger.info('\n--- Task 3: Validate create_tag ---\n');
let testsPassed = 0;
let testsTotal = 0;
// Test 3.1: Create tag with unique name
testsTotal++;
try {
const tagName = `Test${crypto.randomUUID().substring(0, 8)}`;
const result = await callTool('create_tag', { name: tagName });
const tag = JSON.parse(result.content[0].text);
const isValid = tag && tag.id && tag.name === tagName;
logger.test(
'create_tag - Create with unique name',
isValid,
isValid ? `Created tag: ${tag.id}` : 'Tag creation failed'
);
if (isValid) {
testsPassed++;
testState.createdTags.push(tag.id);
}
} catch (error) {
logger.test('create_tag - Create with unique name', false, error.message);
}
// Test 3.2: Structure validation
testsTotal++;
try {
const tagName = `Test${crypto.randomUUID().substring(0, 8)}`;
const result = await callTool('create_tag', { name: tagName });
const tag = JSON.parse(result.content[0].text);
const hasRequiredFields =
tag.hasOwnProperty('id') &&
tag.hasOwnProperty('name') &&
tag.hasOwnProperty('createdAt') &&
tag.hasOwnProperty('updatedAt');
logger.test(
'create_tag - Structure validation',
hasRequiredFields,
hasRequiredFields ? 'All required fields present' : 'Missing required fields'
);
if (hasRequiredFields) {
testsPassed++;
testState.createdTags.push(tag.id);
}
} catch (error) {
logger.test('create_tag - Structure validation', false, error.message);
}
// Test 3.3: Duplicate name handling
testsTotal++;
try {
const tagName = `Test${crypto.randomUUID().substring(0, 8)}`;
// Create first tag
const first = await callTool('create_tag', { name: tagName });
const firstTag = JSON.parse(first.content[0].text);
testState.createdTags.push(firstTag.id);
// Try to create duplicate
try {
await callTool('create_tag', { name: tagName });
logger.test('create_tag - Duplicate name handling', false, 'Should have rejected duplicate name');
} catch (error) {
const isDuplicateError = error.message.includes('already exists') ||
error.message.includes('duplicate') ||
error.message.includes('unique') ||
error.message.includes('409');
logger.test(
'create_tag - Duplicate name handling',
isDuplicateError,
isDuplicateError ? 'Correctly rejected duplicate' : 'Wrong error type'
);
if (isDuplicateError) testsPassed++;
}
} catch (error) {
logger.test('create_tag - Duplicate name handling', false, error.message);
}
return { passed: testsPassed, total: testsTotal };
}
// ========================================
// Test Suite: get_tag
// ========================================
async function testGetTag() {
logger.info('\n--- Task 4: Validate get_tag ---\n');
let testsPassed = 0;
let testsTotal = 0;
// Ensure we have tag IDs to test
if (testState.testTagIds.length === 0 && testState.createdTags.length === 0) {
logger.warn('No tag IDs available for testing. Skipping get_tag tests.');
return { passed: 0, total: 0 };
}
const testTagId = testState.testTagIds.length > 0
? testState.testTagIds[0]
: testState.createdTags[0];
logger.info(`Using tag ID: ${testTagId}`);
// Test 4.1: Retrieve tag by ID
testsTotal++;
try {
const result = await callTool('get_tag', { id: testTagId });
const tag = JSON.parse(result.content[0].text);
const isValid = tag && tag.id === testTagId;
logger.test(
'get_tag - Retrieve by ID',
isValid,
isValid ? `Tag retrieved: ${tag.name}` : 'Failed to retrieve tag'
);
if (isValid) testsPassed++;
} catch (error) {
logger.test('get_tag - Retrieve by ID', false, error.message);
}
// Test 4.2: Structure validation
testsTotal++;
try {
const result = await callTool('get_tag', { id: testTagId });
const tag = JSON.parse(result.content[0].text);
const hasRequiredFields =
tag.hasOwnProperty('id') &&
tag.hasOwnProperty('name') &&
tag.hasOwnProperty('createdAt') &&
tag.hasOwnProperty('updatedAt');
logger.test(
'get_tag - Structure validation',
hasRequiredFields,
hasRequiredFields ? 'All required fields present' : 'Missing required fields'
);
if (hasRequiredFields) testsPassed++;
} catch (error) {
logger.test('get_tag - Structure validation', false, error.message);
}
// Test 4.3: 404 for non-existent ID
testsTotal++;
try {
await callTool('get_tag', { id: '99999999' });
logger.test('get_tag - 404 for non-existent ID', false, 'Should have returned error');
} catch (error) {
const is404 = error.message.includes('404') || error.message.includes('not found') || error.message.includes('Not Found');
logger.test(
'get_tag - 404 for non-existent ID',
is404,
is404 ? 'Correctly returned 404' : 'Wrong error type'
);
if (is404) testsPassed++;
}
return { passed: testsPassed, total: testsTotal };
}
// ========================================
// Test Suite: update_tag
// ========================================
async function testUpdateTag() {
logger.info('\n--- Task 5: Validate update_tag ---\n');
let testsPassed = 0;
let testsTotal = 0;
// Test 5.1: Update tag name
testsTotal++;
try {
// Create a tag to update
const originalName = `Test${crypto.randomUUID().substring(0, 8)}`;
const createResult = await callTool('create_tag', { name: originalName });
const createdTag = JSON.parse(createResult.content[0].text);
testState.createdTags.push(createdTag.id);
// Update the tag
const newName = `Test${crypto.randomUUID().substring(0, 8)}`;
const updateResult = await callTool('update_tag', {
id: createdTag.id,
name: newName
});
const updatedTag = JSON.parse(updateResult.content[0].text);
const isValid = updatedTag && updatedTag.name === newName && updatedTag.id === createdTag.id;
logger.test(
'update_tag - Update name',
isValid,
isValid ? `Name updated successfully` : 'Update failed'
);
if (isValid) testsPassed++;
} catch (error) {
logger.test('update_tag - Update name', false, error.message);
}
// Test 5.2: 404 for non-existent ID
testsTotal++;
try {
await callTool('update_tag', {
id: '99999999',
name: `${config.testTagPrefix}NonExistent`
});
logger.test('update_tag - 404 for non-existent ID', false, 'Should have returned error');
} catch (error) {
const is404 = error.message.includes('404') || error.message.includes('not found');
logger.test(
'update_tag - 404 for non-existent ID',
is404,
is404 ? 'Correctly returned 404' : 'Wrong error type'
);
if (is404) testsPassed++;
}
return { passed: testsPassed, total: testsTotal };
}
// ========================================
// Test Suite: delete_tag
// ========================================
async function testDeleteTag() {
logger.info('\n--- Task 6: Validate delete_tag ---\n');
let testsPassed = 0;
let testsTotal = 0;
// Test 6.1: Delete tag and verify
testsTotal++;
try {
// Create a tag to delete
const tagName = `Test${crypto.randomUUID().substring(0, 8)}`;
const createResult = await callTool('create_tag', { name: tagName });
const createdTag = JSON.parse(createResult.content[0].text);
// Delete the tag
await callTool('delete_tag', { id: createdTag.id });
// Verify it's gone
try {
await callTool('get_tag', { id: createdTag.id });
logger.test('delete_tag - Delete and verify', false, 'Tag still exists after deletion');
} catch (error) {
const is404 = error.message.includes('404') || error.message.includes('not found');
logger.test(
'delete_tag - Delete and verify',
is404,
is404 ? 'Tag successfully deleted' : 'Unexpected error'
);
if (is404) testsPassed++;
}
} catch (error) {
logger.test('delete_tag - Delete and verify', false, error.message);
}
// Test 6.2: 404 for non-existent ID
testsTotal++;
try {
await callTool('delete_tag', { id: '99999999' });
logger.test('delete_tag - 404 for non-existent ID', false, 'Should have returned error');
} catch (error) {
const is404 = error.message.includes('404') || error.message.includes('not found');
logger.test(
'delete_tag - 404 for non-existent ID',
is404,
is404 ? 'Correctly returned 404' : 'Wrong error type'
);
if (is404) testsPassed++;
}
return { passed: testsPassed, total: testsTotal };
}
// ========================================
// Cleanup
// ========================================
async function cleanup() {
if (!config.testFlags.runCleanup) {
logger.info('Cleanup disabled by configuration');
return;
}
logger.info('\n======================================================================');
logger.info(' Cleanup');
logger.info('======================================================================\n');
let cleanedTags = 0;
if (testState.createdTags.length > 0) {
logger.info(`Cleaning up ${testState.createdTags.length} test tags...`);
for (const tagId of testState.createdTags) {
try {
await callTool('delete_tag', { id: tagId });
cleanedTags++;
} catch (error) {
logger.debug(`Failed to delete tag ${tagId}: ${error.message}`);
}
}
logger.success(`✓ Cleaned up ${cleanedTags}/${testState.createdTags.length} test tags`);
}
}
// ========================================
// Main Test Runner
// ========================================
async function runTests() {
console.error('======================================================================');
console.error(' Tags API Validation Test Suite - Story 2.3');
console.error('======================================================================\n');
logger.info('Testing 5 Tags API methods against live n8n instance');
logger.info(`MCP Server: ${config.mcpServerUrl}\n`);
const results = {
list: { passed: 0, total: 0 },
create: { passed: 0, total: 0 },
get: { passed: 0, total: 0 },
update: { passed: 0, total: 0 },
delete: { passed: 0, total: 0 }
};
try {
// Pre-flight checks
console.error('--- Pre-flight Checks ---\n');
const health = await axios.get(config.healthCheckUrl);
logger.info(`Server health: ${health.data.status}\n`);
// Run test suites
if (config.testFlags.runListTests) {
results.list = await testGetTags();
}
if (config.testFlags.runCreateTests) {
results.create = await testCreateTag();
}
if (config.testFlags.runGetTests) {
results.get = await testGetTag();
}
if (config.testFlags.runUpdateTests) {
results.update = await testUpdateTag();
}
if (config.testFlags.runDeleteTests) {
results.delete = await testDeleteTag();
}
// Cleanup
await cleanup();
// Summary
console.error('\n======================================================================');
console.error(' Test Summary Report');
console.error('======================================================================\n');
const totalPassed = results.list.passed + results.create.passed + results.get.passed +
results.update.passed + results.delete.passed;
const totalTests = results.list.total + results.create.total + results.get.total +
results.update.total + results.delete.total;
console.error(`Total tests executed: ${totalTests}`);
console.error(`Passed: ${totalPassed} (${totalTests > 0 ? Math.round(totalPassed/totalTests*100) : 0}%)`);
console.error(`Failed: ${totalTests - totalPassed}`);
console.error(`Skipped: 0\n`);
console.error('Test categories:');
console.error(` list: ${results.list.passed}/${results.list.total} (${results.list.total > 0 ? Math.round(results.list.passed/results.list.total*100) : 0}%)`);
console.error(` create: ${results.create.passed}/${results.create.total} (${results.create.total > 0 ? Math.round(results.create.passed/results.create.total*100) : 0}%)`);
console.error(` get: ${results.get.passed}/${results.get.total} (${results.get.total > 0 ? Math.round(results.get.passed/results.get.total*100) : 0}%)`);
console.error(` update: ${results.update.passed}/${results.update.total} (${results.update.total > 0 ? Math.round(results.update.passed/results.update.total*100) : 0}%)`);
console.error(` delete: ${results.delete.passed}/${results.delete.total} (${results.delete.total > 0 ? Math.round(results.delete.passed/results.delete.total*100) : 0}%)`);
console.error('\n======================================================================');
if (totalPassed === totalTests && totalTests > 0) {
console.error('✓ ALL TESTS PASSED!');
} else {
console.error(`⚠ ${totalTests - totalPassed} TESTS FAILED`);
}
console.error('======================================================================');
process.exit(totalPassed === totalTests ? 0 : 1);
} catch (error) {
logger.error(`Test suite failed: ${error.message}`);
console.error(error.stack);
process.exit(1);
}
}
// Run tests
runTests();