-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtest.js
More file actions
89 lines (74 loc) · 2.5 KB
/
Copy pathtest.js
File metadata and controls
89 lines (74 loc) · 2.5 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
'use strict';
const http = require('http');
const app = require('./server');
const PORT = process.env.PORT || 3000;
const HOST = process.env.HOST || '127.0.0.1';
let passed = 0;
let failed = 0;
// Assertion helper
function assert(condition, label) {
if (condition) {
console.log(`PASS: ${label}`);
passed++;
} else {
console.error(`FAIL: ${label}`);
failed++;
}
}
// HTTP GET request helper with timeout
function request(path, timeout = 5000) {
return new Promise((resolve, reject) => {
const req = http.get(`http://${HOST}:${PORT}${path}`, (res) => {
let body = '';
res.on('data', (chunk) => (body += chunk));
res.on('end', () => {
try {
resolve({ status: res.statusCode, body: JSON.parse(body) });
} catch {
resolve({ status: res.statusCode, body });
}
});
});
req.on('error', reject);
req.setTimeout(timeout, () => {
req.abort();
reject(new Error(`Request timed out: ${path}`));
});
});
}
// Run all tests
async function runTests(server) {
try {
console.log(`\nRunning tests against http://${HOST}:${PORT}\n`);
// Test /health
console.log('Test 1 — GET /health');
const health = await request('/health');
assert(health.status === 200, 'Status code is 200');
assert(health.body.status === 'ok', 'Body.status equals "ok"');
assert(typeof health.body.uptime === 'number', 'Body.uptime is a number');
assert(typeof health.body.timestamp === 'string', 'Body.timestamp is a string');
assert(typeof health.body.version === 'string', 'Body.version is a string');
// Test unknown route
console.log('\nTest 2 — GET /unknown-route');
const notFound = await request('/unknown-route');
assert(notFound.status === 404, 'Status code is 404');
// Summary
console.log(`\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━`);
console.log(` Results: ${passed} passed, ${failed} failed`);
console.log(`━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n`);
server.close();
process.exit(failed > 0 ? 1 : 0);
} catch (err) {
console.error('ERROR during tests:', err);
server.close();
process.exit(1);
}
}
// Start server and run tests
const server = app.listen(PORT, HOST, () => {
runTests(server).catch(err => {
console.error('Test runner failed:', err);
server.close();
process.exit(1);
});
});