Repository navigation
Expand file tree
/
Copy pathrun-tests.js
More file actions
executable file
·237 lines (205 loc) · 6.18 KB
/
Copy pathrun-tests.js
File metadata and controls
executable file
·237 lines (205 loc) · 6.18 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
#!/usr/bin/env node
/**
* Headless browser test runner for grub stars JavaScript tests
* Uses Playwright to run tests in Chromium
*/
const { chromium } = require('playwright');
const path = require('path');
const fs = require('fs');
const http = require('http');
/**
* Simple HTTP server to serve static files
* Needed because ES modules require HTTP/HTTPS protocol (file:// won't work)
*/
function createServer(webDir, port) {
const mimeTypes = {
'.html': 'text/html',
'.js': 'application/javascript',
'.css': 'text/css',
'.json': 'application/json',
};
const server = http.createServer((req, res) => {
// Default to index.html for root path
let filePath = req.url === '/' ? '/test.html' : req.url;
filePath = path.join(webDir, filePath);
// Security: prevent directory traversal
if (!filePath.startsWith(webDir)) {
res.writeHead(403);
res.end('Forbidden');
return;
}
fs.readFile(filePath, (err, data) => {
if (err) {
res.writeHead(404);
res.end('Not found');
return;
}
const ext = path.extname(filePath);
const mimeType = mimeTypes[ext] || 'application/octet-stream';
res.writeHead(200, { 'Content-Type': mimeType });
res.end(data);
});
});
return new Promise((resolve) => {
server.listen(port, () => {
resolve(server);
});
});
}
async function runTests() {
console.log('🧪 Starting JavaScript test suite...\n');
// Check if web directory exists
const webDir = path.join(__dirname, 'web');
if (!fs.existsSync(webDir)) {
console.error('❌ Error: web/ directory not found');
process.exit(1);
}
// Start HTTP server
const port = 8765;
console.log(`Starting HTTP server on port ${port}...`);
const server = await createServer(webDir, port);
const browser = await chromium.launch({
headless: true,
args: [
'--no-sandbox',
'--disable-setuid-sandbox',
'--disable-dev-shm-usage',
'--disable-accelerated-2d-canvas',
'--no-first-run',
'--no-zygote',
'--single-process',
'--disable-gpu',
],
});
try {
const page = await browser.newPage();
// Block external network requests to allow offline testing
// This prevents CDN failures from crashing the test page
await page.route('**/*', (route) => {
const url = route.request().url();
// Allow localhost requests, block external CDN/font requests
if (url.startsWith(`http://localhost:${port}`)) {
route.continue();
} else {
// Abort external requests silently (CDN, fonts, etc.)
route.abort('blockedbyclient');
}
});
// Collect console messages
const consoleMessages = [];
let testResultsFromConsole = null;
page.on('console', (msg) => {
const text = msg.text();
consoleMessages.push(text);
// Forward console output to stdout
console.log(text);
// Parse test results from console output
if (text.includes('📊 Test Results:')) {
const match = text.match(/(\d+)\/(\d+) passed/);
if (match) {
testResultsFromConsole = {
passed: parseInt(match[1]),
total: parseInt(match[2]),
};
}
}
});
// Catch page errors
page.on('pageerror', (error) => {
console.error('❌ Page error:', error.message);
});
// Handle page crashes gracefully
let pageCrashed = false;
page.on('crash', () => {
pageCrashed = true;
});
// Navigate to test page via HTTP
const testUrl = `http://localhost:${port}/test.html`;
console.log(`Loading: ${testUrl}\n`);
try {
await page.goto(testUrl, {
waitUntil: 'domcontentloaded',
timeout: 30000,
});
} catch (error) {
if (!pageCrashed && !testResultsFromConsole) {
throw error;
}
// If page crashed but we have test results, continue
}
// Wait a bit for scripts to load and execute
if (!pageCrashed) {
try {
await page.waitForTimeout(3000);
} catch (e) {
// Page might have crashed during wait
}
}
// Check if we already have results from console parsing
if (testResultsFromConsole) {
await browser.close();
server.close();
const testsPassed = testResultsFromConsole.passed === testResultsFromConsole.total;
if (testsPassed) {
console.log('\n✅ All tests passed!');
process.exit(0);
} else {
console.log(`\n❌ ${testResultsFromConsole.total - testResultsFromConsole.passed} test(s) failed!`);
process.exit(1);
}
}
// Otherwise, wait for tests to complete via title
try {
const testResults = await page.waitForFunction(
() => {
const title = document.title;
if (title.includes('✅') || title.includes('❌')) {
return {
passed: title.includes('✅'),
title: title
};
}
return null;
},
{ timeout: 60000 }
);
// Get test results
const results = await testResults.jsonValue();
const testsPassed = results.passed;
await browser.close();
server.close();
if (testsPassed) {
console.log('\n✅ All tests passed!');
process.exit(0);
} else {
console.log('\n❌ Some tests failed!');
process.exit(1);
}
} catch (error) {
// Final fallback: check console output
if (testResultsFromConsole) {
await browser.close();
server.close();
const testsPassed = testResultsFromConsole.passed === testResultsFromConsole.total;
if (testsPassed) {
console.log('\n✅ All tests passed (from console output)!');
process.exit(0);
} else {
console.log(`\n❌ ${testResultsFromConsole.total - testResultsFromConsole.passed} test(s) failed!`);
process.exit(1);
}
}
throw error;
}
} catch (error) {
console.error('\n❌ Test runner error:', error.message);
await browser.close();
server.close();
process.exit(1);
}
}
// Run tests
runTests().catch((error) => {
console.error('Fatal error:', error);
process.exit(1);
});